Hi,
The following reprex simplifies the issue I am having while working on a fairly complex function. The function has an argument which accepts a dynamic list (in the general sense, not the R sense) of one or more unquoted variables. Following a necessary step of validation and transformation, this "list" of variables becomes a character vector. This vector must be used for various summarization of data. If the vector contains a single variable, using !!sym()
works... but not when there are more.
How would you suggest to properly handle this situation?
Thanks
require(tidyverse)
set.seed(12345)
df <- data.frame(
a = rnorm(100),
x = sprintf('x%s', sample(1:3, 100, replace = TRUE)),
y = sprintf('y%s', sample(1:3, 100, replace = TRUE)),
z = sprintf('z%s', sample(1:3, 100, replace = TRUE))
)
f <- function(data, by){
# Assume that by must be validated/filtered and is ultimately transformed into
# a character
by <- data %>% dplyr::select( {{ by }} ) %>% names()
data %>%
dplyr::group_by( !!sym(by) ) %>%
dplyr::summarize(
mean = mean(a)
)
}
df %>% f(by = z)
df %>% f(by = c(y, z))