1

All the examples i see for curly curly are within the context of writing functions.
I just want to loop around my grouping variables and get frequencies, so i'm trying to get something like this to work:

my_var <- "model"
mpg %>% group_by({{ my_var }}) %>% summarise(n=n())

but this doesn't give the expected output, ie what i would get if i was just using

mpg %>% group_by(model) %>% summarise(n=n())

How can I use non standard evaluation in this simple setting?

Note that i am not asking about a group_by_at type solution but a non-standard evaluation solution, so this is not a duplicate of dplyr group by colnames described as vector of strings

chrisjacques
  • 635
  • 1
  • 5
  • 17

1 Answers1

1

Curly-Curly is used within the functions and with unquoted variables.

library(dplyr)
library(rlang)

my_func <- function(data, var) {
   data %>% group_by({{var}}) %>% summarise(n=n())  
}

my_func(mpg, model)

#   model                  n
#   <chr>              <int>
# 1 4runner 4wd            6
# 2 a4                     7
# 3 a4 quattro             8
# 4 a6 quattro             3
# 5 altima                 6
# 6 c1500 suburban 2wd     5
# 7 camry                  7
# 8 camry solara           7
# 9 caravan 2wd           11
#10 civic                  9
# … with 28 more rows

To use outside functions and with quoted variables we can use sym and evaluate (!!)

mpg %>% group_by(!!sym(my_var)) %>% summarise(n=n())

Or use group_by_at

mpg %>% group_by_at(my_var) %>% summarise(n=n())
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213