fFactory <- function(args) { a <- complicated_a_computation(args) b <- complicated_b_computation(args) function(x) a*x + b*exp(x) } f1 <- fFactory(args1) f2 <- fFactory(args2)
f1(x) f2(x) # will get different result than f1(x) f1 and f2 will look the same but produce different results because environment(f1) contains different values of a and b than environment(f2). Bill Dunlap TIBCO Software wdunlap tibco.com On Wed, Oct 8, 2014 at 2:53 AM, H. Dieter Wilhelm <die...@duenenhof-wilhelm.de> wrote: > Duncan Murdoch <murdoch.dun...@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 > > ______________________________________________ > R-help@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. ______________________________________________ R-help@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.