如何在没有全局变量或超级分配的情况下使用tryCatch

时间:2019-02-20 18:27:40

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

我正在编写一个具有以下形式的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替换为<<-,也会发生类似的问题。我该怎么办?

1 个答案:

答案 0 :(得分:2)

我不确定您为什么尝试在此处使用全局范围。您只需从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)
}