Extract Slopes by group, Broom? Dplyr?

Pass a .id parameter to map_df to convert the names into a column:

library(tidyverse)

Orange %>%
    split(.$Tree) %>%
    map(~lm(age ~ 1 + circumference, data = .x)) %>%
    map_df(broom::tidy, .id = 'tree') %>%
    filter(term == 'circumference')
#>   tree          term  estimate std.error statistic      p.value
#> 1    3 circumference 12.038885 0.8353445  14.41188 2.901046e-05
#> 2    1 circumference 11.919245 0.9188029  12.97258 4.851902e-05
#> 3    5 circumference  8.787132 0.6211365  14.14686 3.177093e-05
#> 4    2 circumference  7.795225 0.5595479  13.93129 3.425041e-05
#> 5    4 circumference  7.169842 0.5719516  12.53575 5.733090e-05

tree is now character instead of an out-of-order ordinal factor, though, so it'll need more cleaning.

3 Likes