'How can I add geographic distance matrix to an igraph network?

I have an igraph network of 169 nodes (neighbourhoods). I've added some vertices attributes using: V(g)$attribute. I'm going to study the impact of the geographic distance between the nodes (neighbourhoods). I've calculated the distance between neighbourhoods based on the longitude and latitude:

head(df)
neighbourhood     lon       lat
      1         41.47141  -81.75226
      2         41.47562  -81.74670
      3         41.47608  -81.73900
      .            .          .
      .            .          .

# Calculate the geographic distance matrix using  distm() from geosphere

dis.matrix <- (distm(cbind(df$lon, df$lat)))

# The result is a geographic matrix of 169x169 (distance in meters)

Now, my question is How can I add these distances to the network (g) in order to study the impact of the distance on linked nodes using Exponential Random Graph Model ergm().



Solution 1:[1]

I think you are looking for this.

library(igraph)
library(geosphere)


df <- data.frame(neighbourhood = c(1, 2, 3),
                 lon           = c(41.47141, 41.47562, 41.47608),
                 lat           = c(-81.75226, -81.74670, -81.73900))

distance.matrix <- distm(subset(df, select = c(lon, lat)))

my.graph <- graph_from_adjacency_matrix(distance.matrix, mode = "undirected", weighted = TRUE)

# At attributes to the vertices.
V(my.graph)$name <- df$neighbourhood
V(my.graph)$lon  <- df$lon
V(my.graph)$lat  <- df$lat

# Remove duplicated edges.
my.graph <- simplify(my.graph)

# The distances are saved in the edges in the variable weight.
E(my.graph)$weight

plot(my.graph, edge.label = E(my.graph)$weight)

HTH!

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 MacOS