Is there an R function to search for rows containing a specific element in a matrix?

Say I have a 4x2 matrix.

 x<- matrix(seq(1:8), 4) 

It contains the following elements

 1 5 2 6 3 7 4 8 

In this specific example, let's say I want to delete rows containing "2" or "7" (without having to manually look in the matrix and delete them). How can I do it?

Here, I came up with something, but it does not do what I want. I want it to return row indexes in a matrix that contain either 2 or 7 .

 remove<- which(2 || 7 %in% x) x<- x[-remove,] 

Can someone help me figure this out? Thanks

+6
source share
3 answers
 x[-which(x == 2 | x == 7, arr.ind = TRUE)[,1],] 

- The easiest and most effective way that I can think of.

single '|' checks if each element is 2 or 7 (which "||" will not do). arr.ind gives each position as a pair of coordinates, and not a single default number. [, 1] selects each row that has 2 or 7.

Hope that helps :)

+7
source

As said @Dirk, which - this is the correct 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, ] 
+3
source

x[-which(...), ] not the right approach ... Why? See what happens if which does not find a match:

 x <- matrix(8, nrow = 4, ncol = 2) x[-which(x == 2 | x == 7, arr.ind = TRUE)[,1],] # [,1] [,2] 

(It does not return anything, but should return the integer x .)

Instead, indexing with gates is a safer approach: you can negate the match vector 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 shorter form:

 x[!rowSums(x == 2 | x == 7), , drop = FALSE] 
+3
source

All Articles