Re: [R] help with eval

From: Gabor Grothendieck <ggrothendieck_at_gmail.com>
Date: Sat 14 May 2005 - 15:28:20 EST

The scope of variables within show.a is not affected by the environment that show.a is called in. The scope of the variables in show.a is determined by the lexical scope of show.a although you can change this via:

  environment(show.a) <- my.env
  show.a() # 200

If you want to create a function that has dynamic (i.e. scope is the caller), rather than lexical scope, do this:

   show2.a <- function() {

      show2.a <- function() a 
      environment(show2.a) <- parent.frame()
      show2.a()

   }
  evalq(show2.a(), my.env) # 200

or you can create a function which evaluates its body in the parent.frame:

   show3.a <- function() eval.parent(substitute(a))    evalq(show3.a(), my.env) # 200

Also, depending on what you actually want to do, the proto package may be applicable.

On 5/13/05, Whit Armstrong <whit@twinfieldscapital.com> wrote:
> I've been looking at the help page for eval for a while, but I can't
> make sense of why this example does not work.
>
> show.a <- function() {
> a
> }
>
> init.env <- function() {
> a <- 200
> environment()
> }
>
> my.env <- init.env()
>
> ls(envir=my.env)
>
> # returns this:
> # > ls(envir=my.env)
> # [1] "a"
>
> # but this does not work:
> eval(expression(show.a()),envir=my.env)
>
> # > eval(expression(show.a()),envir=my.env)
> # Error in show.a() : Object "a" not found
> # >
>
> The help page gives the following:
>
> 'eval' evaluates the expression 'expr' argument in the environment
> specified by 'envir' and returns the computed value. If 'envir' is
> not specified, then 'sys.frame(sys.parent())', the environment
> where the call to 'eval' was made is used.
>
> I would be grateful for any help.
>
> Thanks,
> Whit
>
> [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help@stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
>



R-help@stat.math.ethz.ch mailing list
https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html Received on Sat May 14 15:34:52 2005

This archive was generated by hypermail 2.1.8 : Fri 03 Mar 2006 - 03:31:46 EST