gpt4 book ai didi

r - 当 "warnings()"出现在 R 中时中断循环

转载 作者:行者123 更新时间:2023-12-03 04:51:35 24 4
gpt4 key购买 nike

我遇到一个问题: 我正在运行一个循环来处理多个文件。我的矩阵非常巨大,因此如果我不小心,我经常会耗尽内存。

如果产生任何警告,是否有办法跳出循环?它只是继续运行循环并报告它在很久以后失败......烦人。聪明的 stackoverflow-ers 有什么想法吗?!

最佳答案

您可以通过以下方式将警告转变为错误:

options(warn=2)

与警告不同,错误会中断循环。很好的是,R 还会向您报告这些特定错误是从警告转换而来的。

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

关于r - 当 "warnings()"出现在 R 中时中断循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8217901/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com