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).
probably this is a very very bad workaround...
calling the function twice if warning occurs... though I believe that there must be more elegant solutions
The warnings are issued not before the function returns. See the documentation for options("warn"):
Here is a workaround
Your example does return a warning.
The documentation isn't explicit, but I don't think
last.warning
gets set until the call finishes (especially given the call is part of what can be returned).Here's the code for
suppressWarnings
I've tweaked it a little to count the number of warnings instead.
A test:
Another test: