r - 改变闭包中的变量

标签 r scope closures

这个问题在这里已经有了答案:





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/

相关文章:

javascript - ajax回调函数可以看到父函数的变量吗?

ruby-on-rails - Ruby on Rails - 具有部分 View 的实例变量的范围

Javascript 对象事件处理程序范围,最佳实践?

r - 函数生成;更改其他功能的默认值(部分)

从列表元素中删除重复项

scope - Velocity:是否可以嵌套使用 #@ 和 $bodyContent 的宏?

rust - 调用一个借用为不可变的闭包时,不能在循环中借用为可变的吗?

c# - 如何在 C# 中正确释放匿名委托(delegate)/闭包?

r - data.table 更新对非等价自联接的奇怪行为

r - 确定 R 中的向量中是否有 x 个连续的重复项