R: How can I delete rows if an element in a row satisfies a specific characteristic?

I am trying to figure out a way to delete matrix rows if a cell in that row satisfies a certain characteristic. For instance:

> mm <- matrix(c(1,2,3,2,3,4,1,2,3,4),5,2) > mm [,1] [,2] [1,] 1 4 [2,] 2 1 [3,] 3 2 [4,] 2 3 [5,] 3 4 

I want to delete rows if the 1st column element in this row is 2. At the end I want:

  [,1] [,2] [1,] 1 4 [2,] 3 2 [3,] 3 4 

How can i do this?

What about a more general method, if instead of deleting all rows for which the first column element is 2, I had to delete rows for which the first column element corresponds to the set of numbers contained in the list? for instance

 delete_list <- c(2,3) 

What is the best way to do this?

Thanks in advance.

+6
source share
2 answers

Just use

 mm2 <- mm[mm[,1]!=2,] 

It works because

 mm[,1] != 2 

returns

 [1] TRUE FALSE TRUE FALSE TRUE 

and essentially you use this boolean array to choose which rows to select.

+14
source

Not tested ...

 newmat <- mm[mm[,1]!=2,] 

basically, i think you need.

Edit: damn ninja for one minute!

+2
source

Source: https://habr.com/ru/post/903315/


All Articles