R中出现"warnings()"时断开循环

mma*_*123 98 warnings loops r break

我遇到了一个问题:我正在运行一个循环来处理多个文件.我的矩阵是巨大的,因此如果我不小心,我经常会失去记忆.

如果创建了任何警告,有没有办法摆脱循环?它只是继续运行循环并报告它失败了很久......令人讨厌.任何想法哦明智的stackoverflow-ers ?!

Jos*_*ien 142

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

options(warn=2)
Run Code Online (Sandbox Code Playgroud)

与警告不同,错误会中断循环.很好,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
Run Code Online (Sandbox Code Playgroud)

  • 但默认值为0.所以要恢复_factory settings_使用`选项("警告"= 0)`. (22认同)
  • 然后,使用`options(warn = 1)`恢复默认设置. (20认同)

Mar*_*gan 41

R允许您定义条件处理程序

x <- tryCatch({
    warning("oops")
}, warning=function(w) {
    ## do something about the warning, maybe return 'NA'
    message("handling warning: ", conditionMessage(w))
    NA
})
Run Code Online (Sandbox Code Playgroud)

结果

handling warning: oops
> x
[1] NA
Run Code Online (Sandbox Code Playgroud)

tryCatch后继续执行; 您可以决定通过将警告转换为错误来结束

x <- tryCatch({
    warning("oops")
}, warning=function(w) {
    stop("converted from warning: ", conditionMessage(w))
})
Run Code Online (Sandbox Code Playgroud)

或优雅地处理条件(警告电话后继续评估)

withCallingHandlers({
    warning("oops")
    1
}, warning=function(w) {
    message("handled warning: ", conditionMessage(w))
    invokeRestart("muffleWarning")
})
Run Code Online (Sandbox Code Playgroud)

打印

handled warning: oops
[1] 1
Run Code Online (Sandbox Code Playgroud)


Jos*_*ich 25

设置全局warn选项:

options(warn=1)  # print warnings as they occur
options(warn=2)  # treat warnings as errors
Run Code Online (Sandbox Code Playgroud)

请注意,"警告"不是"错误".循环不会因警告而终止(除非options(warn=2)).