R:深度最å°ç”Ÿæˆæ ‘

时间:2014-10-09 14:43:46

标签: r tree depth

问题R: tree with overlapping strings我è¦æ±‚制作一棵看起æ¥åƒçš„æ ‘

V621   --> V62123  --> V6212355
    --> V621335 --> V62133526
    --> V6216 --> V62162
    --> V621213452
    --> V62126324

它适用于包minimum spanning tree中的igraph,但现在我想确定该树的æ¯ä¸ªå…ƒç´ çš„深度。我怎么这么åšï¼Ÿ

1 个答案:

答案 0 :(得分:3)

如果我们借用previous answer ...

中的所有相关代ç 
df <- read.table(text='verkoop          V621  
verkoopcode      V62123  
verkoopcodenaam  V6212355  
verkoopdatum     V621335  
verkoopdatumchar V62133526  
verkooppr        V6216  
verkoopprijs     V62162  
verkoopsafdeling V621213452  
verkoopsartikel  V62126324')
# use igraph package
require(igraph)
# create adjacency matrix 
adj <- nchar(sapply(df$V1, gsub, x=df$V1, replacement=''))
adj[!sapply(df$V1, grepl, x=df$V1)] <- 0
# name adjecency matrix 
colnames(adj) <- df$V2
# original graph
gr <- graph.adjacency(adj, mode='directed', weighted=TRUE)
layout(matrix(1:2, ncol=2))
plot(gr)
# minimum spanning tree 
mst <- minimum.spanning.tree(gr)

ä½ å¯ä»¥ç”¨

获得深度
shortest.paths(mst, to="V621", weights=rep(1, ecount(mst)))
#            V621
# V621          0
# V62123        1
# V6212355      2
# V621335       1
# V62133526     2
# V6216         1
# V62162        2
# V621213452    1
# V62126324     1

请注æ„,我们必须调整æƒé‡ï¼Œå› ä¸ºé»˜è®¤æƒ…况下graph.adjacency使用adj中的值作为边的æƒé‡ï¼Œå®žé™…上我们åªæƒ³å°†æ¯ä¸ªè¾¹è®¡ä¸ºä¸€ä¸ªã€‚你也å¯ä»¥åšåˆ°

gr <- graph.adjacency(adj>0, mode='directed', weighted=TRUE)
mst <- minimum.spanning.tree(gr)
shortest.paths(mst, to="V621")

将所有默认æƒé‡è®¾ç½®ä¸º1。

è¿™å‡è®¾ä½ çŸ¥é“&#34; V621&#34;是根节点。如果你ä¸çŸ¥é“哪个是根节点,你å¯ä»¥ç”¨

找到它
dx <-degree(mst, mode="out")
root <- names(dx)[dx==0]
shortest.paths(mst, to=root, weights=rep(1, ecount(mst)))