【问题标题】:Breaking loop when "warnings()" appear in R当“警告()”出现在R中时打破循环
【发布时间】:2012-01-03 07:28:23
【问题描述】:

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

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

【问题讨论】:

    标签: r loops warnings break


    【解决方案1】:

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

    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
    

    【讨论】:

    • 之后,使用options(warn=1) 恢复默认设置。
    • 默认值为 0。所以要恢复出厂设置,请使用options("warn"=0)
    • R 中的重置选项通常最好通过 1) op=options(warn=2),2) 做你的事情,然后 3) 使用 options(op) 重置,在这种情况下,这会将你带回 warn=0 .
    【解决方案2】:

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

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

    导致

    handling warning: oops
    > x
    [1] NA
    

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

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

    或优雅地处理条件(在警告调用后继续评估)

    withCallingHandlers({
        warning("oops")
        1
    }, warning=function(w) {
        message("handled warning: ", conditionMessage(w))
        invokeRestart("muffleWarning")
    })
    

    打印出来的

    handled warning: oops
    [1] 1
    

    【讨论】:

    • +1 -- 非常好。我曾想过提及此选项,但无法整理出如此简短而温馨的教程。
    • 用漂亮的for 进行演示会更好:)
    【解决方案3】:

    设置全局warn 选项:

    options(warn=1)  # print warnings as they occur
    options(warn=2)  # treat warnings as errors
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-09-30
      • 2017-10-13
      • 1970-01-01
      • 2023-03-08
      • 2015-09-22
      • 2021-08-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多