(R)使用map()和列表列的更简洁方法

时间:2018-12-27 01:13:11

标签: r tidyverse

由于我听说tidyverse团队正在对它进行修改,所以我试图从rowwise()移到列表列。但是,我不习惯使用purrr函数,因此我觉得必须有一种更好的方法来进行以下操作:

我创建一个列表列,其中包含每个物种的小标题。然后,我想谈一谈,并取某些变量的平均值。第一种情况是使用map,第二种情况是我个人认为比较整洁的按行解决方案。

有人知道在这种情况下使用地图的更好方法吗?

library(tidyverse)
iris %>% 
  group_by(Species) %>% 
  nest() %>% 
  mutate(mean_slength = map_dbl(data, ~mean(.$Sepal.Length, na.rm = TRUE)),
         mean_swidth = map_dbl(data, ~mean(.$Sepal.Width, na.rm = TRUE))
         )
#> # A tibble: 3 x 4
#>   Species    data              mean_slength mean_swidth
#>   <fct>      <list>                   <dbl>       <dbl>
#> 1 setosa     <tibble [50 x 4]>         5.01        3.43
#> 2 versicolor <tibble [50 x 4]>         5.94        2.77
#> 3 virginica  <tibble [50 x 4]>         6.59        2.97

iris %>% 
  group_by(Species) %>% 
  nest() %>% 
  rowwise() %>% 
  mutate(mean_slength = mean(data$Sepal.Length, na.rm = TRUE),
         mean_swidth = mean(data$Sepal.Width, na.rm = TRUE))
#> Source: local data frame [3 x 4]
#> Groups: <by row>
#> 
#> # A tibble: 3 x 4
#>   Species    data              mean_slength mean_swidth
#>   <fct>      <list>                   <dbl>       <dbl>
#> 1 setosa     <tibble [50 x 4]>         5.01        3.43
#> 2 versicolor <tibble [50 x 4]>         5.94        2.77
#> 3 virginica  <tibble [50 x 4]>         6.59        2.97

reprex package(v0.2.1)于2018-12-26创建

1 个答案:

答案 0 :(得分:2)

使用两个map代替一个summarise_at

library(tidyverse)
iris %>% 
   group_by(Species) %>% 
   nest() %>% 
   mutate(out = map(data, ~ 
               .x  %>% 
                 summarise_at(vars(matches('Sepal')), 
              funs(mean_s = mean(., na.rm = TRUE))))) %>% 
   unnest(out)
相关问题