[R] Build function from model formula

Corey Dow-Hygelund godelstheory at gmail.com
Sat Mar 14 01:02:12 CET 2009


Hi fellow R-users,

I am (attempting) to take a formula object, and convert it into a
function which I can feed into optim.  Basically, I have several
functions that fit the formula object to data, and analyze the
results.  The next step would be to combine the fitting function
coefficient results and formula object into a function, which can be
passed to optim.

So, I am looking for a method, set of methods, or package(s) that are
designed to do this process.  So far, I have had no luck in
determining any easy ways to resolve this issue, other than stringing
together a string, and using eval(parse"string").

Example:

formula<-as.formula(y~ (x1+x2)^2 + I(x1^2)+I(x2^2))

# becomes

func(x)<-function{coef[1] + coef[2]*x[1] + coef[3]*x[2]+
coef[4]*x[1]^2+coef[5]*x[2]^2 +coef[6]*x1*x2}

#where coef is a vector containing the fitted coefficient values.


Any ideas?

Corey




More information about the R-help mailing list