我有以下数据:
a=c(1:10)
b=c(16:25)
c=c(24:33)
wa=c(3,7,3,3,3,3,3,3,3,1)
wb=c(3,2,3,3,3,3,3,3,3,8)
wc=c(4,1,4,4,4,4,4,4,4,1)
z=data.frame(a,b,c,wa,wb,wc)
我想获得每条记录的加权平均值。所以我尝试了这个:
weight=apply(subset(z,select=c(wa,wb,wc)),1,function(x) x)
z$weightMean=apply(subset(z,select=c(a,b,c)),1,function(x) weighted.mean(x,weight))
返回了以下错误消息:
Error in weighted.mean.default(x, weight) :
'x' and 'w' must have the same length
然后我尝试了这个:
weight=as.vector(weight)
z$weightMean=apply(subset(z,select=c(a,b,c)),1,function(x) weighted.mean(x,weight))
其中也返回了相同的错误。
我做错了什么?
答案 0 :(得分:4)
这似乎可以解决问题:
> apply(z, 1, function(x) weighted.mean(x[1:3], x[4:6]))
[1] 14.7 7.3 16.7 17.7 18.7 19.7 20.7 21.7 22.7 24.3
这可能会更快一点,但不清楚发生了什么:
> rowSums(z[,1:3] * z[,4:6]) / rowSums(z[,4:6])
[1] 14.7 7.3 16.7 17.7 18.7 19.7 20.7 21.7 22.7 24.3