[R] eval in parent frame: scoping rule confusion

Peter Dalgaard BSA p.dalgaard at biostat.ku.dk
Fri Mar 15 10:42:54 CET 2002


Thomas Lumley <tlumley at u.washington.edu> writes:

> On Thu, 14 Mar 2002, Jonathan Q. Li wrote:
> 
> > Hi all,
> >
> > Look at the following "stupid" function that is created just to show the
> > problem:
> >
> > outlayer <- function(x)
> > {
> > 	inlayer <- function(z){
> > 		e1 <- parent.frame()
> > 		eval(expression(y<-log(z)),e1)
> >  	}
> > 	inlayer(10)
> > y
> > }
> >
> > I have a compilation error when running this. My purpose is to create "y"
> > variable equal to log(z) in
> > the frame of "outlay". How can I achieve this?
> 
> The problem is that you can't evaluate y<-log(z) in the outer frame since
> there is no z in the outer frame.  You want to evaluate y<-log(10) (or
> whatever z happens to be)
> One way to do this is to replace your eval() with
>   eval(substitute(y<-log(z)),e1)
> 
> 
> Whether that's the best way depends on what your real example looks like.

The example tries to use dynamic scope, which may not be the best
idea. The canonical way using *lexical* scope would be:

outlayer <- function(x)
{
    inlayer <- function(z){
          y <<- log(z)
    }
    y <- 0 # or whatever, y must exist before <<- is used
    inlayer(10)
    y
}


-- 
   O__  ---- Peter Dalgaard             Blegdamsvej 3  
  c/ /'_ --- Dept. of Biostatistics     2200 Cph. N   
 (*) \(*) -- University of Copenhagen   Denmark      Ph: (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk)             FAX: (+45) 35327907
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._



More information about the R-help mailing list