簡體   English   中英

將ID應用於樹狀圖中的節點的功能

[英]function to apply ID to nodes in a dendrogram

我想知道是否存在將標識符應用於給定樹狀圖(二叉樹)中所有節點的函數。

所以我想要一個在給定樹上執行以下操作的函數:

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

等等...

並且,如果以二進制ID 110(頭節點的ID)開頭

它的第一個孩子ID應該是1100它的第二個孩子ID應該是1101

注意: dendrapply()將函數應用於樹中的所有節點

包using =“ stats”

 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是什么?

這是取自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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM