Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in R Programming by (5.3k points)

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.

1 Answer

0 votes
by

To select the rows of a matrix that meet a condition, you can do the following:

To create the matrix:

M <- matrix(c(1:20), nrow = 5, ncol =4)

colnames(M) <- c("one", "two", "three","four")

M

     one two three four

[1,]   1   6    11   16

[2,]   2   7    12   17

[3,]   3   8    13   18

[4,]   4   9    14   19

[5,]   5  10    15   20

To select a column by name:

 M[M[, "three"] == 11,]

  one   two three  four 

    1     6    11    16 

To select a column by number:

M[M[, 3] == 11,]

  one   two three  four 

    1     6    11    16 

To keep the selected column(s) as matrices:

M[M[,3] == 11,,drop = FALSE]

     one two three four

[1,]   1   6    11   16

class(M[M[,3] == 11,,drop = FALSE])

[1] "matrix"

Browse Categories

...