I am running a simulation using an iterative algorithm, which should ideally converge at some point. I received numerous warning messages, checked all warnings that were reported and need to report the precise number of warning messages that I got for my choice of convergence criteria.
There were 50 or more warnings (use warnings() to see the first 50)
How can I get the exact number of warning messages in R?
CodePudding user response:
You could set nwarnings
options.
options()$nwarnings ## check current state
# [1] 50
oo <- options(nwarnings=50) ## set, store old options
options()$nwarnings ## check
# [1] 10000
options(oo) ## restore old options
options()$nwarnings ## check
# [1] 50
However, with this approach you only see how many warnings have occurred (and you probably need to set nwarnings
even higher).
In simulation studies you might be interested in which cases the warning occurred. So, alternatively think about storing the warning together with the respective replication. See this nice Q&A here on Stack Overflow.
CodePudding user response:
You can capture each warning message in a vector using withCallingHandlers
. The following loop for example should emit 66 warnings:
for(i in 1:66) {
b <- as.numeric('a')
}
#> There were 50 or more warnings (use warnings() to see the first 50)
But we can catch an indefinite number of warnings if we wrap run our code with a calling handler:
warn_msgs <- character()
for(i in 1:66) {
withCallingHandlers(
{
b <- as.numeric('a')
},
warning = function(w) warn_msgs <<- append(warn_msgs, w$message)
)
}
#> There were 50 or more warnings (use warnings() to see the first 50)
length(warn_msgs)
#> [1] 66
Created on 2022-10-08 with reprex v2.0.2