简体   繁体   中英

Searching rows of matrix by vector

I would like to investigate each row in the matrix and see if its value are larger than the values in the given vector. Then, I would like to convert the values to 1 or 0 depending on whether it is success or not. I am pretty new to programming and despite searching for answer I did not figure it out on my own. Thanks.

v <- c(0.2,0.6,0.1,0.6,0.9)
m <- matrix(c(runif(15,min=0,max=1)),ncol=5,nrow=3)

largerthan <- m>v

You could try

 (m >v[col(m)])+0
 #      [,1] [,2] [,3] [,4] [,5]
 #[1,]    1    0    1    0    0
 #[2,]    1    1    1    1    0
 #[3,]    1    1    1    0    0

Or a slightly faster way would be

 (m > rep(v, each=nrow(m)))+0L

and the original dataset "m" is

 m
 #        [,1]      [,2]      [,3]      [,4]      [,5]
 #[1,] 0.2925740 0.5188971 0.2797356 0.2547251 0.6716903
 #[2,] 0.2248911 0.6626196 0.7638205 0.6048889 0.6729823
 #[3,] 0.7042230 0.9204438 0.8016306 0.3707349 0.3204306

If you need to know whether any of row values are larger than any of the vector elements

 apply((m >v[col(m)]), 1, any)
 #[1] TRUE TRUE TRUE

data

set.seed(24)
m <- matrix(runif(15,min=0,max=1),ncol=5,nrow=3)
v <- c(0.2,0.6,0.1,0.6,0.9)

you can try this code :

ifelse(m > matrix(v, ncol = 5, nrow = 3, byrow = TRUE), 1, 0)
##      [,1] [,2] [,3] [,4] [,5]
## [1,]    1    1    0    0    1
## [2,]    1    0    1    0    0
## [3,]    1    1    1    0    0

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