Merging data frames

Problem

You want to merge two data frames on a given column from each (like a join in SQL).

Solution

  1. # Make a data frame mapping story numbers to titles
  2. stories <- read.table(header=TRUE, text='
  3. storyid title
  4. 1 lions
  5. 2 tigers
  6. 3 bears
  7. ')
  8. # Make another data frame with the data and story numbers (no titles)
  9. data <- read.table(header=TRUE, text='
  10. subject storyid rating
  11. 1 1 6.7
  12. 1 2 4.5
  13. 1 3 3.7
  14. 2 2 3.3
  15. 2 3 4.1
  16. 2 1 5.2
  17. ')
  18. # Merge the two data frames
  19. merge(stories, data, "storyid")
  20. #> storyid title subject rating
  21. #> 1 1 lions 1 6.7
  22. #> 2 1 lions 2 5.2
  23. #> 3 2 tigers 1 4.5
  24. #> 4 2 tigers 2 3.3
  25. #> 5 3 bears 1 3.7
  26. #> 6 3 bears 2 4.1

If the two data frames have different names for the columns you want to match on, the names can be specified:

  1. # In this case, the column is named 'id' instead of storyid
  2. stories2 <- read.table(header=TRUE, text='
  3. id title
  4. 1 lions
  5. 2 tigers
  6. 3 bears
  7. ')
  8. # Merge on stories2$id and data$storyid.
  9. merge(x=stories2, y=data, by.x="id", by.y="storyid")
  10. #> id title subject rating
  11. #> 1 1 lions 1 6.7
  12. #> 2 1 lions 2 5.2
  13. #> 3 2 tigers 1 4.5
  14. #> 4 2 tigers 2 3.3
  15. #> 5 3 bears 1 3.7
  16. #> 6 3 bears 2 4.1
  17. # Note that the column name is inherited from the first data frame (x=stories2).

It is possible to merge on multiple columns:

  1. # Make up more data
  2. animals <- read.table(header=T, text='
  3. size type name
  4. small cat lynx
  5. big cat tiger
  6. small dog chihuahua
  7. big dog "great dane"
  8. ')
  9. observations <- read.table(header=T, text='
  10. number size type
  11. 1 big cat
  12. 2 small dog
  13. 3 small dog
  14. 4 big dog
  15. ')
  16. merge(observations, animals, c("size","type"))
  17. #> size type number name
  18. #> 1 big cat 1 tiger
  19. #> 2 big dog 4 great dane
  20. #> 3 small dog 2 chihuahua
  21. #> 4 small dog 3 chihuahua

Notes

After merging, it may be useful to change the order of the columns. See ../Reordering the columns in a data frame.