Named vector "by" arguments for `dplyr::_join` functions

1k views Asked by At

I am writing a function to dplyr::_join two dataframes by different columns, with the column name of the first dataframe dynamically specified as a function argument. I believe I need to use rlang quasiquotation/metaprogramming but haven't been able to get a working solution. I appreciate any suggestions!

library(dplyr)
library(rlang)
library(palmerpenguins)

# Create a smaller dataset
penguins <-
  penguins %>% 
  group_by(species) %>% 
  slice_head(n = 4) %>% 
  ungroup()

# Create a colors dataset
penguin_colors <-
  tibble(
    type = c("Adelie", "Chinstrap", "Gentoo"),
    color = c("orange", "purple", "green")
  )


# Without function --------------------------------------------------------

# Join works with character vectors
left_join(
  penguins, penguin_colors, by = c("species" = "type")
)
#> # A tibble: 12 x 9
#>    species island bill_length_mm bill_depth_mm flipper_length_… body_mass_g
#>    <chr>   <fct>           <dbl>         <dbl>            <int>       <int>
#>  1 Adelie  Torge…           39.1          18.7              181        3750
#>  2 Adelie  Torge…           39.5          17.4              186        3800
#>  3 Adelie  Torge…           40.3          18                195        3250
#>  4 Adelie  Torge…           NA            NA                 NA          NA
#>  5 Chinst… Dream            46.5          17.9              192        3500
#>  6 Chinst… Dream            50            19.5              196        3900
#>  7 Chinst… Dream            51.3          19.2              193        3650
#>  8 Chinst… Dream            45.4          18.7              188        3525
#>  9 Gentoo  Biscoe           46.1          13.2              211        4500
#> 10 Gentoo  Biscoe           50            16.3              230        5700
#> 11 Gentoo  Biscoe           48.7          14.1              210        4450
#> 12 Gentoo  Biscoe           50            15.2              218        5700
#> # … with 3 more variables: sex <fct>, year <int>, color <chr>

# Join works with data-variable and character vector
left_join(
  penguins, penguin_colors, by = c(species = "type")
)
#> # A tibble: 12 x 9
#>    species island bill_length_mm bill_depth_mm flipper_length_… body_mass_g
#>    <chr>   <fct>           <dbl>         <dbl>            <int>       <int>
#>  1 Adelie  Torge…           39.1          18.7              181        3750
#>  2 Adelie  Torge…           39.5          17.4              186        3800
#>  3 Adelie  Torge…           40.3          18                195        3250
#>  4 Adelie  Torge…           NA            NA                 NA          NA
#>  5 Chinst… Dream            46.5          17.9              192        3500
#>  6 Chinst… Dream            50            19.5              196        3900
#>  7 Chinst… Dream            51.3          19.2              193        3650
#>  8 Chinst… Dream            45.4          18.7              188        3525
#>  9 Gentoo  Biscoe           46.1          13.2              211        4500
#> 10 Gentoo  Biscoe           50            16.3              230        5700
#> 11 Gentoo  Biscoe           48.7          14.1              210        4450
#> 12 Gentoo  Biscoe           50            15.2              218        5700
#> # … with 3 more variables: sex <fct>, year <int>, color <chr>

# Join does NOT work with character vector and data-variable
left_join(
  penguins, penguin_colors, by = c(species = type)
)
#> Error in standardise_join_by(by, x_names = x_names, y_names = y_names): object 'type' not found



# With function -----------------------------------------------------------

# Version 1: Without tunneling
add_colors <- function(data, var) {
  left_join(
    data, penguin_colors, by = c(var = "type")
  )
}

add_colors(penguins, species)
#> Error: Join columns must be present in data.
#> x Problem with `var`.
add_colors(penguins, "species")
#> Error: Join columns must be present in data.
#> x Problem with `var`.

# Version 2: With tunneling
add_colors <- function(data, var) {
  left_join(
    data, penguin_colors, by = c("{{var}}" = "type")
  )
}

add_colors(penguins, species)
#> Error: Join columns must be present in data.
#> x Problem with `{{var}}`.
add_colors(penguins, "species")
#> Error: Join columns must be present in data.
#> x Problem with `{{var}}`.

# Version 2: With tunneling and glue syntax
add_colors <- function(data, var) {
  left_join(
    data, penguin_colors, by = c("{{var}}" := "type")
  )
}

add_colors(penguins, species)
#> Error: `:=` can only be used within a quasiquoted argument
add_colors(penguins, "species")
#> Error: `:=` can only be used within a quasiquoted argument

Created on 2020-10-05 by the reprex package (v0.3.0)

Here are related resources I consulted:

Thank you for your advice.

2

There are 2 answers

1
Ronak Shah On
library(dplyr)
left_join(
  penguins, penguin_colors, by = c(species = "type")
)

The reason why above works is because in by we are creating a named vector like this :

c(species = "type")
#species 
# "type"

You can also do that via setNames :

setNames('type', 'species')

but notice that passing species without quotes fail.

setNames('type', species)

Error in setNames("type", species) : object 'species' not found

So create a named vector with setNames and pass character value in the function.

add_colors <- function(data, var) {
  left_join(
    data, penguin_colors, by = setNames('type', var)
  )
}

add_colors(penguins, 'species')
2
jomcgi On

To add to Ronak's solution you can also achieve this without quotes using ensym

Example:

add_colors <- function(data, var) {

    left_join(
        data, penguin_colors, by = set_names("type", nm = ensym(var))
    )
}