Dayne
Dayne

Reputation: 502

How to skip only a specific type of error in for-loop in R?

I am looping over read_xlsx (from readxl library) to read multiple sheets in an excel. However, if there's an error that the sheet (specified with a certain name - "missing" in below example) is not present, I want it to be ignored and the loop should continue. But at the same time if there's any other error (say related to calculations), then that should not be ignored and thrown as error, while stopping the loop. How to do this?

Note: I used tryCatch / try; they both ignore all types of errors (learning from this answer).

sheets=c("name1","name2","missing","name3")  
for (k in sheets) {
    tryCatch({temp=read_xlsx("someexcel.xlsx",sheet = k,col_names = F)
    some_calc=mean(temp[1,])},error=function(e){})
}

Upvotes: 1

Views: 283

Answers (1)

Humpelstielzchen
Humpelstielzchen

Reputation: 6441

You could try this:

test <- function(x) {
  tryCatch(x,
           error = function(e) {if(conditionMessage(e) == "It's an error") {print("no problem")
                               } else {
                                   stop("It's another error")}
                                                                 })
}

> test(stop("It's an error"))
[1] "no problem"

> test(stop("Mayday mayday"))
 Error in value[[3L]](cond) : It's another error 

conditionMessage captures the error message, so you can evaluate it and act accordingly.

For it to do nothing just "do nothing" {} when the condition is true.

Upvotes: 2

Related Questions