Search code examples
rtibblelookup-tables

Lookup tables in R


I have a tibble with a ton of data in it, but most importantly, I have a column that references a row in a lookup table by number (ex. 1,2,3 etc).

df <- tibble(ref = c(1,1,1,2,5)
             data = c(33,34,35,35,32))

lkup <- tibble(CurveID <- c(1,2,3,4,5)
               Slope <- c(-3.8,-3.5,-3.1,-3.3,-3.3)
               Intercept <- c(40,38,40,38,36)
               Min <- c(25,25,21,21,18)
               Max <- c(36,36,38,37,32))

I need to do a calculation for each row in the original tibble based on the information in the referenced row in the lookup table.

df$result <- df$data - lkup$intercept[lkup$CurveID == df$ref]/lkup$slope[lkup$CurveID == df$ref]

The idea is to access the slope or intercept (etc) value from the correct row of the lookup table based on the number in the data table, and to do this for each data point in the column. But I keep getting an error telling me my data isn't compatible, and that my objects need to be of the same length.


Solution

  • You could also do it with match()

    df$result <- df$data - lkup$Intercept[match(df$ref, lkup$CurveID)]/lkup$Slope[match(df$ref, lkup$CurveID)]
    df$result
    # [1] 43.52632 44.52632 45.52632 45.85714 42.90909