warnings() does not work within a function? How can one work around this?

error-handling, r

Solution

Here's the code for `suppressWarnings`

function (expr) 
{
    withCallingHandlers(expr, warning = function(w) invokeRestart("muffleWarning"))
}

I've tweaked it a little to count the number of warnings instead.

countWarnings <- function(expr) 
{
    .number_of_warnings <- 0L
    frame_number <- sys.nframe()
    ans <- withCallingHandlers(expr, warning = function(w) 
    {
      assign(".number_of_warnings", .number_of_warnings + 1L, 
        envir = sys.frame(frame_number))
      invokeRestart("muffleWarning")
    })
    message(paste("No. of warnings thrown:", .number_of_warnings))
    ans
}

A test:

countWarnings(log(-1))
No. of warnings thrown: 1
[1] NaN

Another test:

foo <- function()
{
  warning("first warning!")
  warning("second warning!")
  warning("third warning!")
  invisible()
}
countWarnings(foo())
No. of warnings thrown: 3
NULL

Problem

``` op <- options(warn=0) #although doesn't work for any value of warn assign("last.warning", NULL, envir = baseenv()) thisDoesntWork<- function() { warning("HEY, this is definitely a warning!") cat(paste("number of warnings:",length(warnings()))) } >thisDoesntWork() Warning in thisDoesntWork() : HEY, this is definitely a warning! number of warnings: 0 ``` Number of warnings should be 1 rather than 0 - it seems that `warnings()` returns nothing if called within a function. Why? How can one work around this to check within a function if warnings occurred, and print them out? I don't want to use `tryCatch`, because then I lose the value that the function returns (it may still return a valid value, even if it generated a warning).

Original source