On Thu, 18 Dec 2008 joseph.g.bo...@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
Thomas Lumley Assoc. Professor, Biostatistics
tlum...@u.washington.edu University of Washington, Seattle
______________________________________________
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.