Skip to content
Prev 327435 / 398502 Next

transform dataframe with look-up table

It would be helpful if you included the expected output for your example, but I think the following does what you want by using merge() for each lookup:

f0 <- function(inputDF, lookupDF)
{
    tmp1 <- merge(inputDF, lookupDF, by.x="Left", by.y="input",all.x=TRUE)
    tmp2 <- merge(tmp1, lookupDF, by.x="Right", by.y="input", all.x=TRUE)
    with(tmp2, data.frame(ID=ID, Right=output.x, Left=output.y)[order(ID), ])
}
# Your example data with an ID column added to track where the output rows came from
myInputDF <- data.frame(
    ID = 1:10,
    Left = c(9, 4, 2, 6, 3, 4, 3, 4, 10, 9),
    Right = c(8, 3, 1, 5, 1, 1, 2, 2, 8, 10))
myLookupDF <- data.frame(
    input = c(5, 10, 4, 8, 6, 5, 7, 2, 9, 10, 2),
    output = c(1, 1, 2, 3, 5, 6, 6, 7, 7, 7, 8))

f0(myInputDF, myLookupDF)
#    ID Right Left
# 12  1     7    3
# 9   2     2   NA
# 1   3     7   NA
# 2   3     8   NA
# 10  4     5    6
# 11  4     5    1
# 3   5    NA   NA
# 4   6     2   NA
# 5   7    NA    7
# 6   7    NA    8
# 7   8     2    7
# 8   8     2    8
# 13  9     1    3
# 14  9     7    3
# 15 10     7    1
# 16 10     7    7

Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com