> I think it's a difficult concept If you pass non-global things via the argument list then you don't have to think about scoping issues so much. E.g., instead of f <- function(x) { g <- function(y) { y + a } a <- 5 g(x) } try f <- function(x) { a <- 5 ; g(x, a) } g <- function(y, a) { y + a } f(x) will give the same result in both.
In addition, passing data through the argument list makes g() usable in many functions. If 'g' uses lexical scoping to find 'a' then you need to redefine 'g' in every function that uses it. Bill Dunlap Spotfire, TIBCO Software wdunlap tibco.com > -----Original Message----- > From: r-help-boun...@r-project.org [mailto:r-help-boun...@r-project.org] On > Behalf > Of David Kulp > Sent: Monday, June 24, 2013 6:22 PM > To: Duncan Murdoch > Cc: r-help@r-project.org > Subject: Re: [R] Lexical scoping is not what I expect > > Indeed, I misread / misunderstood. I think it's a difficult concept that's > hard to explain > and the example wasn't great. But thanks all for straightening me out! > — > David Kulp > > On Mon, Jun 24, 2013 at 6:44 PM, Duncan Murdoch <murdoch.dun...@gmail.com> > wrote: > > > On 13-06-24 4:27 PM, David Kulp wrote: > >> According to http://cran.r-project.org/doc/contrib/Fox-Companion/appendix- > scope.pdf and other examples online, I am to believe that R resolves > variables using > lexical scoping by following the frames up the call stack. > > You appear to have misread it. Lexical scoping follows the chain of > > environments where functions were defined. It ignores the call stack. > > Duncan Murdoch > > However, that's not working for me. For example, the following code, > > taken from the reference above fails instead of returning 7. What am I > > doing wrong? Thanks! > >> > >> f <- function(x) { a<-5; g(x) } > >> g <- function(y) { y + a } > >> f(2) > >> Error in g(x) : object 'a' not found > >> > >> > >> [[alternative HTML version deleted]] > >> > >> ______________________________________________ > >> 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. > >> > [[alternative HTML version deleted]] ______________________________________________ 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.