如何获得iGraph对象直径长度的所有最短路径?

时间:2018-04-20 04:40:39

标签: r igraph sna

我想获得iGraph对象的所有最长的最短路径。有这个功能

get.diameter (graph, directed = TRUE, unconnected = TRUE) 

但它只返回一条路径。因此,如果有很多直径长度的最短路径,那么它将返回第一个找到的路径

1 个答案:

答案 0 :(得分:0)

您可以使用shortest.paths(图形)返回的最短距离矩阵轻松提取哪些节点以什么长度连接。在R中,您可以使用which()arr.ind=TRUE,如下所示:

longest.shortest.paths <- function(graph){
    # Return edgelist of all node-pairs between which the shortest path
    # in a graph are the longest shortest path observed in that graph.

    # Get all the shortest paths of a graph
    shortest.paths = shortest.paths(graph)

    # Make sure that there are no Inf-values caused by isolates in the graph
    shortest.paths[shortest.paths == Inf] <- 0

    # What nodes in the distance matrix are linked by longest shortest paths?
    el <- which(shortest.paths==max(shortest.paths), arr.ind=TRUE)
    colnames(el) <- c("i","j")
    (el)
}

graph <- erdos.renyi.game(100, 140, "gnm", directed=FALSE)
longest.shortest.paths(graph)