If you do want to save all of the warnings, perhaps to an external file, you could wrap the code you are executing in a call to withCallingHandlers()
. It allows you define a 'handler' for warning conditions. The handler is a function that is run each time a warning is encountered; you can use it to do pretty much anything you'd like with the warning message it is passed. (For an excellent short intro to this topic, see Martin Morgan's answer to this SO question.)
Here, I define a handler that: (a) appends the warning message to a file; and (b) uses invokeRestart()
to carry on with evaluation of the function at the place where the warning was thrown. You can obviously modify this to suit your precise needs:
# DEFINE A WRAPPER FUNCTION THAT:
# - EVALUATES A GIVEN EXPRESSION
# - SAVES ALL WARNINGS TO A LOGFILE
saveAllWarnings <- function(expr, logFile="warning_log.R") {
withCallingHandlers(expr,
warning=function(w) {
cat(conditionMessage(w), "\n\n", file=logFile, append=TRUE)
invokeRestart("muffleWarning")
})
}
# TRY IT OUT WITH A MADE UP FUNCTION THAT THROWS SEVERAL WARNINGS
messyFun <- function() {
warning("oops")
warning("boops")
warning("can't I get anything right?")
1
}
saveAllWarnings(messyFun(), logFile="messyFun warning log.R")