Reputation: 567
I have a vector that I want to take the incremental mean of a vector.
a <- 2 4 6 2 4 0 1 0 0 1
This works:
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
But now I want to extend that to a list of vectors and I'm stuck.
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
When I try this, I get the following:
for(i in seq_along(b)) {
print(mean(b[[i]][1:seq_along(b[[i]])[[i]]]))
}
[1] 4.893252
[1] 20.82872
It should return two vectors showing the mean at each index like the previous example, not the total mean of the vector itself
I have no idea how to proceed. Thanks in advance for the help.
Upvotes: 0
Views: 110
Reputation: 206242
Rather than a for loop, you'll be better off just using cumsum()
with division to calculate the cumulative mean. For example
cummean <- function(x) cumsum(x)/seq_along(x)
Then you can just do
cummean(a)
or with a list
lapply(b, cummean)
Upvotes: 6
Reputation: 5405
This work for you?
set.seed(1)
b <- list(x = rnorm(10, mean = 5), x2 = rnorm(10, mean = 20))
lapply(b, function(x) cumsum(x) / seq_along(x))
Upvotes: 0