我试着通过在data.frame上使用聚合来避免耗时的循环.但我需要其中一列的值进入最终计算.
dat <- data.frame(key = c('a', 'b', 'a','b'),
rate = c(0.5,0.4,1,0.6),
v1 = c(4,0,3,1),
v2 = c(2,0,9,4))
>dat
key rate v1 v2
1 a 0.5 4 2
2 b 0.4 0 0
3 a 1.0 3 9
4 b 0.6 1 4
aggregate(dat[,-1], list(key=dat$key),
function(x, y=dat$rate){
rates <- as.numeric(y)
values <- as.numeric(x)
return(sum(values*rates)/sum(rates))
})
Run Code Online (Sandbox Code Playgroud)
注意:该功能只是一个例子!
这个实现的问题是y=dat$rate在dat上提供所有4个速率,当我想要的只是2个聚合速率!Anny对如何做到这一点有所了解?谢谢!