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

如何基于嵌套内容递归删除R列表中checked=TRUE的项

递归删除R嵌套列表中checked = TRUE的项

示例数据(模拟jsTreeR结构)

先定义符合场景的嵌套列表数据:

tree_data <- list(
  list(
    text = "Root 1",
    checked = FALSE,
    children = list(
      list(text = "Child 1.1", checked = TRUE),
      list(
        text = "Child 1.2",
        checked = FALSE,
        children = list(
          list(text = "Grandchild 1.2.1", checked = TRUE),
          list(text = "Grandchild 1.2.2", checked = FALSE)
        )
      )
    )
  ),
  list(
    text = "Root 2",
    checked = TRUE,
    children = list(
      list(text = "Child 2.1", checked = FALSE)
    )
  )
)

Base R 递归解决方案

自定义递归函数,遍历所有层级,移除checked = TRUE的节点,同时清理空的children字段:

remove_checked <- function(x) {
  if (!is.list(x)) return(x)
  
  # 递归处理子节点,过滤掉checked为TRUE的项
  if ("children" %in% names(x)) {
    x$children <- Filter(
      function(item) !isTRUE(item$checked),
      lapply(x$children, remove_checked)
    )
    # 移除空的children字段
    if (length(x$children) == 0) x$children <- NULL
  }
  
  # 如果当前节点checked为TRUE,返回NULL(后续会被过滤),否则返回处理后的节点
  if (isTRUE(x$checked)) NULL else x
}

# 应用函数并过滤掉NULL节点
cleaned_tree <- Filter(Negate(is.null), lapply(tree_data, remove_checked))

验证输出结构:

str(cleaned_tree)
# List of 1
#  $ :List of 2
#   ..$ text    : chr "Root 1"
#   ..$ children:List of 1
#   .. ..$ :List of 2
#   .. .. ..$ text    : chr "Child 1.2"
#   .. .. ..$ children:List of 1
#   .. .. .. ..$ :List of 2
#   .. .. .. .. ..$ text   : chr "Grandchild 1.2.2"
#   .. .. .. .. ..$ checked: logi FALSE

rrapply 包解决方案

如果可以使用第三方包,rrapply的prune模式能更简洁实现需求:

library(rrapply)

cleaned_tree_rrapply <- rrapply(
  tree_data,
  # 匹配所有列表节点且checked为TRUE的项
  condition = function(x) is.list(x) && isTRUE(x$checked),
  # 将匹配项设为NULL
  f = function(x) NULL,
  # 自动修剪掉NULL节点
  how = "prune"
)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 03:42:27