standard eval with `dplyr::count()`

306 views Asked by At

How can I pass a character vector to dplyr::count().

library(magrittr)
variables <- c("cyl", "vs")

mtcars %>% 
  dplyr::count_(variables)

This works well, but dplyr v0.8 throws the warning:

count_() is deprecated. Please use count() instead

The 'programming' vignette or the tidyeval book can help you to program with count() : https://tidyeval.tidyverse.org

I'm not seeing standard evaluation examples of quoted names or of dplyr::count() in https://tidyeval.tidyverse.org/dplyr.html or other chapters of the current versions of the tidyeval book and Programming with dplyr.

My two best guesses after reading this documenation and another SO question is

mtcars %>% 
  dplyr::count(!!variables)

mtcars %>% 
  dplyr::count(!!rlang::sym(variables))

which throw these two errors:

Error: Column <chr> must be length 32 (the number of rows) or one, not 2

Error: Only strings can be converted to symbols

2

There are 2 answers

1
JasonAizkalns On BEST ANSWER

To create a list of symbols from strings, you want rlang::syms (not rlang::sym). For unquoting a list or a vector, you want to use !!! (not !!). The following will work:

library(magrittr)

variables <- c("cyl", "vs")

vars_sym <- rlang::syms(variables)
vars_sym
#> [[1]]
#> cyl
#> 
#> [[2]]
#> vs

mtcars %>%
  dplyr::count(!!! vars_sym)
#> # A tibble: 5 x 3
#>     cyl    vs     n
#>   <dbl> <dbl> <int>
#> 1     4     0     1
#> 2     4     1    10
#> 3     6     0     3
#> 4     6     1     4
#> 5     8     0    14
1
Phoenix Mu On

Maybe you can try

mtcars %>%
  group_by(cyl, vs) %>%
  tally()

This gives

# A tibble: 5 x 3
# Groups:   cyl [3]
    cyl    vs     n
  <dbl> <dbl> <int>
1     4     0     1
2     4     1    10
3     6     0     3
4     6     1     4
5     8     0    14