请考虑以下代码:
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)
结果: …