Using apply in a 'window'

Viewed 799

Is there a way to use apply functions on 'windows' or 'ranges'? This example should serve to illustrate:

a <- 11:20

Now I want to calculate the sums of consecutive elements. i.e.

[11+12, 12+13, 13+14, ...]

The ways I can think of handling this are:

a <- 11:20
b <- NULL
for(i in 1:(length(a)-1))
{
    b <- c(b, a[i] + a[i+1])
}
# b is 23 25 27 29 31 33 35 37 39

or alternatively,

d <- sapply( 1:(length(a)-1) , function(i) a[i] + a[i+1] )
# d is 23 25 27 29 31 33 35 37 39

Is there a better way to do this? I'm hoping there's something like:

e <- windowapply( a, window=2, function(x) sum(x) )  # fictional function
# e should be 23 25 27 29 31 33 35 37 39
3 Answers
Related