Skip to content
Back to formatted view

Raw Message

Message-ID: <loom.20050303T165448-537@post.gmane.org>
Date: 2005-03-03T15:57:21Z
From: Gabor Grothendieck
Subject: creating a formula on-the-fly inside a function

Dr Carbon <drcarbon <at> gmail.com> writes:

: 
: I have a function that, among other things, runs a linear model and
: returns r2. But, the number of predictor variables passed to the
: function changes from 1 to 3. How can I change the formula inside the
: function depending on the number of variables passed in?
: 
: An example:
: 
: get.model.fit <- function(response.dat, pred1.dat, pred2.dat = NULL,
: pred3.dat = NULL)
: {
:     res <- lm(response.dat ~ pred1.dat + pred2.dat + pred3.dat)
:     summary(res)$r.squared
:     # other stuff happens here...
: }


The following allows any number of predictors:

 f <- function(y, ...) summary(lm(y ~., data.frame(y = y, ...)))$r.squared

Another possibility is to just pass the formula itself:

 f <- function(fo) summary(lm(fo))$r.squared