简体   繁体   中英

How to use tryCatch in R

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!

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM