【发布时间】:2015-04-02 03:02:04
【问题描述】:
如何使用 dplyr 中的 summarise_each 计算数据集中所有字段的加权平均值?例如,假设我们要按 cyl 对 mtcars 数据集进行分组,并计算将权重作为 gear 的所有列的加权平均值> 栏目。我尝试了以下方法,但无法正常工作。
mtcars %>% group_by(cyl) %>% summarise_each(funs(weighted.mean(., gear)))
# The line above gives the following output
# Error in weighted.mean.default(c(1, 2, 2, 1, 2, 1, 1, 1, 2, 2, 2), 4.15555555555556) :
# 'x' and 'w' must have the same length
提前感谢您的帮助!
【问题讨论】: