Skip to content
Prev 132675 / 398506 Next

Understanding eval

On Dec 22, 2007, at 4:44 PM, Duncan Murdoch wrote:
Thank you Duncan, for the very clear explanation.

Ok, so the substitute "breaks through" the promise of expr, returning  
as a language object the promise of er, and there's no easy way to  
break through that. I ended up with the following, somewhat uglier  
than I wanted, code, which seems to do what I need in this case, and  
hopefully will still work in the more general case I want it to. The  
idea was to break through the er promise in bar, before sending it  
over to foo. Then foo receives simply an expression, which it can  
then evaluate. Though I seem to have had to work a bit harder on that  
part than I expected to. Perhaps there's an easier way? Or things  
that can go seriously wrong with this way?

foo <- function(fr, expr) {
   ..obj <- list(.=fr)
   ..expr <- substitute(expr)
   ..txt <- parse( text=paste("substitute(",..expr,")") )
   ..expr <- eval(..txt, ..obj, parent.frame())
   ..expr <- eval(..expr, parent.frame())
   eval(..expr, ..obj)
}
bar <- function(parent, er, ...) {
   .fr=parent
   g <- substitute(er)
   foo(.fr, g)
}

 > foo(5,.)
[1] 5
 > bar(5,.)
[1] 5
Haris Skiadas
Department of Mathematics and Computer Science
Hanover College