Search code examples
rlexical-scope

lexical scope in R


I recently learned that R has both lexical and dynamical scoping available, but that it uses lexical scope by default. The next case really confused me:

> x <- 1
> f <- function(y) { x + y }
> f(5)  # we expect 6    
[1] 6
> x <- 10
> f(5)  # shouldn't we again expect 6?
[1] 15

Shouldn't f be evaluated using the environment where (and at the time!) it was defined and not where it was called ? How is this lexical scope? Thanks!


Solution

  • f <- function(y) { x + y }
    

    was defined in the global environment and so for the parts not defined in the function itself (i.e.x), R looks to the global environment for them.

    a=1
    b=2
    f<-function(x)
    {
      a*x + b
    }
    g<-function(x)
    {
      a=2
      b=1
      f(x)
    }
    # compare f(2) and g(2)
    

    This example above is from here and gives a good discussion. Main point being, f() within g() ignores the definitions of a and b in g().


    From the wiki on "Scope"

    In object-oriented programming, dynamic dispatch selects an object method at runtime, though whether the actual name binding is done at compile time or run time depends on the language.