Reputation: 1935
I was looking at R-help on structure()
. The example given by the help file is this:
structure(1:6, dim=2:3)
[,1] [,2] [,3]
[1,] 1 3 5
[2,] 2 4 6
which creates a very nice 2 by 3 matrix. However, when I tried
structure(1:8, dim=2:4)
It won't work. Why? Another question is when should I use this structure()
function? I don't understand why we need it, since we have matrix()
and data.frame()
etc.
Upvotes: 1
Views: 64
Reputation: 838
The reason your code doesn't work is because 2:4
yields (2,3,4). You want c(2,4)
if you want a 2x4 matrix. That said, using structure
to set attributes on a vector to turn in into a matrix is a really odd way of doing that. structure
does nothing more than return a copy of the object with additional/modified attributes, in your case exploiting the fact that R represents matrices as vectors with a dim
attribute.
Upvotes: 4
Reputation: 263441
If you want an array then use the 'array' function.
array(1:8, dim=2:4)
There are not many times when a beginner in R needs 'structure'.
Upvotes: 0