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?