ldply extract standard deviation from coefficients (models)

234 views Asked by At

I use this function to adjust the lm models 101 times:

models <- dlply(mee_chua_sort, "mu", function(df) 
lm(nachher~vorher, data = df))

now I want to extract not only the estimates from the models - which I do using:

mod_coef<-ldply(models, coef)

I want to be apble to extract also the standard deviation, p-value and so on. If I try to use something like:

mod_coef1<-ldply(models, coef(summary(models))[,'Std.Error'])

I get the error: Error: $ operator is invalid for atomic vectors

Could anybody help me on that? I want to to save the other values in a df as I did with mod_coef

Thanks

1

There are 1 answers

0
StupidWolf On BEST ANSWER

The issue is with ldply(models, coef(summary(models)), inside the ldply, you are looping through models and the function needs to work on each element of the list. You need to write a function that does summary first, followed by coef, see

library(dlply)

linmod <- function(df) {
       lm(rbi ~ year, data = mutate(df, year = year - min(year)))
 }

models <- dlply(baseball, .(id), linmod)
mod_coef<-ldply(models, coef)
results <- ldply(models,function(i)coef(summary(i)))


 > head(results)
         id      Estimate  Std. Error     t value     Pr(>|t|)
1 aaronha01 118.923913043  9.44994928 12.58460860 3.013683e-11
2 aaronha01  -1.732213439  0.73567755 -2.35458242 2.835224e-02
3 abernte02   0.554009613  0.44022430  1.25847122 2.274573e-01
4 abernte02  -0.002403238  0.03829954 -0.06274848 9.507953e-01
5 adairje01  18.831034483 11.77420551  1.59934651 1.337547e-01
6 adairje01   0.879310345  1.61731151  0.54368645 5.958584e-01

# to get standard error
> head(results[,"Std. Error"])
[1]  9.44994928  0.73567755  0.44022430  0.03829954 11.77420551  1.61731151