I'm trying to use dplyr
's count()
with a dynamic variable name instead of a column name. Before, I would use count_()
, but this is now deprecated. What is the best replacement?
Minimal reproducible example:
library(dplyr)
df <- data.frame(id = 1:10, city = sample(c("London","Paris","Amsterdam"), 10, replace=TRUE))
colname <- "city"
Here's what I've tried:
df %>% count( city ) # desired output (works but isn't dynamic)
df %>% count( !!colname ) # doesn't work, makes it literally "city"
df %>% count( vars(colname) ) # doesn't work
df %>% count( eval(colname) ) # doesn't work either
df %>% count( eval(parse(text=colname)) ) # works, but is not 'dplyr' ?
df %>% count( eval(sym(colname)) ) # works, but using `sym` from 'rlang'
df %>% count( !!as.name(colname) ) # works, but using `as.name` from 'base'
df %>% count_( colname ) # works, but is deprecated
Not sure whether any of the above is the preferred method, or whether it's something altogether different?
Thanks in advance!
PS. I found the as.name()
solution here.