2

I want to parse rtf files from a folder in the rtf files that resulted in errors during the lapply step.

I am new to using trycatch, so how can I incorporate it in my code(the lapply step) to ignore the errors and continue with the parsing of the next rtf file?

Jane
  • 385
  • 4
  • 11

2 Answers2

2

Does this work for you?

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)})
Max Teflon
  • 1,760
  • 10
  • 16
  • It shows the error ‘’’Error in value [[3L]](cond) : attempt to apply non-function’’’ – Jane Jun 17 '19 at 04:08
  • Oh, yeah, I forgot the `function(e)`-part. Should work now. – Max Teflon Jun 17 '19 at 07:56
  • 1
    Since the `tryCatch`-help-page is a bit useless, you could have a look at [this](https://stackoverflow.com/a/8094059/9524065), which explains it better then I could ever do myself. – Max Teflon Jun 17 '19 at 07:59
0

What's about this ?

foo <- function(x) tryCatch(yourFunction(x), error = function(e) e)
lapply(files, foo)
nghauran
  • 6,648
  • 2
  • 20
  • 29