[R] Lexical scoping is not what I expect

Marc Schwartz marc_schwartz at me.com
Mon Jun 24 23:10:20 CEST 2013


On Jun 24, 2013, at 3:27 PM, David Kulp <dkulp at fiksu.com> 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.  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


You need to follow the full example code in John's Appendix:

f <- function (x) x + a

# Here 'a' is being defined in the global environment
a <- 10

# As is 'x' here
x <- 5


# Note that 10 + 5 would be 15,
# 12 is returned showing that x = 2 and not x = 5
# is being use within f()
> f(2)
[1] 12



# Here is where your code starts
# missing the preceding code where 'a' was
# defined globally

f <- function(x) { a<-5; g(x) }


g <- function(y) y + a


# Now it works, showing that 'a <- 5' within f() is not part of the 
# value returned by g(), which is the goal of John's example code :-)
> f(2)
[1] 12


Regards,

Marc Schwartz



More information about the R-help mailing list