我想计算每个网格平方下降过去三天的降雨量,并将其作为新数据列添加到我的数据中。表。需要明确的是,我要总结降雨当前和以前的两(2)天,每个气象方格计算R data.table中前3行的总和(用网格平方)
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
我试图回答:这条线来工作,但不再做
weather[, rain_3 := filter(rain, rep(1, 2), sides = 1), by = list(square)]
所以在这里我想另一种方法:
# 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))
我将不胜感激任何见解,或者您可能有任何建议。
非常感谢!
你是当场就在于它是dplyr导致该问题。通过使用'detach(“package:dplyr”,unload = TRUE)'我的原始代码再次开始工作。我非常感谢你的洞察力。 – threeisles