Search code examples
rigraph

Finding the distance matrix using igraph


I have a network that is connected like the following:

library(igraph)
network <- graph_from_literal(1--2,2--3,3--4,4--5,3--6,6--7,3--8,8--9)

and have the distance between each segment

> data=data.frame(Origin=c(1,2,3,4,3,6,3,8), Destination=c(2,3,4,5,6,7,8,9), km=c(0.3,0.5,0.2,0.1,1,2,0.6,0.4))
> data
  Origin Destination  km
      1           2 0.3
      2           3 0.5
      3           4 0.2
      4           5 0.1
      3           6 1.0
      6           7 2.0
      3           8 0.6
      8           9 0.4

I would like to find the distance matrix between all points and I tried using

distMatrix <- shortest.paths(data, v=Origin(data), to=Destination(data))

but cannot make it work.

Thanks!


Solution

  • The distances() function will give you a distance matrix. By setting the edge weights, the distance matrix will include these weights in the calculation. In the code below, I create the graph from your dataset data, such that the edges are correctly ordered:

    library("igraph")
    data = data.frame(Origin=c(1,2,3,4,3,6,3,8), Destination=c(2,3,4,5,6,7,8,9), 
      km=c(0.3,0.5,0.2,0.1,1,2,0.6,0.4))
    
    g = graph_from_edgelist(cbind(data$Origin, data$Destination))
    E(g)
    #> + 8/8 edges from 7ad6d28:
    #> [1] 1->2 2->3 3->4 4->5 3->6 6->7 3->8 8->9
    E(g)$weight = data$km
    
    distances(g)
    #>       [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9]
    #>  [1,]  0.0  0.3  0.8  1.0  1.1  1.8  3.8  1.4  1.8
    #>  [2,]  0.3  0.0  0.5  0.7  0.8  1.5  3.5  1.1  1.5
    #>  [3,]  0.8  0.5  0.0  0.2  0.3  1.0  3.0  0.6  1.0
    #>  [4,]  1.0  0.7  0.2  0.0  0.1  1.2  3.2  0.8  1.2
    #>  [5,]  1.1  0.8  0.3  0.1  0.0  1.3  3.3  0.9  1.3
    #>  [6,]  1.8  1.5  1.0  1.2  1.3  0.0  2.0  1.6  2.0
    #>  [7,]  3.8  3.5  3.0  3.2  3.3  2.0  0.0  3.6  4.0
    #>  [8,]  1.4  1.1  0.6  0.8  0.9  1.6  3.6  0.0  0.4
    #>  [9,]  1.8  1.5  1.0  1.2  1.3  2.0  4.0  0.4  0.0
    

    Created on 2021-09-06 by the reprex package (v2.0.1)