问题相当简单,不确定解决方案。我想要做的示例代码是:
library(dplyr)
# initialize a
a = c(5, 6, 8, 9, 10, 15, 7, 9)
# run cummean from dplyr, result
round(cummean(a), digits = 2)
[1] 5.00 5.50 6.33 7.00 7.60 8.83 8.57 8.62
# run weighted.mean from base r, with weights passed as 2nd param
weighted.mean(a, seq(1, length(a), by = 1) / sum(seq(1, length(a), by = 1)))
[1] 9.388889
这里我的问题有点不同。我想计算一个由不同权重加权的cummean向量。为了显示目的而构建我自己的功能,并了解我正在寻找的结果:
round(weighted.cummean(a), digits = 2)
[1] 5.00, 5.67, 6.83, 7.70, 8.47, 10.33, 9.50, 9.39
有关如何计算这些值的参考,您可以在循环中使用weighted.mean为每次计算运行此for循环:
b = c()
for(i in 1:length(a)) {
weights = seq(1, i, by = 1) / sum(seq(1, i, by = 1))
b = c(b, weighted.mean(a[1:i], weights))
}
我想我的问题总结为 - 我们可以使用cummean或类似于cummean的函数将weighted.mean for-loop转换为1行代码吗?
谢谢!
答案 0 :(得分:6)
试试这些:
w <- seq_along(a)
cumsum(a * w) / cumsum(w)
## [1] 5.000000 5.666667 6.833333 7.700000 8.466667 10.333333 9.500000 9.388889
sapply(seq_along(a), function(i) weighted.mean(head(a, i), head(w, i)))
## [1] 5.000000 5.666667 6.833333 7.700000 8.466667 10.333333 9.500000 9.388889
out <- a; for(i in seq_along(a)) out[i] <- weighted.mean(head(a, i), head(w, i)); out
## [1] 5.000000 5.666667 6.833333 7.700000 8.466667 10.333333 9.500000 9.388889
library(dplyr)
cummean(a * w) / cummean(w)
## [1] 5.000000 5.666667 6.833333 7.700000 8.466667 10.333333 9.500000 9.388889
library(zoo)
rollapplyr(a, seq_along(a), function(x) weighted.mean(x, head(w, length(x))))
## [1] 5.000000 5.666667 6.833333 7.700000 8.466667 10.333333 9.500000 9.388889