NSE in count() with characters in a variable

Is there a way to use a character vector of column names?

library(dplyr)
library(tidyverse)

# works
x <- c(quo(a), quo(b))
tibble(a=c(1,2,2,3), b=c(1,2,2,3), c=1:4) %>% count(!!!x)  
#> # A tibble: 3 x 3
#>       a     b     n
#>   <dbl> <dbl> <int>
#> 1     1     1     1
#> 2     2     2     2
#> 3     3     3     1

# doesn't work
x <- c("a", "b")
tibble(a=c(1,2,2,3), b=c(1,2,2,3), c=1:4) %>% count(!!!x)  
#> # A tibble: 1 x 3
#>   `"a"` `"b"`     n
#>   <chr> <chr> <int>
#> 1 a     b         4

Created on 2018-11-21 by the reprex package (v0.2.0).

Quoting with quo and quoted strings are different since quo gives you symbol while strings give you, well, strings. Therefore, you can't treat them the same. If your API takes strings, then you can convert them to symbols with syms and it'll work exactly the same as your quo example:

library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union
library(tidyverse)

x <- c(quo(a), quo(b))
quo_res <- tibble(a=c(1,2,2,3), b=c(1,2,2,3), c=1:4) %>% count(!!!x)  

x <- c("a", "b")
sym_res <- tibble(a=c(1,2,2,3), b=c(1,2,2,3), c=1:4) %>% count(!!!rlang::syms(x))  
dplyr::all_equal(quo_res, sym_res)
#> [1] TRUE

Created on 2018-11-21 by the reprex package (v0.2.1)

3 Likes

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.