As an alternative to @davis answer, you can also use some of the tidyverse tools to get all this workflow done keeping the structure of a table.
library(tidyverse)
tab <- women %>%
as_tibble() %>%
nest() %>%
mutate(model = map(data, ~ lm(height ~ 1 + ., data = .x)),
augmented = map(model, broom::augment))
tab
#> # A tibble: 1 x 3
#> data model augmented
#> <list> <list> <list>
#> 1 <tibble [15 x 2]> <S3: lm> <data.frame [15 x 9]>
You can see that everything is stored in the tibble, inside list column. Notice
the model column that contains the lm objects in a list.
you can then use unnest
to get the result table you want.
tab %>%
unnest(augmented)
#> # A tibble: 15 x 9
#> height weight .fitted .se.fit .resid .hat .sigma .cooksd .std.resid
#> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
#> 1 58.0 115 58.8 0.200 -0.757 0.207 0.387 0.488 -1.93
#> 2 59.0 117 59.3 0.188 -0.332 0.182 0.446 0.0775 -0.833
#> 3 60.0 120 60.2 0.170 -0.193 0.150 0.454 0.0200 -0.477
#> 4 61.0 123 61.1 0.154 -0.0551 0.123 0.458 0.00125 -0.134
#> 5 62.0 126 61.9 0.140 0.0831 0.101 0.457 0.00223 0.199
#> 6 63.0 129 62.8 0.128 0.221 0.0845 0.453 0.0128 0.526
#> 7 64.0 132 63.6 0.119 0.360 0.0733 0.445 0.0285 0.849
#> 8 65.0 135 64.5 0.114 0.498 0.0676 0.433 0.0497 1.17
#> 9 66.0 139 65.7 0.115 0.349 0.0682 0.446 0.0247 0.821
#> 10 67.0 142 66.5 0.120 0.487 0.0749 0.434 0.0536 1.15
#> 11 68.0 146 67.7 0.134 0.338 0.0922 0.446 0.0330 0.807
#> 12 69.0 150 68.8 0.152 0.189 0.119 0.454 0.0142 0.458
#> 13 70.0 154 70.0 0.173 0.0402 0.155 0.458 0.000907 0.0993
#> 14 71.0 159 71.4 0.204 -0.396 0.214 0.439 0.140 -1.02
#> 15 72.0 164 72.8 0.236 -0.832 0.288 0.359 1.01 -2.24
or without using broom
women %>%
as_tibble() %>%
nest() %>%
mutate(lm = map(data, ~ lm(height ~ 1 + ., data = .x)),
fitted = map(lm, "fitted.values")) %>%
unnest(data, fitted)
#> # A tibble: 15 x 3
#> fitted height weight
#> <dbl> <dbl> <dbl>
#> 1 58.8 58.0 115
#> 2 59.3 59.0 117
#> 3 60.2 60.0 120
#> 4 61.1 61.0 123
#> 5 61.9 62.0 126
#> 6 62.8 63.0 129
#> 7 63.6 64.0 132
#> 8 64.5 65.0 135
#> 9 65.7 66.0 139
#> 10 66.5 67.0 142
#> 11 67.7 68.0 146
#> 12 68.8 69.0 150
#> 13 70.0 70.0 154
#> 14 71.4 71.0 159
#> 15 72.8 72.0 164
This kind of workflow allow to apply model by group for example
# dummy dataset
women %>%
as_tibble() %>%
mutate(type = "C1") %>%
bind_rows(women %>% mutate(type = "C2")) %>%
# nesting by type, get list column of one element per type
nest(-type) %>%
# applying function using map to iterate through list column
mutate(model = map(data, ~ lm(height ~ 1 + ., data = .x)),
augmented = map(model, broom::augment))
#> # A tibble: 2 x 4
#> type data model augmented
#> <chr> <list> <list> <list>
#> 1 C1 <tibble [15 x 2]> <S3: lm> <data.frame [15 x 9]>
#> 2 C2 <tibble [15 x 2]> <S3: lm> <data.frame [15 x 9]>
Created on 2018-01-31 by the reprex package (v0.1.1.9000).