r - 如何将列传递给arrange()和mutate()

标签 r dplyr

我想要一个使用 dplyr 且类似于下面的 AddPercentColumns() 的函数。

AddPercentColumns <- function(df, col) {
    # Sorts and adds "Percent" and "Cumulative Percent" columns to a data.frame.
    #
    # Args:
    #   df: data frame
    #   col: column symbol
    #
    # Returns:
    #   Data frame sorted by "col" with new "Percent" and "Cumulative Percent" columns.

    df %>%
        arrange(desc(col)) %>%
        mutate(Percent = col / sum(col) * 100) %>% 
        mutate(Cumulative = cumsum(Percent))
}

但是,我无法理解如何解决 NSE。我可能会传入一个列名字符串并使用 arrange_()mutate_(),但是我不确定如何处理 desc() sum()cumsum()

应该如何使用dplyr编写这个函数?

最佳答案

根据 Konrad 的建议,我将发布另一个不断发展的解决方案。 :)

AddPercentColumns <- function(df, col) {
    # Sorts data.frame and adds "Percent" and "Cumulative Percent" columns.
    #
    # Args:
    #   df: data frame
    #   col: unevaluated column symbol e.g. substitute(col)
    #
    # Returns:
    #   Data frame sorted by "col" with new "Percent" and "Cumulative Percent" columns.

    df %>%
        arrange_(bquote(desc(.(col)))) %>%
        mutate_(Percent = bquote(.(col) / sum(.(col)) * 100)) %>% 
        mutate(Cumulative = cumsum(Percent))
}

绝对更干净、更易于调试和可读。

关于r - 如何将列传递给arrange()和mutate(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29310354/

相关文章:

多列的 R 时间聚合

r - 根据从现有列派生的 TRUE/FALSE 设置新列值

r - 如何使用显示所有年龄级别的个人数据制作人口金字塔,即使 R 中没有该级别的数据?

r - 使用 lazyeval 进行 mutate 的标准评估

R dplyr 使用自定义函数改变多列以创建新列

r - 使用 sf/mapview 连接两组坐标以创建线

r - 在 R 中使用带有 mutate 的循环对具有部分匹配列名的列求和

r - 如何使用dplyr引用变量而不是列

r - 为 r 中的每个变量按组汇总表中的数据

r - 在 R 中打开栅格!和一些统计操作