【问题标题】:Using tryCatch to skip execution upon error without exiting lapply()使用 tryCatch 在错误时跳过执行而不退出 lapply()
【发布时间】:2019-03-01 07:36:31
【问题描述】:

我正在尝试编写一个清理电子表格的函数。但是,某些电子表格已损坏,无法打开。我希望函数能够识别这一点,打印一条错误消息,并跳过函数其余部分的执行(因为我使用lapply() 来遍历文件),然后继续。我当前的尝试如下所示:

candidate.cleaner <- function(filename){

  #this function cleans candidate data spreadsheets into an R dataframe

  #dependency check
  library(readxl)

  #read in

    cand_df <-  tryCatch(read_xls(filename, col_names = F),
    error = function (e){
            warning(paste(filename, "cannot be opened; corrupted or does not exist"))
    })
  print(filename)

  #rest of function

  cand_df[1,1]

}

test_vec <- c("test.xls", "test2.xls", "test3.xls")
lapply(FUN = candidate.cleaner, X = test_vec)

但是,当给定一个不存在的 .xls 文件时,这仍然会在 tryCatch 语句之后执行函数行,这会引发停止,因为我试图索引一个不存在的数据帧。这将退出 lapply 调用。如何编写tryCatch 调用以使其跳过函数其余部分的执行而不退出lapply

【问题讨论】:

  • 一种选择可能是改用try,这将返回一个您可以检查的值,然后将您的代码分支。 purrr 中存在类似的东西,safely
  • 成功了,谢谢!

标签: r error-handling try-catch lapply


【解决方案1】:

可以在tryCatch() 的开头设置一个信号量,表示到目前为止一切正常,然后处理错误并发出错误信号,最后检查信号量并使用适当的函数从函数返回价值。

lapply(1:5, function(i) {
    value <- tryCatch({
        OK <- TRUE
        if (i == 2)
            stop("stopping...")
        i
    }, error = function(e) {
        warning("oops: ", conditionMessage(e))
        OK <<- FALSE                    # assign in parent environment
    }, finally = {
        ## return NA on error
        OK || return(NA)
    })
    ## proceed
    value * value
})

这允许人们继续使用tryCatch() 基础架构,例如,将警告转换为错误。 tryCatch() 块封装了所有相关代码。

【讨论】:

    【解决方案2】:

    事实证明,这可以通过try() 和附加帮助功能以简单的方式完成。

    candidate.cleaner <- function(filename){
    
      #this function cleans candidate data spreadsheets into an R dataframe
    
      #dependency check
      library(readxl)
    
      #read in
      cand_df <- try(read_xls(filename, col_names = F))
      if(is.error(cand_df) == T){
      return(list("Corrupted: rescrape", filename))
      } else {
      #storing election name for later matching
      election_name <- cand_df[1,1]
    }
    }
    

    is.error() 取自 Hadley Wickham 的 Advanced R chapter on debugging。定义为:

    is.error <- function(x) inherits(x, "try-error")
    

    【讨论】:

      猜你喜欢
      • 2017-02-06
      • 1970-01-01
      • 2017-02-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-03
      • 2015-08-20
      • 2011-12-26
      相关资源
      最近更新 更多