dplyr group_by vector of column names?

Viewed 409

I used to be able to group_by_ using a string a column name ("standard evaluation"), but it is deprecated now.

> data(mtcars)
> mtcars %>% group_by_('mpg') %>% tally() %>% head(2)
# A tibble: 2 x 2
    mpg     n
  <dbl> <int>
1  10.4     2
2  13.3     1
Warning message:
`group_by_()` is deprecated as of dplyr 0.7.0.
Please use `group_by()` instead.
See vignette('programming') for more help

Furthermore, it looks like maybe grouping by more than one column never worked with group_by_?

> mtcars %>% group_by_(c('mpg', 'cyl')) %>% tally() %>% head(2)
# A tibble: 2 x 2
    mpg     n
  <dbl> <int>
1  10.4     2
2  13.3     1

How do I get the appropriate tallies using a vector of column names?

For example, a result that looks like:

> mtcars %>% group_by(mpg, cyl) %>% tally() %>% head(2)
# A tibble: 2 x 3
# Groups:   mpg [2]
    mpg   cyl     n
  <dbl> <dbl> <int>
1  10.4     8     2
2  13.3     8     1

but uses c('mpg', 'cyl') ?

EDIT: Using dplyr 1.0.0.

1 Answers

We can use group_by with across from dplyr version >= 1.0.0

library(dplyr)
mtcars %>% 
     group_by(across(all_of(c('mpg', 'cyl')))) %>% 
     tally() %>%
     head(2)
# A tibble: 2 x 3
# Groups:   mpg [2]
#    mpg   cyl     n
#  <dbl> <dbl> <int>
#1  10.4     8     2
#2  13.3     8     1

With older versions, use the group_by_at

mtcars %>%
   group_by_at(c('mpg', 'cyl')) %>%
   tally() %>%
   head(2)
# A tibble: 2 x 3
# Groups:   mpg [2]
#    mpg   cyl     n
#  <dbl> <dbl> <int>
#1  10.4     8     2
#2  13.3     8     1
Related