Skip to content
Prev 342835 / 398506 Next

keep information on the number of warnings

Look at withCallngHandlers for another way to capture warnings.  It
will let you attach warnings from an iteration of your function to the
output of the function so you can later track down the root cause of
the warning.

E.g., the attached captureWarningsAndMessagesWithContext attaches
warnings, messages, and errors to the output, along with a traceback
for each.

captureWarningsAndMessagesWithContext <-
function(expr) {

   warnings <- list()
   messages <- list()
   fmt <- function(cond, sysCalls) {
      c(Message = conditionMessage(cond),
        Call = deparse(conditionCall(cond))[1],
        rev(vapply(sysCalls, function(sc)deparse(sc)[1], "")))
   }
   retval <- list(result=withCallingHandlers(try(expr, silent=TRUE),
                                  warning=function(w){
                                      warnings[[length(warnings)+1]]
<<- fmt(w, sys.calls())
                                      invokeRestart("muffleWarning")
                                  },
                                  message=function(m){
                                      messages[[length(messages)+1]]
<<- fmt(m, sys.calls())
                                      invokeRestart("muffleMessage")
                                  }
                                 )
                  )
   # retval$result will have class "try-error" if there was an error,
   # which the caller can check for.
   retval$messages <- messages
   retval$warnings <- warnings
   retval
}

E.g.,

z <- lapply(list(log, lm, function(x)1/x),
function(fun)captureWarningsAndMessagesWithContext(fun(-1)))

Bill Dunlap
TIBCO Software
wdunlap tibco.com


On Mon, Aug 4, 2014 at 9:24 AM, Luis Borda de Agua
<lbagua.cloud at gmail.com> wrote: