1

I used to do it, using group_by_

library(dplyr)
group_by <- c('cyl', 'vs')
mtcars %>% group_by_(.dots = group_by) %>% summarise(gear = mean(gear))

but now group_by_ is deprecated. I don't know how to do it using the tidy evaluation framework.

pogibas
  • 27,303
  • 19
  • 84
  • 117
danilinares
  • 1,172
  • 1
  • 9
  • 28

2 Answers2

10

New answer

With dplyr 1.0, you can now use selection helpers like all_of() inside across():

df |> 
  group_by(
    across(all_of(my_vars))
  )

Old answer

Transform the character vector into a list of symbols and splice it in

df %>% group_by(!!!syms(group_by))
Lionel Henry
  • 6,652
  • 27
  • 33
3

There is group_by_at variant of group_by:

library(dplyr)
group_by <- c('cyl', 'vs')
mtcars %>% group_by_at(group_by) %>% summarise(gear = mean(gear))

Above it's simplified version of generalized:

mtcars %>% group_by_at(vars(one_of(group_by))) %>% summarise(gear = mean(gear))

inside vars you could use any dplyr way of select variables:

mtcars %>%
    group_by_at(vars(
        one_of(group_by) # columns from predefined set
        ,starts_with("a") # add ones started with a
        ,-hp # but omit that one
        ,vs # this should be always include
        ,contains("_gr_") # and ones with string _gr_
    )) %>%
    summarise(gear = mean(gear))
Marek
  • 49,472
  • 15
  • 99
  • 121