按日期加权平均值

时间:2013-07-13 00:23:52

标签: r mean weighted-average

我有以下数据框:

df = data.frame(date = c("26/06/2013", "26/06/2013",  "26/06/2013",  "27/06/2013", "27/06/2013", "27/06/2013", "28/06/2013", "28/06/2013",   "28/06/2013"), return = c(".51", ".32", ".34", ".39", "1.1", "3.2", "2.1", "5.3", "2.1"), cap = c("500", "235", "392", "213", "134", "144", "232", "155", "213"), weight = c("0.443655723", "0.20851819", "0.347826087", "0.433808554", "0.272912424", "0.293279022", "0.386666667", "0.258333333", "0.355"))

我想计算:

1)“重量”的最后一栏。这是每天“上限”列的权重。

2)加权“上限”表示每天“返回”。我想获得以下输出:

result = data.frame(date = c("26/06/2013", "27/06/2013", "28/06/2013"), cap.weight.mean = c("0.411251109", "1.407881874", "2.926666667"))

3 个答案:

答案 0 :(得分:2)

使用plyr函数的另一种可能性:

library(plyr)
# Change factor to numeric
> df[,-1]<-sapply(df[,-1],function(x){as.numeric(as.character(x))})
> ddply(df,.(date),summarize,cap.weight.mean=weighted.mean(return,weight))
        date cap.weight.mean
1 26/06/2013       0.4112511
2 27/06/2013       1.4078819
3 28/06/2013       2.9266667

答案 1 :(得分:0)

如有必要,请先将因子更改为数字

df$return=as.numeric(levels(df$return))[df$return]
df$cap=as.numeric(levels(df$cap))[df$cap]
df$weight=as.numeric(levels(df$weight))[df$weight]

问题1)

 library(plyr)
 #pretend weight column were absent in df
 ddply(df[,-ncol(df)],"date",function(x) data.frame(x,weight=x$cap/sum(x$cap)))

问题2)

 library(plyr)
 ddply(df,"date",function(x) data.frame(date=x$date[1],cap.weight.mean=sum(x$cap*x$return)/sum(x$cap)))

答案 2 :(得分:0)

这是使用by的另一个选项!

转换为数字后,提到cryo111。

R> by(df, df$date, FUN = function(x) weighted.mean(x$return, w = x$weight) )
df$date: 26/06/2013
[1] 0.4112511
------------------------------------------------------------ 
df$date: 27/06/2013
[1] 1.407882
------------------------------------------------------------ 
df$date: 28/06/2013
[1] 2.926667

这会在result data.frame中生成信息。我猜这就是你要找的东西

这是使用memisc:::aggregate.formula

的另一种解决方案
> library(memisc)
> aggregate(weighted.mean(return, weight) ~ date, data = df)
>        date weighted.mean(return, weight)
1 26/06/2013                     0.4112511
4 27/06/2013                     1.4078819
7 28/06/2013                     2.9266667