Search code examples
rscoping

How does scoping work in R?


a <- 10
f <- function(){
    a <<- 3
    function() {
      a <<- 15
      a <- 5
      return(a)
    }
}
g <- f()
g()
a

When I run the above code I get the following output:

5

15

Can someone please explain how the second output is 15 instead of 3? And the same code returns 10 for a when I do not use "<<-" in the function f.


Solution

  • Just see what your function f returns.

    f()
    function() {
          a <<- 15
          a <- 5
          return(a)
        }
    <environment: 0x000000001f1c7898>
    

    So when you assign this result, a function, to g it becomes that function in the output above. The code line a <<- 3 is never executed when you call g.
    In other words, the second output is explained in the same fashion the first output is explained, g sets the variable a that exists in the globalenv to 15 and returns a value of variable a <- 5 created in its own environment.

    EDIT.
    Note that if, like Dason says in his comment, print a before calling g its value has changed to 3 like you expect it in your question. The code line a <<- 3 was indeed executed when f was called.

    g <- f()   # call 'f'
    
    a          # print 'a', the value has changed
    [1] 3
    
    g()        # now call 'g'
    [1] 5
    
    a          # and the value of 'a' changed again
    [1] 15