Compute rolling sum by id variables, with missing timepoints

后端 未结 4 1943
终归单人心
终归单人心 2020-12-14 03:50

I\'m trying to learn R and there are a few things I\'ve done for 10+ years in SAS that I cannot quite figure out the best way to do in R. Take this data:

 id         


        
4条回答
  •  半阙折子戏
    2020-12-14 04:21

    With runner package one can calculate everything on rolling windows. Below example of using sum_run

    library(runner)
    df %>%
      group_by(id) %>%
      mutate(
        output = sum_run(count, k = 30*4, idx = t)   
      )
    
    #             
    #     1 A     2010-01-15     1       1      1
    #     1 A     2010-02-15     2       3      3
    #     1 B     2010-04-15     3       3      6
    #     1 B     2010-09-15     4       4      4
    #     2 A     2010-01-15     5       5      5
    #     2 B     2010-06-15     6       6      6
    #     2 B     2010-08-15     7      13     13
    #     2 B     2010-09-15     8      21     21
    

提交回复
热议问题