[R] which is the fastest way to make data.frame out of a three-dimensional array?
Petr Savicky
savicky at cs.cas.cz
Sat Feb 25 18:55:31 CET 2012
On Sat, Feb 25, 2012 at 04:54:30PM +0100, Hans Ekbrand wrote:
> foo <- rnorm(30*34*12)
> dim(foo) <- c(30, 34, 12)
>
> I want to make a data.frame out of this three-dimensional array. Each dimension will be a variabel (column) in the data.frame.
Hi.
Try this
n1 <- dim(foo)[1]
n2 <- dim(foo)[2]
n3 <- dim(foo)[3]
df <- cbind(dat=c(foo), expand.grid(dim1=1:n1, dim2=1:n2, dim3=1:n3))
df[1:5, ]
dat dim1 dim2 dim3
1 -0.5765847 1 1 1
2 0.4490040 2 1 1
3 0.2626855 3 1 1
4 0.2206713 4 1 1
5 0.9079324 5 1 1
...
On the contrary to a previous suggestion with foo==foo, this
works also in presence of NA.
Hope this helps.
Petr Savicky.
More information about the R-help
mailing list