Programming with dplyr: what is the most updated syntax for passing multiple colnames to `select()` within a custom function?

I've learned from this answer that one way to pass multiple colnames to dplyr::select() within a custom function is by using dot-dot-dot and rlang::enquos(...) and finally !!! in select().

library(dplyr, warn.conflicts = FALSE)

my_select_func <- function(data, ...) {
  columns <- rlang::enquos(...)
  data %>%
    select(disp, !!!columns)  # I want `disp` to always be included. Otherwise, I would've simply done `select(...)`
}

my_new_dat <- my_select_func(mtcars, am, mpg)

But I wonder if there's a more updated or "best practice" way to do this. Maybe using curly-curly syntax? i.e., {{

Thanks!

I don't believe you need the bang-bang-bang syntax at all. This runs on my machine:

library(dplyr, warn.conflicts = FALSE)

my_select_func <- function(data, ...) {
  data %>%
    select(disp, ...) %>%
    tibble()
}

my_select_func(mtcars, am, mpg)
#> # A tibble: 32 x 3
#>     disp    am   mpg
#>    <dbl> <dbl> <dbl>
#>  1  160      1  21  
#>  2  160      1  21  
#>  3  108      1  22.8
#>  4  258      0  21.4
#>  5  360      0  18.7
#>  6  225      0  18.1
#>  7  360      0  14.3
#>  8  147.     0  24.4
#>  9  141.     0  22.8
#> 10  168.     0  19.2
#> # ... with 22 more rows

Created on 2022-01-26 by the reprex package (v2.0.1)

1 Like

Thanks! Well this is embarrassing :slight_smile:

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.