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

ed0*_*die 5 iteration error-handling for-loop r try-catch

我正在寻找一种简单的方法,如果 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) : no loop for break/next, jumping to top level 
Run Code Online (Sandbox Code Playgroud)

有人可以帮我理解如何使用 R 中的 for 循环来实现这一点吗?

jak*_*kub 1

正如 Dason 指出的,原子向量实际上并不是存储混合数据类型的最佳方式。列表就是为此而设的。考虑以下:

l = list(1, "sunflower", 3)

for(i in seq_along(l)) {
   this.e = l[[i]]
   test <- try(this.e + 1, silent=TRUE)
   calc <- if(class(test) %in% 'try-error') {next} else {this.e + 1}
   print(calc)
}

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

换句话说,你的前一个循环“有效”。它总是失败并进入下一次迭代。