[R] Lexical scoping question
    Jim Rogers 
    jrogers at cantatapharm.com
       
    Fri Feb 28 17:47:26 CET 2003
    
    
  
Hello, 
Could someone please tell me what I am thinking about incorrectly:
f <- function(y) { 
  g <- function(x) x + y
  g
}
In the following, I get what I expect based on my understanding of
lexical scoping:
(f(1))(3) # 4
(f(2))(3) # 5
But now,
fs <- lapply(c(1, 2), f)
fs[[1]](3) # 5  (Why not 4 ?)
fs[[2]](3) # 5
Checking the environments of these functions, I see that "y" is indeed
bound to the value 2 in both cases:
es <- lapply(fs, environment)
ys <- lapply(es, function(env) get("y", env)) # list(2, 2)
?
Thanks for help,
Jim Rogers
James A. Rogers, Ph.D. <rogers at cantatapharm.com>
Statistical Scientist
Cantata Pharmaceuticals
3-G Gill St
Woburn, MA  01801
617.225.9009
Fax 617.225.9010
    
    
More information about the R-help
mailing list