【问题标题】:Error is breaking the for loop: conditional try statement?错误正在打破 for 循环:条件 try 语句?
【发布时间】:2019-12-17 20:52:43
【问题描述】:

我在 R 中有一个 for 循环:

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

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

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

`

try() 是否适合此目的?

【问题讨论】:

    标签: r error-handling try-catch


    【解决方案1】:

    我不知道任何 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 次,但你必须修正语法。推荐其他答案。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多