[R] understanding lexical scope

Thomas Lumley tlumley at u.washington.edu
Fri Dec 19 04:28:53 CET 2008

On Thu, 18 Dec 2008 joseph.g.boyer at gsk.com wrote:

> I am trying to understand the concept of lexical scope in "An Introduction
> to R" by the R Core development team.
> I'd appreciate it if someone would explain why the following example does
> not work:
> q <- function(y) {x + y}; w <- function(x){q(x)}; w(2);
> According to the discussion of Scope on page 46, it seems to me that R
> will interpret the free variable x in q as the parameter x in w, and so
> will
> give w(2) = 2+2.

No, not at all.   The function q() is not defined inside w(), it is defined in the global environment. Inside q(), x is first looked up as a local variable, without success, and then looked up in the environment where q() was defined (the global environment), also without success.

There is an x in the calling environment of q(), ie, inside w(), but finding things in the calling environment is dynamic scope rather than lexical scope.


Thomas Lumley			Assoc. Professor, Biostatistics
tlumley at u.washington.edu	University of Washington, Seattle

More information about the R-help mailing list