How to handle the ... parameter when programming with dplyr

If you are programming in dplyr, you can use the selection mechanism and promises as fellows:

mypull <- function(data, var) {
  data |> pull({{ var }})
}

then you can call for example iris |> mypull(sepal.width and it will work. You can do a similar thing with ...:

my_summarise <- function(.data, ...) {
  .data |>
    group_by(...) |>
    summarise(
      mass = mean(mass, na.rm = TRUE),
      height = mean(height, na.rm = TRUE)
    )
}
starwars |> my_summarise(homeworld, species)

(Example based on https://dplyr.tidyverse.org/articles/programming.html/lab-gas-flow ) .

Now my problem is this: I need to loop over the variables / promises in .... Or, more generally, I need to access arbitrary elements of .... For example, I may want to act only upon the first argument.

I tried the following and many other variations of the same, but can't seem to find the right way of doing that. {{ }} needs a symbol, so I understand why it works on var and ... in the examples above, but how do I make it work in this particular setting?

# obviously wrong
mygroup <- function(data, ...) {
  vars <- rlang::list2(...)[[1]]
  data |> group_by({{vars}})
}

To be clear, I need to loop over the variables. E.g. if the function is called with myfunc(data, var1, var2, var3) I need first to handle column corresponding to var1, then the column corresponding to var2 etc. So to make the example clearer, here is an implementation that works:

myfunc <- function(data, cols) {
  n <- length(cols)
  for(i in 1:n) {
    data <- data |>
      group_by(across(all_of(cols[i]))) |>
      mutate(!!paste0(cols[i], "_mean") := mean(.data[[cols[i]]]))
  }
  data
}

this can be called e.g. with

iris |> myfunc(c("Sepal.Width", "Sepal.Length"))

But I would like to be able to call it like this:

iris |> myfunc(Sepal.Width, Sepal.Length)

Can this be done at all?

{{ }} only works on a single named argument, so for ... you want rlang::enquos(...). That gives you a list of quosures you can index or loop over. For example, vars <- rlang::enquos(...) and then first <- vars[[1]]. To use one inside a verb, unquote it with !!, as in data |> group_by(!!first), and to splice the whole list at once use !!!vars. If you only need the names as strings, purrr::map_chr(vars, rlang::as_label) works too. The "Programming with dplyr" vignette has a short section on passing ... that covers this pattern.