Amount of earnings with different window sizes

I am looking for the fastest way to calculate a moving amount with window resizing. I am using the following code, but for vectors of length 1M it is too slow.

thank

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
+1
source share
1 answer

Try the following:

en <- seq_along(x) + window   # end positions
cum <- cumsum(x)
cum[en] - cum + x
+3
source

Source: https://habr.com/ru/post/1663035/


All Articles