Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Partial sum when using roll_sum

I use rolling_sum to create a 3-month rolling sum for one column. However, it creates NA for rows with now() <3 while I'd like to see partial sum there. There is a Partial argument in the documentation, but says it is not currently implemented!

Here is my data and what I'd like to see:

df =
id   date   variable   3_month_sum_current   3-month_sum_needed
1    1      1          NA                    1
1    2      0          NA                    1
1    3      2          3                     3
1    4      4          6                     6

my code:

library(RcppRoll)
library(dplyr)
df <- df %>%group_by(id) %>% arrange(date) %>%
      mutate(3_month_sum_current = 
             roll_sum(variable, 3, fill=NA, align= 'right', partial = TRUE)
like image 653
Ana Avatar asked Oct 20 '25 09:10

Ana


1 Answers

rollapplyr in the zoo package has a partial= argument.

like image 97
zx8754 Avatar answered Oct 22 '25 00:10

zx8754



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!