Home > OS >  Extract list name of list of lists in for loop r
Extract list name of list of lists in for loop r

Time:05-10

I have a list of lists (mask_pairs_list), and each "sublist" has 2 Nifti files so it looks something like this.enter image description here

I'm looping through this list for (z in mask_pairs_list) and doing something with the "heat map" and "mask" within each element/sublist of the master "mask_pairs_list". I then want to save the resulting Nifti file with a name that includes the name of the sublist like "mordor2_result" or "apple10_result". The problem is when I try to get a character vector within the for loop of the sublist name by using name_placeholder <- names(z) it gets the names within the sublist and returns "heatmap" and "mask". How would I essentially go a layer out, and get the name of the sublist itself?

Thanks!

CodePudding user response:

Something like this should work:

##
#   made up example
#   same structure as you dataset, more or less...
#
set.seed(1)
mask_pairs <- list(
  A = list(heat_map = matrix(1:25, nc=5), 
           mask     = matrix(sample(0:1, 25, replace = TRUE), nc=5)),
  B = list(heat_map = matrix(1:25, nc=5), 
           mask     = matrix(sample(0:1, 25, replace = TRUE), nc=5)),
  C = list(heat_map = matrix(1:25, nc=5), 
           mask     = matrix(sample(0:1, 25, replace = TRUE), nc=5)),
  D = list(heat_map = matrix(1:25, nc=5), 
           mask     = matrix(sample(0:1, 25, replace = TRUE), nc=5))
) 
##
#   you start here
#
fun    <- \(x) x$heat_map * x$mask
result <- sapply(mask_pairs, fun, simplify = FALSE, USE.NAMES = TRUE)
mapply(FUN = \(result, fname) write.csv(result, file=sprintf('%s_result.csv', fname)), 
       result, names(result))

The key is using sapply(..., simplify=FALSE, USE.NAMES=TRUE) to get a named list. Oddly, lapply(...) does not accept the USE.NAMES=... argument, so you have to use sapply(..., simplify=FALSE) which is equivalent to lapply(...).

In this example my fun(...) just applies the mask to the heat map. You would have a different fun(...) and use something other than write.csv(...) obviously.

  • Related