There are two ways you can solve this based on your ability to modify the inputs. If you are allowed to create a different input such as a list, I would opt for approach 1.
Approach 1:
Modify y_now
by instead creating a list showing the computations you will need and defuse the expressions by wrapping them with rlang::expr()
. Then modify the code in group_by
and summarise
to allow for external inputs. :=
notation in group_by for naming, and !!!
for evaluation of defused expressions. This is how it would look like:
x_groups <- c("x" = "am")
y_now <- list(y = rlang::expr(sum(vs)), q = rlang::expr(sum(mpg)), p = rlang::expr(sum(mpg/vs)))
mtcars %>%
group_by(!!sym(names(x_groups)) := !!as.name(x_groups)) %>%
summarise(!!!y_now)
#> # A tibble: 2 × 4
#> x y q p
#> <dbl> <dbl> <dbl> <dbl>
#> 1 0 7 326. Inf
#> 2 1 7 317. Inf
Approach 2:
In this case, you cannot create a different input but work with what you've been given. So you should transform it into the same object as the list y_now
of approach 1, in order to do that you should transform the vector into a list and then turn the expressions into a call. Then apply the same non-standard evaluation expressions as in Approach 1.
x_groups <- c("x" = "am")
y_now <- c("y" = "vs", "q" = "mpg", "p" = "mpg / vs")
y_now <- as.list(y_now) %>%
purrr::map(\(variable) str2lang(paste0("sum(", variable, ")")))
mtcars %>%
group_by(!!sym(names(x_groups)) := !!as.name(x_groups)) %>%
summarise(!!!y_now)
#> # A tibble: 2 × 4
#> x y q p
#> <dbl> <dbl> <dbl> <dbl>
#> 1 0 7 326. Inf
#> 2 1 7 317. Inf