0

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

谢谢!

如果有人看到问题出在哪里,那将有很大帮助...

马修

4

1 回答 1

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)]})
}
于 2015-08-21T09:51:38.960 回答