How to force a For loop() or lapply() to run with error message in R

I edited @Rui Barradas idea of tryCatch(). You can try to do something like below. The IsValues will get either the link value or bad is.

IsValues <- list()
for (i in 1:length(link_questions)) {
  question_to_pdf <- paste0("https://stackoverflow.com",
                            link_questions[i])

  IsValues[[i]] <- tryCatch(
    {
      message(paste("Converting", i))

      pagedown::chrome_print(question_to_pdf)
    },
    error=function(cond) {
      message(paste("Cannot convert", i))
      # Choose a return value in case of error
      return(i)
    }) 
}

Than, you can rbind your values and extract the bad is:

do.call(rbind, IsValues)[!grepl("\\.pdf$", do.call(rbind, IsValues))]

[1] "3"  "5"  "19" "31"

You can read more about tryCatch() in this answer.

Tags:

R