[R] Retrieving value computed in inner function call

From: Juan Pablo Lewinger <lewinger_at_usc.edu>
Date: Wed 13 Sep 2006 - 00:34:13 GMT


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



R-help@stat.math.ethz.ch 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. Received on Wed Sep 13 10:40:30 2006

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.1.8, at Wed 13 Sep 2006 - 06:30:04 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.