7

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.

Akavall
  • 82,592
  • 51
  • 207
  • 251
  • Contained within [How to select rows from data.frame with 2 conditions](http://stackoverflow.com/questions/1536590/how-to-select-rows-from-data-frame-with-2-conditions) (and within every introduction to R manual ever written). – Ari B. Friedman Dec 07 '11 at 18:32

2 Answers2

14

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.

nico
  • 50,859
  • 17
  • 87
  • 112
2

Not tested...

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

is basically what I think you're after.

Edit: damn, ninja'd by one minute!

Carl Witthoft
  • 20,573
  • 9
  • 43
  • 73