r - 将中间列表输出保存在 dplyr 管道中,并将其映射回管道下游的另一个列表 - R

标签 r dplyr pca ggbiplot

我正在使用 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))

enter image description here

为了回应您的评论,如果您想添加第三个参数,您可以使用 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))

enter image description here

关于r - 将中间列表输出保存在 dplyr 管道中,并将其映射回管道下游的另一个列表 - R,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58074117/

相关文章:

python - 如何在python中进行PCA和SVM分类

r - R plot() 或 ggplot2() 中的对数 y 轴刻度线

html - 项目符号列表未在 blogdown .rmd 文件中呈现

r - 如何使用 dplyr 函数在数据表中添加新列?

r - dplyr:带有 rbind_all 与 bind_rows 的数据框的向量列表

python - sklearn 中估算器管道的参数 clf 无效

r - 将数据库中的项目池化,直到达到最小样本量并找到 R 中的所有排列

r - 结合名义变量的运行

r - Dplyr 计数/多个过滤器计数

python - 学习 : How to apply dimensionality reduction on huge data set?