Handing over the column name of a data frame in a function to the dplyr function count() in R?

Viewed 58

How can I hand over the argument ColName of my function foo to the R function count? ColName is the name of the column in the dataframe.

library(scales)
library(dplyr)

foo <- function(df, ColName, YearCol){

    percentData <- df %>% 
        group_by(format(as.Date(df[,YearCol]),"%Y")) %>% 
        count(ColName) %>%   # does not work like this, also df[,ColName] does not work
        mutate(ratio=scales::percent(n/sum(n)))

 }
1 Answers

You can use the .dots parameter of select to choose the columns you're interested in.

foo <- function(df, ColName, YearCol){
    percentData <- df %>% 
        select(.dots = c(ColName, YearCol)) %>%
        group_by(format(as.Date(.dots2), "%Y")) %>% 
        count(.dots1) %>%  
        mutate(ratio=scales::percent(n/sum(n)))
    percentData
}
Related