Generate named list from all combinations of two vectors

Viewed 66

My goal is to generate a named list of replicates within each sample type such that I can call them with samples$cell.wt.control. I have code that works, it's just absurdly long and I feel like there ought to be a simpler way. There are questions on how to make named lists from two vectors and how to make all combinations of two vectors, but nothing I could find making a named list from all combinations of two vectors, using one as a name of the results.

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"
2 Answers

You can do this with purrr:

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

Output:

$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"

Having to feed this in and out of a dataset seems to make this overly complex. You could loop over it with Map which will name automatically based on the first argument:

Map(paste, samples_base, list(replicates), sep=".")
#List of 4
# $ cell.wt.control       : chr [1:3] "cell.wt.control.A" "cell.wt.control.B" ...
# $ cell.wt.protein_ko    : chr [1:3] "cell.wt.protein_ko.A" "cell.wt.protein_ko.B" ...
# $ cell.mutant.control   : chr [1:3] "cell.mutant.control.A" "cell.mutant.control.B" ...
# $ cell.mutant.protein_ko: chr [1:3] "cell.mutant.protein_ko.A" "cell.mutant.protein_ko.B" ...
Related