I would like to merge two data frames matching on either/or of two pairs of columns. The idea is to give me a merge if a either Date1 or Date2 in the first dataframe match Date3 in the second data frame. First I duplicated the Date3 into Date3A and Date3B, because matching 2 to 1 gave an error. And while it runs here in the sample data, it only appended NA to each row in my real data.
IDx<-c("A","B","C","D")
Date1<-c("04-04-2004","05-05-2005","06-06-2006", "07-07-2007")
Date2<-c("04-04-2005","05-05-2005","06-06-2007","05-05-2005")
dfx<-data.frame(IDx,Date1,Date2)
# dfx looks like
# IDx Date1 Date2
#1 A 04-04-2004 04-04-2005
#2 B 05-05-2005 05-05-2005
#3 C 06-06-2006 06-06-2007
#4 D 07-07-2007 05-05-2005
IDy<-c("E","F","G","H")
Date3A<-c("04-04-2008","05-05-2005","06-06-2006","07-07-2007")
Date3B<-c("04-04-2008","05-05-2005","06-06-2006","07-07-2007")
dfy<-data.frame(IDy, Date3A,Date3B)
#note that Date3A and Date3B are exact matches.
# dfy
# IDy Date3A Date3B
#1 E 04-04-2008 04-04-2008
#2 F 05-05-2005 05-05-2005
#3 G 06-06-2006 06-06-2006
#4 H 07-07-2007 07-07-2007
Here is what I tried
NewDF<-merge(x=dfx, y=dfy, by.x =c("Date1", "Date2"), by.y=c("Date3A","Date3B"), all.x=TRUE)
#NewDF looks like
# Date1 IDx Date2 IDy Date3B
#1 04-04-2004 A 04-04-2005 <NA> <NA>
#2 05-05-2005 B 05-05-2005 F 05-05-2005
#3 06-06-2006 C 06-06-2007 G 06-06-2006
#4 07-07-2007 D 05-05-2005 H 07-07-2007
I should be getting a fifth row to match D with either H or F.
Here it runs, but when I tried it with my real data, it only appended NA to each row.
So, for now, I am running them twice, like so
NewDF<-merge(x=dfx, y=dfy, by.x =c("Date1"), by.y=c("Date3A"), all.x=TRUE)
NewDF2<-merge(x=NewDF, y=dfy, by.x =c("Date2"), by.y=c("Date3A"), all.x=TRUE)
Now I get the right answer but the matches appear twice in each row (wide) and I want the matches to be one to each row (long).
#> NewDF2
# Date2 Date1 IDx IDy.x Date3B.x IDy.y Date3B.y
#1 04-04-2005 04-04-2004 A <NA> <NA> <NA> <NA>
#2 05-05-2005 05-05-2005 B F 05-05-2005 F 05-05-2005
#3 05-05-2005 07-07-2007 D H 07-07-2007 F 05-05-2005
#4 06-06-2007 06-06-2006 C G 06-06-2006 <NA> <NA>
Can anyone help figure out what is going wrong? There are no NA's in the Date3 column(s).