rollsum
is defined within rollmean.R
as follows:
rollsum <- function(x, k, fill = if (na.pad) NA, na.pad = FALSE,
align = c("center", "left", "right"), ...) {
UseMethod("rollsum")
}
where the method is:
rollsum.zoo <- function(x, k, fill = if (na.pad) NA, na.pad = FALSE,
align = c("center", "left", "right"), ...) {
if (!missing(na.pad)) warning("na.pad is deprecated. Use fill.")
align <- match.arg(align)
if (length(dim(x)) == 2) {
# merge is the only zoo specific part of this method
out <- do.call("merge", c(lapply(1:NCOL(x), function(i) {
rollsum(x[, i, drop = TRUE], k, fill = fill, align = align, ...)
}), all = FALSE))
if (ncol(x) == 1) dim(out) <- c(length(out), 1)
colnames(out) <- colnames(x)
return(out)
}
n <- length(x)
stopifnot(k <= n)
ix <- switch(align,
"left" = { 1:(n-k+1) },
"center" = { floor((1+k)/2):ceiling(n-k/2) },
"right" = { k:n })
xu <- unclass(x)
y <- xu[k:n] - xu[c(1, seq_len(n-k))] # difference from previous
y[1] <- sum(xu[1:k]) # find the first
# sum precomputed differences
rval <- cumsum(y)
x[ix] <- rval
na.fill(x, fill = fill, ix)
}
If you step through the function you'll see it's actually not because of cumsum
that the result evaluates to NA where you'd expect 15 (or at least that's not the first cause of it -- if you were to fix the current problem maybe cumsum
would also cause a problem, I don't know). It's the line
y <- xu[k:n] - xu[c(1, seq_len(n-k))]
.
rollsum
is a new function in the zoo
package and doesn't yet handle NA's well, so I'd suggest staying with rollapply
.