【发布时间】:2015-12-15 11:29:24
【问题描述】:
我想计算过去三天每个方格的降雨量,并将其作为新列添加到我的 data.table 中。为了清楚起见,我想总结每个气象网格方格当前和之前两 (2) 天的降雨量
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))
如果您有任何见解或建议,我将不胜感激。
非常感谢!
【问题讨论】:
标签: r filter data.table zoo