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

如何将Data Frame转换为递归列表结构(树形结构)?

将父子关系DataFrame转换为嵌套树形列表(R语言实现)

要把父子结构的DataFrame转成支持任意深度嵌套的树形列表,用递归函数是最直接的方案,完全适配多层级场景。

核心递归函数

build_tree <- function(data, parent_id) {
  # 筛选当前父节点对应的所有子节点
  children <- data[data$ParentID == parent_id, ]
  
  # 没有子节点时返回空,最终结构里就不会生成children字段
  if (nrow(children) == 0) {
    return(NULL)
  }
  
  # 递归生成每个子节点的树形结构
  lapply(seq(nrow(children)), function(i) {
    child <- children[i, ]
    list(
      text = child$Child,
      children = build_tree(data, child$Child)
    )
  })
}

调用示例

用你提供的测试数据验证:

roles_data <- data.frame(
  Child = c("A", "B", "C", "D", "E", "F"),
  ParentID = c(NA, "A", "B", "B", "D", "D"),
  stringsAsFactors = FALSE  # 强制用字符类型,避免因子匹配出错
)

# 生成树形结构,顶级节点对应ParentID为NA的记录
tree_output <- build_tree(roles_data, NA)

运行后tree_output的结构和你给出的desired_output完全一致,打印验证:

str(tree_output)
# List of 1
#  $ :List of 2
#   ..$ text    : chr "A"
#   ..$ children:List of 1
#   .. ..$ :List of 2
#   .. .. ..$ text    : chr "B"
#   .. .. ..$ children:List of 2
#   .. .. .. ..$ :List of 1
#   .. .. .. .. ..$ text: chr "C"
#   .. .. .. ..$ :List of 2
#   .. .. .. .. ..$ text    : chr "D"
#   .. .. .. .. ..$ children:List of 2
#   .. .. .. .. .. ..$ :List of 1
#   .. .. .. .. .. .. ..$ text: chr "E"
#   .. .. .. .. .. ..$ :List of 1
#   .. .. .. .. .. .. ..$ text: chr "F"

代码说明

  • 递归函数build_tree每次只处理当前父节点的子节点,对每个子节点重复调用自身生成子树,天然支持无限层级嵌套
  • 当节点没有子节点时,children会返回NULL,最终结构里就不会显示该字段(和示例里的节点C逻辑一致)
  • 必须设置stringsAsFactors = FALSE,否则ParentID或Child列会被转成因子类型,导致父节点匹配失败

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 12:30:00