[R] Lexical scoping is not what I expect

Gabor Grothendieck ggrothendieck at gmail.com
Mon Jun 24 22:44:45 CEST 2013

On Mon, Jun 24, 2013 at 4:27 PM, David Kulp <dkulp at fiksu.com> wrote:
> According to http://cran.r-project.org/doc/contrib/Fox-Companion/appendix-scope.pdf and other examples online, I am to believe that R resolves variables using lexical scoping by following the frames up the call stack.  However, that's not working for me.  For example, the following code, taken from the reference above fails instead of returning 7.  What am I doing wrong?  Thanks!
> f <- function(x) { a<-5; g(x) }
> g <- function(y) { y + a }
> f(2)
> Error in g(x) : object 'a' not found

What you have described is called dynamic scoping. What lexical
scoping is is that it resolves free variables based on where the
function is _defined_, not where it is run and it has nothing to do
with the call stack.  a is a free variable in g and so when g is run R
looks up a in the environment where g was defined which is the global
environment and there is no a there.

Statistics & Software Consulting
GKX Group, GKX Associates Inc.
tel: 1-877-GKX-GROUP
email: ggrothendieck at gmail.com

More information about the R-help mailing list