这个问题在这里已经有了答案:
Global and local variables in R
(3 个回答)
7年前关闭。
我对 R 很陌生,但是来自 Scheme——它也是词法范围的并且有闭包——我希望能够改变闭包中的外部变量。
例如,在
foo <- function() {
s <- 100
add <- function() {
s <- s + 1
}
add()
s
}
cat(foo(), "\n") # prints 100 and not 101
我希望
foo()
返回 101,但实际上返回 100:$ Rscript foo.R
100
我知道 Python 有
global
关键字来声明变量的范围(但不适用于此示例)。 R 需要类似的东西吗?我究竟做错了什么?
更新
啊,问题是在
add
我正在创建一个新的局部变量 s
阴影外s
?如果是这样,我该如何变异 s
不创建局部变量?
最佳答案
使用 <<-
add()
中的赋值运算符功能。
来自 ?"<<-"
:
The operators
<<-
and->>
are normally only used in functions, and cause a search to made through parent environments for an existing definition of the variable being assigned. If such a variable is found (and its binding is not locked) then its value is redefined, otherwise assignment takes place in the global environment. Note that their semantics differ from that in the S language, but are useful in conjunction with the scoping rules of R. See ‘The R Language Definition’ manual for further details and examples.
关于r - 改变闭包中的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23313500/