[R] Applying 'lm' in each group

Chuck Cleland ccleland at optonline.net
Sat Jan 10 20:37:53 CET 2009


On 1/10/2009 12:55 PM, Bhargab Chattopadhyay wrote:
> Hi,
> 
> 
>  I want to do regression in each group. I made the group the following way. Now I want to run regression in each of the three groups..
> Suppose , 
> x<-c(0.5578196,6.5411662,13.2728619,2.0217271,6.7216176,3.37220617,2.5773252,7.2600583,15.3731026,3.4140288,8.1335874,
>     15..6476637,4.3014084,9.1224379,18.5605355,4.7448394,11.9296663,18.5866354,12.3797674,18.7572812,2.70433816,2.88924220,
>     2.94688208,3.37154364,2.26311786,3.31002593)
>   
> y<-c(18.63654,233.55387,152.61107,103.49646,234.55054,14.2767453,160.78742,150.35391,223.89225,168.55567,190.51031,
>     227.68339,152.42658,208.70115, 223.91982, 221.70702, 213.71135,168.0199, 222.69040,228.49353, 164.95750,243.18828,
>     229.94688,313.37154364,202.263786,139.31002593)
> 
> n<-length(x)
> m<-3;
> r<-8;
> c<-r*(m-1);
> g1<-rep(1:(m-1),each=r);        
> g<-c(g1,rep(m,n-c))
> xg<-split(x,g);
> yg<-split(y,g);
> 
> Now if I write lm(yg~xg) then it won't work. Please advice how to proceed.

mdf <- data.frame(y,x,g)

lapply(split(mdf, g), function(X){lm(y ~ x, data = X)})
$`1`

Call:
lm(formula = y ~ x, data = X)

Coefficients:
(Intercept)            x
      76.11        10.85


$`2`

Call:
lm(formula = y ~ x, data = X)

Coefficients:
(Intercept)            x
    166.693        3.580


$`3`

Call:
lm(formula = y ~ x, data = X)

Coefficients:
(Intercept)            x
    218.412       -0.735

> Thanks in advance.
> 
> Bhargab
> 
> 
> 
>       
> 	[[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.

-- 
Chuck Cleland, Ph.D.
NDRI, Inc. (www.ndri.org)
71 West 23rd Street, 8th floor
New York, NY 10010
tel: (212) 845-4495 (Tu, Th)
tel: (732) 512-0171 (M, W, F)
fax: (917) 438-0894




More information about the R-help mailing list