问题R: tree with overlapping strings我è¦æ±‚制作一棵看起æ¥åƒçš„æ ‘
V621 --> V62123 --> V6212355
--> V621335 --> V62133526
--> V6216 --> V62162
--> V621213452
--> V62126324
它适用于包minimum spanning tree
ä¸çš„igraph
ï¼Œä½†çŽ°åœ¨æˆ‘æƒ³ç¡®å®šè¯¥æ ‘çš„æ¯ä¸ªå…ƒç´ 的深度。我怎么这么åšï¼Ÿ
ç”案 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)))