[R] understanding lexical scope

Wayne F wdf61 at mac.com
Sat Dec 20 05:05:12 CET 2008

joseph.g.boyer wrote:
> Thomas, Jeff, Mark, Antonio,
> Thank you for your answers. They have helped me clarify how R functions 
> work. They work differently from SAS functions (which SAS calls macros.)
> To me, while the coding is quite awkward, the execution is logical. The 
> variable x has been defined by the call to the macro w, so there is no 
> problem when SAS encounters a reference to x in the macro q.
> ...
> But in the equivalent code in R, 
> q <- function(y) y +x; w <- function(x) q(x); w(2);
> when R can't find the second argument of q in the local environment of the 
> macro q, it doesn't look in the local environment of the macro w, it goes 
> all the way back to  the global environment, as you have all pointed out.

When you think of it as "all the way back to the global environment", you're
introducing confusion. The lexical scoping way of doing it means that you
can look at q right now and tell where it's going to look for x: first in q,
then in the environment where you are defining it (global in this instance),
etc. There's nothing dynamic about where it finds x. It does not matter how
you call q or what w -- which might not even exist -- might or might not do.

The way you previously preferred depends entirely on how q is called.
Imagine you have not just w, but w1, w2, w3, w4, ..., w77, and each one does
something different -- many do not have x as parameter -- and several of
them call each other before calling q. You cannot begin to tell ahead of
time where x will come from, and it would be extremely hard to figure out
the order of calls that actually occur to figure out which x you're going to

In your very simple example where q is always called by w and w never
attempts to do anything tricky, it's not hard to see, but in the real world,
it would make your head spin.

You're still thinking in the dynamic sense when you talk about "all the way
View this message in context: http://www.nabble.com/understanding-lexical-scope-tp21084267p21101765.html
Sent from the R help mailing list archive at Nabble.com.

More information about the R-help mailing list