Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R - ignore error on warn in certain scenarios, get results

Tags:

r

try-catch

I set options( warn = 2 ). I require awareness of a warning when triggered and prefer to stop execution. That said, in a few cases a warning is expected and the program should continue execution. Using tryCatch() properly traps the error, however the resulting data is not available.

Here's a concrete example:

x = c(1,2,3,4,5,6)
y = c(1,1,1,0,0,0)
result = glm( y~x , family = binomial( link = "logit" ) )

Wrapping glm in tryCatch(), the result isn't populated. That makes sense since glm's warning is converted into an error before it has the chance to return. Is there a best practice in this scenario? Is it simply to set options(warn=0) before the glm call and then restore after the call? Or is there a better pattern?

I'm certain this is what I want to do. There is no standard for warnings. Sometimes a warning is trivial whereas other times its quite serious. That's why I convert warnings to errors as default. Still, I need the ability to ignore warnings in certain situations where I'm absolutely certain that I can ignore the warning. In those cases, I want the result!

Edit
Here's the try-catch:

tryCatch(  { result = glm( y~x , family = binomial( link = "logit" ) ) } , error = function(e) { print("test") } )
like image 206
SFun28 Avatar asked Apr 21 '11 17:04

SFun28


1 Answers

Try suppressWarnings()

http://stat.ethz.ch/R-manual/R-patched/library/base/html/warning.html

 x = c(1,2,3,4,5,6)
 y = c(1,1,1,0,0,0)
 result = suppressWarnings(glm( y~x , family = binomial( link = "logit" ) ))
 result

 Call:  glm(formula = y ~ x, family = binomial(link = "logit"))

 Coefficients:
 (Intercept)            x  
      165.32       -47.23  

 Degrees of Freedom: 5 Total (i.e. Null);  4 Residual
 Null Deviance:      8.318 
 Residual Deviance: 2.215e-10    AIC: 4 

Edit 1 ==================================

If you want to show the error from the above glm() statement somewhere later in your code, you can add the warnings() statement.

 stoerr <- warnings()   
 stoerr

 Warning message:
 glm.fit: fitted probabilities numerically 0 or 1 occurred
like image 77
bill_080 Avatar answered Sep 30 '22 01:09

bill_080