How to prevent dropping dimensions in a matrix/array?

When you create a matrix in the usual way like this,

> a <- matrix(rnorm(10),2,5)
> a
       [,1]      [,2]       [,3]       [,4]       [,5]
 [1,]  1.3488918 0.6225795 -0.7444514  1.3130491  1.7877849
 [2,] -0.2385392 0.5656759  0.9037435 -0.2217444 -0.2656875

the dimension dropped after picking up a single row or column in this way,

> b <- a[,1]
> b
 [1]  1.3488918 -0.2385392
 > dim(b)
 NULL

The solution is to try it with a parameter drop = FALSE,

> b <- a[,1,drop = FALSE]
 > b
            [,1]
 [1,]  1.3488918
 [2,] -0.2385392
 > dim(b)
 [1] 2 1

Leave a Reply

Your email address will not be published. Required fields are marked *