The diff function in R returns suitably lagged and iterated differences.
x = c(1, 2, 1, 3, 11, 7, 5)
diff(x)
# [1] 1 -1 2 8 -4 -2
diff(x, lag=2)
[1] 0 1 10 4 -6
Is there anyway to customize this so that we can use functions other than difference? For example, sum:
itersum(x)
# 3 3 4 14 18 12
You can use
zoo::rollapply
For the record, I asked this question to figure out how to register sign changes in a vector of numbers, thanks to @dickoa 's answer, I got it done this way:
In base R, there is the
filter
function. It is not as friendly and general aszoo::rollapply
but it is extremely fast. In your case, you are looking to apply a convolution filter with weightsc(1, 1)
:To give you more ideas, here is how the
diff
andcumsum
functions can be re-written in terms offilter
:In general, if you are looking to roll a binary function, then
head
andtail
is probably the easiest and fastest way to go as it will take advantage of vectorized functions: