You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在展开嵌套列表时保留二级列表的名称

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 16:17:49