【问题标题】:How to use trycatch to skip errors and move on to next in the list如何使用 trycatch 跳过错误并转到列表中的下一个
【发布时间】:2019-10-29 15:40:06
【问题描述】:

我想从 rtf 文件中的文件夹中解析 rtf 文件,该文件夹在 lapply 步骤期间导致错误。

我刚开始使用trycatch,那么如何将它合并到我的代码中(lapply 步骤)以忽略错误并继续解析下一个 rtf 文件?

【问题讨论】:

    标签: r text-mining


    【解决方案1】:

    这对你有用吗?

    yourFunction <- function(x) {
      rtf <- read_rtf(x, verbose = FALSE, row_start = "*| ", row_end = "",
                      cell_end = " | ", ignore_tables = FALSE, check_file = TRUE)
    
      text <- unlist(strsplit(rtf, "\\."))
    
      toMatch <- c("bitcoin", "fund")
      matches <- unique(grep(paste(toMatch,collapse="|"), 
                             text, value=TRUE))
      matches <- data.frame(matches)
    }
    
    results = lapply(files, function(x){
      tryCatch(yourFunction(x), 
               error = function(e)print(paste(x, 'did not want')), 
               finally = 0)})
    

    【讨论】:

    • 它显示错误'''错误值[[3L]](cond):尝试应用非功能'''
    • 哦,是的,我忘记了function(e)-部分。现在应该可以工作了。
    • 由于tryCatch-help-page 有点没用,你可以看看this,它解释得比我自己做的更好。
    【解决方案2】:

    这是怎么回事?

    foo <- function(x) tryCatch(yourFunction(x), error = function(e) e)
    lapply(files, foo)
    

    【讨论】:

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