如何在展开嵌套列表时保留二级列表的名称
Solution to Flatten Nested Lists While Preserving Second-Level Names
Great question! I totally get why unlist() isn't working for you here—it's designed to flatten all the way down to atomic elements, which adds those unwanted prefixes and numbering when dealing with nested lists of objects (like your plot objects).
Here's a straightforward fix that exactly delivers what you need:
Method 1: Base R with do.call(c, ...)
This approach merges all sublists from the first level into a single top-level list, keeping only the original second-level names without any extra prefixes.
Example Code
First, let's recreate your sample nested list:
# Build your example nested list my_list <- list( listA = list( listA_a = c(1, 2), listA_g = c(1, 2) ), listB = list( listB_b = c(1, 2) ) )
Now apply the solution:
# Flatten to top-level list with preserved second-level names flattened_list <- do.call(c, my_list) # View the result flattened_list
Output
$listA_a [1] 1 2 $listA_g [1] 1 2 $listB_b [1] 1 2
Method 2: Tidyverse with purrr::flatten()
If you're already using the tidyverse, purrr::flatten() does the exact same thing in a more readable way:
library(purrr) flattened_list <- flatten(my_list)
Why This Works
Both methods work by merging the inner lists (your listA_a, listA_g, listB_b) directly into a single top-level list, rather than breaking down the elements inside those lists (which is what unlist() does). This preserves the original names of the inner list items perfectly, and it works seamlessly for plot objects or other custom list-based structures—no need to rename anything manually.
内容的提问来源于stack exchange,提问作者Pernii

