SkyWalker
SkyWalker

Reputation: 14307

How to handle R warnings in a loop?

I have a use-case where I need some control flow based on the number of warnings generated by some piece of code:

# clear all warnings 
assign("last.warning", NULL, envir = baseenv())

for (i in 0:100) {
   # call warning-generating code here

   x <- warnings()
   cat(paste('There were',length(x),'warnings generated\n'))
   if (length(x)>10) {
      # do something
   }

   # clear all warnings again
   assign("last.warning", NULL, envir = baseenv())
}

For some reason this code doesn't work. The code will always give There were 0 warnings generated ... why? If I run the warning generating code in question outside the loop it produces non-zero variable number of warnings ...

Upvotes: 0

Views: 692

Answers (1)

GWD
GWD

Reputation: 1464

Not sure if this is what you are aiming for?

# clear all warnings 
assign("last.warning", NULL, envir = baseenv())
x <- rep(NA, 100)
for (i in 1:100) { 
 # call warning-generating code here
  x[i] <- warning()
  cat(paste('There were',sum(!is.na(x)),'warnings generated\n'))
  if (sum(!is.na(x))>10) {
# do something
  }
  # clear all warnings again
  assign("last.warning", NULL, envir = baseenv()
}

Looks like a typo - afaik warnings() will just show you warnings - which still are NULL at this pint in the loop; warning() will generate.

Upvotes: 2

Related Questions