Skip to content

warning inside loop

4 messages · Rense Nieuwenhuis, jim holtman, William Dunlap

#
Hi,

I'm running some data simulations using (mixed effects)* regression models
that show difficulty to converge. Therefore, I seek a way of capturing
warnings (of false convergence) inside a loop.

Inside that loop, I modify data and estimate a model. I do so many times
with slightly different modifications of the data. Next, I extract some of
the model parameters and store these in a matrix. However, as some of the
models do not converge well, some of the stored parameters are extracted
from the ill-converged models. Therefore, I seek a way of automatically
detecting whether the estimation procedure has resulted in a warning, so I
can distinguish between the well- and ill-converged models.

I have been trying to use functions as warnings(), as well as using the
object last.warning, but unfortunately to no avail.

Although I cannot provide a reproducible example, I schematically represent
the procedure I seek to use below:


for (i in 1:10)
{
<<modify data>>
<<estimate model>>

<<<evaluate whether estimation produced warning>>>

<<extract model parameters, and store whether warning occured>>
}

I hope any one can give some guidelines on how to deal with warnings inside
a loop.

With Kind regards,

Rense





*Although I use the lme4 package for that actual analysis, I sent my
question to this mailinglist (instead of the R mixed list) because I believe
this is a general issue, rather than one associated exclusively with mixed
models.
#
Try withCallingHandlers(), as in the following function
with returns the value of the expression along with
any warning messages as a list:
function (expr) 
{
    warnings <- character()
    retval <- withCallingHandlers(expr, warning = function(ex) {
        warnings <<- c(warnings, conditionMessage(ex))
        invokeRestart("muffleWarning")
    })
    list(Value = retval, Warnings = warnings)
}
<environment: R_GlobalEnv>

Typical usage would be:
[[1]]
[[1]]$Value
[1] NaN

[[1]]$Warnings
[1] "NaNs produced"


[[2]]
[[2]]$Value
[1] -Inf

[[2]]$Warnings
character(0)


[[3]]
[[3]]$Value
[1] 0

[[3]]$Warnings
character(0)

Perhaps there is some encapsulation of this already in some
package, as try() encapsulates error catching.

Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com
#
Dear William,

thank you kindly for this solution: it provides exactly what I need,
especially due to the fact that the encapsulating function returns a list,
from which I can extract all the information I need.

kind regards,

Rense Nieuwenhuis
William Dunlap wrote: