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. Joe Boyer Statistical Sciences Renaissance Bldg 510, 3233-D Mail Stop RN0320 8-275-3661 cell: (610) 209-8531 [[alternative HTML version deleted]]
2008/12/18 <joseph.g.boyer at gsk.com>:> 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,Why? R will look at the enclosing environment, which here is the workspace. Maybe you meant:> w <- function(x){ q <- function(y) x+y; q(x)}; w(2)which works as you said. HTH, Antonio.> and so > will > give w(2) = 2+2. > > > > > > Joe Boyer > Statistical Sciences > Renaissance Bldg 510, 3233-D > Mail Stop RN0320 > 8-275-3661 > cell: (610) 209-8531 > [[alternative HTML version deleted]] > > ______________________________________________ > R-help at 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. >-- Antonio, Fabio Di Narzo Ph.D. student at Department of Statistical Sciences University of Bologna, Italy
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 Thomas Lumley Assoc. Professor, Biostatistics tlumley at u.washington.edu University of Washington, Seattle