R语言for循环中dataRetrieval拉取USGS水温数据遇报错时跳过无数据站点的方法
问题根因
你遇到的missing value where TRUE/FALSE needed报错,本质是当循环遍历到无符合条件站点的州/属地时,后续步骤返回的空/空值对象触发了R的逻辑判断校验异常,并非dataRetrieval包本身的接口问题。完全可以通过next语句配合空值校验实现自动跳过无站点地区的需求,无需手动筛选移除无数据的州/属地。
优化后可直接运行的代码
library(dataRetrieval) library(dplyr) library(lubridate) statCd <- "00003" # 日均均值统计码 startDate <- "1990-01-01" endDate <- "2019-12-31" states <- stateCd[,2] # 提取全量州/属地缩写列表,无需手动筛选 saveDat_temp <- data.frame() # 提前初始化空结果框,替代循环内的首次分支判断 for(i in seq_along(states)) { cur_state <- states[i] # 拉取当前州的水温观测元数据,增加容错避免接口临时报错中断 tempDat_states = tryCatch( whatNWISdata(stateCd = cur_state, parameterCd = "00010"), error = function(e) NULL ) # 接口无返回/空返回时直接跳过 if(is.null(tempDat_states) || nrow(tempDat_states) == 0) next # 筛选日均水温观测记录 temp_states = tempDat_states %>% filter(stat_cd == statCd) %>% mutate(period = as.Date(endDate) - as.Date(startDate)) # 无日均水温观测记录时直接跳过 if(is.null(temp_states) || nrow(temp_states) == 0) next # 计算观测年份范围,筛选完全覆盖目标时段的站点 temp_states$end_year <- year(temp_states$end_date) temp_states$start_year <- year(temp_states$begin_date) temp_states <- temp_states[temp_states$start_year <= year(startDate) & temp_states$end_year >= year(endDate),] # 无符合时段要求的站点时直接跳过 if(is.null(temp_states) || nrow(temp_states) == 0) next # 追加州缩写列,合并到最终结果集 temp_states$STUSAB = cur_state saveDat_temp = rbind(saveDat_temp, temp_states) }
关键调整说明
- 在每一步可能返回空值的节点增加校验,当结果为空/空值时直接执行
next跳过后续合并操作,从根源上避免空对象触发的逻辑判断报错 - 增加
tryCatch容错,避免接口临时超时、报错导致整个循环中断 - 提前初始化空结果数据框,替代原循环中
i == 1的分支判断逻辑,减少分支判断的出错概率 - 将硬编码的年份判断替换为与全局定义的
startDate、endDate联动的计算,避免全局参数修改后代码不同步 - 直接提取
stateCd中的全量州/属地缩写列,完全省去手动索引、删除无数据州的冗余操作
内容的提问来源于stack exchange,提问作者tassones
相关产品推荐
相关产品推荐

