[R] which is the fastest way to make data.frame out of a three-dimensional array?
Hans Ekbrand
hans at sociologi.cjb.net
Sat Feb 25 20:23:10 CET 2012
First, thank you both Bert and Petr for your excellent answers.
Berts solution seems somewhat faster, and Petrs is - in my opion at
least - slightly more elegant.
> foo <- rnorm(36 * 150 * 170)
> dim(foo) <- c(36, 150, 170)
> n <- dim(foo)
>
> system.time(my.df <- data.frame(dat = as.vector(foo),
+ dim1 = rep(seq_len(n[1]), n[2]*n[3]),
+ dim2 = rep(rep(seq_len(n[2]), e=n[1]), n[3]),
+ dim3 = rep(seq_len(n[3]), e = n[1]*n[2])))
user system elapsed
0.932 0.156 1.090
>
> system.time(my.df <- cbind(temp=c(foo), expand.grid(dim1=1:n[1], dim2=1:n[2], dim3=1:n[3])))
user system elapsed
0.980 0.252 1.244
>
--
Hans Ekbrand (http://sociologi.cjb.net) <hans at sociologi.cjb.net>
More information about the R-help
mailing list