I have the following code:
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 is a list of Seurat objects.
In the outer loop I'm looping over the Seurat objects, for the inner loop I want to loop over each of the lists in top_genes. So when i = 1 I want j to move along condition_1_top_genes, then when i=2, I want j to move along condition_2_top_genes, etc.
Any help on this syntax would be appreciated.
CodePudding user response:
[
, wouldn't extract the list
element, we need [[
to go inside the list and extract as vector. Also, we can use a single for
loop instead of nested as top_genes
showed is not a nested list
but a list
of vector
s
for(i in seq_along(top_genes)) {
top_genes[[i]] <- seq_along(top_genes[[i]]) * 3
}
CodePudding user response:
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)
If I understand you correctly, you'd probably want to change the way you define the list 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
)
Now you top_genes
is a named list, you can access list elements in top_genes
with [[""]] operator.
> 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"
So in your for loop, you can do:
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])
}
}