Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get exact number of warnings() in R

Tags:

loops

r

warnings

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?

like image 812
R-ista Avatar asked Oct 18 '25 02:10

R-ista


2 Answers

You could set nwarnings options.

options()$nwarnings  ## check current state
# [1] 50

oo <- options(nwarnings=10000)  ## 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.

like image 83
jay.sf Avatar answered Oct 19 '25 16:10

jay.sf


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

like image 23
Allan Cameron Avatar answered Oct 19 '25 17:10

Allan Cameron



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!