There is a filter function in the R database. It is not as friendly and generally as zoo::rollapply , but it is very fast. In your case, you want to apply a convolution filter with weights c(1, 1) :
itersum <- function(x, n = 2) tail(filter(x, rep(1, n)), sides = 1), -(n-1)) itersum(x) # 3 3 4 14 18 12
To give you more ideas, here's how the diff and cumsum can be rewritten in terms of filter :
diff <- function(x) head(filter(x, c(1, -1)), -1) cumsum <- function(x) filter(x, 1, method = "recursive")
In general, if you want to drill a binary function, then head and tail are probably the easiest and fastest way, since it will use vectorized functions:
itersum <- function(x) tail(x, -1) + head(x, -1) diff <- function(x) tail(x, -1) - head(x, -1) sign.change <- function(x) tail(sign(x), -1) != head(sign(x), -1)
source share