gpt4 book ai didi

r - 计算 R data.table 中前 3 行的总和(通过 grid-square)

转载 作者:行者123 更新时间:2023-12-03 15:05:14 25 4
gpt4 key购买 nike

我想计算每个网格方块在过去三天内下降的降雨量,并将其添加为我的 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))

如果您有任何见解或建议,我将不胜感激。

非常感谢!

最佳答案

这是使用最新 data.table 的快速有效的解决方案版本 (v 1.9.6+)

weather[, rain_3 := Reduce(`+`, shift(rain, 0:2)), by = square]
weather
# 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

这里的基本思想是 shift rain列两次,然后总结行。

关于r - 计算 R data.table 中前 3 行的总和(通过 grid-square),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32649913/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com