Search code examples
rlistapplyplyrsapply

aggregating model summaries from list of models


I am running same models several times on different subset of data, for example,

  data("mtcars")
  head("mtcars")

  table(mtcars$cyl, useNA = "ifany")

I am fitting the model (mpg ~ hp + wt) for each cylinder type.

 foo <- mtcars %>%
          group_by(cyl) %>%
             nest() %>%
               mutate(model= map(data, rms::ols(mpg ~ hp + wt, data = .)))

When I try this

  foo %>%
    {map(.$model, summary)}

I get the model summary from all three models but this does not include the estimates for intercept.

I am not interested in fitting the model using lm function, I am specifically interested in solutions involving fitting rms::ols() function.

Any help on aggregating the summaries from multiple models using rms::ols() and that includes estimates for intercept, will be very helpful. Thanks.


Solution

  • As stated in the comments, your question is more about having a custom summary function.

    Note that what you called "induvidual model summary, foo$model" is not a summary (as in output for a summary function), is just the default printing method of a rms object.

    You can use summary.lm():

    foo %>%
      {map(.$model, summary.lm)}
    

    Extra: if you don't want your models saved as a tibble, you can use group_split -> map, instead of group_by -> nest -> map:

    foo <- mtcars %>%
      group_split(cyl) %>%
      map(~ rms::ols(mpg ~ hp + wt, data = .x))
    

    Now, foo is a list and you can do more naturally:

    map(foo, summary.lm)