I am fitting a model to each group in a dataset. I am nesting the data by the grouping variable and then using map to fit a model to each group. Then I store the tidied model information as columns in a nested tibble.
I'd like to save each of these columns as its own file, this example saves them as sheets in a excel workbook.
Is there a way to not to unnest each column individually as a new tibble? Can all columns be unnested at once to a new list of tibbles? One that can be used in other functions (like writing an excel file)?
library(tidyverse)
library(broom)
data(mtcars)
df <- mtcars
nest.df <- df %>% nest(-carb)
results <- nest.df %>%
mutate(fit = map(data, ~ lm(mpg ~ wt, data=.x)),
tidied = map(fit, tidy),
glanced = map(fit, glance),
augmented = map(fit, augment))
glanced.df <- results %>%
unnest(glanced, .drop=T)
tidied.df <- results %>%
unnest(tidied, .drop=T)
augmented.df <- results %>%
unnest(augmented, .drop=T)
myList <- list(glanced.df, tidied.df, augmented.df)
names(myList) <- c("glance", "tidy", "augment")
openxlsx::write.xlsx(myList, file = "myResults.xlsx")