Created
January 11, 2017 18:00
-
-
Save ateucher/d62f92952bf7367bee6ebdae412679e2 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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