rmergecorrespondence

Merging dataframes using a correspondence table using R


I would like to write a function which merges two dataframes (mydf1 and mydf2) according to a correspondence table (mykeys). Consider the following example:

mydf1=data.frame(id1=1:5,myvar1=letters[1:5])
mydf2=data.frame(id2=LETTERS[1:5],myvar2=letters[6:10])

mykeys=data.frame(id1=1:3,id2=LETTERS[1:3])

The result should be

# id1 id2 myvar1 myvar2
# 1   A   a      f
# 2   B   b      g
# 3   C   c      h

Any idea?


Solution

  • We could use merge after placing the datasets in a list. Modified based on comments from @CathG and the edit in OP's dataset.

    Reduce(merge, list(mykeys, mydf1, mydf2))