tidyverse join two data sets with dynamic column names for by column

Viewed 881

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...

1 Answers
left_join(x, y, by = setNames(y_name, x_name))
#   a1  new
# 1  1    a
# 2  2    b
# 3  3 <NA>

What your by= vector was doing

setNames(c('x', 'y'), c(x_name, y_name))
#  a1  a2 
# "x" "y" 

Whereas you needed

c(a1 = "a2")
#   a1 
# "a2" 
setNames(y_name, x_name)
#   a1 
# "a2" 
Related