Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selective suppressWarnings() that filters by regular expression

Tags:

r

warnings

In an attempt to generate code that runs without warnings and hence can be run with options(warn=2), I am looking for an implementation of the suppressWarnings routine that would only filter warnings that match a given (vector of) regular expressions. Some warnings are just beyond my control, like the famous

Unrecognized record type 7, subtype 18 encountered in system file

when reading certain SPSS files, and I want to selectively suppress these without affecting possible other warnings.

Is there already an implementation of this functionality?

like image 312
krlmlr Avatar asked May 13 '13 08:05

krlmlr


1 Answers

Suppress warnings with withCallingHandlers and invokeRestart, using the "muffleWarning" restart mentioned on ?warning

withCallingHandlers({
    x <- 0
    warning("Unrecognized record 123")
    x <- x + 1
    warning("another warning")
    x + 1
}, warning = function(w) {
    if (startsWith(conditionMessage(w), "Unrecognized record"))
        invokeRestart("muffleWarning")
})

This has the output

[1] 2
Warning message:
In withCallingHandlers({ : another warning

(use tryCatch if instead you would like to stop on warning). As @BenBolker mentions this doesn't handle translations; making a more elaborate regex isn't going to be satisfactory. For catching one's own warnings, one could make and throw a subclass of warning.

like image 158
Martin Morgan Avatar answered Sep 29 '22 17:09

Martin Morgan