Reputation: 180
I have a matrix m
, that contains vectors a and b.
m<-matrix(a,b,nrow=1000,ncol=2)
How would I extract rows within the matrix where the condition a>b
, vice versa applies then save them into a new vector?
Upvotes: 0
Views: 102
Reputation: 193517
I'm not clear on what you mean by "...then save them into a new vector".
However, for extracting the relevant rows, you can use basic comparison of the values in each column and subset based on that.
Here's some sample data. (5 rows should be sufficient to demonstrate,)
set.seed(1)
x <- matrix(rnorm(10), nrow = 5, dimnames=list(NULL, c("a", "b")))
x
# a b
# [1,] -0.6264538 -0.8204684
# [2,] 0.1836433 0.4874291
# [3,] -0.8356286 0.7383247
# [4,] 1.5952808 0.5757814
# [5,] 0.3295078 -0.3053884
Compare "a" and "b" from matrix "x" and extract the relevant rows.
x[x[, "a"] > x[, "b"], ]
# a b
# [1,] -0.6264538 -0.8204684
# [2,] 1.5952808 0.5757814
# [3,] 0.3295078 -0.3053884
Do the same for "a < b".
Upvotes: 1