0

I want to merge two data frames based on two conditions (Name and Date). If no match found I want it to return as NA.

df1:

Date      Name  Value1   Value2 
2009-03   A     30       456
2009-04   A     33       346
2009-05   A     50       856
2009-03   B     80       44
2009-04   B     34       665
2009-03   C     35       756
2009-04   D     64       66

df2:

Name  Date      ValueX
A     2009-03   34
A     2009-04   466
A     2009-05   55
B     2009-03   65
B     2009-04   568
C     2009-03   56
C     2009-04   676

I want the merge to look something like this:

Date      Name  Value1   Value2 **ValueX**
2009-03   A     30       456    34
2009-04   A     33       346    466
2009-05   A     50       856    55
2009-03   B     80       44     65
2009-04   B     34       665    568
2009-03   C     35       756    56
2009-04   D     64       66     NA

I have tried the following:

df3 <- left_join(df1, df2, by = c("Date" = "Date", "Name" = "Name"), df1$ValueX)
df3 <- df1
df3$ValueX <- ifelse(
  is.na(match(paste(df1$Date, df1$Name), paste(df2$Date, df2$Name))), 
  df2$ValueX
)
df3 = merge(df1, df2, by.x=c("Date", "Name"), by.y=c("Date", "Name"), all.x=TRUE)

Any suggestions on how to solve this?

TylerH
  • 20,799
  • 66
  • 75
  • 101
  • `merge(df1, df2, all.x = TRUE)` does give your expected output , right? which is same as what you have tried. What is the issue? – Ronak Shah Mar 27 '19 at 13:04

2 Answers2

0

Try this:

library(tidyverse)
df3 <- df1 %>% left_join(df2, by= c("Date","Name"))
TobKel
  • 1,293
  • 8
  • 20
  • Or use `df3 <- df1 %>% full_join(df2, by= c("Date","Name"))` if you want to return NA if there is no match. – TobKel Mar 27 '19 at 13:02
0

You can try this in data.table

library(data.table)
setDT(df1, key = c("Date","Name"))
setDT(df2, key = c("Name", "Date"))
merge(df1, df2, all.x = TRUE)
#returns
      Date Name Value1 Value2 ValueX
1: 2009-03    A     30    456     34
2: 2009-03    B     80     44     65
3: 2009-03    C     35    756     56
4: 2009-04    A     33    346    466
5: 2009-04    B     34    665    568
6: 2009-04    D     64     66     NA
7: 2009-05    A     50    856     55
Chriss Paul
  • 1,101
  • 6
  • 19