0 votes
1 view
in R Programming by (5.1k points)

I am having an issue: I am running a loop to process multiple files. My matrices are enormous and therefore I often run out of memory if I am not careful.

Is there a way to break out of a loop if any warnings are created? It just keeps running the loop and reports that it failed much later... annoying. Any ideas?!

1 Answer

0 votes
by (24.7k points)

To break a loop when warnings appear, you can convert the warnings to errors which unlike warnings interrupt the loop.

For example:

j <- function() {

   for (i in 1:4) {

     cat(i, "\n")

     as.numeric(c("1", "NA"))

   }}

 # warn = 0 (default) -- warnings as warnings!

 j()

Warning in j() : NAs introduced by coercion

Warning in j() : NAs introduced by coercion

Warning in j() : NAs introduced by coercion

Warning in j() : NAs introduced by coercion

# warn = 2 -- warnings as errors

options(warn=2)

j()

 Error in j() : (converted from warning) NAs introduced by coercion 

Use options(warn=1) to restore the default setting.

Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...