Skip to content

Applying 'lm' in each group

4 messages · Bhargab Chattopadhyay, David Winsemius, Ben Bolker +1 more

#
Did you read the error message? Generally saying "doesn't work" will  
elicit undesirable responses.

Now would be a good time to read the Posting Guide:

http://www.R-project.org/posting-guide.html

Including:
"Say exactly what happened, including any error messages you received. "

 > lm(yg~xg)
Error in model.frame.default(formula = yg ~ xg, drop.unused.levels =  
TRUE) :
   invalid type (list) for variable 'yg'

You need to offer lm an object that it can use. You actually shot  
yourself in the foot by turning your data into a list. It's not clear  
what you actually want, but perhaps this will move you a bit further  
along:

  dfg <- data.frame(y=unlist(yg), x=unlist(xg), g=g)
  lm(y ~ x | g, data= dfg)

Which would also be the same result as the following (without the  
detour to the yg and xg lists.)

lm(y ~ x + g)

It's also possible that what you really wanted was:

lm(y ~ x + as.factor(g)) # which estimates mean differences of grp=2  
and grp=3 from grp=1 with a common estimated slope of y on x.

Or even lm(y ~ x * as.factor(g)) which gives you separate slopes and  
mean differences from those estimated for group 1 for groups 2 and 3  
and is most consistent with the phrase "separate regressions in each  
of three groups".
#
Bhargab Chattopadhyay <bhargab_1 <at> yahoo.com> writes:
Now I want to run regression
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
#
On 1/10/2009 12:55 PM, Bhargab Chattopadhyay wrote:
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