I'm trying to do a rolling difference in a dataset. I have a table like this:
Year Count
2017 5
2017 6
2017 7
2017 6
2017 8
And I would like to get a column for difference, which is calculated from the 5th row onward. So it will look like this
Index Count Diff
1 5 NA
2 6 NA
3 7 NA
4 6 NA
5 8 NA
6 3 -2
7 4 -2
8 9 2
9 2 -4
10 1 -7
Right now I just subset the count column and combine with zeros for the calculation. Is there a more tidy way of doing this?
Here's what I'm doing now:
a <- df$Count[1:5]
b <- rep(0,5)
df$Count1 <- c(b,a)
df$Diff <- df$Count - df$Count1
You could use lag
from dplyr
as follows
df$Diff <- df$Count - dplyr::lag(df$Count, n = 5)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With