[R] Get variable names from results of lm()

William Dunlap wdunlap at tibco.com
Wed May 23 21:31:03 CEST 2012


You might want to look at
  https://stat.ethz.ch/pipermail/r-help/2012-April/310582.html

Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com


> -----Original Message-----
> From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org] On Behalf
> Of Marc Schwartz
> Sent: Wednesday, May 23, 2012 12:13 PM
> To: Peter Ehlers
> Cc: r-help at r-project.org; jdub
> Subject: Re: [R] Get variable names from results of lm()
> 
> 
> On May 23, 2012, at 1:42 PM, Peter Ehlers wrote:
> 
> > On 2012-05-23 09:55, R. Michael Weylandt wrote:
> >> I think the easiest that comes to mind is simply
> >>
> >> names(coef(myMod))
> >>
> >> But did you look at myMod$terms[[3]] ? That seems to be the RHS of the
> >> formula input (in the few cases I tried)
> >>
> >> Best,
> >> Michael
> >
> > It depends a bit on just what the OP wants. In case one of the
> > predictors is a factor, say 'grp' with levels c('A','B','C'), the
> > coefs will include the names 'grpB' and 'grpC'. If only the
> > name 'grp' is wanted, one could use myMod$terms[[3]] or
> > equivalently formula(myMod)[[3]]. It might be instructive for the
> > OP to look at as.list(formula(myMod)). formula(myMod) is a
> > language object which has the tilde operator operate on
> > the LHS (component 2) and the RHS (component 3).
> >
> > Peter Ehlers
> 
> 
> Just to throw out another solution here, the function ?all.vars is helpful:
> 
> LM <- lm(Petal.Length ~ ., data = iris)
> 
> > formula(LM)
> Petal.Length ~ Sepal.Length + Sepal.Width + Petal.Width + Species
> 
> > all.vars(formula(LM))
> [1] "Petal.Length" "Sepal.Length" "Sepal.Width"  "Petal.Width"
> [5] "Species"
> 
> 
> Regards,
> 
> Marc Schwartz
> 
> 
> >> On Wed, May 23, 2012 at 10:58 AM, jdub<jack at ramas.com>  wrote:
> >>>
> >>> What is the best way to get the variable names used in lm() from its
> >>> results?
> >>>
> >>> Stumbling around I found I could get the response variable name from
> >>>
> >>> myMod$terms[[2]]
> >>>
> >>> but using
> >>>
> >>> myMod$terms[[1 ]]
> >>>
> >>> gives a tilda.
> >>>
> >>> I found the names buried in other places in the model object and in the
> >>> summary of the model, but is there a more direct way, similar to using
> >>> coef(myMod) to get the coefficients?
> 
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list