簡體   English   中英

循環遍歷列表列表

[英]Looping over a list of lists

我有以下代碼:

condition_1_top_genes = list("abc", "def", "efg")
condition_2_top_genes = list("a35", "2353", "rea3")
condition_3_top_genes = list("fae", "wai", "wtes")

top_genes = list(condition_1_top_genes, 
                 condition_2_top_genes,
                 condition_3_top_genes)

genotypes <- list("genotype1" = genotype1, 
                  "genotype2" = genotype2,
                  "genotype3"  genotype3)

for (i in length(genotypes)){
  for (j in ????){
    FeaturePlot(genotypes[[i]], features = ??)
  }
}

genotypes 是 Seurat 對象的列表。

在外循環中,我循環遍歷 Seurat 對象,對於內循環,我想遍歷 top_genes 中的每個列表。 因此,當 i = 1 時,我希望 j 沿着 condition_1_top_genes 移動,然后當 i=2 時,我希望 j 沿着 condition_2_top_genes 移動,等等。

對此語法的任何幫助將不勝感激。

[ ,不會提取list元素,我們需要[[進入列表並提取為向量。 此外,我們可以使用單個for循環而不是嵌套,因為top_genes顯示的不是嵌套list ,而是vectorlist

for(i in seq_along(top_genes)) {
     top_genes[[i]] <- seq_along(top_genes[[i]]) * 3
}
condition_1_top_genes = list("abc", "def", "efg") condition_2_top_genes = list("a35", "2353", "rea3") condition_3_top_genes = list("fae", "wai", "wtes") top_genes = list(condition_1_top_genes, condition_2_top_genes, condition_3_top_genes)

如果我理解正確,您可能想要更改定義列表top_genes的方式。

# Define genes in character vector, allowing you to use concise syntax later on
condition_1_top_genes = c("abc", "def", "efg")
condition_2_top_genes = c("a35", "2353", "rea3")
condition_3_top_genes = c("fae", "wai", "wtes")

# Define list elements with names
top_genes = list(
  condition_1_top_genes = condition_1_top_genes, 
  condition_2_top_genes = condition_2_top_genes,
  condition_3_top_genes = condition_3_top_genes
)

現在您的top_genes是一個命名列表,您可以使用 [[""]] 運算符訪問top_genes中的列表元素。

> top_genes[["condition_1_top_genes"]]
[1] "abc" "def" "efg"

# with paste0 function, you can access arbitrary list element
> i=1
> top_genes[[paste0("condition_",i,"_top_genes")]]
[1] "abc" "def" "efg"

# To access jth gene in condition_1_top_genes
> j=1
> top_genes[[paste0("condition_",i,"_top_genes")]][j]
[1] "abc"

因此,在您的 for 循環中,您可以執行以下操作:

for (i in length(genotypes)){
  for (j in length(top_genes[[paste0("condition_",i,"_top_genes")]])){
    FeaturePlot(genotypes[[i]], features = top_genes[[paste0("condition_",i,"_top_genes")]][j])
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM