I would like to merge 2 df's where in df1 contains 2 columns and df2 1 column, how to apply function merge in this case?
Here is sample case:
df1 <- data.frame(var1=letters[1:5],var2=letters[6:10])
df2 <- data.frame(var3=letters[1:10])
False attempt:
merge(df1,df2,by.x=c("var1","var2"),by.y="var3",all.y=TRUE)
How to merge these two df's so that the matching search uses both columns of df1 (var1 & var2) and operates on df2 (var3)?
Desired output:
var1 var2 var3
1 a f a
2 b g b
3 c h c
4 d i d
5 e j e
6 <NA> <NA> f
7 <NA> <NA> g
8 <NA> <NA> h
9 <NA> <NA> i
10 <NA> <NA> j
EDIT: Improved data (I hope):
df1 <- data.frame(var1=c(letters[1:5],rep("x",5)),var2=c(letters[6:10],rep("x",5)))
df2 <- data.frame(var3=letters[1:10])
Desired output:
var1 var2 var3
1 a f a
2 b g b
3 c h c
4 d i d
5 e j e
6 x x f
7 x x g
8 x x h
9 x x i
10 x x j
merge
twice may be one possible solution. – Metrics