How do I extract elements from a nested list only using the purrr package? In this case I want to get a vector of intercepts after splitting a data.frame. I have accomplished what I need using lapply(), but I would like to use only functions purrr package.
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 have tried map() and at_depth() but nothing seemed to work for me.
map
? If you delete the function namelapply
and replace it withmap
- exact same arguments - it works just fine. – Gregor Thomasmap
useful here. It looks like you can do some short-cut coding compared tolapply
. Likemap_dbl(c(1, 1))
for indexing nested lists. – aosmith