How to subset matrix based on condition if both numbers in row <0 or >0 in R?

Viewed 55

This is my matrix

             [,1]  [,2]
M            -1    -5
T             8    -4
W            -3     9
Th            4     5
F             7    -2

I want my output to include Monday and Thursday

This is my code but I would like to see if i could use one of the apply() functions to show the output together and have more efficient code!

m[m[,1]<0 & m[,2]<0,, drop=FALSE]

m[m[,1]>0 & m[,2]>0,,drop=FALSE]
``

3 Answers

A simple base R option

m[do.call("*",asplit(m,2))>0,]

which gives

   [,1] [,2]
M    -1   -5
Th    4    5

An option with rowSums

 m[!rowSums(m  < 0)|!rowSums(m > 0),]
#  [,1] [,2]
#M    -1   -5
#Th    4    5

data

m <-  structure(c(-1L, 8L, -3L, 4L, 7L, -5L, -4L, 9L, 5L, -2L), .Dim = c(5L, 
2L), .Dimnames = list(structure(c("M", "T", "W", "Th", "F"), .Dim = c(5L, 
1L), .Dimnames = list(NULL, "V1")), NULL))

Yes, you can use apply like this:

m[apply(m, 1, function(x) diff(sign(x)) == 0),]
#>    [,1] [,2]
#> M    -1   -5
#> Th    4    5

Data

m <- structure(c(-1L, 8L, -3L, 4L, 7L, -5L, -4L, 9L, 5L, -2L), .Dim = c(5L, 
2L), .Dimnames = list(structure(c("M", "T", "W", "Th", "F"), .Dim = c(5L, 
1L), .Dimnames = list(NULL, "V1")), NULL))

m
#>    [,1] [,2]
#> M    -1   -5
#> T     8   -4
#> W    -3    9
#> Th    4    5
#> F     7   -2
Related