[R] Evaluation of global variables in function definitions

Duncan Murdoch murdoch.duncan at gmail.com
Wed Oct 8 22:02:10 CEST 2014


On 08/10/2014 5:53 AM, H. Dieter Wilhelm wrote:
> Duncan Murdoch <murdoch.duncan at gmail.com> writes:
>
> > On 07/10/2014 2:45 AM, H. Dieter Wilhelm wrote:
> >> Hello (),
> >>
> >> I'd like to do the following
> >>
> >> a <- 3
> >> f1 <- function (x){
> >>   a*x^2
> >> }
> >>
> >> a <- 5
> >> f2 <- function (x){
> >>   a*x^2
> >> }
> >>
> >> plotting f1, f2, ...
> >>
> >> but f1 and f2 are the same, how can I evaluated the variables in the
> >> function definition?
> >>
> >> Thank you
> >>        Dieter
> > See the "open.account" example in section 10.7, "Scope", of the
> > Introduction to R manual.
>
> Sorry but above section teaches my how to change global variables in
> functions.

That's only part of what it tells you.  The open.account example binds 
values into the environment of the function.  That's what you want to 
do:  when you create f1, you want the values of a,b,c, etc. bound into 
its environment.  Then when you create f2, you want new values bound 
there.  So do it something like this:

makefun <- function(a,b,c,d) {
   force(a); force(b); force(c); force(d) # evaluate them now!
   function(x)  a*x+b*exp(x)+c/x+...
}

a <- complicated_a_computation(args1)
b <- complicated_b_computation(args1)
c <- ...
d
...

f1 <- makefun(a,b,c,d)

a <- complicated_a_computation(args2)
b <- complicated_b_computation(args2)
c <- ...
d
...

f2 <- makefun(a,b,c,d)

Duncan Murdoch

>   But I would like to overcome the "lazy evaluation" of global
> variables in functions.  Because I can't put expensive computations into
> each function.
>
> a <- complicated_a_computation(args1)
> b <- complicated_b_computation(args1)
> c <- ...
> d
> ...
>
> f1 <- function(x) a*x+b*exp(x)+c/x+...
>
> a <- complicated_a_computation(args2)
> b <- complicated_b_computation(args2)
> c <- ...
> d
> ...
>
> f2 <- function(x) a*x+b*exp(x)+c/x +...
>
> Yes in principle I could rename the global variables to a1, a2, b1, b2,
> ...  But I'd like to learn the principles of R.  Is above somehow
> possible with the use of the substitute() command?
>
> Thanks



More information about the R-help mailing list