我有一个有向循环矩阵,需要提取任何i和j之间的所有简单路径。
以下是我的前任。矩阵:
>M2<-matrix(c(1,1,0,0,0,1,1,1,1,0,0,1,1,1,0,0,1,0,1,1,0,0,0,1,1), 5, byrow=T)
>colnames(M2)<-c("A", "B", "C", "D", "E")
>row.names(M2)=colnames(M2)
>M2
A B C D E
A 1 1 0 0 0
B 1 1 1 1 0
C 0 1 1 1 0
D 0 1 0 1 1
E 0 0 0 1 1
我使用igraph
使用graph_from_adjency_matrix
函数将矩阵转换为图形对象。
>graph<-graph_from_adjacency_matrix(M2, mode=c("directed"), weighted=NULL, diag=F, add.colnames=NULL, add.rownames=NA)
>graph
IGRAPH DN-- 5 9 --
+ attr: name (v/c)
+ edges (vertex names):
[1] A->B B->A B->C B->D C->B C->D D->B D->E E->D
从那里我使用all_simple_paths
函数来获取i和j之间的所有简单路径。在这里开始我的问题。
1)我可以指定j(参数to
has to=V(graph)
)为所有可能的终点顶点。但我不能指定from
参数来计算寻找所有顶点的路径有可能的起点。我必须一次指定我的每个变量。任何解决方案?
2)all_simple_path
函数运行良好,并为我提供i和j之间的所有简单路径,例如对于从A
开始并以任何可能的j结尾的简单路径:
>Simple_path_list<-all_simple_paths(graph, from ="A", to=V(graph), mode = c("out"))
>Simple_path_list
[[1]]
+ 2/5 vertices, named:
[1] A B
[[2]]
+ 3/5 vertices, named:
[1] A B C
[[3]]
+ 4/5 vertices, named:
[1] A B C D
[[4]]
+ 5/5 vertices, named:
[1] A B C D E
[[5]]
+ 3/5 vertices, named:
[1] A B D
[[6]]
+ 4/5 vertices, named:
[1] A B D E
我的问题是,我需要收集所有这些路径并列入一个列表,例如:
Paths
A B
A B C
A B C D
A B C D E
A B D
A B D E
我尝试创建一个列表并使用普通list<-Simple_path_list[1]
左右调用路径名,但我总是与路径一起检索所涉及的顶点数量的信息(例如{{1 }})。关于如何只检索路径名而不是其他信息的任何想法?
答案 0 :(得分:2)
lapply
上的all_simple_paths
函数生成列表列表(即每个顶点的路径列表)。使用unlist(..., recursive = F)
将列表列表简化为列表,然后使用names
或igraph
&#39; s as_ids
来提取顶点ID独奏。
library(igraph)
M2<-matrix(c(1,1,0,0,0,1,1,1,1,0,0,1,1,1,0,0,1,0,1,1,0,0,0,1,1), 5, byrow=T)
colnames(M2)<-c("A", "B", "C", "D", "E")
row.names(M2)=colnames(M2)
M2
graph<-graph_from_adjacency_matrix(M2, mode=c("directed"), weighted=NULL, diag=F, add.colnames=NULL, add.rownames=NA)
l <- unlist(lapply(V(graph) , function(x) all_simple_paths(graph, from=x)), recursive = F)
paths <- lapply(1:length(l), function(x) as_ids(l[[x]]))
这会产生:
> paths
[[1]]
[1] "A" "B"
[[2]]
[1] "A" "B" "C"
[[3]]
[1] "A" "B" "C" "D"
[[4]]
[1] "A" "B" "C" "D" "E"
[[5]]
[1] "A" "B" "D"
[[6]]
[1] "A" "B" "D" "E"
[[7]]
[1] "B" "A"
[[8]]
[1] "B" "C"
[[9]]
[1] "B" "C" "D"
[[10]]
[1] "B" "C" "D" "E"
[[11]]
[1] "B" "D"
[[12]]
[1] "B" "D" "E"
[[13]]
[1] "C" "B"
[[14]]
[1] "C" "B" "A"
[[15]]
[1] "C" "B" "D"
[[16]]
[1] "C" "B" "D" "E"
[[17]]
[1] "C" "D"
[[18]]
[1] "C" "D" "B"
[[19]]
[1] "C" "D" "B" "A"
[[20]]
[1] "C" "D" "E"
[[21]]
[1] "D" "B"
[[22]]
[1] "D" "B" "A"
[[23]]
[1] "D" "B" "C"
[[24]]
[1] "D" "E"
[[25]]
[1] "E" "D"
[[26]]
[1] "E" "D" "B"
[[27]]
[1] "E" "D" "B" "A"
[[28]]
[1] "E" "D" "B" "C"
对于all_shortest_paths
,您必须将每个节点的路径列表分组为排除测地信息。
l <- lapply(V(graph), function(x) all_shortest_paths(graph, from = x))
l <- lapply(l, function(x) x[[-2]])
l <- unlist(l, recursive = F)
paths <- lapply(1:length(l), function(x) as_ids(l[[x]]))