问题描述
我遇到了一个问题: 我正在运行一个循环来处理多个文件.我的矩阵很大,因此如果我不小心的话,我经常会用光内存.
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.
如果创建了任何警告,是否有一种方法可以打破循环?它只是继续运行循环,并在以后报告失败了,这很烦人.任何想法哦,明智的stackoverflow-ers?!
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?!
推荐答案
您可以使用以下方法将警告变为错误:
You can turn warnings into errors with:
options(warn=2)
与警告不同,错误将中断循环.很好,R还会向您报告这些特定的错误是从警告中转换而来的.
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
这篇关于当"warnings()"出现时,中断循环.出现在R中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!