9

我有一个 data.frame ,其中两列代表一个层次结构树,带有父节点和节点。

我想以一种可以用作 function 输入的方式d3treed3Networkpackage.json 转换它的结构。

这是我的数据框:

df <- data.frame(c("Canada","Canada","Quebec","Quebec","Ontario","Ontario"),c("Quebec","Ontario","Montreal","Quebec City","Toronto","Ottawa"))
names(df) <- c("parent","child")

我想把它改造成这种结构

Canada_tree <- list(name = "Canada", children = list(
                                                list(name = "Quebec", 
                children = list(list(name = "Montreal"),list(name = "Quebec City"))),
                                                 list(name = "Ontario", 
                children = list(list(name = "Toronto"),list(name = "Ottawa")))))

我已经使用下面的代码成功地转换了这个特殊情况:

fill_list <- function(df,node) node <- as.character(node)if (is.leaf(df,node)==TRUE){
    return (list(name = node))
  }
  else {
    new_node = df[df[,1] == node,2]

    return (list(name = node, children =  list(fill_list(df,new_node[1]),fill_list(df,new_node[2]))))
  }

问题是,它只适用于每个父节点正好有两个孩子的树。您可以看到我将两个孩子(new_node[1] 和 new_node[2])硬编码为递归函数的输入。

我试图找出一种方法,我可以像父节点的子节点一样多次调用递归函数。例子:

fill_list(df,new_node[1]),...,fill_list(df,new_node[length(new_node)])

我尝试了这 3 种可能性,但都没有奏效:

首先:创建一个包含所有函数和参数的字符串,然后进行评估。它返回此错误could not find function fill_functional(df,new_node[1])。那是因为我的函数毕竟不是在我调用它的时候创建的。

fill_functional <- function(df,node) {
  node <- as.character(node)
  if (is.leaf(df,node)==TRUE){
    return (list(name = node))
  }
  else {
    new_node = df[df[,1] == node,2]
    level <- length(new_node)
    xxx <- paste0("(df,new_node[",seq(level),"])")
    lapply(xxx,function(x) eval(call(paste("fill_functional",x,sep=""))))

  }
}

第二:使用for循环。但我只得到了我的根节点的孩子。

L <- list()
fill_list <- function(df,node) {
  node <- as.character(node)
  if (is.leaf(df,node)==TRUE){
    return (list(name = node))
  }
  else {
    new_node = df[df[,1] == node,2]

    for (i in 1:length(new_node)){
      L[i] <- (fill_list(df,new_node[i]))
    }

    return (list(name = node, children = L))
  }
}

第三:创建一个用函数元素填充列表的函数,并且只更改参数。但是我无法完成任何有趣的事情,而且我担心我会遇到与上述第一次尝试相同的问题。

4

1 回答 1

11

这是一个递归定义:

maketreelist <- function(df, root = df[1, 1]) {
  if(is.factor(root)) root <- as.character(root)
  r <- list(name = root)
  children = df[df[, 1] == root, 2]
  if(is.factor(children)) children <- as.character(children)
  if(length(children) > 0) {
    r$children <- lapply(children, maketreelist, df = df)
    }
  r
  }

canadalist <- maketreelist(df)

这会产生你想要的东西。此函数假定您传入的data.frame(or ) 的第一列包含该列,第二列包含. 它还需要一个允许您指定起点的参数。它将默认为列表中的第一个父级。matrixparentchildroot

但如果你真的有兴趣玩树。包裹igraph可能很有趣

library(igraph)
g <- graph.data.frame(df)
plot(g)

igraph 中的加拿大树

于 2014-05-23T23:10:36.833 回答