I am trying to figure out a way to delete rows of matrix if a cell in that row satisfies a certain characteristic. For example:
> 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 that row is 2. At the end I want this:
[,1] [,2]
[1,] 1 4
[2,] 3 2
[3,] 3 4
How could I do this?
And what about a more general method if instead of deleting all rows who's first column element is 2, I needed to delete rows who's first column element corresponds to a set of numbers that are contained in a list? For example
delete_list <- c(2,3)
What is the best way to do this?
Thank You in advance.
Just use
mm2 <- mm[mm[,1]!=2,]
This works because
mm[,1] != 2
returns
[1] TRUE FALSE TRUE FALSE TRUE
and essentially you are using this boolean array to choose which rows to pick.