[R] Applying 'lm' in each group

Ben Bolker bolker at ufl.edu
Sat Jan 10 20:34:05 CET 2009


Bhargab Chattopadhyay <bhargab_1 <at> yahoo.com> writes:

> 
> 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 , 
> w
> 
> Now if I write lm(yg~xg) then it won't work. Please advice how to proceed.
> 
> Thanks in advance.
> 

 The one-liner is


mapply(function(x,y) lm(y~x,data=data.frame(x,y)),xg,yg,
       SIMPLIFY=FALSE)

Perhaps easier to understand:

results <- list()
for (i in seq(along=xg)) {
  results[[i]] <- lm(yg[[i]]~xg[[i]])
}

  Ben Bolker




More information about the R-help mailing list