Returning a vector of attributes shared by a set of features

I have a list of objects lm

(linear model).

How can I select a specific element (like intercept, rank or remainders) from all objects in one call?

+2


source to share


2 answers


I am using a package plyr

and then if my list of objects was called modelOutput

and I want to get all the predicted values ​​I would do this:

modelPredictions <- ldply(modelOutput, as.data.frame(predict))

      

if I want all the coefficients I do like this:



modelCoef <- ldply(modelOutput, as.data.frame(coef))

      

Hadley recently showed me how to do this in a previous question .

+3


source


First, I'll create 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 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 say, there are other fitness related quantities available. Above, I just captured the coefficients with a function coef()

. For more information see the following command:

names(summary(fit[[1]]))

      

+2


source







All Articles