【问题标题】:How to return the index causing an error in R如何返回导致R中错误的索引
【发布时间】:2021-06-20 20:15:11
【问题描述】:

我正在处理一个循环,我想提取在 R 中导致错误的索引并将其放入一个单独的对象中。

这是一个从堆栈溢出帖子中的answer 修改的示例。它会跳过并报告错误的性质。

for (i in 1:15) {
  tryCatch({
    print(i)
    if (i==7) stop("Urgh, the iphone is in the blender !")
    if (i==9) stop("Urgh, the iphone is in the blender !")
    if (i==14) stop("Urgh, the iphone is in the blender !")

  }, error=function(e){cat("ERROR :",conditionMessage(e), "\n")})
}

除了跳过和报告错误之外,我如何改进这段代码以创建一个单独的对象,其中包含导致错误的索引?这样,它就会创建一个对象 Index Error,其中包含 7、9 和 14。

谢谢!

【问题讨论】:

    标签: r loops error-handling try-catch


    【解决方案1】:

    您可以尝试使用<<- 运算符来保存错误的索引。

    var <- c()
    for (i in 1:15) {
      tryCatch({
        print(i)
        if (i==7) stop("Urgh, the iphone is in the blender !")
        if (i==9) stop("Urgh, the iphone is in the blender !")
        if (i==14) stop("Urgh, the iphone is in the blender !")
        
      }, error=function(e){
        cat("ERROR :",conditionMessage(e), "\n")
        var <<- c(var, i)
        })
    }
    
    var
    #[1]  7  9 14
    

    【讨论】:

    • 哇,这真的很酷!不知道&lt;&lt;- 是一种可能性。我必须阅读它!谢谢!
    【解决方案2】:

    这里有两种方法,都带有lapply循环,只是错误函数返回的内容不同。
    错误消息显示为message,而不是cat。这是因为在包中使用catprint 是不受欢迎的。

    1。返回索引i

    result <- lapply(1:15, function(i) {
      tryCatch({
        print(i)
        if (i==7) stop("Urgh, the iphone is in the blender !")
        if (i==9) stop("Urgh, the iphone is in the blender !")
        if (i==14) stop("Urgh, the iphone is in the blender !")
        
      }, error=function(e){
        msg <- paste("ERROR :", conditionMessage(e))
        message(msg)
        i
      })
    })
    #[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
    #ERROR : Urgh, the iphone is in the blender !
    #[1] 10
    #[1] 11
    #[1] 12
    #[1] 13
    #[1] 14
    #ERROR : Urgh, the iphone is in the blender !
    #[1] 15
    
    unlist(result)
    #[1]  7  9 14
    

    2。返回错误e

    此解决方案返回错误本身,以后可以检索该错误。 message 的输出被省略。

    result <- lapply(1:15, function(i) {
      tryCatch({
        print(i)
        if (i==7) stop("Urgh, the iphone is in the blender !")
        if (i==9) stop("Urgh, the iphone is in the blender !")
        if (i==14) stop("Urgh, the iphone is in the blender !")
        
      }, error=function(e){
        msg <- paste("ERROR :", conditionMessage(e))
        message(msg)
        e
      })
    })
    
    err <- which(sapply(result, inherits, "error"))
    err
    #[1]  7  9 14
    
    result[[14]]$message
    #[1] "Urgh, the iphone is in the blender !"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-06-18
      • 1970-01-01
      • 1970-01-01
      • 2019-12-27
      • 2015-11-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多