-3

我有以下数据框:

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"))
4

3 回答 3

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
于 2013-07-13T02:16:32.337 回答
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)))
于 2013-07-13T02:01:06.897 回答
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

这会在您的resultdata.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
于 2013-07-13T02:03:40.703 回答