r - 使用 purrr 递归处理任意层次结构

标签 r recursion purrr tidyverse

假设我想根据某些特定标准修剪由 R 中的嵌套列表层次结构组成的树。我可以使用 lapply 来“轻松”地做到这一点:

# Based an example from the NetworkD3 documentation
# https://christophergandrud.github.io/networkD3/

URL <- paste0(
  "https://cdn.rawgit.com/christophergandrud/networkD3/",
  "master/JSONdata//flare.json")

flare <- jsonlite::fromJSON(URL, simplifyDataFrame = FALSE)

# Leaf nodes have a "size" attribute. Let's say we want to 
# prune all the nodes with size < 5000.

prune <- function(tree) {
  if ("children" %in% names(tree)) {
    p <- lapply(tree$children, prune)
    pp <- p[!unlist(lapply(p, is.null))]
    copied_tree = list()
    copied_tree$name = tree$name
    copied_tree$children = pp
    return(copied_tree)
  } else if (tree$size < 5000) {
    return(NULL)
  }
  return(tree)
}

pruned <- prune(flare)

R for Data Science 中,Hadley Wickham discusses purrr 可以替换 apply 系列函数来处理分层数据的许多场景。但是,这些示例似乎要么处理单嵌套列表,要么处理深度嵌套列表的特定节点。

有没有一种方法可以使用 purrr 来完成上面讨论的递归任务?

最佳答案

library(purrr)
prune_2 <- function(tree) {
  # print(tree$name)
  # print(map_lgl(tree$children, ~ "size" %in% names(.x)))
  tree$children %<>%  
    map_if(~ "children" %in% names(.x), prune_2) %>% 
    discard(~ if ("size" %in% names(.x)) .x$size < 5000 else FALSE)
  tree
}
pruned_2 <- prune_2(flare)
identical(pruned, pruned_2)
# [1] TRUE

关于r - 使用 purrr 递归处理任意层次结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41573995/

相关文章:

r - 使用 geom_segment 在 ggplot 中绘制 'type = b' - 调整轴比参数

python - python中的简单列表递归

java - 递归以获取数组中的所有变体总和

删除数据框中变量的镜像组合

r - 使用map和fcase更新嵌套列表的元素

r - Data.table: "group counter"基于给定列或另一列

r - 编织xtable : how to position tables between text?

r - 在 R 中,将维度名称带入矩阵乘积中

multithreading - 将递归分成更细的递归粒度

r - 我可以在给定的 case_when true 子句中进行多项分配吗?