Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in R Programming by (7.3k points)
edited by

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
edited by

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()

1

Warning in j() : NAs introduced by coercion

2

Warning in j() : NAs introduced by coercion

3

Warning in j() : NAs introduced by coercion

4

Warning in j() : NAs introduced by coercion

# warn = 2 -- warnings as errors

options(warn=2)

j()

1

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

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

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...