R dplyr rolling sum

后端 未结 3 776
青春惊慌失措
青春惊慌失措 2020-11-27 06:12

i am implementing a rolling sum calculation through dplyr, but in my database i have a number of variables that have only one or only a few observations, causing an (k is sm

3条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-27 06:27

    You can instead use RcppRoll::roll_sum which returns NA if the sample size(n) is less than the window size(k).

    set.seed(1)
    dg$count = rpois(dim(dg)[1], 5) 
    library(RcppRoll)
    library(dplyr)
    dg %>%
         arrange(site,year,animal) %>%
         group_by(site, animal) %>%
         mutate(roll_sum = roll_sum(count, 2, align = "right", fill = NA))    
    #       site year animal count roll_sum
    #1    Boston 2000    dog     4       NA
    #2    Boston 2001    dog     5        9
    #3    Boston 2002    dog     3        8
    #4    Boston 2003    dog     9       12
    #5    Boston 2004    dog     6       15
    #6  New York 2000    dog     4       NA
    #7  New York 2001    dog     8       12
    #8  New York 2002    dog     8       16
    #9  New York 2003    dog     6       14
    #10 New York 2004    cat     2       NA
    

提交回复
热议问题