Skip to content

Instantly share code, notes, and snippets.

@druedin
Created June 15, 2013 20:34
Show Gist options
  • Save druedin/5789512 to your computer and use it in GitHub Desktop.
Save druedin/5789512 to your computer and use it in GitHub Desktop.
Moving average handling NA
namav <- function(x,k=3){
x <- c(rep(NA, k),x,rep(NA,k)) # add NA on both sides
n <- length(x)
return(sapply((k+1):(n-k), function(i) sum(x[(i-k):(i+k)],na.rm=TRUE)/(2*k+1-sum(is.na(x[(i-k):(i+k)])))))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment