How to convert data frame to 3d array in R

I have a data frame that I want to convert to a three-dimensional array. One of the columns in the data frame should serve as a grouping variable for dividing the frame into 2d matrices, which can be combined into an array. In the following minimum working example, the data frame should be matrixed by the variable "i" and then combined into a 4x4x2 array. The solution should be practical for large data sets and ideally can be generalized to convert a data frame to an n-dimensional array.

# Make reproducible set.seed(123) df <- { data.frame(i=rep(1:2, each=4), x=rep(rep(0:1, each=2), 2), y=rep(rep(0:1, 2), 2), l=rnorm(8)) } df # ixyl # 1 1 0 0 -0.56047565 # 2 1 0 1 -0.23017749 # 3 1 1 0 1.55870831 # 4 1 1 1 0.07050839 # 5 2 0 0 0.12928774 # 6 2 0 1 1.71506499 # 7 2 1 0 0.46091621 # 8 2 1 1 -1.26506123 

Note. I suspect that Hadley Wickham Plire can provide the necessary tool, perhaps ridiculously?

+7
arrays r
source share
2 answers

Here is what I will probably do:

 library(abind) abind(split(df, df$i), along=3) # , , 1 # # ixyl # 5 1 0 0 -0.56047565 # 6 1 0 1 -0.23017749 # 7 1 1 0 1.55870831 # 8 1 1 1 0.07050839 # # , , 2 # # ixyl # 5 2 0 0 0.1292877 # 6 2 0 1 1.7150650 # 7 2 1 0 0.4609162 # 8 2 1 1 -1.2650612 
+6
source share

It looks like you are looking for split :

 > split(df, df$i) $`1` ixyl 1 1 0 0 -0.56047565 2 1 0 1 -0.23017749 3 1 1 0 1.55870831 4 1 1 1 0.07050839 $`2` ixyl 5 2 0 0 0.1292877 6 2 0 1 1.7150650 7 2 1 0 0.4609162 8 2 1 1 -1.2650612 

The result is a list two data.frame separated by an "i" column.


To get an array , you got a Josh response, or you can use simplify2array from the R base:

 > simplify2array(by(df, df$i, as.matrix)) , , 1 ixyl 1 1 0 0 -0.56047565 2 1 0 1 -0.23017749 3 1 1 0 1.55870831 4 1 1 1 0.07050839 , , 2 ixyl 1 2 0 0 0.1292877 2 2 0 1 1.7150650 3 2 1 0 0.4609162 4 2 1 1 -1.2650612 
+7
source share

All Articles