2

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

wibeasley
  • 5,000
  • 3
  • 34
  • 62

2 Answers2

5

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
JasonAizkalns
  • 20,243
  • 8
  • 57
  • 116
  • 1
    You might clarify the term "unquoting" as specifically referring to converting a character vector to an R "symbol", since the term quoting might alternatively be interpreted as the use of the function `quote`, for which one form of "reversal" might then be accomplished with `as.character` which would then deliver a different sort of "quoted" value. – IRTFM Mar 19 '19 at 19:26
0

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
Phoenix Mu
  • 648
  • 7
  • 12
  • 2
    The OP is trying to do this programmatically, such as with tidyeval, not by supplying specific column names in `group_by` – camille Mar 19 '19 at 19:30