Skip to content
Prev 257734 / 398503 Next

Matching a vector with a matrix row

Joshua and Luis

Neither of you is exactly solving the problem as stated, see
below. Luis, could you clarify if you want rows that are _equal_
to a vector or rows with entries _contained_ in a vector?

If

m <- matrix(c("A", "B", "C", "B", "A", "A"), 3, 2)
LHS <- c("A", "B")

then LHS equals the first row only, while

apply(m, 1, function(x) all(x %in% LHS))
[1]  TRUE  TRUE FALSE

finds the rows with entries contained in LHS and

which(m %in% LHS)
[1] 1 2 4 5 6

finds all entries in m that equals an entry in LHS. While
you can turn the latter into the former, this will have some
computational costs too. The R-code

apply(m, 1, function(x) all(x == LHS))
[1]  TRUE FALSE FALSE

finds the rows that are equal to LHS.

- Niels
On 22/04/11 00.18, Joshua Wiley wrote: