Reputation: 193
I know how to take the lagged difference:
delX = diff(x)
But the only way I know to take the lagged sum is:
sumY = apply(embed(c(0,y),2),1, sum)
Is there a function that can take the lagged sum? This way (or sliding the index in some other fashion) is not very intuitive.
Upvotes: 0
Views: 1086
Reputation: 70266
Two more options:
x <- 1:10
x + dplyr::lag(x)
# [1] NA 3 5 7 9 11 13 15 17 19
x + data.table::shift(x)
# [1] NA 3 5 7 9 11 13 15 17 19
Note that you can easily change the number of lags in both functions. Instead of lagging, you can also create a leading vector by using dplyr::lead()
or data.table::shift(x, 1L, type = "lead")
. Both functions also allow you to specify default values (which are NA
by default).
Upvotes: 0
Reputation: 44614
You're looking for filter
:
x <- 1:10
filter(x, filter=c(1,1), sides=1)
# [1] NA 3 5 7 9 11 13 15 17 19
You could also use head
and tail
:
head(x, -1) + tail(x, -1)
# [1] 3 5 7 9 11 13 15 17 19
Upvotes: 3