df <- data.frame(A = c(1,1,1), B = c(2,2,3))
variables <- c("A", "B")
dplyr::count(df, !!!rlang::sym(variables))
Error: Only strings can be converted to symbols
Run `rlang::last_error()` to see where the error occurred.
It works if variables
is either A
or B
, but not both.
CodePudding user response:
For this syms
is needed. According to ?sym
sym() creates a symbol from a string and syms() creates a list of symbols from a character vector.
dplyr::count(df, !!!rlang::syms(variables))
A B n
1 1 2 2
2 1 3 1
CodePudding user response:
There are several ways to do this. The problem with the OPs method is that sym()
will return a single symbol, but we need a list of symbols. Use the excellent answer by akrun, with the vectorized syms
or purrr::map(sym)
.
Or, without rlang, double/tripple bangs etc, we can do it within dplyr with across(all_of())
Library(tidyverse)
count(df, !!!syms(variables)) #As suggested by @akrun
count(df, across(all_of(variables)))
count(df, !!!map(variables, sym))
A B n
1 1 2 2
2 1 3 1