使用聚合来计算月加权平均值

时间:2015-11-13 12:08:21

标签: r time-series aggregate

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

            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

有没有办法解决这种情况?

2 个答案:

答案 0 :(得分:2)

使用aggregate()是不可能的,因为您的权重向量在aggregate()期间未被分区。您可以使用包by()中的split()sapply()data.table或其他包ddply()或函数plyr或包{{1}中的函数}}

dplyrsplit()的例子:

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

答案 1 :(得分:1)

如果您没有安装plyrdplyrdata.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
相关问题