我用igraph。
我希望你找到 2 个节点之间的所有可能路径。
目前,似乎不存在任何函数来查找 igraph 中 2 个节点之间的所有路径
我发现这个主题在 python 中给出代码: All possible paths from one node to another in adirected 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])
谢谢!
如果有人看到问题出在哪里,那将有很大帮助...
马修