[R] Retrieving value computed in inner function call

Juan Pablo Lewinger lewinger at usc.edu
Wed Sep 13 02:34:13 CEST 2006


Dear R users,

Consider the following example function:

f = function(a,b) {
    g = function(x) a*x + b
    h = function(x) g(x)^2 + x^2
    opt = optimize(h,lower = -1, upper = 1)
    x.min = opt$minimum
    h.xmin = opt$objective
    g.xmin = g(x.min)
    return(c(x.min, h.xmin, g.xmin))
}

In my real problem the function that plays the role of "g" is costly 
to compute. Now, to minimize "h", "optimize" calls "h" with different 
values of x. In particular, at the end of the optimization, "h" would 
be called with argument x.min, the minimizer of h(x). Therefore, 
buried somewhere, there has to be a call to "g" with argument x=x.min 
which I would like to retrieve in order to avoid the extra call to 
"g" in the line before the return. Can this be done without too much pain?

I'd very much appreciate any help.



Juan Pablo Lewinger
Department of Preventive Medicine
University of Southern California



More information about the R-help mailing list