[R] creating a formula on-the-fly inside a function
Gabor Grothendieck
ggrothendieck at myway.com
Thu Mar 3 16:57:21 CET 2005
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
More information about the R-help
mailing list