Consecutive/Rolling sums in a vector in R

user2834313 picture user2834313 · Oct 5, 2013 · Viewed 29.8k times · Source

Suppose in R I have the following vector :

[1 2 3 10 20 30]

How do I perform an operation whereby at each index 3 consecutive elements are summed, resulting in the following vector :

[6 15 33 60]

where the first element = 1+2+3, the second element = 2+3+10 etc...? Thanks

Answer

Jilber Urbina picture Jilber Urbina · Oct 5, 2013

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.