Jacob Bauer
Jacob Bauer

Reputation: 13

How can I save results of multiple R models to a csv?

I was able to create a tibble with results of 12 linear models as lists with the code below. These are linear models between average monthly flow (MMF) and watershed area (DRAINAGE_AREA_GROSS) and the output can bee seen in the picture.

MMF_reggression <- flow_average %>% group_by(Month) %>%
 do(model = lm(MMF ~ DRAINAGE_AREA_GROSS, data = .))

I want to export the coefficients of the lists to CSV, but I am having trouble dealing with them because they are in this tibble.

So no the end of the world but would like to not have manually put those into a .csv. Any solutions to this would be greatly appreciated.

tibble of lists

I can't get approaches like this to work:

write.csv(coef(MMF_reggression[[,2]]), file = 'regionalregression.csv')

I can save results in a text file with:

sink("model_summary.txt")
print(MMF_reggression[[2]])
sink()

Upvotes: 0

Views: 101

Answers (2)

Andre Wildberg
Andre Wildberg

Reputation: 19191

Unlisting and summarizing first should work with write.csv if model has the coefficients variable.

library(dplyr)

write.csv(MMF_reggression %>% 
            rowwise() %>% 
            summarize(coeff = list(coef(model))) %>% 
            tidyr::unnest_wider(coeff), 
  file = "regionalregression.csv")

Upvotes: 1

Ben Bolker
Ben Bolker

Reputation: 226742

I'd recommend broom::tidy() for translating your results into a workflow-friendly format.

library(tidyverse)
library(broom)
mtcars %>% group_by(cyl) %>%
 do(model = lm(hp ~ mpg, data = .)) %>%
 mutate(tbl = list(tidy(model))) %>%
 unnest(tbl) %>%
 select(-model)
# A tibble: 6 × 6
    cyl term        estimate std.error statistic p.value
  <dbl> <chr>          <dbl>     <dbl>     <dbl>   <dbl>
1     4 (Intercept)   147.       35.6      4.14  0.00252
2     4 mpg            -2.43      1.32    -1.84  0.0984 
3     6 (Intercept)   164.      147.       1.12  0.313  
4     6 mpg            -2.12      7.40    -0.286 0.786  
5     8 (Intercept)   294.       84.3      3.49  0.00445
6     8 mpg            -5.65      5.51    -1.02  0.326  

You can then select() whichever columns you want to keep and write them out to the CSV.

I would suggest

lmList(hp~mpg|cyl, data = mtcars) |> broom.mixed::tidy()

but the tidy method appears to be broken ATM ... ???

Upvotes: 1

Related Questions