[R] about eval and eval.parent
Thomas Lumley
tlumley at u.washington.edu
Fri Nov 18 16:05:10 CET 2005
On Fri, 18 Nov 2005, ronggui wrote:
> x<-1
> f<-function(){
> x<-3
> eval(substitute(x+y,list(y=10)))
> }
> f() #13
>
> x<-1
> f<-function(){
> x<-3
> eval(substitute(x+y,list(y=10)), envir = sys.frame(sys.parent()))
> }
> f() #11
>
> x<-1
> f<-function(){
> x<-3
> eval.parent(substitute(x+y,list(y=10)))
> }
> f()#11
>
>
> the help page says:
> "If 'envir' is
> not specified, then 'sys.frame(sys.parent())', the environment
> where the call to 'eval' was made is used. "
>
> But it seems that the first one is not equal to the second one.
No, it isn't. This is because default arguments are evaluated inside the
function but explicit argumnets are evaluated in the calling frame
In the first one, sys.frame(sys.parent()) is evaluated in the environment
inside f(), and so refers to the frame from which f() was called. That's
what you would expect from pass-by-value
In the second one, sys.frame(sys.parent()) is evaluated inside
substitute() and refers to the environment inside f(). That might be
surprising, which is why it is documented.
-thomas
More information about the R-help
mailing list