Warnings in R - note
I am trying to run a function (glm) in R 1000 times (with slightly different inputs each time). Sometimes I get a warning (because a split happens) - all I want to do is count how many times it happens (so how many times in 1000 iterations I get the warning "glm.fit: probabilities are set numerically 0 or 1 happened") ...
So my code will look something like this:
warningCount <- 0
for(i in 1:1000) {
[generate data]
glm(y ~ ., family="binomial", data=generated_data)
if( I got the warning ) warningCount <- warningCount + 1
}
I just want to know how to write a line if (I got a warning) is correct.
thank
source to share
I would use tryCatch()
to catch, check and act on warnings.
## A function that randomly emits one of two warnings
f <- function() if(runif(1) > .7) warning("Ouch") else warning("Hmmm")
## A function to catch and process warnings, adding to a global counter
## when one of them includes the string "Ouch"
saidOuch <- function(w) {
if(grepl("Ouch", as.character(w))) {ww <<- ww+1}
}
## Run your analyses, each wrapped in a tryCatch()
ww <- 0
for(i in 1:100) tryCatch(f(), warning = saidOuch)
ww
## [1] 32
In your specific case, if you decide not to tackle the perfect separation problem in a different way , you can catch and count the warnings with a function like this
perfectSeparation <- function(w) {
if(grepl("fitted probabilities numerically 0 or 1 occurred",
as.character(w))) {ww <<- ww+1}
}
## Test it with a function that will fit glm that often emit the warning of interest
fitglm <- function() {
dat <- data.frame(x=rnorm(3), y=sample(0:1, 3, replace=TRUE))
glm(y~x, data=dat, family="binomial")
}
ww <- 0
for(i in 1:100) tryCatch(fitglm(), warning = perfectSeparation)
ww
# [1] 45
source to share
You can use tryCatch
to get the warning correctly:
lapply(1:1000, function(u){
[generate some data]
tryCatch(glm(y ~ ., family="binomial", data=generated_data),
warning = function(w) list(glm(y ~ ., family="binomial", data=generated_data), w)
})
This is where it catches warnings and results, but you can only catch the warning if you like.
source to share