r - if else 或条件语句在警告消息后更改 for 循环函数

标签 r event-handling

我正在运行一个 for 循环来在大型数据集中包装一个函数。这是一个渔业函数,对向量“ll”执行方程。矢量 ll 是 for 循环的关键,为每次迭代创建 ll 进行了大量的争论。我在这里包含了循环的重要部分。 mod<-removal(ll, method = "Burnham", Tmult = 5)

但是,为了使方程有效,向量中的数字必须是递减的。如果不是,该函数将运行,但会用 NA 填充结果(模型统计数据)。出于分析目的,如果发生这种情况,结果应该只是 1.5*sum(ll)。我想在这个循环中构建一个包装器语句,其本质上是说“如果发生此警告,则将 sum(ll) 乘以 1.5”,但我不知道如何在 R 中构建该条件。感谢任何帮助!

最佳答案

您可能想使用tryCatch()。使用此示例代码,其中 vectors 的第二个元素抛出警告:

vectors <- list(
  c(1, 2, 3),
  c(NA, NA, NA),
  c(7, 8, 9)
)

out <- numeric(length(vectors))
for (i in seq_along(vectors)) {
  out[[i]] <- max(vectors[[i]], na.rm = TRUE)
}
# Warning message:
# In max(vectors[[i]], na.rm = TRUE) :
#   no non-missing arguments to max; returning -Inf

out
# 3 -Inf    9

如果您想在发生警告时返回-99,您可以这样做:

for (i in seq_along(vectors)) {
  out[[i]] <- tryCatch(
    max(vectors[[i]], na.rm = TRUE),
    warning = \(w) -99
  )
}

out
# 3 -99    9

但是,仅处理特定警告会更安全:

for (i in seq_along(vectors)) {
  out[[i]] <- tryCatch(
    max(vectors[[i]], na.rm = TRUE),
    warning = \(w) {
      if (grepl("no non-missing arguments to max; returning -Inf", w$message)) {
        -99
      } else {
        max(vectors[[i]], na.rm = TRUE)
      }
    }
  )
}

out
# 3 -99    9

关于r - if else 或条件语句在警告消息后更改 for 循环函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75475429/

相关文章:

r - 如何使用传单在r中偏移折线

python - 如何将Python的日志输出重定向到Kivy标签?

c++ - 使用 Bind() 到 wxButton 的事件处理函数 - wxWidgets 3.0

javascript - 如何在 JavaScript 中编写鼠标按下事件?

python - 无法在 python jupyter 笔记本中使用 ggplot2

r - 确定 R 中连续数字的序列

r - term.formula(formula) : '.' in formula and no 'data' argument 中的错误

r - 将多组 jpg 图像组合成一个 jpg/png r

java - 使用 setOnAction 添加现有处理程序方法

javascript - 使用 Scriptaculous 拖放防止 JavaScript 单击事件