[R] Grouped regression

David Winsemius dwinsemius at comcast.net
Sun Jul 8 13:29:29 CEST 2012

On Jul 8, 2012, at 4:11 AM, Suresh Krishna wrote:

> Hi,
> I am a very occasional user of R, and will be grateful for some  
> help  in constructing a regression across groups.
> Here is an example:
> library(MASS)
> attach(cats)
> Sex[120:144]<-factor(TG) #Renaming some males to transgender, to  
> create 3 groups, male, female and transgender

That throws an error for me. (and I expected it to do so since I was  
guessing the "TG" was not in the levels of cats$Sex.) The error  
actually had nothing to do with the lack of a "TG"  level, but was  
instead due to the lack of a TG object in my workspace. Didn't you get  
an error?

If a level does not exist then you need to add it before you make  
assignments to a facotr variable:

 > levels(Sex) <- c(levels(Sex), "TG")
 > Sex[120:144]<-"TG"
 > table(Sex)
  F  M TG
47 72 25

> out<-lm(Bwt~Sex/Hwt) #Gives me 3 separate linear regressions for  
> groups M, F and TG
> What I now want to do is to examine subsets of this, where groups F  
> and TG have the same slope (and/or intercept). I want to do this in  
> such a way that future calls to anova() for model comparison will  
> recognize the subset structure: so I do not want to just reset the  
> levels with F to TG and then examine the regression.

I'm getting the sense that this is homework. You offer no information  
about you business or academic affiliations and appear not to have  
read the Posting Guide. Also setting up regressions is covered in the  
"Introduction to R" which you are requested to have reviewed before  
asking questions on Rhelp. Section 11 would be particularly relevant  


David Winsemius, MD
Heritage Laboratories
West Hartford, CT

More information about the R-help mailing list