2013-05-21 71 views
0

我使用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]) 

謝謝!

如果有人看到哪裏出了問題,那將是很大的幫助......

馬修

+0

'我試圖將它移植到R [來自Python]'< - 如果你想讓你的代碼高效, –

+1

您可以通過提供用於創建'graph'和'farth'的小版本的代碼來讓您的示例具有可再現性嗎? – flodel

+0

看看http://igraph.sourceforge.net/doc/R/shortest.paths.html – user1929959

回答

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)]}) 
} 
+0

感謝Johannux,它像一個魅力:)我也發現有一個可能會完成相同的事情在igraph all_simple_paths函數。 –

相關問題