How to merge two data frames of different length having same values in all columns but at different positions?


To merge two data frames of different length having same values in all columns but at different positions, we can follow the below steps −

  • First of all, create two data frames.
  • Then, merge them using merge function with all argument set to FALSE.

Create the data frame

Let's create a data frame as shown below −

 Live Demo

> x<-sample(1:5,20,replace=TRUE)
> y<-sample(1:5,20,replace=TRUE)
> z<-sample(1:5,20,replace=TRUE)
> df1<-data.frame(x,y,z)
> df1

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

Output

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

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

 Live Demo

> x<-sample(1:5,20,replace=TRUE)
> y<-sample(1:5,20,replace=TRUE)
> z<-sample(1:5,20,replace=TRUE)
> df2<-data.frame(x,y,z)
> df2

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

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

Merge the two data frames

Using merge function to merge df1 and df2 −

> DF<-merge(df1,df2,by=c("x","y","z"),all=FALSE)
> DF
  x y z
1 1 1 1
2 1 3 2
3 3 2 3
4 3 3 2

Updated on: 13-Aug-2021

353 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements