cálculo da soma das 3 linhas anteriores em R data.table (por quadrado da grade)

Gostaria de calcular a precipitação que caiu nos últimos três dias para cada quadrado da grade e adicioná-la como uma nova coluna em minha tabela de dados. Para ser claro, quero resumir os dois (2) dias atuais e ANTERIORES da precipitação, para cada quadrado da grade meterológica

library ( zoo )
library (data.table)


# making the data.table
rain           <- c(NA, NA, NA, 0, 0, 5, 1, 0, 3, 10)  # rainfall values to work with
square         <- c(1,1,1,1,1,1,1,1,1,2)               # the geographic grid square for the rainfall measurement
desired_result <- c(NA, NA, NA, NA, NA, 5, 6, 6, 4, NA )  # this is the result I'm looking for (the last NA as we are now on to the first day of the second grid square)
weather <- data.table(rain, square, desired_result)  # making the data.table

Minha tentativa de responder: essa linha costumava funcionar, mas não funciona mais

weather[, rain_3 := filter(rain, rep(1, 2), sides = 1), by = list(square)]  

Então, aqui estou tentando outro método:

# this next line gets the numbers right, but sums the following values, not the preceeding ones. 
weather$rain_3 <- rollapply(zoo(weather$rain), list(seq(-2,0)), sum)

# here I add in the by weather$ square, but still no success
weather$rain_3 <- rollapply(zoo(weather$rain), list(seq(-2,0)), sum, by= list(weather$square))

Eu apreciaria muito quaisquer idéias ou sugestões que você possa ter.

Muito Obrigado!

questionAnswers(5)

yourAnswerToTheQuestion