Breaking loop when “warnings()” appear in R

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, "\n")
        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

Leave a Comment