Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using apply in a 'window'

Tags:

r

apply

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
like image 444
user2175594 Avatar asked Feb 15 '23 09:02

user2175594


1 Answers

Here's an anternative using rollapply from zoo package

> rollapply(a, width=2, FUN=sum )
[1] 23 25 27 29 31 33 35 37 39

zoo package also offers rollsum function

> rollsum(a, 2)
[1] 23 25 27 29 31 33 35 37 39
like image 146
Jilber Urbina Avatar answered Feb 27 '23 14:02

Jilber Urbina