Extract elements from nested list only using functions from purrr package

The map functions have some shorthand coding for indexing nested lists. A helpful snippet from the help page:

To index deeply into a nested list, use multiple values; c("x", "y") is equivalent to z[["x"]][["y"]].

So using code for nested indexes along with map_dbl, which reduces to a vector, you can simply do:

mtcars %>%
    split(.$cyl) %>%
    map(~lm(mpg ~ wt, data = .)) %>%
    map_dbl(c(1, 1))

       4        6        8 
39.57120 28.40884 23.86803 

I also found this blog post introducing purrr 0.1.0 useful, as it gave a few more example of the shorthand coding that I ended up using.

Tags:

R

Purrr