Skip to content
Prev 65334 / 398502 Next

creating a formula on-the-fly inside a function

On Thu, 2005-03-03 at 10:28 -0500, Dr Carbon wrote:
Consider using as.formula() to take a character vector that you pass as
an argument instead of specifying each IV separately:

get.model.fit <- function(my.form)
{
    res <- lm(as.formula(my.form))
    summary(res)$r.squared
    # other stuff happens here...
}


Then call it with:

get.model.fit("y ~ x1 + x2 + x3")

Internally, the vector will be converted to:
y ~ x1 + x2 + x3

Doing it this way provides for greater flexibility if you want to use a
more complicated formula construct.

See ?as.formula for more information and further examples, including the
use of paste() if you want to separate the DV from the IVs for an
additional approach for a long set of similarly named IV's (ie x1:x25).

HTH,

Marc Schwartz