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

谢谢!
如果有人发现问题所在,那将是很大的帮助…
马修

最佳答案

我还尝试将同一个解决方案从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)]})
}

10-04 20:57