cálculo de la suma de las 3 filas anteriores en R data.table (por cuadrícula)
Me gustaría calcular la lluvia que ha caído en los últimos tres días para cada cuadrícula y agregar esto como una nueva columna en mi tabla de datos. Para ser claros, quiero resumir los dos (2) días de lluvia actuales y ANTERIORES, por cada cuadrado de la cuadrícula 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
Mi intento de responder: esta línea solía funcionar, pero ya no funciona
weather[, rain_3 := filter(rain, rep(1, 2), sides = 1), by = list(square)]
Así que aquí estoy probando otro 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))
Agradecería mucho cualquier idea o sugerencia que pueda tener.
¡Muchas gracias!