Merge Two Data Frames by common Columns in R Programming – merge() Function
Last Updated :
12 Jun, 2020
Improve
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:
# 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) |
Output:
row1 row2 col2 1 a d Hello 2 b e Geeks 3 c f gfg
Example 2:
# 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) |
Output:
row2 row1 col2 1 1 d Hello 2 2 e Geeks 3 3 f gfg