There are a few ways you can calculate the mobile 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 zoo
package, as raised in the comments, has a function for this, but it does not perform 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 on the performance of the solutions raised shows that even though it is about 80 times faster than with
zoo
, the solution with
base
still loses to the solution with
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