1

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){})
}

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Great! Worked perfectly. Just had to customize the error with the looping variable. Just one small thing. In the else section, how to ensure that the original error (which would have been thrown without tryCatch) is displayed instead of (or besides) the customized error?
Awesome! Just do stop(conditionMessage(e)) inside else .
Ignore! Got the answer. Just added conditionMessage(e). Worked.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.