How to create a data frame with combinations of values in R?


Suppose we have two values 0 and 1 then how many combinations of these values are possible, the answer is 8 and these combinations are (0,0), (1,0), (0,1), (1,1). In R, we can use expand.grid function to create these combinations but to save it in a data frame, we would need to use as.data.frame function.

Example

 Live Demo

df1<-as.data.frame(expand.grid(c(0,1),c(0,1)))
df1

Output

   Var1 Var2
1   0   0
2   1   0
3   0   1
4   1   1

Example

 Live Demo

df2<-as.data.frame(expand.grid(c(0,1),c(0,1),c(0,1)))
df2

Output

 Var1 Var2 Var3
1 0    0    0
2 1    0    0
3 0    1    0
4 1    1    0
5 0    0    1
6 1    0    1
7 0    1    1   
8 1    1    1

Example

 Live Demo

df3<-as.data.frame(expand.grid(c(0,1,2),c(0,1,2),c(0,1,2)))
df3

Output

  Var1 Var2 Var3
1  0    0    0
2  1    0    0
3  2    0    0
4  0    1    0
5  1    1    0
6  2    1    0
7  0    2    0
8  1    2    0
9  2    2    0
10 0    0    1
11 1    0    1
12 2    0    1
13 0    1    1
14 1    1    1
15 2    1    1
16 0    2    1
17 1    2    1
18 2    2    1
19 0    0    2
20 1    0    2
21 2    0    2
22 0    1    2
23 1    1    2
24 2    1    2
25 0    2    2
26 1    2    2
27 2    2    2

Example

 Live Demo

df4<-as.data.frame(expand.grid(c(0,1,2),c(0,1,2)))
df4

Output

Var1 Var2
1 0 0
2 1 0
3 2 0
4 0 1
5 1 1
6 2 1
7 0 2
8 1 2
9 2 2

Example

 Live Demo

df5<-as.data.frame(expand.grid(c(1,2),c(1,2),c(1,2)))
df5

Output

  Var1 Var2 Var3
1  1    1    1
2  2    1    1
3  1    2    1
4  2    2    1
5  1    1    2
6 2     1    2
7 1     2    2
8 2     2    2

Updated on: 07-Oct-2020

465 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements