gpt4 book ai didi

r - 使用 data.table 汇总每月序列(统计特定事件)

转载 作者:行者123 更新时间:2023-12-01 08:13:47 24 4
gpt4 key购买 nike

我希望这是一个可以接受的 R/data.table 问题。

我有一个 3 列表:

  • id 地理位置 ID(303,453 个位置)
  • 25 年 1990-2014 月
  • spei 一个介于 -7 和 7 之间的气候指数。

我需要统计整个 1990-2014 年期间每个地点发生的干旱情况。干旱事件被定义为“SPEI 持续为负且 SPEI 达到 -1.0 或更小值的时期。当 SPEI 首次低于零时干旱开始,并以第一个正 SPEI 值结束-1.0 或更小的值"。

我知道使用 shift() 和滚动连接这应该是可行的,但非常欢迎一些帮助!

# Sample table structure
dt <- data.table(
id = rep(1:303453, each=25*12),
month = rep(seq(as.Date("1990-01-01"), as.Date("2014-12-31"), "month"), 303453),
spei = runif(303453*25*12, -7, 7))

# A minimal example with 1 location over 12 months
library(data.table)
library(xts)

dt <- data.table(
id = rep("loc1", each=12),
month = seq(as.Date("2014-01-01"), as.Date("2014-12-31"), "month"),
spei = c(-2, -1.1, -0.5, 1.2, -1.2, 2.3, -1.7, -2.1, 0.9, 1.2, -0.9, -0.2))

spei.ts <- xts(dt$spei, order.by=dt$month, frequency="month")
plot(spei.ts, type="bars")

enter image description here

这显示了 1 年期间的 3 次干旱事件。这就是我需要识别和统计的。

希望你们中的一些人更习惯于使用时间序列。非常感谢,--Mel。

最佳答案

这是获得您想要的结果的起点。专家可能会建议提高速度。

编辑:通过删除 paste 提高了约 8 倍的速度。

library(data.table)
set.seed(42)
n <- 300 # 303453 will be ~1000 times slower
dt <- data.table(
id = rep(1:n, each=25*12),
month = rep(seq(as.Date("1990-01-01"), as.Date("2014-12-31"), "month"), n),
spei = runif(n*25*12, -7, 7))

system.time({
dt[, `:=`(neg = (spei < 0), neg1 = (spei <= -1))]
dt[, runid := ifelse(neg, rleid(neg), NA)]
res <- dt[!is.na(runid),
.(length = .N[any(neg1)], start = min(month), end = max(month)),
by = .(id, runid)][!is.na(length)]

})
# user system elapsed
# 0.345 0.000 0.344

# counts of droughts per id:
res[, .(nDroughts = .N), by = id]

# list of droughts per id: (NB: don't include 1st positive value after)
res[, .(droughtN = seq_len(.N), start, end), by = id]

关于r - 使用 data.table 汇总每月序列(统计特定事件),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38890034/

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