R语言如何合并复杂列表内不同层级的嵌套元素?
多层嵌套列表规整合并为目标tibble的实现
可复现的前置测试代码
先复现给出的嵌套结构,同时规避对象名与内置函数重名的问题:
# 构造内嵌数据框列表 df1 <- list(data.frame(f1 = c(1:3), f2 = c("a","b","c"))) df2 <- list(data.frame(f1 = c(4:6), f2 = c("d","e","f"))) df3 <- list(data.frame(f1 = c(7:9), f2 = c("x","y","z"))) # 构造单条记录的tibble单元 list1 <- tibble("table1", "comment1", df1) list2 <- tibble("table2", "comment2", df2) list3 <- tibble("table3", "comment3", df3) # 组装最终的外层嵌套列表 nested_list <- list(list1, list2, list3)
结构拆解说明
每个嵌套tibble单元的固定位置元素对应最终结果的字段:
- 第1列的字符值:对应结果中的
table_name列 - 第2列的字符值:为冗余注释信息,无需纳入最终结果
- 第3列的嵌套列表元素:内含带
f1、f2字段的数据框,分别对应结果中的f1列和value列
实现代码
基于tidyverse生态完成结构拆解与拼接,无需手动编写循环逻辑:
library(tidyverse) final_result <- nested_list |> map_dfr(\(tbl_item) { # 按固定索引提取对应字段 cur_table_name <- tbl_item[[1, 1]] cur_inner_df <- tbl_item[[1, 3]][[1]] # 重命名f2为目标列名value,补充表名字段 cur_inner_df |> rename(value = f2) |> mutate(table_name = cur_table_name, .before = f1) })
输出结果
代码运行后直接得到预期的tibble结构:
final_result # A tibble: 9 × 3 table_name f1 value <chr> <int> <chr> 1 table1 1 a 2 table1 2 b 3 table1 3 c 4 table2 4 d 5 table2 5 e 6 table2 6 f 7 table3 7 x 8 table3 8 y 9 table3 9 z
注意事项:原示例代码中直接将外层列表命名为
list,会覆盖R基础包内置的list()构造函数,后续代码运行极易出现逻辑报错,实际开发中请使用不与内置函数、常用包函数重名的对象命名。
内容的提问来源于stack exchange,提问作者ds_worthington
相关产品推荐
相关产品推荐

