Reputation: 459
The data are:
a <- matrix(c(1,1,2,2,'a','b','c','d'),4,2)
b <- c(1,'a')
So the first row of a
matches b
. If I want to return the index of the row in the matrix a
(which is 1), what code would I apply in r? I tried:
which((a[,1]==b[1])&(a[,2]==b[2])), is there any other option?
Upvotes: 4
Views: 923
Reputation: 388982
Couple of more options :
which(colSums(t(a) != b) == 0)
and
which(rowSums(sweep(a, 2, b, `!=`)) == 0)
Upvotes: 1
Reputation: 101538
Another option but with match
match(list(b),asplit(a,1))
or
match(asplit(t(b),1),asplit(a,1))
or
match(as.data.frame(t(t(b))),as.data.frame(t(a)))
Upvotes: 3
Reputation: 887148
We can replicate the 'b' by the row
of 'a' and do an elementwise comparison, then wrap the which
to get the index
which(a == b[row(a)])
Note that this gives the index of the element. If we need the index of row where everything matches.
which(rowSums(a == b[col(a)]) == ncol(a))
Or
which(a == b)
Upvotes: 3