Re: [R] creating a formula on-the-fly inside a function

From: Gabor Grothendieck <ggrothendieck_at_myway.com>
Date: Fri 04 Mar 2005 - 02:57:21 EST

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



R-help@stat.math.ethz.ch mailing list
https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html Received on Fri Mar 04 09:49:11 2005

This archive was generated by hypermail 2.1.8 : Fri 03 Mar 2006 - 03:30:40 EST