【发布时间】:2018-03-22 14:57:04
【问题描述】:
我怎样才能从purrr::map 得到一个命名列表,就像使用plyr::dlply 一样?我在这里提供一个代表。可以看出,plyr::ldply 返回一个命名列表,而purrr::map 没有。我还检查了 2 年前的一个类似问题 (How to get list name and slice name with pipe and purrr),但这并没有太大帮助,因为 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 年 3 月 22 日创建。
我正在尝试摆脱plyr 并在我的脚本中完全依赖tidyverse,但我可以用plyr 做的一些事情我仍在试图弄清楚如何使用purrr 和这是其中之一。
【问题讨论】:
-
试试
my_way <- iris %>% split(.$Species) %>% map(~ggplot(.,mapping = aes(x = Sepal.Length, y = Sepal.Width)) + geom_point() + geom_smooth(method = "lm")); names(my_way) -
@Jimbou 不错!但如果可能的话,我想在数据框中执行此操作。我会等着看其他人是否会提供一些替代解决方案。