小编ed0*_*die的帖子

如果错误,则在 R 中的 for 循环中进行下一次迭代

我正在寻找一种简单的方法,如果 for 循环内的操作出错,则继续进行 R 中 for 循环的下一次迭代。

我在下面重新创建了一个简单的案例:

for(i in c(1, 3)) {
  test <- try(i+1, silent=TRUE)
  calc <- if(class(test) %in% 'try-error') {next} else {i+1}
  print(calc)
}
Run Code Online (Sandbox Code Playgroud)

这正确地给出了以下计算值。

[1] 2
[1] 4
Run Code Online (Sandbox Code Playgroud)

但是,一旦我更改 i 中的向量以包含非数字值:

for(i in c(1, "a", 3)) {
  test <- try(i+1, silent=TRUE)
  calc <- if(class(test) %in% 'try-error') {next} else {i+1}
  print(calc)
}
Run Code Online (Sandbox Code Playgroud)

这个for循环不起作用。我希望得到与上面相同的计算值,向量不包括 i 中的非数字值。

我尝试使用 tryCatch 如下:

for(i in c(1, "a", 3)) {
  calc <- tryCatch({i+1}, error = function(e) {next})
  print(calc)
}
Run Code Online (Sandbox Code Playgroud)

但是,我收到以下错误:

Error in value[[3L]](cond) …
Run Code Online (Sandbox Code Playgroud)

iteration error-handling for-loop r try-catch

5
推荐指数
1
解决办法
8474
查看次数

标签 统计

error-handling ×1

for-loop ×1

iteration ×1

r ×1

try-catch ×1