You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决R语言RunDS函数的'argument of length 0'错误

问题描述

使用drought包的RunDS()函数分析数据时,当所有z值均不低于设定阈值(示例中阈值thre=-0.8,所有数据的z都大于该值),程序触发错误:

Error in st[i]:ed[i] : argument of length 0

需求:无符合条件数据时,直接在结果列填充0。

示例代码与数据:

library(drought)
thre=-0.8
Res <- RunDS(z, thre)

# 对应数据
Month Year   z
1     2021  0.8
2     2021  1.2
3     2021  1.3
4     2021  1.4
5     2021  1.8
6     2021  2.1
7     2021  2.5
8     2021  2.9
9     2021  1.7
10    2021  1.5
11    2021  0.8
12    2021  0.5
解决方案

可以通过两种方式处理这个问题:

方式一:提前判断数据

先检查是否存在低于阈值的观测值,分支执行逻辑:

library(drought)
thre <- -0.8
# 替换your_data为你实际的数据框名称
your_data <- data.frame(
  Month = 1:12,
  Year = rep(2021,12),
  z = c(0.8,1.2,1.3,1.4,1.8,2.1,2.5,2.9,1.7,1.5,0.8,0.5)
)

has_drought <- any(your_data$z < thre)

if (has_drought) {
  Res <- RunDS(your_data$z, thre)
  # 合并原数据与结果,保持结构完整
  Res <- cbind(your_data[,c("Month","Year")], z=your_data$z, Res)
} else {
  # 生成全0结果列,匹配RunDS输出结构
  Res <- data.frame(
    Month = your_data$Month,
    Year = your_data$Year,
    z = your_data$z,
    # 根据RunDS实际输出列名调整,比如假设结果列是Drought_Severity
    Drought_Severity = rep(0, nrow(your_data))
  )
}

方式二:捕获错误处理

用tryCatch()捕获特定错误,触发时返回全0结果:

library(drought)
thre <- -0.8
your_data <- data.frame(
  Month = 1:12,
  Year = rep(2021,12),
  z = c(0.8,1.2,1.3,1.4,1.8,2.1,2.5,2.9,1.7,1.5,0.8,0.5)
)

Res <- tryCatch(
  {
    res_run <- RunDS(your_data$z, thre)
    cbind(your_data[,c("Month","Year")], z=your_data$z, res_run)
  },
  error = function(e) {
    if (grepl("argument of length 0", e$message)) {
      data.frame(
        Month = your_data$Month,
        Year = your_data$Year,
        z = your_data$z,
        Drought_Severity = rep(0, nrow(your_data))
      )
    } else {
      # 非目标错误则重新抛出
      stop(e)
    }
  }
)

注意:请根据RunDS()函数的实际输出列名,调整代码中结果列的名称(示例中用Drought_Severity作为占位),确保最终结果结构符合预期。

内容的提问来源于stack exchange,提问作者Sana

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 12:41:25