0

I'd like to calculate the moving average of a vector using all the values till the current value. So that:

c(1, 2, 1, 4, 5, 10)

would return

 1.00 1.50 1.33 2.00 2.60 3.83

I used a loop like this:

out = c()
for (i in 1:length(x)) {
  m = mean(x[1:i])
  out = c(out, m)
}

Are there any packages with a built in function for this? Or is there a better way to do this?

Rafael
  • 3,096
  • 1
  • 23
  • 61

1 Answers1

0

What about

v <- c(1, 2, 1, 4, 5, 10)
cumsum(v)/(1:length(v))
MR_MPI-BGC
  • 265
  • 3
  • 11