0

I'm rewriting some Code in a Project where I need to group by (and summarise) a variablename from a character variable, similar to this:

test <- mtcars
x <- "gear"

This would work with group_by_ the deprecated standard evaluation version of group_by like this:

test %>% 
  group_by_(x) %>%
  summarise(mpg=mean(mpg)

Is it possible to archive this with group_by and quoting and unqouting x or can I use selection helpers like matches in group_by?

I cannot change the way x is stored, because other parts of the project still use split-lapply like split(test, test[, x]) ...

snaut
  • 2,261
  • 18
  • 37
  • 1
    use `get` ? `test %>% group_by(get(x)) %>% summarise(mpg=mean(mpg))` – Ronak Shah Aug 23 '18 at 07:48
  • 1
    Related to https://stackoverflow.com/questions/51944709/using-variable-column-names-in-dplyr-summarise – kath Aug 23 '18 at 07:54
  • 2
    If it is not necessary for you to use exactly the `group_by` function, you can try `group_by_at(vars(one_of(x)))`. – tmfmnk Aug 23 '18 at 07:58
  • @RonakShah Yes, the link in kath's comment is a dupe. – Rui Barradas Aug 23 '18 at 08:00
  • @tmfmnk thanks, that's exactly what I was looking for. – snaut Aug 23 '18 at 08:18
  • Please consider removing the duplicate flag, if I'm not mistaken the `group_by_at solution does not really apply in the possible original post but is exactly what I was looking for here. – snaut Aug 23 '18 at 08:27

1 Answers1

1

You need to convert it to a symbol first

test %>% 
  group_by(!!rlang::sym(x)) %>%
  summarise(mpg=mean(mpg))
Shinobi_Atobe
  • 1,793
  • 1
  • 18
  • 35