为什么我的 R 运行 在动态范围内?不应该是词法的吗?

Why does my R run in dynamic scoping? Shouldn't it be lexical?

我刚刚在 class 中了解到 R 使用词法作用域,并在我的计算机上的 R Studio 中对其进行了测试,我得到的结果适合动态作用域,而不是词法?这不应该在 R 中发生吗?我运行:

y <- 10
f <- function(x) {
  y <- 2
  y^3
}
f(3)

f(3) 结果是 4 (2^3) 而不是 100 (10^3)​​,尽管我的 class 展示了这张幻灯片:http://puu.sh/pStxA/0545079dbe.png。这不是动态作用域吗?我可能只是看错了,但是菜单上是否有一个模式可以将作用域切换为词法,或者发生了什么?

您的代码已在函数本身内分配了 y,它在全局环境中的 y 之前被查找。

来自这篇优秀文章 (http://www.r-bloggers.com/environments-in-r/):"When a function is evaluated, R looks in a series of environments for any variables in scope. The evaluation environment is first, then the function’s enclosing environment, which will be the global environment for functions defined in the workspace."

用更简单的特定于你的情况的语言:当你调用变量 "y" 时,R 在函数的环境中寻找 "y",如果找不到,那么它会转到你的工作区。举例说明:

y <- 10

f <- function(x) {
  y^3
}

f(3)

将产生输出:

> f(3)
[1] 1000