This is what my data frame looks like:
library(data.table)
df <- fread(\'
Name EventType Date SalesAmount RunningTotal Runningt
Here's an approach using foverlaps function from data.table package:
require(data.table)
setDT(df)[, end := as.Date(EventDate, format="%d/%m/%Y")
][, start := end - 365L]
setkey(df, Name, start, end)
olaps = foverlaps(df, df, nomatch=0L, which=TRUE)
olaps = olaps[xid >= yid, .(ans = sum(dt$SalesAmount[yid])), by=xid]
df[olaps$xid, Runningtotal := olaps$ans]
You can remove the start and end columns, if necessary, by doing:
df[, c("start", "end") := NULL]
Would be nice to know how fast/slow it is..