Reputation: 179
Consider the following matrix:
MAT <- matrix(nrow=3,ncol=3,1:9)
[,1] [,2] [,3]
[1,] 1 4 7
[2,] 2 5 8
[3,] 3 6 9
I want to retrieve the row number if I provide a vector which exactly matches a row in MAT
. So if I provide c(2,5,8)
, I should get back 2. I'm unsure how to accomplish this; the closest thing I know is using which
to find the location of a single number in a matrix. An alternate could be a very slow quadruple for
loop checking if the given vector matches a row in the matrix. Is there a one line solution for this problem?
Upvotes: 0
Views: 687
Reputation: 66844
You can use identical
to test, apply
loop and which
to identify:
which(apply(MAT,1,function(x) identical(x,c(2L,5L,8L))))
[1] 2
Note that the values in the matrix are stored as integers, so you need to specify that in the vector to test.
Upvotes: 3
Reputation: 60070
You can apply
a simple matching function to each row, then use which
to find the row number:
search_vec = c(2, 5, 8)
vec_matches = apply(MAT, 1, function(row, search_vec) all(row == search_vec), search_vec)
row_num = which(vec_matches)
Upvotes: 2