[R] The default argument 'envir' of eval()

Duncan Murdoch murdoch at stats.uwo.ca
Tue Feb 9 18:31:56 CET 2010


On 09/02/2010 12:18 PM, bluesky315 at gmail.com wrote:
> In ?eval, it says
>
>     ...  If ‘envir’ is not
>     specified, then the default is ‘parent.frame()’ (the environment
>     where the call to ‘eval’ was made).
>
> I tried the following example with "eval(expr)"  and "eval(expr,
> parent.frame())" in f(). The results are different, which are not
> consistent with the help. Could somebody let know whether I
> misunderstand the help? Or there is something with the help?
>   

The help is correct, you misunderstood it.  Default values for arguments 
are evaluated in the evaluation frame of the function.  Explicit 
arguments are evaluated in the evaluation frame of the caller.  
parent.frame() has different meanings in those two contexts.

Duncan Murdoch
>
> > expr=expression(print(paste('x =', x)))
> > x=0
> > f=function() {
> +   x=2
> +   eval(expr)
> +   eval(expr, parent.frame())
> +   eval(expr, parent.frame(2))
> +   eval(expr, parent.frame(3))
> + }
> > g=function() {
> +   x=1
> +   f()
> + }
> >
> > g()
> [1] "x = 2"
> [1] "x = 1"
> [1] "x = 0"
> [1] "x = 0"
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>



More information about the R-help mailing list