Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to calculate the roll sum without summing the current date?

I have a dataframe:

var 1 Day
0 1
0 2
1 3
1 4
1 5
1 6
0 7
0 8

I would like to calculate k-days rollsum without accounting for the current day.
For example,

3-days rollsum will be calculated as below:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

var 1 Day sum
0 1 NA
0 2 NA
1 3 NA
1 4 1
1 5 2
1 6 3
0 7 3
0 8 2

>Solution :

You may use any of the rolling function with k = 3 and lag the result by 1 step.

library(dplyr)
library(zoo)

k <- 3

df %>% mutate(sum = lag(rollsumr(var1, k, fill = NA)))

#  var1 Day sum
#1    0   1  NA
#2    0   2  NA
#3    1   3  NA
#4    1   4   1
#5    1   5   2
#6    1   6   3
#7    0   7   3
#8    0   8   2

data

df <- structure(list(var1 = c(0L, 0L, 1L, 1L, 1L, 1L, 0L, 0L), Day = 1:8), 
row.names = c(NA, -8L), class = "data.frame")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading