[R] Capturing warnings with capture.output

Sebastien Bihorel Sebastien.Bihorel at cognigencorp.com
Thu Sep 5 13:12:05 CEST 2013


Dear R-users,

I would like to follow-up on a old thread by Hadley Wickham about 
capturing warnings with capture.output. My goal is to evaluate a 
function call and capture the results of the function call plus warning 
calls and messages if a warning is returned. For instance, in the 
following case, I would like to capture the 3 lines of text returned by R

 > log(-1)
[1] NaN
Warning message:
In log(-1) : NaNs produced

In Hadley's thread, a combination of capture.output and a custom 
"withWarnings" function was proposed to capture warnings but this seems 
to only capture the warning message and the results of the function call.

withWarnings <- function(expr) {
      wHandler <- function(w) {
       cat(w$message, "\n")
       invokeRestart("muffleWarning")
      }
      withCallingHandlers(expr, warning = wHandler)
}

 > out <- capture.output(withWarnings(log(-1)))
 > out
[1] "NaNs produced " "[1] NaN"

In withWarnings, the wHandler function manipulate an object w, which I 
understand to be a list with a call and message levels. All my attempts 
to manipulate w$call failed because w$call is of class language. I don't 
know how to work with this class and I would appreciate any advise on 
how to process this type of object. Again, the goal is to store both 
call and message in the output of the withWarnings function.

Thank you

Sebastien



More information about the R-help mailing list