0

R beginner here, need ur help. Lets say we have a matrix like this one:

     1   2   3
1    1   0   0
2    0   1   0
3    0   0   1
4    1   1   0
5    1   0   1 
6    0   1   1
7    1   1   1

Next we have a certain vector f.e. (1, 0, 1), wich would be matching row 5. Whats the best way to get the index 5 from the matrix given that vector? I have allready read the questions R - fastest way to select the rows of a matrix that satisfy multiple conditions and In R, select rows of a matrix that meet a condition but i think the situation differs in this case. Thanx for your input!

Community
  • 1
  • 1
brun0
  • 77
  • 8
  • Hi. Why do you think your situation differs? In my opinion, the links you post are good solutions for your problem. But maybe I'm missing something. Could you clarify? Thanks. – lrnzcig Nov 05 '16 at 12:10
  • @Imzcig Guess you are right, but i have the feeling that there must be a more elegant way of doing it, as my vectors and the count of columns is quite large... For my example posted, they would certainly be good solutions. – brun0 Nov 05 '16 at 12:30
  • can I check all rows where this pattern is matched 66% of the times – R Vij Mar 04 '19 at 10:13

2 Answers2

1

I can propose combination of which, apply, and all functions.

m <- matrix(c(1,0,0,0,1,0,0,0,1,1,1,0,1,0,1,0,1,1,1,1,1), 7, byrow=TRUE)

which(apply(m, 1, function(x) return(all(x == c(1,0,1)))))

[1] 5 
Istrel
  • 2,508
  • 16
  • 22
1

We can use rowSums

which(rowSums(m1 == rep(c(1,0,1), each = nrow(m1)))==3)
#5 
#5 
akrun
  • 874,273
  • 37
  • 540
  • 662