mihoo
mihoo

Reputation: 157

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

Upvotes: 1

Views: 48

Answers (2)

akrun
akrun

Reputation: 886928

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)

Upvotes: 2

Mamoun Benghezal
Mamoun Benghezal

Reputation: 5314

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

Upvotes: 2

Related Questions