小编tom*_*mas的帖子

R tryCatch块中的变量范围:<<是否需要更改在tryCatch之前定义的局部变量?

请考虑以下代码:

test1 <- "a"
test2 <- "a"
tryCatch(stop(), error= function(err){
  print(test1)
  print(test2)
  test1 <- "b"
  test2 <<- "b"
})
Run Code Online (Sandbox Code Playgroud)

结果:

print(test1)
[1] "a"
print(test2)
[1] "b"
Run Code Online (Sandbox Code Playgroud)

变量test1的值在tryCatch块中可见,但使用"< - "运算符更改它不会影响其在tryCatch块之外的值.

如果使用<<分配新值,则它具有所需的效果.为什么?

在tryCatch块中使用<< - 运算符是一种推荐的方法来更改此块外部的局部变量的值吗?会有一些意想不到的副作用吗?

编辑:基于Bernhard的答案,以下代码是否弥补了解决此问题的正确方法?

test1 <- "a"
test2 <- "a"
new_values<-tryCatch(
  {
    print("hello")
    stop()
  }
, error= function(err){
  # I want to change the test1 and test 2 variables to "b" only if error occurred.
  test1 <- "b"
  test2 <- "b"
  return(list(test1=test1,test2=test2))
})
if (is.list(new_values))
{
  test1<-new_values$test1
  test2<-new_values$test2
}
Run Code Online (Sandbox Code Playgroud)

结果: …

scope exception-handling r

5
推荐指数
1
解决办法
1492
查看次数

标签 统计

exception-handling ×1

r ×1

scope ×1