我想要一个使用 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/