0

我想知道是否有一个函数将标识符应用于给定树状图(二叉树)中的所有节点。

所以我想要一个函数,它在给定树上之后会执行以下操作:

attr(tr,"ID")             ## should give 1   or  1 

attr(tr[[1]],"ID")        ## should give 2  or 10

attr(tr[[2]],"ID")        ## should give 3  or 11

attr(tr[[c(1,1)]],"ID")   ##  should give 4  or 100

ETC...

并且,如果以 binaryID 110(头节点的 ID)开头

它的第一个孩子 ID 应该是 1100 它的第二个孩子 ID 应该是 1101

注意: -dendrapply()将函数应用于树中的所有节点

包使用=“统计”

 D=rbind(
+ c(1,1,1,1,1),
+ c(1,2,1,1,1),
+ c(2,2,2,2,2),
+ c(2,2,2,2,1),
+ c(3,3,3,3,3),
+ c(3,3,3,3,2))

Ddend=as.dendrogram(hclust.vector(D))

funID<-function(tr,StartID){
 .....
 attr(n,"ID")= ID  # for all the nodes in tr
 }

funID 是什么?

4

1 回答 1

1

这是取自stats:::reorder.dendrogram并修改的代码,以适应使用递增整数标记根和每个叶子的目的。它可能不完全符合您的规格,但看看它是否符合...

label.leaves <- 
 function (x, wts) 
 { N=1
     if (!inherits(x, "dendrogram")) 
         stop("we require a dendrogram")
     oV <- function(x, wts) {
         if (is.leaf(x)) {
             attr(x, "ID") <- N; N <<- N+1
             return(x)
         }
         k <- length(x)
         if (k == 0L) 
             stop("invalid (length 0) node in dendrogram")
         vals <- numeric(k)
         for (j in 1L:k) { N <- N+1
             b <- oV(x[[j]], wts)
             x[[j]] <- b
             vals[j] <- N; N <- N+1
         }
       x
     }
     stats:::midcache.dendrogram(oV(x, wts))
 }

测试:

> Ddend.L <- label.leaves(Ddend)
> rapply(Ddend.L, function(x) return( attr(x, "ID") ))
[1] 1 2 3 4 5 6
于 2012-09-10T03:26:52.690 回答