R dataframe基于行关联列值匹配计算洪水事件持续时长技术咨询
R计算DataFrame中洪水事件持续时长解决方案
完整实现代码
library(tidyverse) library(lubridate) FloodingDuration <- TempData %>% # 按分组筛选整小时观测数据 group_by(NestID, Nest, Year) %>% filter(minute(Datetime) == 0) %>% # 计算逐小时温度差,标记洪水事件 mutate( TempDrop = Temp - lag(Temp, n = 1, default = first(Temp)), Flooded = TempDrop < -0.45 ) %>% group_by(NestID) %>% # 为独立洪水事件分配ID,避免连续Flooded标记被判定为多事件 mutate( flood_event_id = cumsum(Flooded & !lag(Flooded, default = FALSE)) ) %>% # 提取洪水事件上一行的时间、温度作为参考值,同事件内向下填充 group_by(NestID, flood_event_id) %>% mutate( From = if_else(flood_event_id > 0, lag(Datetime)[Flooded][1], NA_POSIXct_), ref_temp = if_else(flood_event_id > 0, lag(Temp)[Flooded][1], NA_real_) ) %>% # 筛选存在洪水事件的记录,匹配首个温度回升到参考值以上的时间 filter(flood_event_id > 0) %>% summarise( From = first(From), To = first(Datetime[Temp >= ref_temp], na_rm = TRUE), .groups = "drop" ) %>% # 计算事件持续时长,单位为天 mutate( Duration = as.numeric(difftime(To, From, units = "days")) ) %>% # 聚合得到每个NestID的最大洪水时长 group_by(NestID) %>% summarise( MaxDuration = max(Duration, na_rm = TRUE), .groups = "drop" )
关键逻辑说明
- 用
flood_event_id标记独立洪水事件,避免连续多行Flooded==TRUE被误判为多个独立事件 - 每个事件取首次
Flooded==TRUE行的上一行时间作为From,对应温度作为回升参考值 - 每个事件范围内匹配首个温度大于等于参考值的时间作为
To - 若存在温度未回到参考值的异常情况,可按需补充逻辑,比如将
To替换为该NestID的最大观测时间
内容的提问来源于stack exchange,提问作者bex
相关产品推荐
相关产品推荐

