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?