[R] Fitting model with varying number of predictors
Prof Brian Ripley
ripley at stats.ox.ac.uk
Fri Nov 18 09:32:34 CET 2005
On Fri, 18 Nov 2005, Juni Joshi wrote:
>
> I need to fit a number of models with different number of predictors
> in each model. Say for example, I have three predictors: x1, x2, x3
> and I want to fit three models:
>
> lm(y~x1+x2)
> lm(y~x2+x3)
> lm(y~x1+x2+x3)
>
> Instead of typing all models, what I want is to create a variable
> which can take the right hand side of the models. I tried this with
> paste function.
>
> xxx <- paste("x1","x2",sep=+) for the first
This gives a syntax error!
> xxx <- paste("x2","x3", sep = +) for the second
> xxx <- paste("x1","x2","x2", sep = +) for the third and then fit a
> single model
>
> lm(y~xxx)
>
> It did not work. Please suggest how to do it.
You want a formula here, and you also need to use code without syntax
errors. For example
> xxx <- paste("x1", "x2", sep="+")
> lm(as.formula(paste("y ~", xxx)))
But a better idea would be to put all your variables into a data frame DF
and do
use <- c("x1", "x2") # set as appropriate
lm(y ~ ., data=DF[c("y", use)])
--
Brian D. Ripley, ripley at stats.ox.ac.uk
Professor of Applied Statistics, http://www.stats.ox.ac.uk/~ripley/
University of Oxford, Tel: +44 1865 272861 (self)
1 South Parks Road, +44 1865 272866 (PA)
Oxford OX1 3TG, UK Fax: +44 1865 272595
More information about the R-help
mailing list