Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate rolling difference in R

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
like image 932
ajax2000 Avatar asked Feb 10 '18 20:02

ajax2000


1 Answers

You could use lag from dplyr as follows

df$Diff <- df$Count - dplyr::lag(df$Count, n = 5)
like image 51
markus Avatar answered Sep 22 '22 17:09

markus