[R] Coefficient names when using lm() with contrasts

Greg Snow Greg.Snow at imail.org
Wed Aug 3 20:02:14 CEST 2011


If you add column names to your contrast matrix (treat3) then those names will be used in the coefficient names.

-- 
Gregory (Greg) L. Snow Ph.D.
Statistical Data Center
Intermountain Healthcare
greg.snow at imail.org
801.408.8111


> -----Original Message-----
> From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-
> project.org] On Behalf Of Peter Morgan
> Sent: Wednesday, August 03, 2011 6:12 AM
> To: r-help at r-project.org
> Subject: [R] Coefficient names when using lm() with contrasts
> 
> Dear R Users,
> 
> Am using lm() with contrasts as below. If I skip the contrasts()
> statement, I get the coefficient names to be
> > names(results$coef)
> [1] "(Intercept)" "VarAcat"     "VarArat"     "VarB"
> 
> which are much more meaningful than ones based on integers.
> 
> Can anyone tell me how to get R to keep the coefficient names based on
> the
> factor levels whilst using contrasts rather than labelling them with
> integers?
> 
> Many thanks in advance,
> 
> Pete
> 
> Cardiff, UK
> 
> > dt=read.table("testreg.txt",sep=",",header=T)
> > dt
>    ID VarA VarB VarC
> 1   1  cat    2   23
> 2   2  dog    3   56
> 3   3  rat    5   35
> 4   4  cat    2   43
> 5   5  cat    7   51
> 6   6  dog    3   31
> 7   7  dog    4   65
> 8   8  rat    1   18
> 9   9  rat    6   49
> 10 10  dog    3   28
> > dt$VarA=relevel(dt$VarA,ref="dog")
> > treat3=matrix(-1/3,ncol=2,nrow=3); for (i in 1:2) {treat3[i+1,i]=2/3}
> > contrasts(dt$VarA)=treat3
> > levels(dt$VarA)
> [1] "dog" "cat" "rat"
> > results=lm(formula=VarC~VarA+VarB, data=dt)
> > names(results$coef)
> [1] "(Intercept)" "VarA1"       "VarA2"       "VarB"
> 	[[alternative HTML version deleted]]
> 
> ______________________________________________
> 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