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

后端 未结 1 1903
谎友^
谎友^ 2021-01-17 01:11

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 su

相关标签:
1条回答
  • 2021-01-17 01: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
    
    0 讨论(0)
提交回复
热议问题