# How to create a 3D-array from data frame in R?

A 3D-array is a 3-dimensional array and it is actually a collection of 2D arrays. We can create a 3D-array of a data frame in R by using simplify2array function, this function will break the data frame into arrays that will form a 3D-array.

## Example1

Consider the below data frame:

Live Demo

> set.seed(254)
> x<-sample(0:1,20,replace=TRUE)
> y<-rpois(20,5)
> z<-rpois(20,3)
> a<-rpois(20,5)
> b<-rpois(20,4)
> c<-rpois(20,8)
> df1<-data.frame(x,y,z,a,b,c)
> df1

## Output

x y z a b c
1 0 4 6 9 5 5
2 0 5 1 4 2 1
3 0 6 1 4 5 6
4 1 6 3 5 4 12
5 1 9 8 6 6 11
6 1 8 2 6 2 7
7 0 4 4 6 4 4
8 1 6 2 4 3 4
9 0 5 0 3 4 9
10 0 2 2 4 3 7
11 1 6 1 5 5 7
12 1 8 1 2 4 9
13 0 3 3 4 4 11
14 1 7 3 2 6 11
15 1 8 2 6 4 15
16 0 7 1 5 2 12
17 1 6 1 2 5 7
18 1 6 6 3 2 10
19 1 7 1 5 2 5
20 1 4 2 6 2 6

Creating 3D-array from df1:

## Example

> simplify2array(by(df1,df1$x,as.matrix)) df1$x: 0

## Output

x y z a b c
1 0 4 6 9 5 5
2 0 5 1 4 2 1
3 0 6 1 4 5 6
7 0 4 4 6 4 4
9 0 5 0 3 4 9
10 0 2 2 4 3 7
13 0 3 3 4 4 11
16 0 7 1 5 2 12

## Output

g1 g2 g3 g4
1 2 1.3239241 1.467573 6
6 2 1.4972085 1.847154 8
13 2 0.7776044 1.070726 7
16 2 0.9838087 1.807298 6

## Output

g1 g2 g3 g4
3 4 0.9902820 1.161732 11
4 4 0.7175320 1.814506 4
7 4 1.5698800 1.570466 11
10 4 0.4746240 1.243342 11
12 4 1.4137269 1.289525 5
14 4 1.3936072 1.313207 5
15 4 0.6832531 1.496392 3
18 4 1.7064870 1.517545 6

Updated on: 19-Nov-2020

1K+ Views