簡體   English   中英

將 function 中的數據幀的列名移交給 dplyr function count() in ZE28796D3D48ZEAF13

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

如何將我的 function foo的參數ColName移交給 R function count ColName是 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)))

 }

您可以使用select.dots參數來選擇您感興趣的列。

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
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM