I am currently working R in data.table and am looking for an easy way to implement a rolling lag sum. I can find posts on lags and posts on various sum functions but haven't been successful finding one in which sum and lag are combined in the way I am looking to implement it (rolling back 3 days).
I have a data set that resembles the following-
id agedays diar
1 1 1
1 2 0
1 3 1
1 4 1
1 5 0
1 6 0
1 7 0
1 8 1
1 9 1
1 10 1
3 2 0
3 5 0
3 6 0
3 8 1
3 9 1
4 1 0
4 4 0
4 5 0
4 6 1
4 7 0
I want to create a variable "diar_prev3" that holds the rolling sum of diar for the past 3 days prior to the current agedays value. Diar_prev3 would be NA for the rows in which agedays < 4 The data set would look like the following :
id agedays diar diar_prev3
1 1 1 NA
1 2 0 NA
1 3 1 NA
1 4 1 2
1 5 0 2
1 6 0 2
1 7 0 1
1 8 1 0
1 9 1 1
1 10 1 2
3 2 0 NA
3 5 0 0
3 6 0 0
3 8 1 0
3 9 1 1
4 1 0 NA
4 4 0 0
4 5 0 0
4 6 1 0
4 7 0 1
I have tried a basic lag function, but am unsure how to implement this with a rolling sum function included. Does anyone have any functions they recommend using to accomplish this?
****Edited to fix an error with ID==2
zoo::rollsum
– Allan Cameronid
? How is value at row 6 2? – Ronak Shah