简体   繁体   中英

Rolling sum with varying window sizes

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

Try this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM