我有以下数据帧:
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"))
使用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
如有必要,请先将因子更改为数字
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)))
这是使用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