df1 <- data.frame(id=c(1,2,3,4,5,8), var=c("a","b","c","d","e","t"), stringsAsFactors = F)
df2 <- data.frame(id=c(1,2,3,4,5,6,7), var=c("e","f","c","d","e","g","h"), stringsAsFactors = F)
df <- data.frame(id=c(1,2,3,4,5,6,7,8))
I need to join to get the var value for df but I would like the var value for df2 rather than df1, and if there is not an equivalent in df2, then I would like to take it from df1. I have this but is there an easier way to do this? and how can I add a column to see where var came from?
df %>% left_join(df1, by="id") %>% left_join(df2, by="id") %>%
dplyr::mutate(var=ifelse(!is.na(var.x), var.x, var.y))