Disable specific warnings
By romain francois on Wednesday, May 20 2009, 19:47 - Permalink
[This post is inspired from this thread on R-help]
The suppressWarnings function allows to call a function and suppress whatever warning it might generate. This uses the calling handler and restart mechanism of R to invoke the special "muffleWarning" restart when a warning is detected by the handler.
The downside is that it removes all warnings, and this might not be what you want. Consider that simple function that gives two warnings:
f <- function( x) { warning( "bla bla" ) y <- x + 3 warning( "yada yada" ) y } > f(5) [1] 8 Warning messages: 1: In f(5) : bla bla 2: In f(5) : yada yada > suppressWarnings( f(5) ) [1] 8
What if I wanted to remove "bla bla" warnings and not "yada yada" warnings, because I know that "bla bla" warnings are expected and are more disturbing that useful. Currently, suppressWarnings
does not offer that possibility, but you can make you own calling handler that handles warnings the way you want:
> h <- function(w) if( any( grepl( "bla", w) ) ) invokeRestart( "muffleWarning" ) > withCallingHandlers( f(5), warning = h ) [1] 8 Warning message: In f(5) : yada yada
Comments
Are you aware of any configurable logging packages for R? Because that's what you seem to be aiming at with the above. It's pretty annoying that most people seem to do stuff like that in an ad hoc way again and again....
Would be nice if one would have at least different logging levels (debug, info, warn, error), configurable output (which levels, show where/when generated?) and redirection (console, file, mail). Basically some reasonable subset of commons logging, for example.
I am not aware of any such functionality, otherwise I would use it quite intensively. What you can do is create a custom condition and catch it with withCallingHandlers, but for this to really useful, you would need to have the ability to set top level calling handlers.
I once made a request for that on R-devel, but did not get any feedback, I am not sure what it means