Skip to content

Instantly share code, notes, and snippets.

@thomas-neitmann
Last active December 8, 2019 06:52
Show Gist options
  • Save thomas-neitmann/dfbad76385fa448d1aedf1eadc3dd97d to your computer and use it in GitHub Desktop.
Save thomas-neitmann/dfbad76385fa448d1aedf1eadc3dd97d to your computer and use it in GitHub Desktop.
If you ever tried to pass a string as an argument to a dplyr function you probably got frustrated. This just doesn't work. But don't give up, instead have a look at the solution below.
suppressMessages(library(dplyr))
data("mtcars")
mtcars %>% group_by(cyl) %>% summarise(n = n())
#> # A tibble: 3 x 2
#> cyl n
#> <dbl> <int>
#> 1 4 11
#> 2 6 7
#> 3 8 14
var <- "cyl"
# this doesn't work
mtcars %>% group_by(var) %>% summarise(n = n())
#> Error: Column `var` is unknown
# that's the solution
mtcars %>% group_by(!!sym(var)) %>% summarise(n = n())
#> # A tibble: 3 x 2
#> cyl n
#> <dbl> <int>
#> 1 4 11
#> 2 6 7
#> 3 8 14
# this works but has an unintended side effect
mtcars %>% group_by(get(var)) %>% summarise(n = n())
#> # A tibble: 3 x 2
#> `get(var)` n
#> <dbl> <int>
#> 1 4 11
#> 2 6 7
#> 3 8 14
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment