我使用igraph。
我想找到2个节点之间的所有可能路径。
目前,似乎没有任何函数可以找到igraph中2个节点之间的所有路径
我发现这个主题在python中提供代码: All possible paths from one node to another in a directed tree (igraph)
我试图将它移植到R但我有一些小问题。它给了我错误:
Error of for (newpath in newpaths) { :
for() loop sequence incorrect
以下是代码:
find_all_paths <- function(graph, start, end, mypath=vector()) {
mypath = append(mypath, start)
if (start == end) {
return(mypath)
}
paths = list()
for (node in graph[[start]][[1]]) {
if (!(node %in% mypath)){
newpaths <- find_all_paths(graph, node, end, mypath)
for (newpath in newpaths){
paths <- append(paths, newpath)
}
}
}
return(paths)
}
test <- find_all_paths(graph, farth[1], farth[2])
这是一个取自igrah软件包的虚拟代码,从中获取示例图和节点:
actors <- data.frame(name=c("Alice", "Bob", "Cecil", "David",
"Esmeralda"),
age=c(48,33,45,34,21),
gender=c("F","M","F","M","F"))
relations <- data.frame(from=c("Bob", "Cecil", "Cecil", "David",
"David", "Esmeralda"),
to=c("Alice", "Bob", "Alice", "Alice", "Bob", "Alice"),
same.dept=c(FALSE,FALSE,TRUE,FALSE,FALSE,TRUE),
friendship=c(4,5,5,2,1,1), advice=c(4,5,5,4,2,3))
g <- graph.data.frame(relations, directed=FALSE, vertices=actors)
farth <- farthest.nodes(g)
test <- find_all_paths(graph, farth[1], farth[2])
谢谢!
如果有人发现问题所在,那将会有很大的帮助......
马修
答案 0 :(得分:1)
我还试图将同样的解决方案从Python翻译成R,然后提出以下内容似乎为我做了这个工作:
# Find paths from node index n to m using adjacency list a.
adjlist_find_paths <- function(a, n, m, path = list()) {
path <- c(path, list(n))
if (n == m) {
return(list(path))
} else {
paths = list()
for (child in a[[n]]) {
if (!child %in% unlist(path)) {
child_paths <- adjlist_find_paths(a, child, m, path)
paths <- c(paths, child_paths)
}
}
return(paths)
}
}
# Find paths in graph from vertex source to vertex dest.
paths_from_to <- function(graph, source, dest) {
a <- as_adj_list(graph, mode = "out")
paths <- adjlist_find_paths(a, source, dest)
lapply(paths, function(path) {V(graph)[unlist(path)]})
}