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

如何将固定结构的R DataFrame转换为指定格式的嵌套列表?

将层级结构DataFrame转换为嵌套列表(R语言)

问题背景

现有如下结构的R DataFrame:

df <- data.frame(
      all = c("All product","All product","All product","All product","All product","All product","All product","All product",
              "All product","All product","All product","All product","All product","All product","All product","All product"),
      category = c("Agriculture","Agriculture","Agriculture","Agriculture", "Agriculture","Agriculture","Agriculture","Agriculture",
                   "Non Agriculture", "Non Agriculture", "Non Agriculture", "Non Agriculture","Non Agriculture", "Non Agriculture", "Non Agriculture", "Non Agriculture"),
      HS2 = c("01","01","01","01","02","02","02","02","03","03","03","03","04","04","04","04"),
      HS4 = c("0101","0101","0102","0102","0201","0201","0202","0202","0301","0301","0302","0302","0401","0401","0402","0402"),
      HS6 = c("010101","010102", "010201","010202","020101","020102","020201","020202","030101","030102", "030201","030202","040101","040102","040201","040202")
    )

需要将其自动转换为指定格式的嵌套列表,当DataFrame数据更新时仍能保持结构自动生成。

解决方案

通过递归函数可以实现层级结构的自动转换,具体步骤如下:

1. 数据预处理:保留唯一层级路径

原数据存在重复的层级组合,先筛选出所有唯一的路径:

library(dplyr)

# 去重,保留每条唯一的层级路径
unique_df <- df %>% distinct(all, category, HS2, HS4, HS6)

2. 编写递归构建树的函数

该函数会从指定层级开始,递归生成每个节点及其子节点:

build_tree <- function(data, level_index = 1) {
  # 获取当前处理的列名
  current_col <- colnames(data)[level_index]
  # 获取当前层级的唯一值
  unique_vals <- unique(data[[current_col]])
  
  # 遍历每个唯一值生成节点
  lapply(unique_vals, function(val) {
    # 筛选当前值对应的子数据集
    sub_data <- data[data[[current_col]] == val, ]
    
    # 判断是否还有下一层级需要处理
    if (level_index < ncol(sub_data)) {
      # 递归生成子节点列表
      children <- build_tree(sub_data, level_index + 1)
      list(
        text = val,
        type = ifelse(level_index == 1, "root", "child"),
        children = children
      )
    } else {
      # 最底层节点,无children字段
      list(
        text = val,
        type = "child"
      )
    }
  })
}

3. 生成目标嵌套列表

调用递归函数生成最终的嵌套列表,外层包裹一层list以匹配示例格式:

nodes <- list(build_tree(unique_df)[[1]])

验证输出

可以通过str(nodes)查看生成的嵌套列表结构,其层级、字段与手动编写的示例完全一致。

逻辑说明

  • 递归函数从顶层列(all)开始,依次处理每一层级的唯一值
  • 顶层节点的type设为"root",其余所有节点统一设为"child"
  • 当处理到最后一列(HS6)时,不再生成children字段
  • 预处理去重确保每个层级路径只生成一次节点

内容的提问来源于stack exchange,提问作者akshay bholee

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 21:39:58