【问题标题】:How to use tryCatch without global variables or superassignment如何在没有全局变量或超赋值的情况下使用 tryCatch
【发布时间】:2019-07-14 12:52:24
【问题描述】:

我正在编写一个带有以下形式的 tryCatch() 循环的 R 包,其中我首先尝试使用容易出错的方法拟合模型,但如果第一次失败则使用更安全的方法:

# this function adds 2 to x
safe_function = function(x) {

  tryCatch( {
    # try to add 2 to x in a stupid way that breaks
    new.value = x + "2"

  }, error = function(err) {
           message("Initial attempt failed. Trying another method.")
           # needs to be superassignment because inside fn
           assign( x = "new.value",
                  value = x + 2,
                  envir=globalenv() )
         } )

  return(new.value)
}

safe_function(2)

此示例按预期工作。但是,使用 assign 会在检查包是否已准备好 CRAN 时触发注释:

Found the following assignments to the global environment

如果我将assign 替换为<<-,也会出现类似的问题。我能做什么?

【问题讨论】:

  • 你不能new.value <- tryCatch( { x + "2" }, error = function(err) x+2 ) 吗?

标签: r environment-variables global-variables cran scoping


【解决方案1】:

我不确定您为什么要在这里使用全局范围。您可以只返回来自try/catch 的值。

safe_function = function(x) {

  new.value <-   tryCatch( {
    # try to add 2 to x in a stupid way that breaks
    x + "2"
  }, error = function(err) {
    message("Initial attempt failed. Trying another method.")
    x + 2
  } )

  return(new.value)
}

【讨论】:

    猜你喜欢
    • 2013-08-04
    • 1970-01-01
    • 2012-08-11
    • 1970-01-01
    • 2013-09-12
    • 2014-04-02
    • 2016-10-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多