Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
322 views
in Technique[技术] by (71.8m points)

Breaking loop when "warnings()" appear in R

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 oh wise stackoverflow-ers?!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can turn warnings into errors with:

options(warn=2)

Unlike warnings, errors will interrupt the loop. Nicely, R will also report to you that these particular errors were converted from warnings.

j <- function() {
    for (i in 1:3) {
        cat(i, "
")
        as.numeric(c("1", "NA"))
}}

# warn = 0 (default) -- warnings as warnings!
j()
# 1 
# 2 
# 3 
# Warning messages:
# 1: NAs introduced by coercion 
# 2: NAs introduced by coercion 
# 3: NAs introduced by coercion 

# warn = 2 -- warnings as errors
options(warn=2)
j()
# 1 
# Error: (converted from warning) NAs introduced by coercion

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...