[R] generate a series of fucntion

Richard A. O'Keefe ok at cs.otago.ac.nz
Tue Jul 22 02:22:36 CEST 2003

ximing wu <xiwu at uoguelph.ca> wrote:
	> I want to generate a large amount of functions,
	> say f=function(x,t) exp(-t[1]-t[2]*g_1(x)-t[3]*g_2(1+x))
	> where g_1(x) and g_2(x) are from a long list of moments, such 
	> as x, x^2, 
	> log(x), log(1+x) .. and so on.
	> Any suggestions on how to do this efficiently?

Unfortunately, outer() doesn't like function elements.

Let's suppose you have vectors g.1[1:n] and g.2[1:n],
and that you want to construct a list f[1:n] of functions.

f <- lapply(1:n, function(i) {
        p <- g.1[i]
        q <- g.2[i]
        function (x, t) exp(-t[1] - t[2]*p(x) - t[3]*q(x))

will make a list of n functions.  Note that the function passed to lappy()
returns a function.  In R, it returns a *different* function each time,
and each of these points to an environment with its own copy of p and q.

More information about the R-help mailing list