Freeego
Freeego

Reputation: 135

How to calculate betweenness of cities on the road network with igraph

My aim is to calculate the betweenness centrality of cities on a road network with igraph. Firstly I use points2network function from shp2graph package to put the city nodes on the road network. Then I use nel2igraph function to convert the network into igrah data. For example, the network is g1.

set.seed(123)
        
D <- read.table(
  sep=',',
  header=T,
  text=
    'from,to, length
A,B,5
A,C,2
D,E,3
F,G,1
H,I,6
B,H,8
D,A,4
F,B,7
') 



g1 <- graph.data.frame(D,directed=F)

plot(g1)

The network is like this:

enter image description here

In this network, E,C,B,I are the cities. Other nodes are the points originally from the road network. When I use betweenness function with igraph, it will include all the nodes in the network. But I just need the city nodes to be calculated. The cities' relationship should be like g2:

 D <- read.table(
      sep=',',
      header=T,
      text=
        'from,to,length
    E,C,9
    E,B,12
    B,C,7
    B,I,14
    ')

g2 <- graph.data.frame(D,directed=F)
plot(g2)

enter image description here

Does anyone know a method to just calculate the betweenness of the cities? Thanks!

Upvotes: 1

Views: 235

Answers (1)

ThomasIsCoding
ThomasIsCoding

Reputation: 102519

You can try distances like below

D2$length <- distances(
  set_edge_attr(g1,
    name = "weight",
    value = D$length
  )
)[as.matrix(D2)]

which gives

> D2
  from to length
1    E  C      9
2    E  B     12
3    B  C      7
4    B  I     14

Update

If you are expecting the betweenness of vertices, you can try

> distances(graph.data.frame(D2, directed = FALSE)) <= 1
      E    B     C     I
E  TRUE TRUE  TRUE FALSE
B  TRUE TRUE  TRUE  TRUE
C  TRUE TRUE  TRUE FALSE
I FALSE TRUE FALSE  TRUE

Data

> dput(D2)
structure(list(from = c("E", "E", "B", "B"), to = c("C", "B",
"C", "I")), class = "data.frame", row.names = c(NA, -4L))

Upvotes: 0

Related Questions