Skip to content
Prev 263205 / 398502 Next

for loop and linear models

Hi:

(a) What Brian said...

(b) Here's one way to generate a list of model objects from which you
can extract the pieces you may want.

# Generate a fairly minimal, reproducible data set
set.seed(345)   # makes results below reproducible
dd <- data.frame(X = rnorm(100), Y = rnorm(100),
                  gp = factor(rep(LETTERS[1:5], each = 20)))

# Basically, split the data frame by gp into a list of sub-data frames
# and fit lm() to each piece. We use the plyr package for this:
library(plyr)
mlist <- dlply(dd, .(gp), function(d) lm(Y ~ X, data = d))

# mlist is a list of lm objects, from which you can extract salient
# pieces using the l*ply functions from plyr. For example,

# return the coefficients from each model fit:
gp (Intercept)            X
1  A -0.05670893 -0.008741077
2  B -0.41071309 -0.134832968
3  C -0.02007992  0.379762195
4  D  0.04168990  0.213085495
5  E  0.19094314  0.010481033

# R^2:
gp           V1
1  A 9.287934e-05
2  B 1.684219e-02
3  C 1.200286e-01
4  D 4.235989e-02
5  E 7.294735e-05

# Table of coefficients, SEs and significance tests
# (outputs a list)
llply(mlist, function(m) summary(m)$coefficients)

# Data frame of predicted values and residuals (multiple outputs):
ldply(mlist, function(m) data.frame(pred = fitted(m), res = resid(m)))

HTH,
Dennis
On Mon, Jun 20, 2011 at 12:23 PM, ivan <i.petzev at gmail.com> wrote: