Max M - 4 months ago 28

R Question

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

Answer

One simple way would be to just use `sapply`

and transpose the result, rather than `lapply`

.

```
t(sapply(list.lm,coefficients))
# (Intercept) cyl runif(32)
# [1,] 35.43360 -2.774654 4.163870
# [2,] 38.71960 -2.840392 -1.896252
# [3,] 38.97739 -2.784622 -3.955039
```

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