[R] understanding lexical scope

Antonio, Fabio Di Narzo antonio.fabio at gmail.com
Fri Dec 19 02:29:51 CET 2008


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



More information about the R-help mailing list