![](/img/trans.png)
[英]Find subset of a graph using node id's (must include all nodes connected to id's supplied)
[英]How to define the difference between id's nodes of graph?
我有一個圖g
n = 8
m <- t(matrix(c(
0,0,0,0,0,0,0,8,
3,0,0,0,0,0,0,0,
5,0,0,5,1,0,0,0,
0,0,6,0,0,7,1,0,
0,6,2,0,0,0,0,0,
0,0,0,0,0,0,0,0,
7,4,0,0,8,0,0,3,
0,3,0,0,0,9,0,0),ncol=n))
library(igraph)
g <- graph_from_adjacency_matrix(m, weighted=TRUE, mode="directed")
V(g1)$name <- letters[1:n]
經過一些計算,我得到了帶有頂點名稱的向量str
:
str <- c("dca", "dgb", "dc", NA, "dce", "df", "dg", "dg")
我需要找到唯一節點和 plot 一棵樹,其中根節點是str
中的第一個符號。
我的嘗試是:
str[is.na(str)]<-"";
vname <- noquote(unique(strsplit((paste0(str, collapse="")),"")[[1]]))
vname
# d c a g b e f
vid <- match( vname, V(g1)$name )
vid
# 4 3 1 7 2 5 6
可以看出g
和vid
的節點區別在於h
節點,它的id
是8。
預期結果是:
問題。 plot一棵樹,如何定義id的節點的差異,刪除對應邊的頂點?
您可以使用subgraph.edges
:
# find wanted edges
str <- unique(str[!is.na(str)])
keep_edges <- apply(
X = unique(
do.call(rbind, lapply(strsplit(str, ""), function(x) embed(x, 2)[,2:1]))
),
MARGIN = 1,
paste0,
collapse = "|"
)
# subgraph containing only wanted edges
g <- subgraph.edges(g1, keep_edges)
nodes <- V(g)$name
plot(g, layout = igraph::layout_as_tree)
您可以使用eval
+ graph_from_literal
+ gsub
創建如下圖 object g
tryCatch({
if (all(is.na(str))) warning("All NAs in the input array!")
g <- eval(
str2lang(
sprintf(
"graph_from_literal(%s)",
toString(gsub("(?<=.)(?=.)", "-+", na.omit(str), perl = TRUE))
)
)
)
})
你會看到
> g
IGRAPH fe5b7ea DN-- 7 6 --
+ attr: name (v/c)
+ edges from fe5b7ea (vertex names):
[1] d->c d->g d->f c->a c->e g->b
和plot(g, layout = layout_as_tree)
給出
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.