Left join with multiple conditions in R

You can join on more than one variable. The example df you give would actually make a suitable lookup table for this:

value_lookup <- data.frame(
  type = c('q1', 'q1', 'q2', 'q2', 'q3', 'q3'),
  id = c(1, 2, 1, 3, 1, 2),
  value = c('yes', 'no', 'one hour', 'more than two hours', 'blue', 'yellow')
)

Then you just merge on both type and id:

df <- left_join(df, value_lookup, by = c('type', 'id'))  

Usually when I need a lookup table like that I store it in a CSV rather than write it all out in the code, but do whatever suits you.

Tags:

R

Dplyr