purrr:按(嵌套)和引导程序分组

问题描述 投票:0回答:1

我计算了mpg数据集中mtcars变量的引导程序样本的平均值。我的代码如下所示(请让我知道是否有“更好的实践”来做。):

mean_mpg <- function(x) {
    rsample::analysis(x) %>% 
        pull(mpg) %>% 
        mean()
}

mtcars2 <- rsample::bootstraps(mtcars) %>% 
    mutate(mean_mpg = purrr::map(splits, mean_mpg)) %>% 
    tidyr::unnest(mean_mpg) %>% 
    select(-splits)

但是,现在我想对分组的数据集执行相同的操作。例如:

mtcars %>% 
    group_by(am)
# now calculate boostrap means of `mpg` for each `am` group

最佳方法是什么?

dplyr purrr tidymodels
1个回答
1
投票

我想我会nest(),而不是group_by()

这里是关于如何为整个数据集的每个引导重采样找到均值mpg的略微修改版本。

library(rsample)
library(tidyverse)

bootstraps(mtcars) %>%
  mutate(mpg = map(splits, ~ analysis(.) %>% pull(mpg)),
         mean_mpg = map_dbl(mpg, mean))
#> # Bootstrap sampling 
#> # A tibble: 25 x 4
#>    splits          id          mpg        mean_mpg
#>  * <list>          <chr>       <list>        <dbl>
#>  1 <split [32/10]> Bootstrap01 <dbl [32]>     18.8
#>  2 <split [32/13]> Bootstrap02 <dbl [32]>     20.4
#>  3 <split [32/9]>  Bootstrap03 <dbl [32]>     21.1
#>  4 <split [32/12]> Bootstrap04 <dbl [32]>     19.4
#>  5 <split [32/10]> Bootstrap05 <dbl [32]>     19.8
#>  6 <split [32/11]> Bootstrap06 <dbl [32]>     20.1
#>  7 <split [32/13]> Bootstrap07 <dbl [32]>     19.1
#>  8 <split [32/11]> Bootstrap08 <dbl [32]>     18.7
#>  9 <split [32/13]> Bootstrap09 <dbl [32]>     19.3
#> 10 <split [32/13]> Bootstrap10 <dbl [32]>     20.9
#> # … with 15 more rows

这是我将如何为am的每个值创建引导重采样,然后为这些重采样找到mpg的平均值。

mtcars %>% 
  nest(-am) %>%
  mutate(nested_boot = map(data, bootstraps)) %>%
  select(-data) %>%
  unnest(nested_boot) %>%
  mutate(mpg = map(splits, ~ analysis(.) %>% pull(mpg)),
         mean_mpg = map_dbl(mpg, mean))
#> # A tibble: 50 x 5
#>       am splits         id          mpg        mean_mpg
#>    <dbl> <list>         <chr>       <list>        <dbl>
#>  1     1 <split [13/4]> Bootstrap01 <dbl [13]>     21.9
#>  2     1 <split [13/4]> Bootstrap02 <dbl [13]>     24.0
#>  3     1 <split [13/5]> Bootstrap03 <dbl [13]>     24.8
#>  4     1 <split [13/5]> Bootstrap04 <dbl [13]>     25.9
#>  5     1 <split [13/3]> Bootstrap05 <dbl [13]>     24.0
#>  6     1 <split [13/5]> Bootstrap06 <dbl [13]>     22.1
#>  7     1 <split [13/4]> Bootstrap07 <dbl [13]>     24.3
#>  8     1 <split [13/4]> Bootstrap08 <dbl [13]>     25.0
#>  9     1 <split [13/5]> Bootstrap09 <dbl [13]>     22.7
#> 10     1 <split [13/6]> Bootstrap10 <dbl [13]>     23.3
#> # … with 40 more rows

reprex package(v0.3.0)在2020-05-26创建

© www.soinside.com 2019 - 2024. All rights reserved.