Skip to content
Prev 302522 / 398503 Next

Force evaluation of a symbol when a function is created

Thank you both, this was very helpful.  I need to study environments more. Do either of you know a good source?
 

-----Original Message-----
From: Bert Gunter [mailto:gunter.berton at gene.com] 
Sent: Monday, August 06, 2012 6:03 PM
To: William Dunlap
Cc: Schoenfeld, David Alan,Ph.D.,Biostatistics; r-help at r-project.org
Subject: Re: [R] Force evaluation of a symbol when a function is created

Thanks to both: Cute question, clever, informative answer.

However, Bill, I don't think you **quite** answered him, although the
modification needed is completely trivial. Of course, I could never
have figured it out without your response.

Anyway, I interpret the question as asking for the function definition
to _implicitly_ pick up the value of Y at the time the function is
defined, rather than explicitly assigning it in local(). The following
are two essentially identical approaches: I prefer the second, because
it's more transparent to me, but that's just a matter of taste.

Y <- 3
F <-local({y <- Y;function(x)x*y})
G <- evalq(function(x)x*y,env=list(y=Y))

Yielding:
[1] 15
[1] 15
[1] 15
[1] 15
[1] 10
[1] 10

Cheers,
Bert
On Mon, Aug 6, 2012 at 2:24 PM, William Dunlap <wdunlap at tibco.com> wrote: