首页 > 解决方案 > 错误正在打破 for 循环:条件 try 语句?

问题描述

我在 R 中有一个 for 循环:

for i in seq(1 , nrow(df)){
  try(function(i),silent=T)
}

我想对此进行修改,以便如果出现错误消息,该函数会再重复一次 for 循环。如果再次失败——

message(paste("function failed twice for", i))

`

try() 是用于此目的的正确功能吗?

标签: rerror-handlingtry-catch

解决方案


我不知道任何 R 但我的猜测是你可以做这样的事情:

errorCount = 0
for i in seq(1 , nrow(df)){
  tryCatch(function(i),silent=T, 
          error = {errorCount +=1,
          tryCatch(function(i), silent=T, 
                   error = {errorCount +=1
                            print("2 times error")
                            tryCatch(function(i), silent=T, 
                            error = {errorCount +=1
                            tryCatch(function(i), silent=T, 
                            error = {print("3 times error: Did not repeat")
                                     break})
                            } )
                   })
          )
}

对不起我糟糕的代码 - 我按照你的要求让它发生了 3 次,但你必须修复语法。推荐其他答案。


推荐阅读