【问题标题】:Using aggregate to compute monthly weighted average使用聚合计算每月加权平均值
【发布时间】:2016-02-15 00:24:07
【问题描述】:

我需要计算每月加权平均值。数据框如下所示:

            Month Variable Weighting
460773 1998-06-01       11    153.00
337134 1998-06-01        9      0.96
473777 1998-06-01       10    264.00
358226 1998-06-01        6      0.52
414626 1998-06-01       10     34.00
341020 1998-05-01        9      1.64
453066 1998-05-01        5     26.00
183276 1998-05-01        8      0.51
403729 1998-05-01        6    123.00
203005 1998-05-01       11      0.89

当我使用aggregate 例如,

 Output <- aggregate(Variable ~ Month, df , mean )
 Output
       Month Variable
1 1998-05-01      7.8
2 1998-06-01      9.2

但是,当我尝试向聚合添加权重时,我得到了正确的结果,例如,

Output <- aggregate(Variable ~ Month, df , FUN = weighted.mean, w = df$Weighting)

我得到一个不同向量长度的错误:

Error in weighted.mean.default(X[[1L]], ...) : 
'x' and 'w' must have the same length

有没有办法补救这种情况?

【问题讨论】:

    标签: r time-series aggregate


    【解决方案1】:

    使用aggregate() 是不可能的,因为您的权重向量在aggregate() 期间未分区。您可以使用by() 或split() 加上sapply() 或附加包data.table 或来自包ddply() 的函数plyr 或来自包dplyr 的函数

    split() 加上sapply() 的示例:

    sapply(split(df, df$Month), function(d) weighted.mean(d$Variable, w = d$Weighting))
    

    结果:

    1998-05-01 1998-06-01 
       5.89733   10.33142 
    

    by() 的变体

    by(df, df$Month, FUN=function(d) weighted.mean(d$Variable, w = d$Weighting)) # or
    unclass(by(df, df$Month, FUN=function(d) weighted.mean(d$Variable, w = d$Weighting)))
    

    带包plyr

    library(plyr)
    ddply(df, ~Month, summarize, weighted.mean(Variable, w=Weighting))
    

    data.table

    library(data.table)
    setDT(df)[, weighted.mean(Variable, w = Weighting), Month]
    

    【讨论】:

    • 谢谢!这很有帮助。有没有办法忽略 NA?因为当这些函数遇到 NA 时,它们会自动将总分设为 NA。
    • 是的,weighted.mean()有一个参数na.rm=,请阅读函数的文档。
    • 是的,谢谢,我有一个语法错误,所以它对我不起作用。
    【解决方案2】:

    如果您没有安装plyr、dplyr 或data.table 并且由于某些原因无法安装它们,仍然可以使用aggregate 计算每月加权平均值,您只需要做以下技巧,

    df$row <- 1:nrow(df) #the trick
    aggregate(row~Month, df, function(i) mean(df$Variable[i])) #mean
    aggregate(row~Month, df, function(i) weighted.mean(df$Variable[i], df$Weighting[i])) #weighted mean
    

    这里是输出:

    平均值:

    > aggregate(row~Month, df, function(i) mean(df$Variable[i]))
           Month row
    1 1998-05-01 7.8
    2 1998-06-01 9.2
    

    加权平均值:

    > aggregate(row~Month, df, function(i) weighted.mean(df$Variable[i], df$Weighting[i]))
           Month      row
    1 1998-05-01  5.89733
    2 1998-06-01 10.33142
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-04
      • 1970-01-01
      • 2023-04-05
      • 1970-01-01
      • 2011-02-12
      相关资源
      最近更新 更多