Reputation: 4473
I am seeking the fastest way of computing the rolling sum with changing window size. I use the following code, but for vectors of length 1M, it is far too slow.
Thanks
set.seed(1)
n = 10L
x = runif(n)
window = pmin(sample(1:10, n, TRUE), n:1-1)
s = function(x, w){
n = length(x)
out = rep(NA, n)
for(i in 1:n){
k = w[i]
out[i] = sum(x[i:(i+k)])
}
out
}
s(x, window)
# [1] 2.11869372 1.85318505 4.87750614 3.61375247 3.39644499 3.19476306 2.29637338 1.35169811
# [9] 0.69090031 0.06178627
Upvotes: 2
Views: 493
Reputation: 270020
Try this:
en <- seq_along(x) + window # end positions
cum <- cumsum(x)
cum[en] - cum + x
Upvotes: 3