Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Merge DataFrames by Row Names in R

  • Last Updated : 14 Sep, 2021

In this article, we are going to see how to merge Dataframe by Row Name using merge in R Programming Language. 

The merge() function in base R can be used to merge input dataframes by common columns or row names. The merge() function retains all the row names of the dataframes, behaving similarly to the inner join. The dataframes are combined in order of the appearance in the input function call. 

Syntax: merge(x, y, by, all)

Arguments : 

  • x, y – The input dataframes
  • by – specifications of the columns used for merging. In case of merging using row names, the by attribute uses ‘row.names’ value.
  • all – logical true or false.

Example 1: Merge Dataframe

The output displayed is in the order of row numbers of x dataframe followed by y dataframe row numbers.



R




# creating a dataframe
data_frame1 <- data.frame(col1 = c(6:8),
                         col2 = letters[1:3],
                         col3 = c(1,4,NA))
  
print ("Original DataFrame1")
print (data_frame1)
data_frame2 <- data.frame(col1 = c(5:7),
                          col2 = letters[7:9])
  
print ("Original DataFrame2")
print (data_frame2)
data_frame_merge <- merge(data_frame1, data_frame2,
                          by = 'row.names', all = TRUE)
  
print ("Merged DataFrame")
print (data_frame_merge)

Output:

Example 2: Merge unequal Dataframe

In case of the unequal number of row numbers in the dataframes, the dataframe with the lesser number of rows is supplied with NA values, which appear in the merged dataframe. 

R




#creating a dataframe
data_frame1 <- data.frame(col1 = c(6:8),
                         col2 = letters[1:3],
                         col3 = c(1,4,NA))
  
print ("Original DataFrame1")
print (data_frame1)
data_frame2 <- data.frame(col4 = c(5:6),
                          col5 = letters[7:8])
  
print ("Original DataFrame2")
print (data_frame2)
data_frame_merge <- merge(data_frame1, data_frame2,
                          by = 'row.names', all = TRUE)
  
print ("Merged DataFrame")
print (data_frame_merge)

Output:




My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!