R: RunningTotal in the last 365 days window by Name

前端 未结 1 1787
春和景丽
春和景丽 2021-01-15 20:33

This is what my data looks like. The rightmost column is my Desired Column.

Name  EventType  EventDate  SalesAmount RunningTotal Runningtotal(prior365Days)
J         


        
相关标签:
1条回答
  • 2021-01-15 21:23
    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))
    
    0 讨论(0)
提交回复
热议问题