Is there an R function for finding the rows that contains a specific element in a matrix?
x[-which(x == 2 | x == 7, arr.ind = TRUE)[,1],]
is the simplest, most efficient way I can think of.
the single '|' checks if each element is 2 or 7 (which '||' won't do). arr.ind gives each position as a pair of coordinates, rather than the default single number. [,1] selects each row which has a 2 or 7.
Hope that helps :)
As @Dirk said, which
is the right function, here is my answer:
index <- apply(x, 1, function(a) 2 %in% a || 7 %in% a)
> index
[1] FALSE TRUE TRUE FALSE
x[index, ]
x[-which(...), ]
is not the right approach... Why? See what happens in case which
finds no match:
x <- matrix(8, nrow = 4, ncol = 2)
x[-which(x == 2 | x == 7, arr.ind = TRUE)[,1],]
# [,1] [,2]
(it returns nothing, while it should return the whole x
.)
Instead, indexing with logicals is the safer approach: you can negate the vector of matches without risking the odd behavior shown above. Here is an example:
x[!(rowSums(x == 2 | x == 7) > 0), , drop = FALSE]
which can also be written in the shorter form:
x[!rowSums(x == 2 | x == 7), , drop = FALSE]