[Rd] Using IDs to suppress specific messages and warnings

Richard Cotton richierocks at gmail.com
Thu Sep 10 11:52:02 CEST 2015


The suppressMessages and suppressWarnings functions currently suppress
all the message or warnings that are generated by the input
expression.

The ability to suppress only specific messages or warnings is
sometimes useful, particularly for cases like file import where there
are lots of things that can go wrong.

Suppressing only messages that match a regular expression has rightly
been rejected as problematic due to non-portability across locales.
See, for example,

https://stat.ethz.ch/pipermail/r-devel/2012-October/065089.html

A better way of suppressing certain conditions would be to allow them
to have an identifier.  (This is how MATLAB allows control over
individual conditions.)

The implementation ought to be fairly simple.

simpleMessage, simpleWarning, and simpleError gain an id arg, which is
stored in their structure.

simpleMessage <- function (message, call = NULL, id = NULL)
{
  structure(
    list(message = message, call = call, id = id),
    class = c("simpleMessage", "message", "condition")
  )
}

I envisage IDs being strings, for example, the "NaN produced" warning
when you ask call, e.g., sqrt(-1) could have an ID of
"base:sqrt:nan_produced".

suppressMessage and suppressWarnings gain an ids arg, defaulting to
NULL, which preserves existing behaviour.  If it takes a character
vector, messages with the IDs provided get muffled.  Something like:

suppressMessages <- function (expr, ids = NULL)
{
  withCallingHandlers(
    expr,
    message = function(c)
    {
       if(is.null(ids) || (inherits(c, "simpleMessage") && c$id %in%
as.character(ids)))
       {
         invokeRestart("muffleMessage")
       }
    }
  )
}

The hard part is providing IDs for all the existing messages in R and
its packages.  It's certainly do-able, but I imagine would take quite
a lot of time.

Is there any enthusiasm for implementing this feature, or something like it?

-- 
Regards,
Richie

Learning R
4dpiecharts.com



More information about the R-devel mailing list