I have a list of lm (linear model) objects.
How can I select a particular element (such as the intercept, rank, or residuals) from all the objects in a single call?
I have a list of lm (linear model) objects.
How can I select a particular element (such as the intercept, rank, or residuals) from all the objects in a single call?
First I'll generate some example data:
> set.seed(123)
> x <- 1:10
> a <- 3
> b <- 5
> fit <- c()
> for (i in 1:10) {
+ y <- a + b*x + rnorm(10,0,.3)
+ fit[[i]] <- lm(y ~ x)
+ }
Here's one option for grabbing the estimates from each fit:
> t(sapply(fit, function(x) coef(x)))
(Intercept) x
[1,] 3.157640 4.975409
[2,] 3.274724 4.961430
[3,] 2.632744 5.043616
[4,] 3.228908 4.975946
[5,] 2.933742 5.011572
[6,] 3.097926 4.994287
[7,] 2.709796 5.059478
[8,] 2.766553 5.022649
[9,] 2.981451 5.020450
[10,] 3.238266 4.980520
As you mention, other quantities concerning the fit are available. Above I only grabbed the coefficients with the coef()
function. Check out the following command for more:
names(summary(fit[[1]]))
I use the plyr package and then if my list of objects was called modelOutput and I want to get out all the predicted values I would do this:
modelPredictions <- ldply(modelOutput, as.data.frame(predict))
if I want all the coefficients I do this:
modelCoef <- ldply(modelOutput, as.data.frame(coef))
Hadley originally showed me how to do this in a previous question.