How to merge data in R?

1. Using the cbind() function—only if the data frames have the same number of rows, and the records are the same and in the same order:

df <- cbind(df1, df2)Powered By 

2. Using the rbind() function to combine the data frames vertically—only if they have an equal number of identically named columns of the same data type and appearing in the same order:

df <- rbind(df1, df2)Powered By 

3. Using the merge() function to merge data frames by a column in common, usually an ID column:

  • Inner join:
df <- merge(df1, df2, by="ID")Powered By 
  • Left join:
df <- merge(df1, df2, by="ID", all.x=TRUE)Powered By 
  • Right join:
df <- merge(df1, df2, by="ID", all.y=TRUE)Powered By 
  • Outer join:
df <- merge(df1, df2, by="ID", all=TRUE)Powered By 

4. Using the join() function of the dplyr package to merge data frames by a column in common, usually an ID column:

df <- join(df1, df2, by="ID", type="type_of_join")Powered By 

The type parameter takes in one of the following values: innerleftright, or full.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *