0

Let's say I have two data.frames df1 and df2:

> df1
    Var1   Var2
1    "A"    "D"
2    "B"    "E"
3    "C"    "F"

> df2
    Var3   Var4
1    "C"    "H"
2    "B"    "I"
3    "G"    "J"
4    "A"    "K"

I want to combine/merge df1 with df2 in a way that the values of Var1 and Var3 are matched where possible and NA otherwise. The important thing is that I want to preserve the mapping between the values of Var1and Var2. In this simple example I would end up with:

> df2
    Var3   Var4   Var1   Var2
1    "C"    "H"    "C"    "F"
2    "B"    "I"    "B"    "E"
3    "G"    "J"     NA     NA
4    "A"    "K"    "A"    "D"

Any ideas on a general way to achieve this? The number of variables in each data.frame is not necessarily equal in reality as in this example. Cheers! :)

CHRD
  • 1,917
  • 1
  • 15
  • 38

1 Answers1

0

Using match:

Indices <- match(df2$Var3, df1$Var1)

df2$Var1<-df1$Var1[Indices]
df2$Var2<-df1$Var2[Indices]
user3640617
  • 1,546
  • 13
  • 21