[R] eval parent.frame() twice

Peter Dalgaard P.Dalgaard at biostat.ku.dk
Fri Aug 7 13:27:40 CEST 2009


Rune Schjellerup Philosof wrote:
> Hi
> 
> I want to use a function (update) that in its body uses
> eval(call, parent.frame())
> 
> I would like to use this function in a function that does not contain
> the variables referred to in 'call'. Those variables are instead in the
> parent.frame() of my function (named 'second' below)
> 
> Like this:
> a <- 2
> 
> evalu <- function(obj) {
>  call <- obj$call
>  eval(call, parent.frame())
> }
> first <- function() {
>  a <- 3
>  obj <- list(call=expression(a))
>  second(obj)
> }
> second <- function(obj) {
>  eval(evalu(obj), parent.frame())
> }
> 
> first() #returns 2, but I want 3.
> 
> 
> How do I change 'second' such that the value of 'a' from 'first' is
> returned?
> 

You could use the "n" argument to parent.frame (or eval.parent) inside
"evalu" and go two generations back instead of one. Somewhat neater, you
could pass the desired environment directly to evalu, as in

e <- parent.frame()
evalu(obj, e)

(I'm not sure it is actually needed to separate out the calculation of
"e", but I tend to be paranoid about evaluating parent.frame() in
function arguments.)


-- 
   O__  ---- Peter Dalgaard             Øster Farimagsgade 5, Entr.B
  c/ /'_ --- Dept. of Biostatistics     PO Box 2099, 1014 Cph. K
 (*) \(*) -- University of Copenhagen   Denmark      Ph:  (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk)              FAX: (+45) 35327907




More information about the R-help mailing list