我正在使用 dplyr 管道在数据集中的组上运行 pcas。我从 group_split
开始,所以正在处理一个列表。为了运行 prcomp()
函数,只能包含每个列表的 numeric
列,但我希望引入 factor
列最后返回绘图。我尝试使用 { 保存中间输出。 ->> temp}
通过管道的一半,但由于它是一个列表,我不知道在绘图时如何索引分组列。
library(tidyverse)
library(ggbiplot)
iris %>%
group_split(Species, keep = T) %>% #group by species, one pca per species
{. ->> temp} %>% # save intermediate output to preserve species column for use in plotting later
map(~.x %>% select_if(is.numeric) %>% select_if(~var(.) != 0) %>%
prcomp(scale. = TRUE))%>% #run pca on numeric columns only
map(~ggbiplot(.x), label=temp$Species)#plot each pca, labeling points as species names form the temporary object
这可以为iris
数据集中的每个物种生成一个主成分分析图,但由于temp$species = NULL
,这些点没有被标记。
最佳答案
如果您使用 map2()
并将 .y
参数作为物种列表传递,您可以获得我认为您想要的结果。请注意,在原始代码中,labels
参数位于 ggbiplot()
函数之外,因此被忽略。
library(tidyverse)
library(ggbiplot)
iris %>%
group_split(Species, keep = T) %>%
{. ->> temp} %>%
map(~.x %>%
select_if(is.numeric) %>%
select_if(~var(.) != 0) %>%
prcomp(scale. = TRUE)) %>%
map2(map(temp, "Species"), ~ggbiplot(.x, labels = .y))
为了回应您的评论,如果您想添加第三个参数,您可以使用 pmap()
而不是 map2()
。在下面的示例中,将向 pmap()
传递 ggbiplot()
参数的(嵌套)数据列表。请注意,我更改了 new
变量,使其成为一个因素,而不是跨组的常数。
iris %>%
mutate(new = factor(sample(1:3, 150, replace = TRUE))) %>%
group_split(Species, keep = T) %>%
{. ->> temp} %>%
map(~.x %>%
select_if(is.numeric) %>%
select_if(~var(.) != 0) %>%
prcomp(scale. = TRUE)) %>%
list(map(temp, "Species"), map(temp, "new")) %>%
pmap(~ ggbiplot(pcobj = ..1, labels = ..2, groups = ..3))
关于r - 将中间列表输出保存在 dplyr 管道中,并将其映射回管道下游的另一个列表 - R,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58074117/