Warnings in R - making note -
i'm trying run function (glm) in r 1000 times (with different inputs each time). i'll warning (because separation occurs) - want count how many times occurs (so how many times in 1000 iterations warning "glm.fit: fitted probabilities numerically 0 or 1 occurred").
so code like:
warningcount <- 0 for(i in 1:1000) { [generate data] glm(y ~ ., family="binomial", data=generated_data) if( got warning ) warningcount <- warningcount + 1 } i want know how write line if( got warning ) properly.
thanks
i'd use trycatch() catch, inspect, , act upon warnings.
## function randomly emits 1 of 2 warnings f <- function() if(runif(1) > .7) warning("ouch") else warning("hmmm") ## function catch , process warnings, adding global counter ## when 1 of them includes string "ouch" saidouch <- function(w) { if(grepl("ouch", as.character(w))) {ww <<- ww+1} } ## run analyses, each wrapped in trycatch() ww <- 0 for(i in 1:100) trycatch(f(), warning = saidouch) ww ## [1] 32 for specific case, if decide not deal issue of perfect separation in some other way, can catch , count warnings function this:
perfectseparation <- function(w) { if(grepl("fitted probabilities numerically 0 or 1 occurred", as.character(w))) {ww <<- ww+1} } ## test function fit glm's emit 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
Comments
Post a Comment