Skip to content

Instantly share code, notes, and snippets.

@dsparks
Created November 30, 2012 16:54
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save dsparks/4176957 to your computer and use it in GitHub Desktop.
Save dsparks/4176957 to your computer and use it in GitHub Desktop.
Rolling means with zoo
doInstall <- TRUE
toInstall <- c("zoo")
if(doInstall){install.packages(toInstall, repos = "http://cran.us.r-project.org")}
lapply(toInstall, library, character.only = TRUE)
ftseIndex <- EuStockMarkets[, 4]
plot(ftseIndex, col = "GRAY")
# Calculate 10-day rolling mean, quickly:
smoothIndex <- rollmean(x = ftseIndex, # original series
k = 30, # width of the rolling window
fill = NA) # Pads head and/or tail with NA
length(ftseIndex) == length(smoothIndex)
lines(smoothIndex, col = "RED")
# If there are NA values in the original series, you'll need rollapply()
ftseIndex[c(40, 90, 300)] <- NA
smoothIndex2 <- rollapply(data = ftseIndex, # original series
width = 90, # width of the rolling window
FUN = mean, na.rm = T, # Any arbitrary function
fill = NA) # Padding
lines(smoothIndex2, col = "GREEN")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment