Home > Software design >  How can I reference a character within my list of characters as a string in a for-loop
How can I reference a character within my list of characters as a string in a for-loop

Time:07-15

I have several character lists, and a list of these character lists.

C1 <- c('a', 'b', 'c')
C2 <- c('d', 'e', 'f')
C3 <- c('g', 'h', 'i')

char_list <- list(C1, C2, C3)

within my nested for loop, I am trying to have each generated FeaturePlot exported as

"C1_a", "C1_b", "C1_c", "C2_a", "C2_b", "C2_c" etc...

for(c in char_list){
  for(g in c){
    png(paste0(c, '_', g, ".png"))
    plot(FeaturePlot(object = MG_Subset1, reduction = "umap", label = TRUE, min.cutoff = 0, features = g))
    dev.off()
  }
}

What I end up with is "a_a", "a_b", "a_c", "d_d", "d_e", "d_e" etc...

Could anyone tell me how to reference my char_list contents as a string without breaking the for-loop so that I can adjust the below line to reference c as "C1", or "C2"?

png(paste0(c, '_', g, ".png"))

Thank you so much.

CodePudding user response:

Here, we may need to create a named list. It can be done by specifying the name on the lhs of = or using mget to extract the values of the objects based on the object name patterns

char_list <- list(C1 = C1, C2 = C2, C3 = C3)
#char_list <- mget(ls(pattern = "^C\\d $"))

Then loop over the sequence of the list or the names of the list and then extract the list elements

 for(i in seq_along(char_list)) {
   c <- char_list[[i]]
   nm <- names(char_list[i])
   for(g in c) {
    png(paste0(nm, '_', g, ".png"))
   plot(FeaturePlot(object = MG_Subset1, reduction = "umap", label = TRUE, min.cutoff = 0, features = g))
   dev.off()
   }
 
 } 
  • Related