【问题标题】:function to apply ID to nodes in a dendrogram将 ID 应用于树状图中的节点的函数
【发布时间】:2012-09-09 23:59:17
【问题描述】:

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

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

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

等等……

并且,如果以 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 是什么?

【问题讨论】:

  • 请至少注意您用于树状图的packagedendrapply,以使您的示例可重现
  • @mnel dendrapply 是一个基本的 R 函数 - 它在包 stats 中。

标签: r dendrogram


【解决方案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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-26
    • 1970-01-01
    • 1970-01-01
    • 2019-04-18
    • 1970-01-01
    • 2021-12-23
    相关资源
    最近更新 更多