【问题标题】:Extract elements from nested list only using functions from purrr package仅使用 purrr 包中的函数从嵌套列表中提取元素
【发布时间】:2016-04-17 12:54:50
【问题描述】:

如何仅使用 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

我尝试了 map() 和 at_depth(),但似乎没有什么对我有用。

【问题讨论】:

  • 你是如何尝试map的?如果您删除函数名称 lapply 并将其替换为 map - 完全相同的参数 - 它工作得很好。
  • 我发现map 的帮助页面在这里很有用。与lapply 相比,您似乎可以进行一些快捷编码。像 map_dbl(c(1, 1)) 一样用于索引嵌套列表。
  • @Gregor。啊啊啊!这太明显了。谢谢

标签: r purrr


【解决方案1】:

map 函数有一些用于索引嵌套列表的速记编码。帮助页面中的一个有用的 sn-p:

要深入索引嵌套列表,请使用多个值; 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 

我还发现 blog post 介绍 purrr 0.1.0 很有用,因为它提供了我最终使用的速记编码的更多示例。

【讨论】:

  • 完美。这对我来说是最好的答案,因为它不会输出那些带有名称作为属性的向量。干杯!
【解决方案2】:

使用扫帚的整洁功能

library(purrr)
library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union
library(tidyr)
library(broom)

cyl_group<-mtcars %>% group_by(cyl) %>% 
        nest()
        
cyl_lm<-cyl_group %>% mutate(
        mod=map(data,~lm(mpg ~ wt, data = .x))
) %>% mutate(coef=map(mod,~tidy(.x))) %>% unnest(coef)
cyl_lm
#> # A tibble: 6 x 8
#> # Groups:   cyl [3]
#>     cyl data             mod    term      estimate std.error statistic   p.value
#>   <dbl> <list>           <list> <chr>        <dbl>     <dbl>     <dbl>     <dbl>
#> 1     6 <tibble [7 x 10~ <lm>   (Interce~    28.4      4.18       6.79   1.05e-3
#> 2     6 <tibble [7 x 10~ <lm>   wt           -2.78     1.33      -2.08   9.18e-2
#> 3     4 <tibble [11 x 1~ <lm>   (Interce~    39.6      4.35       9.10   7.77e-6
#> 4     4 <tibble [11 x 1~ <lm>   wt           -5.65     1.85      -3.05   1.37e-2
#> 5     8 <tibble [14 x 1~ <lm>   (Interce~    23.9      3.01       7.94   4.05e-6
#> 6     8 <tibble [14 x 1~ <lm>   wt           -2.19     0.739     -2.97   1.18e-2

reprex package (v0.3.0) 于 2020 年 8 月 19 日创建

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-22
    • 1970-01-01
    • 2019-09-30
    • 1970-01-01
    • 2023-03-22
    • 2023-04-01
    相关资源
    最近更新 更多