join datasets using a quosure as the by argument

Another way of passing a column into a function where the join happens with "LHS" = "RHS" could look like this:

data("mtcars")

library(tidyverse)

function_left_join <- function(x) {

  mtcars %>% 
    left_join(mtcars, by = names(select(., {{x}})))

}

head(function_left_join(mpg))
#>    mpg cyl.x disp.x hp.x drat.x  wt.x qsec.x vs.x am.x gear.x carb.x cyl.y
#> 1 21.0     6    160  110   3.90 2.620  16.46    0    1      4      4     6
#> 2 21.0     6    160  110   3.90 2.620  16.46    0    1      4      4     6
#> 3 21.0     6    160  110   3.90 2.875  17.02    0    1      4      4     6
#> 4 21.0     6    160  110   3.90 2.875  17.02    0    1      4      4     6
#> 5 22.8     4    108   93   3.85 2.320  18.61    1    1      4      1     4
#> 6 22.8     4    108   93   3.85 2.320  18.61    1    1      4      1     4
#>   disp.y hp.y drat.y  wt.y qsec.y vs.y am.y gear.y carb.y
#> 1  160.0  110   3.90 2.620  16.46    0    1      4      4
#> 2  160.0  110   3.90 2.875  17.02    0    1      4      4
#> 3  160.0  110   3.90 2.620  16.46    0    1      4      4
#> 4  160.0  110   3.90 2.875  17.02    0    1      4      4
#> 5  108.0   93   3.85 2.320  18.61    1    1      4      1
#> 6  140.8   95   3.92 3.150  22.90    1    0      4      2

The c() function doesn't support the rlang bangs so you'll have to take a more traditional approach to building your parameter. You can do

join_by_quosure <- function(data, left_index, var_to_impute, right_index){
  require(dplyr)

  left_index <- enquo(left_index)
  right_index <- enquo(right_index)
  var_to_impute <- enquo(var_to_impute)

  by = set_names(quo_name(right_index), quo_name(left_index))

  left_join(data, 
            data %>% select(!!right_index, !!var_to_impute),
            by = by)
}

Tags:

R

Dplyr