2012-01-10 80 views
1

我自学R,好了,更像是玩了; Binary Tree包是具体的。当我在那个页面上得到了这个例子后,我想我会尝试从终端节点向父节点走树。这个特定的包似乎没有getParent()函数/方法(我可以看出)会做我想做的。如何在R中走上一棵树?

所以我想我应该树转换为其他对象:一个图形,文本字符串,不管,但是我似乎没有有足够好的谷歌福来找到我要找的数组。我仍然试图找到解决方案。

因此,如何会怎么会有人谁知道他(她)在做向上走的树在网页上给出的例子吗?

+1

请阅读更仔细:“二叉树类{}党”。这不是二叉树包。 – 2012-01-10 04:37:30

回答

3

嗯,这里是遍历树,并增加了家长的每个节点的功能。

addParent <- function(n, parent = NULL) { 
    n$parent <- parent 
    if (!n$terminal) { 
     n$left <- Recall(n$left, n) 
     n$right <- Recall(n$right, n) 
    } 
    n 
} 

# Example usage 
airq <- subset(airquality, !is.na(Ozone)) 
airct <- ctree(Ozone ~ ., data = airq, 
       controls = ctree_control(maxsurrogate = 3)) 
[email protected] <- addParent([email protected]) 
leaves <- nodes(airct, unique(where(airct))) 
leaves[[1]]  # node 5 
leaves[[1]]$parent # node 4 

# And here's a way to "walk up the tree" 
walkUp <- function(n) { 
    cat("Node", n$nodeID, "\n") 
    n <- n$parent 
    if(!is.null(n)) Recall(n) 
} 

for(n in leaves) { cat("---\n"); walkUp(n) } 

BTW,我想我宁愿上树比走到它;-)

+0

我在这里咀嚼很多东西!谢谢! – user63741 2012-01-11 23:29:07