我使用igraph。R中2個頂點之間的所有路徑
我想要找到2個節點之間的所有可能路徑。
就目前而言,似乎沒有存在任何功能,找到所有2個節點之間的路徑中的igraph
我發現這個問題,讓代碼在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])
謝謝!
如果有人看到哪裏出了問題,那將是很大的幫助......
馬修
'我試圖將它移植到R [來自Python]'< - 如果你想讓你的代碼高效, –
您可以通過提供用於創建'graph'和'farth'的小版本的代碼來讓您的示例具有可再現性嗎? – flodel
看看http://igraph.sourceforge.net/doc/R/shortest.paths.html – user1929959