Why does my R run in dynamic scoping? Shouldn'

2020-05-09 18:33发布

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条回答
走好不送
2楼-- · 2020-05-09 19:29

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
查看更多
登录 后发表回答