How to join two data frames with the same row order using dplyr in R?

R ProgrammingServer Side ProgrammingProgramming

When we have one common column in two data frames then joining of those data frames might be used to create a bigger data frame. This will help us to analyze a combined data set with many characteristics. We can do this by using inner_join function of dplyr package.

Example

Consider the below data frames −

> set.seed(111)
> x1<-rep(c(1,2,3,4,5),times=4)
> R1<-sample(1:100,20)
> df1<-data.frame(x1,R1)
> df1
  x1  R1
 1 1  78
 2 2  84
 3 3  83
 4 4  47
 5 5  25
 6 1  59
 7 2  69
 8 3  35
 9 4  72
10 5  26
11 1  49
12 2  45
13 3  74
14 4   8
15 5 100
16 1  96
17 2  24
18 3  48
19 4  95
20 5   7
> x1<-rep(c(1,2),times=5)
> R2<-sample(1:100,10)
> df2<-data.frame(x1,R2)
> df2
x1 R2
1 1 21
2 2 15
3 1 1
4 2 9
5 1 63
6 2 40
7 1 25
8 2 35
9 1 71
10 2 52

Loading dplyr package −

> library(dplyr)

Merging two data frames −

> inner_join(df2,df1)
Joining, by = "x1"
x1 R2 R1
1 1 21 78
2 1 21 59
3 1 21 49
4 1 21 96
5 2 15 84
6 2 15 69
7 2 15 45
8 2 15 24
9 1 1 78
10 1 1 59
11 1 1 49
12 1 1 96
13 2 9 84
14 2 9 69
15 2 9 45
16 2 9 24
17 1 63 78
18 1 63 59
19 1 63 49
20 1 63 96
21 2 40 84
22 2 40 69
23 2 40 45
24 2 40 24
25 1 25 78
26 1 25 59
27 1 25 49
28 1 25 96
29 2 35 84
30 2 35 69
31 2 35 45
32 2 35 24
33 1 71 78
34 1 71 59
35 1 71 49
36 1 71 96
37 2 52 84
38 2 52 69
39 2 52 45
40 2 52 24
raja
Published on 12-Aug-2020 12:50:03
Advertisements