[R] Evaluation of global variables in function definitions

H. Dieter Wilhelm dieter at duenenhof-wilhelm.de
Wed Oct 8 11:53:47 CEST 2014


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.  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
-- 
Best wishes
H. Dieter Wilhelm
Darmstadt, Germany



More information about the R-help mailing list