重复循环,直到找不到错误

use*_*076 1 r

我有一个执行一系列操作的循环.

在某些情况下,没有解决问题的方法,因此代码会返回错误.

如果我继续重新运行循环,最终它会找到一个没有错误执行的解决方案.

我想将循环嵌入到一个while()重复循环的语句中,直到程序没有返回任何错误或警告.

我不想抓住错误.相反,我想重复尝试,直到没有错误.

如何才能做到这一点?

这是一个小例子:

a<-matrix(NA,ncol=1,nrow=sample(1:5,1))
a[sample(1:5,1),1]<-10
Run Code Online (Sandbox Code Playgroud)

在这里有时这可以做到有时它不能.当然这是一个非常玩具的例子,但重点是我想重复这两行代码直到没有错误.

Ser*_*asa 5

tryCatch是你的朋友:

for (i in 1:10) {
  tryCatch({
    print(i)
    if (i==7) stop("Urgh, the iphone is in the blender !")
  }, error=function(e){cat("ERROR :",conditionMessage(e), "\n")})
}

[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
[1] 6
[1] 7
ERROR : Urgh, the iphone is in the blender ! 
[1] 8
[1] 9
[1] 10
Run Code Online (Sandbox Code Playgroud)

显然,你可能想用一段时间而不是for.

  • 谢谢你的帮助.错误消息由程序提供.如何在tryCatch中添加?你有一个if(i == 7),但就我而言,它应该是'if error' (2认同)