data.table - R: RunningTotal in the last 365 days window by Name -


this data looks like. rightmost column desired column.

name  eventtype  eventdate  salesamount runningtotal runningtotal(prior365days) john    email      1/1/2014      0          0            0 john    sale       2/1/2014     10          10           10 john    sale       7/1/2014     20          30           30 john    sale       4/1/2015     30          60           50  john    webinar    5/1/2015      0          60           50 tom     email      1/1/2014      0          0            0 tom     sale       2/1/2014     15          15           15 tom     sale       7/1/2014     10          25           25 tom     sale       4/1/2015     25          50           35  tom     webinar    5/1/2015      0          50           35 

i trying running total of salesamount each name in last 365 days window. general "runningtotal" column used:

df<- df%>%    group_by (name)%>%     mutate(runningtotal = cumsum(salesamount)) 

but dont know how running total in last 365 day window.kindly help. sincerely appreciated!

df$eventdate <- as.date(df$eventdate, format="%d/%m/%y") df <- df %>%    group_by (name) %>%    arrange(eventdate) %>%     mutate(day = eventdate - eventdate[1])  f <- vectorize(function(i)     sum(df[df$name[i] == df$name & df$day[i] - df$day >= 0 &               df$day[i] - df$day <= 365, "salesamount"]), vec="i") df$runningtotal365 <- f(1:nrow(df)) 

Comments

Popular posts from this blog

Java 3D LWJGL collision -

spring - SubProtocolWebSocketHandler - No handlers -

methods - python can't use function in submodule -