[R] Intercepts in linear models.

Liaw, Andy andy_liaw at merck.com
Thu Mar 23 20:48:52 CET 2006


update() simply calls the model fitting function again using the new
arguments, which means one redundant model fit.

What I would do is construct the formula beforehand, e.g.,

myformula <- if (cflag) y ~ x else y ~ x - 1

or something like that.

Andy

From: Gabor Grothendieck
> 
> You can use update to modify a formula:
> 
>    fo <- y ~ x
>    fo <- update(fo, . ~ . -1)
> 
> willl remove the intercept.  See ?update.formula
> 
> On 3/23/06, Rolf Turner <rolf at math.unb.ca> wrote:
> > A colleague asked me if there is a way to specify with a
> > ***variable*** (say ``cflag'') whether there is an intercept in a 
> > linear model.
> >
> > She had in mind something like
> >
> >        lm(y ~ x - cflag)
> >
> > where cflag could be 0 or 1; if it's 0 an intercept should
> > be fitted, if it's 1 then no intercept.
> >
> > This doesn't work ``of course''.  The cflag just gets treated as 
> > another predictor and because it is of the wrong length an error is 
> > generated.
> >
> > The best I could come up with was
> >
> >        lm(as.formula(paste("y ~ x -",cflag)))
> >
> > Which is kludgy.  It (of course!) also be done using an
> > if statement.
> >
> > Is there a sexier way?
> >
> >                                cheers,
> >
> >                                        Rolf Turner
> >
> > ______________________________________________
> > R-help at 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
> >
> 
> ______________________________________________
> R-help at 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
> 
>




More information about the R-help mailing list