I want to join two data frames where I need to pass the "by" columns as dynamic ones. I was trying to follow this solution here (How to pass column names for inner join by 2 column sets as variables with dplyr), but still get an error.
library(tidyverse)
x <- data.frame(a1 = c(1, 2, 3))
y <- data.frame(a2 = c(1, 2, 4),
new = c("a", "b", "c"))
x_name <- "a1"
y_name <- "a2"
x %>%
left_join(., y, by = setNames(c('x', 'y'), c(x_name, y_name)))
But I'll get the following error:
Error: Join columns must be present in data. x Problem with
a2.
Desired outcome:
a1 new
1 a
2 b
3 NA
Any ideas? I have tried multiple ways of passing the names dynamically with as.names, !!as.names, paste0...