How do you pull nested data from the same source to make a tibble?
women %>% lm(height~1+.,.) %>% .$fitted.values # THIS WORKS
women %>% lm(height~1+.,.) %>% .$model # THIS WORKS
women %>% lm(height~1+.,.) %>% as_tibble(.$model, .$fitted.values) # THIS DOESN'T WORK
Pipes generally put the Left-Hand Side into the Right-Hand Side as the first argument, and that's Not Ideal in this case. If you use the data pronoun . to manually specify position, the pipe sometimes doesn't implicitly include it as the first argument—but exactly when that happens is a little tricky.
if you enclose that last part of the pipe in braces, you can ensure that the pronoun isn't placed first:
women %>% lm(height~1+.,.) %>% {as_tibble(.$model, .$fitted.values)}
This way the pipe evaluates to as_tibble(.$model, .$fitted.value) and not as_tibble(., .$model, .$fitted.value). (I only just learnt this trick reading your post! Wish I'd known it earlier )
An alternative to @rensa 's answer is to use the %$% operator from magrittr. It exposes only the variables from the LHS object in the RHS object (Note that model is a data.frame and fitted.values is a vector so you need to turn fitted.values into a data.frame to bind them).
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.
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).