How to create the combination of rows in two data frames having same columns in R?


To create the combination of rows in two data frames having same columns in R, we can follow the below steps −

  • First of all, create two data frames.
  • Then, combine the rows in the data frames with expand.grid and cbind with do.call.

Create the data frames

Let's create a data frame as shown below −

 Live Demo

Class<-sample(c("I","II","III"),6,replace=TRUE)
Score<-sample(1:20,6)
df1<-data.frame(Class,Score)
df1

On executing, the above script generates the below output(this output will vary on your system due to randomization) −

 Class Score
1 III 1
2 III 13
3 III 10
4 I   2
5 II  7
6 II  17

Let’s create another data frame df2 as shown below −

Example

 Live Demo

Class<-sample(c("I","II","III"),6,replace=TRUE)
Score<-sample(1:20,6)
df2<-data.frame(Class,Score)
df2
  Class Score
1 III    2
2 I      1
3 III    7
4 III    15
5 I      12
6 III    13

Combine rows of the data frames

Using cbind function with expand.grid and do.call function to combine the rows in df1 and df2 −

 Live Demo

Class<-sample(c("I","II","III"),6,replace=TRUE)
Score<-sample(1:20,6)
df1<-data.frame(Class,Score)
Class<-sample(c("I","II","III"),6,replace=TRUE)
Score<-sample(1:20,6)
df2<-data.frame(Class,Score)
do.call(cbind.data.frame,Map(expand.grid,df1=df1,df2=df2))

Output

   Class.df1 Class.df2 Score.df1 Score.df2
1  III         III        1         2
2  III         III        13        2
3  III         III        10        2
4  I           III        2         2
5  II          III        7         2
6  II          III        17        2
7  III          I         1         1
8  III          I         13        1
9  III          I         10        1
10 I            I         2         1
11 II           I         7         1
12 II           I         17        1
13 III          III       1         7
14 III          III       13        7
15 III          III       10        7
16 I            III        2        7
17 II           III        7        7
18 II           III       17        7
19 III          III       1         15
20 III          III       13        15
21 III          III       10        15
22 I            III       2         15
23 II           III       7         15
24 II           III       17        15
25 III          I         1         12
26 III          I        13         12
27 III          I        10         12
28 I            I        2          12
29 II           I        7          12
30 II           I        17         12
31 III          III      1          13
32 III          III      13         13
33 III          III      10         13
34 I            III      2          13
35 II           III      7          13
36 II           III      17         13

Updated on: 14-Aug-2021

289 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements