There are a few ways you can calculate the moving sum in the r:
R-base
diff(c(0, cumsum(1:10)), 5)
# 15 20 25 30 35 40
This proposal can be generalized as a function:
soma_movel <- function(x, n) {
diff(c(0, cumsum(x)), n)
}
Zoo
The package zoo
, as raised in the comments, it has a function for this, but it does not play very well
zoo::rollsum(1:10, 5)
# 15 20 25 30 35 40
Comparison
set.seed(123)
vetor <- rnorm(1e5) # 100 mil números
# As funções retornam valores iguais?
all.equal(zoo::rollsum(vetor, 5), soma_movel(vetor, 5))
# [1] TRUE
Finally, a comparison in the performance of the solutions raised shows that even being more about 80 times faster than with the zoo
, the solution with the base
still loses to the solution with the RcppRoll
presented by Daniel in 5 times.
microbenchmark::microbenchmark(
zoo = zoo::rollsum(vetor, 5),
base = soma_movel(vetor, 5),
cpp = RcppRoll::roll_sum(vetor, n = 5),
times = 30
)
Unit: microseconds
expr min lq mean median uq max neval cld
zoo 200659.545 204218.475 208418.887 206276.601 209928.673 255552.267 30 b
base 2229.273 2536.157 3379.694 2633.918 2755.286 7725.985 30 a
cpp 452.116 514.725 6966.097 558.089 577.333 188068.577 30 a
With the package
zoo
, tryrollsum(presidents, k = 5)
.– Rui Barradas