title: How to handle R warnings in a loop?
body: <p>I have a use-case where I need some control flow based on the number of warnings generated by some piece of code:</p>
  
  <pre><code># clear all warnings 
  assign("last.warning", NULL, envir = baseenv())
  
  for (i in 0:100) {
     # call warning-generating code here
  
     x &lt;- warnings()
     cat(paste('There were',length(x),'warnings generated\n'))
     if (length(x)&gt;10) {
        # do something
     }
  
     # clear all warnings again
     assign("last.warning", NULL, envir = baseenv())
  }
  </code></pre>
  
  <p>For some reason this code doesn't work. The code will always give <code>There were 0 warnings generated</code> ... why? If I run the warning generating code in question outside the loop it produces non-zero variable number of warnings ... </p>