简体   繁体   中英

Comparing vectors in a matrix in R

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?

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".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM