Select rows of a matrix that meet a condition

peter2108 picture peter2108 · Mar 22, 2011 · Viewed 432.7k times · Source

In R with a matrix:

     one two three four
 [1,]   1   6    11   16
 [2,]   2   7    12   17
 [3,]   3   8    11   18
 [4,]   4   9    11   19
 [5,]   5  10    15   20

I want to extract the submatrix whose rows have column three = 11. That is:

      one two three four
 [1,]   1   6    11   16
 [3,]   3   8    11   18
 [4,]   4   9    11   19

I want to do this without looping. I am new to R so this is probably very obvious but the documentation is often somewhat terse.

Answer

neilfws picture neilfws · Mar 22, 2011

This is easier to do if you convert your matrix to a data frame using as.data.frame(). In that case the previous answers (using subset or m$three) will work, otherwise they will not.

To perform the operation on a matrix, you can define a column by name:

m[m[, "three"] == 11,]

Or by number:

m[m[,3] == 11,]

Note that if only one row matches, the result is an integer vector, not a matrix.