首页 > 解决方案 > 将函数中数据框的列名移交给 R 中的 dplyr 函数 count()?

问题描述

如何将ColName函数的参数移交foo给 R 函数countColName是数据框中列的名称。

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)))

 }

标签: rdplyr

解决方案


您可以使用.dots参数select来选择您感兴趣的列。

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
}

推荐阅读