从 purrr::map 中获取命名列表,就像在 plyr::ldply 中一样

getting named lists from purrr::map like in plyr::ldply

我如何才能像使用 plyr::dlply 那样从 purrr::map 获取命名列表?我在这里提供一个代表。可以看出,plyr::ldply returns 是一个命名列表,而 purrr::map 不是。我还检查了 2 年前的一个类似问题 (),但这并没有多大帮助,因为 purrr::map 没有被用在数据框内的列表列上,这就是我想要的做。

library(tidyverse)
library(plyr)

# creating a list of plots with purrr
plotlist_purrr <- iris %>%
  dplyr::group_by(.data = ., Species) %>%
  tidyr::nest(data = .) %>%
  dplyr::mutate(
    .data = .,
    plots = data %>% purrr::map(
      .x = .,
      .f = ~ ggplot2::ggplot(
        data = .,
        mapping = aes(x = Sepal.Length, y = Sepal.Width)
      ) + geom_point() + geom_smooth(method = "lm")
    )
  )

# see the names of the plots
names(plotlist_purrr$plots)
#> NULL

# creating a list of plots with plyr
plotlist_plyr <- plyr::dlply(
  .data = iris,
  .variables = .(Species),
  .fun = function(data)
    ggplot2::ggplot(
      data = data,
      mapping = aes(x = Sepal.Length, y = Sepal.Width)
    ) + geom_point() + geom_smooth(method = "lm")
)

# see the names of the plots
names(plotlist_plyr)
#> [1] "setosa"     "versicolor" "virginica"

reprex package (v0.2.0) 创建于 2018-03-22。

我正试图摆脱 plyr 并在我的脚本中完全依赖 tidyverse 但我可以用 plyr 做的一些事情我仍在努力弄清楚如何使用 purrr,这就是其中之一。

你可以试试

library(tidyverse)
my_way <- iris %>%
  group_by(Species) %>%
  nest() %>%
  mutate(plots= data %>%  
                  map(~ggplot(., aes(x= Sepal.Length, y= Sepal.Width)) +
                        geom_point() + 
                        geom_smooth(method= "lm"))) %>% 
  mutate(plots= set_names(plots, Species))

my_way
# A tibble: 3 x 3
Species      data              plots   
<fct>        <list>            <list>  
1 setosa     <tibble [50 x 4]> <S3: gg>
2 versicolor <tibble [50 x 4]> <S3: gg>
3 virginica  <tibble [50 x 4]> <S3: gg>

names(my_way$plots)
[1] "setosa"     "versicolor" "virginica" 

您只需要在执行 map

之前使用 purrr::set_names(Species)
library(plyr)
library(tidyverse)

# creating a list of plots with purrr
plotlist_purrr <- iris %>%
  dplyr::group_by(.data = ., Species) %>%
  tidyr::nest(data = .) %>%
  dplyr::mutate(
    .data = .,
    plots = data %>% 

      purrr::set_names(Species) %>%

      purrr::map(
      .x = .,
      .f = ~ ggplot2::ggplot(
        data = .,
        mapping = aes(x = Sepal.Length, y = Sepal.Width)
      ) + geom_point() + geom_smooth(method = "lm")
    )
  )

# see the names of the plots
names(plotlist_purrr$plots)

#> [1] "setosa"     "versicolor" "virginica"

reprex package (v0.2.0) 创建于 2018-03-22。