0

Say I have a matrix in R:

MyMat <- matrix(1:15, ncol = 3)

     [,1] [,2] [,3]
[1,]    1    6   11
[2,]    2    7   12
[3,]    3    8   13
[4,]    4    9   14
[5,]    5   10   15

This matrix has dimensions 5 3. Now, I'd like to subset it depending on values in the first column:

MyMat <- MyMat[MyMat[, 1] < 3, ]

This gives me a smaller matrix with dimensions 2 3. So far, so good. Now let's say my there isn't a row that fulfills my subsetting criterion.

    MyMat <- MyMat[MyMat[, 1] < 1, ]

This gives me a matrix with dimensions 0 3, which makes perfect sense. However, when my subsetting criterion gives only one row there's a problem:

    MyMat <- MyMat[MyMat[, 1] < 2, ]

When I request the dimensions I get NULL rather than 1 3. Instead of returning a matrix, I get an integer array with a length of 3. This is a frustrating special case. I can work around it by always recasting the result of a subsetting operation as a matrix, like this,

    MyMat <- matrix(MyMat[MyMat[, 1] < 2, ], ncol = 3)    

but this feels kludgey and verbose. My question is this: Is there a better was of subsetting that is guaranteed to return a matrix regardless of the number of rows and doesn't require that I recast the result?

Dan
  • 11,370
  • 4
  • 43
  • 68
  • 2
    You want `MyMat[MyMat[, 1] < 2, , drop = FALSE]`. The help page is at `help(\`[\`)` – Frank Apr 22 '16 at 20:32
  • By the way, "array" means something different in R than in other programming languages. See `?array` if you're interested. – Frank Apr 22 '16 at 20:34
  • 1
    That's exactly what I wanted! Thanks @Frank. PS What would be the correct term for the data structure that I called an array? – Dan Apr 22 '16 at 20:37
  • A vector. See chapter 2 here: https://cran.r-project.org/doc/manuals/r-release/R-intro.html#Simple-manipulations-numbers-and-vectors This manual is also part of the R installation: type `help.start()` and there should be a link on the page that is opened. – Frank Apr 22 '16 at 20:40
  • More specifically an atomic vector. In R lists are also vectors. – IRTFM Apr 22 '16 at 21:38

0 Answers0