计算 R data.table 中前 3 行的总和(按方格) [英] calculating sum of previous 3 rows in R data.table (by grid-square)
问题描述
我想计算过去三天每个方格的降雨量,并将其作为新列添加到我的 data.table 中.为了清楚起见,我想总结当前和之前两 (2) 天的降雨量,对于每个气象网格方格
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 sum up the current and PREVIOUS two (2) days of rainfall, for each meterological grid square
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
我的回答是:这条线曾经有效,但不再有效
My attempt to answer: this line used to work, but no longer does
weather[, rain_3 := filter(rain, rep(1, 2), sides = 1), by = list(square)]
所以我在这里尝试另一种方法:
So here I am trying another method:
# 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))
如果您有任何见解或建议,我将不胜感激.
I would greatly appreciate any insights or suggestions you may have.
非常感谢!
推荐答案
weather[, rain_3 := filter(rain, rep(1, 3), sides = 1), by = list(square)]
#Error in filter(rain, rep(1, 3), sides = 1) :
# 'filter' is longer than time series
weather[, rain_3 := if(.N > 2) filter(rain, rep(1, 3), sides = 1) else NA_real_,
by = square]
# rain square desired_result rain_3
# 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
注意不要加载 dplyr,因为它掩盖了 filter
.如果需要 dplyr,可以显式调用 stats::filter
.
Take care that dplyr is not loaded because it masks filter
. If you need dplyr, you can call stats::filter
explicitly.
这篇关于计算 R data.table 中前 3 行的总和(按方格)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!