Extract items from a nested list only using functions from purrr package

How to extract items from a nested list using purrr package only? In this case, I want to get the intercept vector after splitting data.frame. I did what I needed using lapply (), but I would like to use only the purrr package functions.

library(purrr) mtcars %>% split(.$cyl) %>% map( ~lm(mpg ~ wt, data = .)) %>% # shorthand NOTE: ~ lm lapply(function(x) x[[1]] [1]) %>% # extract intercepts <==is there a purrr function for this line? as_vector() # convert to vector 

I tried map () and at_depth (), but nothing worked for me.

+5
source share
1 answer

map functions have some abbreviated coding for indexing nested lists. Useful snippet from the help page:

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

Thus, using code for nested indices along with map_dbl , which boils down 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 some more examples of the abbreviated coding I used.

+12
source

Source: https://habr.com/ru/post/1240467/


All Articles