R/mvavg.R

Defines functions mvavg

Documented in mvavg

#' Simple Moving Average
#'
#' @param x numeric vector
#' @param n number of average
#'
#' @return a shorter numeric vector where y[i] = mean(x[i:(i+n-1)])
#' @export
#'
#' @examples
#' mvavg(1:10, 2)
#' mvavg(1:10, 2, TRUE)
mvavg <- function(x, n, rm.na = FALSE) {
  s <- sapply(seq(1, length(x) - n + 1), function(i) mean(x[i:(i+n-1)]))
  if (!rm.na) return(c(s, rep(NA, n-1)))
  else return(s)
}
yanxianUCSB/yxhelper documentation built on April 20, 2020, 4:09 p.m.