首页 > 解决方案 > 从两个向量的所有组合生成命名列表

问题描述

我的目标是在每个样本类型中生成一个命名的重复列表,以便我可以使用samples$cell.wt.control. 我有有效的代码,它只是荒谬的长,我觉得应该有一个更简单的方法。有关于如何从两个向量制作命名列表以及如何制作两个向量的所有组合的问题,但我找不到任何从两个向量的所有组合中制作命名列表,使用一个作为结果的名称。

library(tidyverse)

samples_base = c("cell.wt.control",
                 "cell.wt.protein_ko",
                 "cell.mutant.control",
                 "cell.mutant.protein_ko")
replicates = LETTERS[1:3]

samples = 
  outer(samples_base, replicates, paste, sep = ".") %>% t %>% as.data.frame %>% 
  set_names(samples_base) %>% 
  mutate_if(is.factor, as.character) %>% 
  pivot_longer(starts_with("cell")) %>% 
  group_by(name) %>% summarize(sample = list(value)) %>% deframe

#$cell.mutant.control
#[1] "cell.mutant.control.A" "cell.mutant.control.B" "cell.mutant.control.C"

#$cell.mutant.protein_ko
#[1] "cell.mutant.protein_ko.A" "cell.mutant.protein_ko.B" "cell.mutant.protein_ko.C"

#$cell.wt.control
#[1] "cell.wt.control.A" "cell.wt.control.B" "cell.wt.control.C"

#$cell.wt.protein_ko
#[1] "cell.wt.protein_ko.A" "cell.wt.protein_ko.B" "cell.wt.protein_ko.C"

标签: rdplyr

解决方案


你可以这样做purrr

samples_base %>%
    set_names() %>%
    purrr::map(~ paste0(., ".", replicates))

输出:

$cell.wt.control
[1] "cell.wt.control.A" "cell.wt.control.B" "cell.wt.control.C"

$cell.wt.protein_ko
[1] "cell.wt.protein_ko.A" "cell.wt.protein_ko.B" "cell.wt.protein_ko.C"

$cell.mutant.control
[1] "cell.mutant.control.A" "cell.mutant.control.B" "cell.mutant.control.C"

$cell.mutant.protein_ko
[1] "cell.mutant.protein_ko.A" "cell.mutant.protein_ko.B" "cell.mutant.protein_ko.C"

推荐阅读