Looking to calculate a rolling sum of counts in R. I reviewed this SO thread :
and others.
library(tidyverse)
library(RcppRoll)
client <- c('a','a','b','b','c','c')
count <- c(1,2,3,5,6,4)
date <- c('2018-01-31','2018-02-28','2018-01-31','2018-02-28','2018-01-
31','2018-02-28')
df <- data.frame(client, count, date)
rolling<- df %>%
arrange(client, date) %>%
group_by(client, date ) %>%
mutate(roll_sum = rollapplyr(count, 12, sum, partial=T))
Can someone point out what I am doing wrong so I can correct this? The roll_sum in this example is only equal to the original count. I would like to create a rolling sum of the groups.
Updating to show sample with more than 12 months of data:
library(tidyverse)
library(RcppRoll)
client <- c('a')
count <- c(1,2,3,5,6,4,4,8,6,9,10,12,13)
date <- c('2018-01-31','2018-02-28','2018-03-31','2018-04-30','2018-05-
31','2018-06-30', '2018-07-31','2018-08-31','2018-09-30','2018-10-31','2018-
11-30','2018-12-31', '2019-01-31')
df <- data.frame(client, count, date)
rolling<- df %>%
arrange(client, date) %>%
group_by(client) %>%
mutate(roll_sum = rollapplyr(count, 12, sum, partial=T))
Updated to show desired output:
Client Period Count 12 Month Rolling Sum
a 2018-01-31 1 1
a 2018-02-28 2 3
a 2018-03-31 3 6
a 2018-04-30 4 10
a 2018-05-31 5 15
a 2018-06-30 6 21
a 2018-07-31 7 28
a 2018-08-31 8 36
a 2018-09-30 9 45
a 2018-10-31 10 55
a 2018-11-30 11 66
a 2018-12-31 12 78
a 2019-01-31 5 82
Note the row for 2019-01-31 starts a new 12 month period. Each month after should also Thanks in advance