Partly related to this question and this one , I am having problems calculating the moving amount. Unlike these questions, I would like to try using zoo:rollsumas a similar rollapplyanswer here . (But if there is a way data.tableto do this, by all means.)
Let's start with some data:
set.seed(123)
some_dates <- function(){as.Date('1980-01-01') + sort(sample.int(1e4,100))}
d <- data.table(cust_id = c(rep(123,100),rep(456,100)),
purch_dt = c(some_dates(), some_dates()),
purch_amt = round(runif(200, 1, 100),2) )
head(d)
I would like to make a rolling 365-day purchase amount for each customer, calculated for each day of the transaction.
The answer here suggests the following approach:
First, create dummy strings for all pairs of client data using cross-connect, for example:
setkey(d, cust_id, purch_dt)
dummy <- d[ CJ(unique(cust_id), seq(min(purch_dt), max(purch_dt), by='day') ) ]
, ( , min/max customer_dt).
, rollsumr 365- .
:
dummy[, purch_365 := rollsumr(x=purch_amt, k=365, na.rm=TRUE) , by=cust_id]
purch_365 NA :
Warning messages:
1: In `[.data.table`(dummy, , `:=`(purch_365, rollsumr(x = purch_amt, :
Supplied 9550 items to be assigned to group 1 of size 9914 in column 'purch_365' (recycled leaving remainder of 364 items).
, 364 = k-1 2 2 cust_id s. , .
# Desired output:
# cust_id purch_dt purch_amt purch_365
# 1: 123 1980-01-08 24.63 24.63
# 2: 123 1980-09-03 96.27 120.90
# 3: 123 1981-02-24 60.54 156.81
!