How to Merge two DataFrames in R

Here are the different ways to merge two DataFrames in R:

(1) Inner Join:

inner_merged <- merge(df1, df2, by = "Id")

(2) Left Join:

left_merged <- merge(df1, df2, by = "Id", all.x = TRUE)

(3) Right Join:

right_merged <- merge(df1, df2, by = "Id", all.y = TRUE)

(4) Full Outer Join:

outer_merged <- merge(df1, df2, by = "Id", all = TRUE)

Examples of Merging two DataFrames in R

Example 1: Inner Join

To apply an inner join in R:

df1 <- data.frame(Id = c(333, 444, 555, 777, 999),
                 Product = c("laptop", "printer", "tablet", "desk", "chair")
                 )

df2 <- data.frame(Id = c(333, 444, 666, 777, 888),
                 Price = c(1200, 150, 300, 450, 200)
                 )

inner_merged <- merge(df1, df2, by = "Id")

print(inner_merged)

The result is an inner join:

   Id Product Price
1 333  laptop  1200
2 444 printer   150
3 777    desk   450

Example 2: Left Join

To apply a left join:

df1 <- data.frame(Id = c(333, 444, 555, 777, 999),
                 Product = c("laptop", "printer", "tablet", "desk", "chair")
                 )

df2 <- data.frame(Id = c(333, 444, 666, 777, 888),
                 Price = c(1200, 150, 300, 450, 200)
                 )

left_merged <- merge(df1, df2, by = "Id", all.x = TRUE)

print(left_merged)

The result is a left join:

   Id Product Price
1 333  laptop  1200
2 444 printer   150
3 555  tablet    NA
4 777    desk   450
5 999   chair    NA

Example 3: Right Join

To apply a right join:

df1 <- data.frame(Id = c(333, 444, 555, 777, 999),
                 Product = c("laptop", "printer", "tablet", "desk", "chair")
                 )

df2 <- data.frame(Id = c(333, 444, 666, 777, 888),
                 Price = c(1200, 150, 300, 450, 200)
                 )

right_merged <- merge(df1, df2, by = "Id", all.y = TRUE)

print(right_merged)

The result is a right join:

   Id Product Price
1 333  laptop  1200
2 444 printer   150
3 666    <NA>   300
4 777    desk   450
5 888    <NA>   200

Example 4: Full Outer Join

To apply a full outer join:

df1 <- data.frame(Id = c(333, 444, 555, 777, 999),
                 Product = c("laptop", "printer", "tablet", "desk", "chair")
                 )

df2 <- data.frame(Id = c(333, 444, 666, 777, 888),
                 Price = c(1200, 150, 300, 450, 200)
                 )

outer_merged <- merge(df1, df2, by = "Id", all = TRUE)

print(outer_merged)

The result is a full outer join:

   Id Product Price
1 333  laptop  1200
2 444 printer   150
3 555  tablet    NA
4 666    <NA>   300
5 777    desk   450
6 888    <NA>   200
7 999   chair    NA

Leave a Comment