rrolling-computationsliding-windowrolling-sum

Sum values in a rolling/sliding window


I have the following vector:

x = c(1, 2, 3, 10, 20, 30)

At each index, 3 consecutive elements are summed, resulting in the following vector:

c(6, 15, 33, 60)

Thus, first element is 1 + 2 + 3 = 6, the second element is 2 + 3 + 10 = 15, et.c


Solution

  • What you have is a vector, not an array. You can use rollapply function from zoo package to get what you need.

    > x <- c(1, 2, 3, 10, 20, 30)
    > #library(zoo)
    > rollapply(x, 3, sum)
    [1]  6 15 33 60
    

    Take a look at ?rollapply for further details on what rollapply does and how to use it.