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

Dr Carbon drcarbon at gmail.com
Thu Mar 3 16:28:10 CET 2005

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)
    # other stuff happens here...

y <- rnorm(10)
x1 <- y + runif(10)
x2 <- y + runif(10)
x3 <- y + runif(10)
get.model.fit(y, x1, x2, x3)
get.model.fit(y, x1, x2)
get.model.fit(y, x1)

Many thanks....

> version
platform i386-pc-mingw32
arch     i386           
os       mingw32        
system   i386, mingw32  
major    2              
minor    0.1            
year     2004           
month    11             
day      15             
language R

More information about the R-help mailing list