仅使用purrr包中的函数从嵌套列表中提取元素

hac*_*ckR 7 r purrr

如何仅使用purrr包从嵌套列表中提取元素?在这种情况下,我希望在分割data.frame后得到一个截距矢量.我已经使用lapply()完成了我需要的东西,但我想只使用函数purrr包.

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
Run Code Online (Sandbox Code Playgroud)

我试过map()和at_depth()但似乎没有什么对我有用.

aos*_*ith 16

这些map函数有一些用于索引嵌套列表的速记编码.帮助页面中的一个有用的片段:

要深入索引到嵌套列表,请使用多个值; c("x","y")等效于z [["x"]] [["y"]].

因此,使用嵌套索引的代码map_dbl,减少为向量,您可以简单地执行:

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

       4        6        8 
39.57120 28.40884 23.86803 
Run Code Online (Sandbox Code Playgroud)

我还发现这篇博文介绍了purrr 0.1.0很有用,因为它给出了一些我最终使用的速记编码的例子.