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

霸气de小男生 提交于 2019-12-09 03:58:41

问题


I just learned in class that R uses lexical scoping, and tested it out in R Studio on my computer and I got results that fit dynamic scoping, not lexical? Isn't that not supposed to happen in R? I ran:

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

And f(3) came out to be 4 (2^3) not 100 (10^3), even though my class presented this slide: http://puu.sh/pStxA/0545079dbe.png . Isn't that dynamic scoping? I may just be looking at this wrong, but is there a mode on a menu somewhere where you can switch the scoping to lexical, or what is happening?


回答1:


Your code has assigned y within the function itself, which is looked up before the y in the global environment.

From this excellent article (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."

In simpler language specific to your case: when you call the variable "y", R looks for "y" in the function's environment, and if it fails to find one, then it goes to your workspace. An example to illustrate:

y <- 10

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

f(3)

Will produce output:

> f(3)
[1] 1000


来源:https://stackoverflow.com/questions/38230070/why-does-my-r-run-in-dynamic-scoping-shouldnt-it-be-lexical

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!