Max M - 1 year ago 63
R Question

# Extract coefficients from a list of estimation objects

I saw some similar questions but my questions seems to be simpler.

I am running a more complicated regression than my MWE and end up with a list of estimation objects. I was wondering if there is a more elegant way of extracting the coefficients of the list, than using another for loop over the number or names of the list.

``````list.lm<-list()
for(i in 1:3) {
list.lm[[i]]<-lm(mpg~cyl+runif(32), data=mtcars)
}
``````

I know that I can use apply to get the coeffcients, but I cannot transform this

``````sapply(list.lm,coefficients)
``````

or

`````` t(sapply(list.lm, coefficients))
``````

ok then I can do

``````data.frame(iteration=seq(1,3),t(sapply(list.lm,coefficients)))
``````

which is the same as with my loop

``````results<-data.frame(iteration=numeric(),intercept=numeric(), cyl=numeric(), rand=numeric())
for(i in 1:3) {
results[i,]<-c(iteration=i,coefficients(list.lm[[i]]))
}
results
``````

One simple way would be to just use `sapply` and transpose the result, rather than `lapply`.
``````t(sapply(list.lm,coefficients))
You might also want to look into Hadley's `purrr` package and/or David Robinson's `broom` package. See https://blog.rstudio.org/2015/09/29/purrr-0-1-0/ and https://cran.r-project.org/web/packages/broom/broom.pdf