【问题标题】:How to fix the error "'x' and 'w' must have the same length" in summarise_all()?如何修复 summarise_all() 中的错误“'x' 和 'w' 必须具有相同的长度”?
【发布时间】:2019-07-02 15:22:46
【问题描述】:

我想使用 dplyr::summarise_all() 和 weighted.mean 来计算每个组的许多列的加权平均值。

我尝试直接使用匿名函数,但它返回错误: 'x' 和 'w' 必须具有相同的长度。我知道我可以使用 summarise() 和 weighted.mean,但是这样我需要指定所有列名,这不是我想要的。

result = df%>%
  group_by(A)%>%
  summarise_all(function(x){weighted.mean(x, .$B)})

这里的数据框有组列A,权重列B和其他列。我希望 A 中的每个组的 B 列的其他列值的加权平均值。我希望我可以使用 dplyr 和 weighted.mean 来做到这一点,但我可以使用其他可用的方法。

【问题讨论】:

    标签: r dplyr anonymous-function group-summaries


    【解决方案1】:

    我们不需要.$ 作为.$ 提取整列值而不是对应于分组结构的值

    df %>%
       group_by(A)%>%
       summarise_all(list(~ weighted.mean(., B)))
    

    如果我们显式提供参数,也可以不使用 lambda 函数 (~) 来编写

    df %>%
       group_by(A)%>%
       summarise_all(weighted.mean, w = B)
    

    【讨论】:

      猜你喜欢
      • 2014-01-29
      • 2014-08-22
      • 1970-01-01
      • 1970-01-01
      • 2017-11-15
      • 1970-01-01
      • 2023-03-16
      • 1970-01-01
      • 2019-05-04
      相关资源
      最近更新 更多