我有一个向量,我想采用向量的增量平均值.
a <- 2 4 6 2 4 0 1 0 0 1
Run Code Online (Sandbox Code Playgroud)
这有效:
for(i in seq_along(a)) {
print(mean(a[1:seq_along(a)[[i]]]))
}
[1] 2
[1] 3
[1] 4
[1] 3.5
[1] 3.6
[1] 3
[1] 2.714286
[1] 2.375
[1] 2.111111
[1] 2
Run Code Online (Sandbox Code Playgroud)
但现在我想把它扩展到一个向量列表,我被卡住了.
b <- list(x = rnorm(10, mean = 5), x2 = rnorm(10, mean = 20))
b
$x
[1] 4.893252 5.129610 4.599701 5.409024 4.666844 5.787243 5.697621 2.968771 5.216302 6.268629
$x2
[1] 19.50947 22.14797 20.80683 19.47857 21.24126 18.36233 20.57424 19.68233 20.67508 19.83930
Run Code Online (Sandbox Code Playgroud)
当我尝试这个时,我得到以下内容:
for(i in seq_along(b)) {
print(mean(b[[i]][1:seq_along(b[[i]])[[i]]]))
}
[1] 4.893252
[1] 20.82872
Run Code Online (Sandbox Code Playgroud)
它应返回两个向量,显示每个索引的均值,如前一个示例,而不是向量本身的总平均值
我不知道该怎么办.在此先感谢您的帮助.
而不是for循环,你最好只使用cumsum()除法来计算累积均值.例如
cummean <- function(x) cumsum(x)/seq_along(x)
Run Code Online (Sandbox Code Playgroud)
然后就可以了
cummean(a)
Run Code Online (Sandbox Code Playgroud)
或列表
lapply(b, cummean)
Run Code Online (Sandbox Code Playgroud)