Using dplyr::count() with variable column names

less than 1 minute read

Based on this StackOverflow thread and this R-bloggers post

If calling the count() function inside a custom function for example, using a variable name as input to match the column to count, the variable name will be a string. And because dplyr quotes the arguments, we need to unquote the argument.

One option is to use across():
df %>% count(across(colname))

Another is to use !!as.name().

My concrete use:

count_drug <- function(drug) {
  colname <- (paste0("rut_", drug))
  df %>% 
    count(Major_geno, !!as.name(colname)) %>% 
    add_column("drug" = drug) %>% 
    rename(category = !!as.name(colname))
}

Tags:

Updated:

Leave a Comment