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!
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.This example above is from here and gives a good discussion. Main point being,
f()
withing()
ignores the definitions ofa
andb
ing()
.From the wiki on "Scope"