Skip to content

Instantly share code, notes, and snippets.

@ateucher
Created January 11, 2017 18:00
Show Gist options
  • Save ateucher/d62f92952bf7367bee6ebdae412679e2 to your computer and use it in GitHub Desktop.
Save ateucher/d62f92952bf7367bee6ebdae412679e2 to your computer and use it in GitHub Desktop.
# Inspired by Aman Verma's work in rcaaqs
rolling_mean <- function(x, width, thresh = width) {
avail <- !is.na(x)
x[is.na(x)] <- 0
rolled_sum <- cumsum(x) - dplyr::lag(cumsum(x), width, default = 0)
rolled_avail <- cumsum(avail) - dplyr::lag(cumsum(avail), width, default = 0)
ret <- rolled_sum / rolled_avail
ret[rolled_avail < thresh] <- NA
ret
}
set.seed(42)
foo <- rnorm(20)
rolling_mean(foo, 3)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment