Merge Two Data Frames by common Columns in R Programming – merge() Function

merge() function in R Language is used to merge two data frames by common columns.

Syntax: merge(arg1, arg2, by.x, by.y)

Parameters:
arg1 and arg2: Data frames to be merged
by.x: Common argument of first data frame
by.y: Common argument of second data frame

Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

# R program to merge two data frames
  
# Creating data frames
df1 <- data.frame(row1 = c("a", "b", "c"), row2 = c("d", "e", "f"))
df2 <- data.frame(col1 = c("a", "b", "c"), col2 = c("Hello", "Geeks", "gfg"))
  
# Calling merge() function
df <- merge(df1, df2, by.x ="row1", by.y ="col1")
print(df)

chevron_right


Output:

  row1 row2  col2
1    a    d Hello
2    b    e Geeks
3    c    f   gfg

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

# R program to merge two data frames
  
# Creating data frames
df1 <- data.frame(row1 = c("d", "e", "f"), row2 = c(1, 2, 3))
df2 <- data.frame(col1 = c(1, 2, 3), col2 = c("Hello", "Geeks", "gfg"))
  
# Calling merge() function
df <- merge(df1, df2, by.x ="row2", by.y ="col1")
print(df)

chevron_right


Output:

  row2 row1  col2
1    1    d Hello
2    2    e Geeks
3    3    f   gfg



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

1


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.