Search code examples
rpurrrlm

Extract r.squared from multiple models with purrr::map()


I have the following three linear models:

models <- mtcars %>% 
  split(.$cyl) %>% 
  map(~lm(mpg ~ wt, data = .))

Now I want to extract r.squared from all of the three models with purrr::map(). I've tried the following two ways but they both produce an error (i.e., "Error: Can't convert a summaryDefault/table object to function"):

models %>% 
  map(summary) %>% 
  map_dbl(~.$r.squared)

models %>% 
  map(summary) %>% 
  map_dbl("r.squared")

What's the issue and how can it be solved?


Solution

  • library(tidyverse)
    
    models <- mtcars %>% 
      split(.$cyl) %>% 
      map(~lm(mpg ~ wt, data = .))
    

    Manually doing it you can do:

    summary(models[[1]])$r.squared
    

    And then using map:

    #and in map loop map_dfr
    map_dfr(models, ~summary(.)$r.squared)
    # # A tibble: 1 x 3
    #     `4`   `6`   `8`
    #   <dbl> <dbl> <dbl>
    # 1 0.509 0.465 0.423
    

    Or

     map_dfr(models, ~ glance(.x) %>%
                       dplyr::select(r.squared))
    
    # A tibble: 3 x 1
    #  r.squared
    #      <dbl>
    #1     0.509
    #2     0.465
    #3     0.423