Calculate cumulative average (mean)
Solution 1:
In analogy to the cumulative sum of a list I propose this: The cumulative average avg of a vector x would contain the averages from 1st position till position i.
One method is just to compute the the mean for each position by summing over all previous values and dividing by their number.
By rewriting the definition of the arithmetic mean as a recursive formula. One gets
avg(1) = x(1)
and
avg(i) = (i-1)/i*avg(i-1) + x(i)/i; (i > 1)
Evaluating this expression for every element of your vector (or list, one-dimensional array or however you call it) gives you the cumulative average.
This recursive method comes in handy if you have to calculate an average over very large or very many integers and would run into an overflow if you had to store their cumulative sum.
Example
In your example
1, 2, 3, 4, 5
we get
1, 1.5, 2, 2.5, 3
Solution 2:
This is an old question and there have been lot of changes since then. I just thought of updating it with a dplyr
answer. dplyr
has a cummean
function which directly gives the cumulative mean of the vector.
vec <- c(1, 2, 3, 4, 5)
library(dplyr)
cummean(vec)
#[1] 1.0 1.5 2.0 2.5 3.0