Give base R's text-only warnings a class¶
Source: R/classed-warnings.R ยท Help: ?with_classed_warnings
with_classed_warnings() evaluates expr and re-signals the base R and
stats warnings listed by classed_warning_rules() as classed warnings, so
they can be handled by class instead of by matching their text:
Usage¶
Arguments¶
expr- An expression to evaluate.
w- A warning condition.
Value¶
with_classed_warnings() returns the value of expr.
classify_warning() returns the classed warning, or NULL when no rule
matches. classed_warning_rules() returns a data frame with one row per
recognised message template, and in fields the values it carries.
Details¶
withCallingHandlers(
with_classed_warnings(glm(y ~ x, family = binomial, data = d)),
dataexcept_separation_warning = function(w) ...
)
Recognition does not depend on the session language. A warning is compared with its template translated through R's own message catalogue, the one R used to write the warning, so the same code works in an English, German or Portuguese session. Templates with values are format strings, matched with their placeholders as slots, and plural messages are matched in every form of the language.
Besides base R and stats, the rules cover the convergence warnings of survival's Cox and parametric models and of lme4's mixed models.
Each classed warning keeps the original message and call, stores the
original warning in parent, and records the matching rule in rule. A
warning that carries values -- the iterations kmeans() ran, the code
optim() returned in arima(), the gradient lme4 measured -- has them as
fields too, named in the fields column of classed_warning_rules().
Warnings no rule matches pass through untouched, as does everything else
expr signals. Written to an envelope, a classed warning has a type such
as "SeparationWarning" and the original simpleWarning as its cause.
classify_warning() does the recognition for a single warning object.
Examples¶
separated <- data.frame(y = c(0, 0, 1, 1), x = 1:4)
# Handle one family of warnings by class, whatever the session language.
withCallingHandlers(
with_classed_warnings(glm(y ~ x, family = binomial, data = separated)),
dataexcept_separation_warning = function(w) {
message("Perfect separation: ", conditionMessage(w))
invokeRestart("muffleWarning")
},
dataexcept_convergence_warning = function(w) invokeRestart("muffleWarning")
)
# Or fail closed: turn non-convergence into an error.
try(withCallingHandlers(
with_classed_warnings(glm(y ~ x,
family = binomial, data = separated,
control = glm.control(maxit = 5)
)),
dataexcept_convergence_warning = function(w) {
stop(convergence_error("glm", iterations = 5L, parent = w))
}
))
classed_warning_rules()[, c("type", "template")]