user18441
user18441

Reputation: 663

finding the rows containing any element of a list, in R

suppose I have the following matrix:

mm <- matrix(c(1,2,3,5,3,6,7,9,3,4,2,2,2,1,1,1,2,4,4,0,2,5,6,2,3,0,1,2,1,1,8,2,7,1,2,3,1,2,0,3),10,2)

Now I would like to see which rows present, TWO of ANY of these values:

values<-c(2,3,4,9)

for instance, I would like to highlight a hypothetical row containing:

2,3

or

9,4

so, both elements of the row need to be in the "values" list.

any idea?

thank you very much in advance!

Tina.

Upvotes: 1

Views: 415

Answers (1)

agstudy
agstudy

Reputation: 121568

Something like this (I wonder if there is simpler!)

mm[rowSums(matrix(mm %in% values, nrow(mm)) == 2, ]
     [,1] [,2]
[1,]    2    2
[2,]    3    2
[3,]    9    4
[4,]    3    4

Upvotes: 3

Related Questions