dplyr join data frame in side a function using function arguments as by.x and by.y

481 Views Asked by At

I wanted to do left_join inside a function using function arguments to tell the code which should be 'by.x' and 'by.y'. In the example below, I wanted to use 'a2' and 'a3' arguments of function 'aa' - in place of "x1" and "a" in the 'by' parameter. AM confused how to use benefits of rlang package here

aa <- function(a1,a2,a3){
  a1 %>% left_join(a1, by=c("x1"="a"))
}
xx<-data.frame(a=c(1:2), x1=c(2:3))
aa(xx,"x1","a")
1

There are 1 best solutions below

0
Vlad C. On BEST ANSWER

If I understand your question correctly and your goal is to be able to pass to the function the names of the columns you're joining by, the below should work:

aa <- function(a1,a2,a3){
  a1 %>% left_join(a1, by=setNames(a3, a2))
}

xx<-data.frame(a=c(1:2), x1=c(2:3))
aa(xx,"x1","a")

Specifying the columns by using c(a2=a3) wouldn't work in this situation and I replaced it with setNames(a3, a2).