【发布时间】:2017-09-29 13:34:03
【问题描述】:
我正在尝试使用 dplyr 和 summarise_all 计算加权平均值。我见过类似的问题,最具体地说是这篇文章: How do I compute weighted average using summarise_each?
这看起来很简单,但我不断收到 object 'weight' not found 错误消息。
这是一个可重现的例子:
data <- tibble::tribble(~group, ~weight, ~x1, ~x2,
1, 1, 3, 2,
1, 1, 4, 7,
1, 1, 1, 4,
2, 1, 2, 2,
2, 1, 5, 3,
2, 1, 4, 2)
# Just regular means
data %>%
dplyr::group_by(group) %>%
dplyr::summarize_all(mean)
# First attempt
data %>%
dplyr::group_by(group) %>%
dplyr::summarize_all(weighted.mean(., weight))
# Second attempt based on syntax from post above
data %>%
dplyr::group_by(group) %>%
dplyr::summarize_all(funs(weighted.mean(., weight)), -weight)
这就是我运行这段代码时发生的情况:
> data %>%
+ dplyr::group_by(group) %>%
+ dplyr::summarize_all(mean)
# A tibble: 2 x 4
group weight x1 x2
<dbl> <dbl> <dbl> <dbl>
1 1 1 2.666667 4.333333
2 2 1 3.666667 2.333333
>
> data %>%
+ dplyr::group_by(group) %>%
+ dplyr::summarize_all(weighted.mean(., weight))
Error in weighted.mean.default(., weight) : object 'weight' not found
>
> data %>%
+ dplyr::group_by(group) %>%
+ dplyr::summarize_all(funs(weighted.mean(., weight)), -weight)
Error in eval_bare(dot$expr, dot$env) : object 'weight' not found
非常感谢任何有关为什么会发生这种情况以及我可以做些什么(如果有的话)的信息。
谢谢!
【问题讨论】: