2

I'm running a bunch of logit models, some of them with perfect separation which returns a glm warning. Here a dataset that shows the problem:

DT <- iris
str(DT)
DT$binary <- as.numeric(DT$Petal.Width>1)
DT$dummy <- as.numeric(as.numeric(DT$Species)>2)

mylogit <- glm(binary~Sepal.Length+dummy,data = DT, family=binomial(link='logit'))

I'm collecting estimates, model fit, etc from mylogit inside an apply function and would like to add a dummy showing if this warning was returned. However, I don't understand the tryCatch() syntax enough and the examples I find are mostly aimed at returning warnings etc. I'm looking for something like:

if(warning is returned){x <- 1}

Is tryCatch() the wrong approach?

Jakob
  • 1,325
  • 15
  • 31

2 Answers2

2

tryCatch would be the correct approach. I agree with you that some examples are not as clear and had some trouble with tryCatch in the past myself as well. I always find the following SO answer a helpful reference: How to write trycatch in R

onnhoJ
  • 56
  • 7
2

Yes, tryCatch is the right function to use:

x <- 0
tryCatch(
    mylogit <- glm(binary~Sepal.Length+dummy,data = DT, family=binomial(link='logit')),
    warning = function(w) { x <<- x + 1 }
)

The <<- is necessary, as you are assigning to a variable that is outside the scope of the function. (Usually that is a bad idea but here it is necessary.)

If you want to do something with the warning text, use conditionMessage(w).

user1310503
  • 557
  • 5
  • 11
  • thanks! Thats very helpful. Do I always have to use a function inside warning? I think warning=x<-1 works as well no? – Jakob May 23 '17 at 12:25
  • I think you always have to supply a function. For me, `warning=x<-1` gives "Error in tryCatchOne ... attempt to apply non-function" – user1310503 May 23 '17 at 12:28
  • as an aside: are the spaces in your function coincidence or is that on purpose and more readable? I noticed some people edit spaces into my questions sometimes... – Jakob May 23 '17 at 12:31
  • 1
    It's on purpose to make it more readable. You should do it! See [Google's R Style Guide](https://google.github.io/styleguide/Rguide.xml) or the [style guide by Hadley Wickham](http://adv-r.had.co.nz/Style.html). – user1310503 May 23 '17 at 12:38