Search code examples
rmoving-average

Calculating a non-overlapping moving average


I'm trying to calculate a moving average of a timeseries in R, but I'm getting unsuccessful results.

Here is what I have done:

Sample vector:

library(gtools)
test <- sample(1:100, 50)

testrunning <- running(test, width=10, by=10, FUN=mean, trim=0, na.rm=TRUE)

It produces a result, but the result is not the average of the windows in my data; rather, it is an average of the window. Like so:

testrunning

## 1:10 11:20 21:30 31:40 41:50 
## 5.5  15.5  25.5  35.5  45.5 

Solution

  • I think I found the problem. It should be fun and not FUN:

    running(test, width = 10, by = 10, fun = mean, trim = 0, na.rm = TRUE)
    

    You could also do:

    sapply(split(test, (seq_along(test) - 1) %/% 10), mean)