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

R ProgrammingServer Side ProgrammingProgramming

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

Example

df1$x: 1

Output

x y z a b c
4 1 6 3 5 4 12
5 1 9 8 6 6 11
6 1 8 2 6 2 7
8 1 6 2 4 3 4
11 1 6 1 5 5 7
12 1 8 1 2 4 9
14 1 7 3 2 6 11
15 1 8 2 6 4 15
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

Example2

Live Demo

> g1<-sample(1:4,20,replace=TRUE)
> g2<-rnorm(20,1,0.3)
> g3<-runif(20,1,2)
> g4<-rpois(20,5)
> df2<-data.frame(g1,g2,g3,g4)
> df2

Output

g1 g2 g3 g4
1 2 1.3239241 1.467573 6
2 1 0.7099436 1.881370 3
3 4 0.9902820 1.161732 11
4 4 0.7175320 1.814506 4
5 1 0.5081105 1.162827 7
6 2 1.4972085 1.847154 8
7 4 1.5698800 1.570466 11
8 3 0.6383917 1.471682 7
9 1 1.1184017 1.003588 5
10 4 0.4746240 1.243342 11
11 1 1.1368320 1.158829 7
12 4 1.4137269 1.289525 5
13 2 0.7776044 1.070726 7
14 4 1.3936072 1.313207 5
15 4 0.6832531 1.496392 3
16 2 0.9838087 1.807298 6
17 3 1.0371888 1.039574 9
18 4 1.7064870 1.517545 6
19 3 1.0512661 1.013286 4
20 1 1.0290387 1.899809 9

Example

> simplify2array(by(df2,df2$g1,as.matrix))
df2$g1: 1

Output

g1 g2 g3 g4
2 1 0.7099436 1.881370 3
5 1 0.5081105 1.162827 7
9 1 1.1184017 1.003588 5
11 1 1.1368320 1.158829 7
20 1 1.0290387 1.899809 9

Example

df2$g1: 2

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

Example

df2$g1: 3

Output

g1 g2 g3 g4
8 3 0.6383917 1.471682 7
17 3 1.0371888 1.039574 9
19 3 1.0512661 1.013286 4

Example

df2$g1: 4

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
raja
Published on 19-Nov-2020 07:59:50
Advertisements