[R] lexical scope

Laurent Gautier laurent at cbs.dtu.dk
Tue Apr 22 07:31:36 CEST 2003


On Tue, Apr 22, 2003 at 04:07:39PM +1200, Robin Hankin wrote:
> Hi everyone
> 
> another documented feature that was a bit unexpected for me:
> 
> R> x <- 19
> R> f <- function(t){t+x}
> R> f(100)
> [1] 119
> 
> --as expected: x is visible from within f()
> ..but...
> 
> 
> R> g <- function(a){x <- 1e99 ; return(f(a))}
> R> g(4)
> [1] 23
> 
> --the "x" that is visible from within g() is just 19, which is not the
>   one I expected it to find.
> 
> 
> R> rm(x)
> R> g(4)
> Error in f(a) : Object "x" not found
> 
> --g() looks in the first search path place and finds it empty,
>   returning an error.
> 
> 
> QUESTIONS:
> Why doesn't g()  "keep looking" ?
> How do I tell g() where to find x?
> Where to look for documentation for this?
> 

(TENTATIVE) ANSWERS:

1- becase the enclosing frame for f is .GlobalEnv.
2- f <- function(t){t+get("x", envir=parent.frame())}
3- R language definition p.22 is a place to start


Hopin' it helps,




L.
>  
> 
> -- 
> 
> Robin Hankin, Lecturer,
> School of Geography and Environmental Science
> Tamaki Campus
> Private Bag 92019 Auckland
> New Zealand
> 
> r.hankin at auckland.ac.nz
> tel 0064-9-373-7599 x6820; FAX 0064-9-373-7042
> 
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://www.stat.math.ethz.ch/mailman/listinfo/r-help

-- 
--------------------------------------------------------------
currently at the National Yang-Ming University in Taipei, Taiwan
--------------------------------------------------------------
Laurent Gautier			CBS, Building 208, DTU
PhD. Student			DK-2800 Lyngby,Denmark	
tel: +45 45 25 24 89		http://www.cbs.dtu.dk/laurent



More information about the R-help mailing list