calculating sum of previous 3 rows in R data.table (by grid-square)

前端 未结 6 1455
一生所求
一生所求 2020-12-03 23:32

I would like to calculate the rainfall that has fallen over the last three days for each grid square, and add this as a new column in my data.table. To be clear, I want to s

6条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-04 00:19

    A dplyr solution:

    library(dplyr)
    weather %>% 
      group_by(square) %>% 
      mutate(rain_3 = rain + lag(rain) + lag(rain, n = 2L))
    

    Result:

    Source: local data table [10 x 4]
    
        rain square desired_result rain_3
       (dbl)  (dbl)          (dbl) (dbl)
    1     NA      1             NA    NA
    2     NA      1             NA    NA
    3     NA      1             NA    NA
    4      0      1             NA    NA
    5      0      1             NA    NA
    6      5      1              5     5
    7      1      1              6     6
    8      0      1              6     6
    9      3      1              4     4
    10    10      2             NA    NA
    

    If you want to assign rain3 to your dataset, you can use the %<>% symbol from maggritr in your pipe:

    library(magrittr)
    weather %<>%
      group_by......
    

提交回复
热议问题