Returns an n-by-1 matrix from a multidimensional array
I was very surprised when I found out what for x <- array(0, c(5,3,1))
, for example. x[2,,]
returns a vector
instead of 2D array
(or matrix
).
Why is this array explicitly interpreted as 5 vectors of length 3 instead of 5 3-by-1 arrays? attr(array(0, c(5,3,1)), "dim")
gives [1] 5 3 1
as expected, so it seems like the last dimension is not lost.
How can I make sure I am getting a two dimensional array? I understand that arrays are nothing more than vectors with additional attributes, but I do not understand this obvious "inconsistent" behavior.
Please enlighten me :) I am using a 3D array in the context of another function to store multiple matrices. In general, these matrices have the form nmm, where, in particular, m can be 1 (although usually it is higher).
This is a classic and has been in the R FAQ for over a decade: use drop=FALSE
to prevent a 1 row / column matrix from collapsing into a vector.
R> M <- matrix(1:4,2,2)
R> M
[,1] [,2]
[1,] 1 3
[2,] 2 4
R> M[,1]
[1] 1 2
R> M[,1,drop=FALSE]
[,1]
[1,] 1
[2,] 2
R>