Reputation: 21
I have a nested list and want to create a character vector (for file paths/outputs) by iterating over the elements of the list and the sub-elements of each element in R. The list has 174 elements, and each of those elements has five sub-elements (the names of these sub-elements are consistent across each element of the list).
See, for example, the following nested list, which has two elements with five sub-elements each:
iter1 <- list(item1 = "a", item2 = "b",item3 = "c", item4 = "d",item5 = "e")
iter2 <- list(item1 = "a", item2 = "b",item3 = "c", item4 = "d",item5 = "e")
All <- list(iter1 = iter1, iter2 = iter2)
The desired vector output would follow the following structure (assuming all outputs are being saved in a folder labeled, 'output':
[1] "output/iter1_item1.png"
[2] "output/iter1_item2.png"
[3] "output/iter1_item3.png"
[4] "output/iter1_item4.png"
[5] "output/iter1_item5.png"
[6] "output/iter2_item1.png"...etc.
Unless I'm mistaken, the length of the character vector should be 870 (174*5).
I am very close with the following code:
for(i in 1:length(All)){
output_names <- paste0("output/",names(All[i]),"_",names(All[[i]]),".png")}
It produces a character vector with the length of 5 - essentially, the first element with each of the five sub-elements. I would like the code to iterate over each element so that the rest of them are captured as well (the above reproducible example only contains two elements, but my original list contains 175 elements).
Thanks in advance for any help on this issue.
Upvotes: 0
Views: 839
Reputation: 28695
Using the example data, you can repeat the top-level names the appropriate number of times, and sapply
over the list to ger the bottom level names.
paste0('output/', rep(names(All), lengths(All)), '_', sapply(All, names), '.png')
# [1] "output/iter1_item1.png" "output/iter1_item2.png" "output/iter1_item3.png"
# [4] "output/iter1_item4.png" "output/iter1_item5.png" "output/iter2_item1.png"
# [7] "output/iter2_item2.png" "output/iter2_item3.png" "output/iter2_item4.png"
# [10] "output/iter2_item5.png"
If your sublists have different lengths you need unlist(lapply(All, names))
instead of sapply(All, names)
.
Upvotes: 0