#' Cumulative means, variances, standard deviations
#'
#' \code{cummean}, \code{cumvar} and \code{cumsd} compute
#' cumulative mean, variance and standard deviation.
#' \code{welford} uses Welford on-line algorithm for
#' computing cumulative mean and variance.
#'
#' @param x numeric vector
#'
#' @references
#' Knuth, D.E. (1998). The Art of Computer Programming, Vol. 2:
#' Seminumerical Algorithms, 3rd edn., p. 232. Boston: Addison-Wesley.
#'
#' @references
#' Welford, B.P. (1962). Note on a method for calculating corrected sums
#' of squares and products. Technometrics, 4(3):419–420.
#'
#' @references
#' Chan, T.F., Golub, G.H., & LeVeque, R.J. (1983).
#' Algorithms for Computing the Sample Variance: Analysis and Recommendations.
#' The American Statistician, 37, 242-247.
#'
#' @references
#' Ling, R.F. (1974). Comparison of Several Algorithms for Computing Sample
#' Means and Variances. Journal of the American Statistical Association,
#' 69(348), 859-866.
#'
#' @name cumsd
#' @export
cumsd <- function(x) sqrt(cumvar(x))
#' Cumulative sum, product and mean
#'
#' Cumulative sum, product and mean functions that ignore
#' missing values (if \code{na.rm = TRUE}).
#'
#' @param x numeric vector
#' @param missing if \code{FALSE} missing values are marked
#' as missing in the output; otherwise (default)
#' they are replaced with the previous value
#' in the sequence
#'
#' @export
cumSum <- function(x, missing = FALSE) {
nas <- is.na(x)
x[nas] <- 0
out <- cumsum(x)
if (missing)
out[nas] <- NA
out
}
#' @rdname cumSum
#' @export
cumProd <- function(x, missing = FALSE) {
nas <- is.na(x)
x[nas] <- 1
out <- cumprod(x)
if (missing)
out[nas] <- NA
out
}
#' @rdname cumSum
#' @export
cumMean <- function(x, missing = FALSE) {
nas <- is.na(x)
x[nas] <- 0
out <- cumsum(x)/cumsum(as.numeric(!nas))
if (missing)
out[nas] <- NA
out
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.