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
Published
Categorized as Default, R

By Feng Li

Dr. Feng Li is an Associate Professor of Statistics in the School of Statistics and Mathematics at Central University of Finance and Economics in Beijing, China. Feng obtained his Ph.D. degree in Statistics from Stockholm University, Sweden in 2013. His research interests include Bayesian computation, econometrics and forecasting, and distributed learning. His recent research output appeared in statistics and forecasting journals such as the International Journal of Forecasting and Statistical Analysis and Data Mining, AI journals such as Expert Systems with Applications, and medical journals such as BMJ Open.

Leave a comment

Your email address will not be published.