Hi:

Here's an example of how to extract pieces from model objects using the plyr
package. I'm using the attitude data set from the datasets package
(autoloaded).

# Generate four models
m1 <- lm(rating ~ ., data = attitude)
m2 <- lm(rating ~ complaints + learning, data = attitude)
m3 <- lm(rating ~ complaints * learning, data = attitude)
m4 <- lm(rating ~ complaints, data = attitude)
# Combine them into a list
mlist <- list(m1 = m1, m2 = m2, m3 = m3, m4 = m4)

# Utility functions:
# In this context, x represents a generic model object. We want
# to extract the same information from each object.
# Can package these (or others) into a single function if you
# wish to output a list object.

# Sums of squares extraction:
ss <- function(x) summary(x)$coefficients[, 2]

# R^2
r2 <- function(x) summary(x)$r.squared

# Model and residual df:
dfs <- function(x) summary(x)$df[1:2]

# ldply() takes a list object as input and returns a data frame object
# llply() takes a list object as input and returns a list
# Each call applies a utility function to each component model in the list
library(plyr)
ldply(mlist, r2)
ldply(mlist, dfs)
llply(mlist, ss)

HTH,
Dennis

On Fri, Jan 21, 2011 at 8:42 AM, Michael Costello <
michaelavcostello@gmail.com> wrote:

> Folks,
>
> I am trying to get a loop to run which increments the object name as part
> of
> the loop.  Here "fit1" "fit2" "fit3" and "fit4" are linear regression
> models
> that I have created.
>
> > for (ii in c(1:4)){
> + SSE[ii]=rbind(anova(fit[ii])$"Sum Sq")
> + dfe[ii]=rbind(summary(fit[ii])$df)
> + }
> Error in anova(fit[ii]) : object 'fit' not found
>
> Why isn't it looking for object 'fit1' instead of 'fit'?
>
> The idea is that it would store in SSE1 the Sum Sq of the model fit1, and
> so
> on for the other 3 models.  Is there a way to do this in R?  I can do it in
> Stata, but am only somewhat knowledgeable in R.
>
> -Michael
>
>        [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help@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.
>

	[[alternative HTML version deleted]]

