How to match a column in a data frame with a column in another data frame in R?

R ProgrammingServer Side ProgrammingProgramming

To match a column in a data frame with a column in another data frame, we can use match function. For example, if we have two data frames called df1 and df2 each having one similar column and the second having an extra column then the matching can be done for similar columns and a new column in the first data frame can be created based on that match and the second column the second data frame. Check out the below examples to understand how it works.

Example1

Live Demo

> df1<-data.frame(x1=sample(0:2,20,replace=TRUE))
> df1

Output

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

Example

> df2<-data.frame(x1=rpois(20,2),x2=rpois(20,5))
> df2

Output

   x1 x2
1   2  5
2   2  5
3   3  6
4   0  5
5   1  3
6   1  5
7   2  6
8   1  3
9   4  6
10  0  5
11  1  0
12  3  4
13  1  3
14  1  4
15  2  6
16  1  5
17  2  2
18  3  8
19  0  5
20  1  6

Example

> df1$x2<-df2$x2[match(df1$x1,df2$x1)]
> df1

Output

   x1 x2
1   2  5
2   2  5
3   1  3
4   0  5
5   2  5
6   2  5
7   2  5
8   2  5
9   2  5
10  1  3
11  1  3
12  2  5
13  1  3
14  0  5
15  2  5
16  2  5
17  2  5
18  2  5
19  2  5
20  2  5

Example2

Live Demo

> y1<-sample(c("A","B","C"),20,replace=TRUE)
> df3<-data.frame(y1)
> df3

Output

   y1
1   A
2   C
3   C
4   A
5   C
6   B
7   C
8   B
9   B
10  C
11  B
12  C
13  B
14  A
15  A
16  C
17  B
18  B
19  A
20  A

Example

> y1<-sample(c("A","B","C","D","E"),20,replace=TRUE)
> y2<-sample(LETTERS[1:4],20,replace=TRUE)
> df4<-data.frame(y1,y2)
> df4

Output

   y1 y2
1   E  C
2   A  D
3   C  B
4   C  D
5   D  B
6   B  D
7   D  C
8   C  B
9   D  D
10  C  A
11  B  D
12  B  C
13  C  B
14  B  D
15  D  C
16  B  B
17  E  C
18  D  B
19  A  D
20  B  C

Example

> df3$y2<-df4$y2[match(df3$y1,df4$y1)]
> df3

Output

   y1 y2
1   A  D
2   C  B
3   C  B
4   A  D
5   C  B
6   B  D
7   C  B
8   B  D
9   B  D
10  C  B
11  B  D
12  C  B
13  B  D
14  A  D
15  A  D
16  C  B
17  B  D
18  B  D
19  A  D
20  A  D
raja
Published on 05-Mar-2021 11:45:42
Advertisements