0

I'm trying to merge two data frames based on 2 columns in each. I want to merge the Territory column and IDMate column from Data Frame 2 to Data Frame 1 based on matching ID and Year columns.

Data Frame 1:

        ID Year
     1  1 1998
     2  2 2001
     3  3 2005
     4  4 2008

Data Frame 2:

       ID Year Territory  IDMate
    1  1 1998         A    22
    2  1 1999         B    24
    3  1 2000         C    25
    4  2 2001         D    26
    5  2 2002         E    27
    6  3 2005         F    28
    7  4 2008         G    29

Goal is to get this:

       ID Year Territory  IDMate
    1  1 1998         A    22
    2  2 2001         D    26
    3  3 2005         F    28
    4  4 2008         G    29
Jennifer Diamond
  • 113
  • 2
  • 11

2 Answers2

-1

common <- intersect(data.frame1$col, data.frame2$col) data.frame2[common,]

Hopefully, this will get you what you want

  • Thanks! I haven't tried this code yet because I used the one George Wood recommended and it seemed to have worked. Thanks for helping! I really appreciate it! – Jennifer Diamond Jul 03 '17 at 22:37
-1

You can use left_join from dplyr:

library(dplyr)
res <- left_join(df1, df2, by = c("ID", "Year"))

#  ID Year Territory IDMate
#   1 1998         A     22
#   2 2001         D     26
#   3 2005         F     28
#   4 2008         G     29
George Wood
  • 1,914
  • 17
  • 18