Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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…

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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()
   }
 
 } 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading