How to use tryCatch in R

user52463 picture user52463 · Jul 17, 2014 · Viewed 7.1k times · Source

I would like to use try() or tryCatch() or a function like this to detect if there is an error in my model called "fit1". If the model is fine, I want to use "fit1", otherwise I want to use "fit2"

fit1<-glmer(stat ~ dataint + DBH + DBH2 + (1|site_plot), family=binomial(link="logit"))

fit2<-glm (stat ~ dataint + DBH + DBH2, family=binomial(link="logit"))

Do you know how to do this? I don't add any data because my problem is probably easy to solve, but if it's needed, I can upload them.

THanks!

Answer

Sarunas picture Sarunas · Jul 17, 2014

Using try or tryCatch is not difficult. To read more about error handling, I suggest reading Hadley Wickham's new upcoming book's chapter Advanced R Programming: Exceptions and Debugging. Its just wonderful!

For your specific example, you can use one of these two functions bellow: using try allows you to continue execution of a function call even if error occurs (which you can take note of later), while with tryCatch you can specify error handling in advance:

select<-function(data, formula1, formula2){

  fit1 <- try(lm(formula1, data))
  fit2 <- lm(formula2, data)

  if(is(fit1, "try-error")) fit2 else fit1
}

select1<-function(data, formula1, formula2){

  tryCatch(lm(formula1, data), error = function(e) lm(formula2, data))

}

But that of course works if you know that only the first model can fail. There might be other scenarios, so think those over. Good luck!