问题描述
我的目标是使用 igraph 计算道路网络上城市的介数中心性。首先,我使用 shp2graph 包中的 points2network 函数将城市节点放在道路网络上。然后我使用 nel2igraph 函数将网络转换为 igrah 数据。 比如网络是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,7
')
g1 <- graph.data.frame(D,directed=F)
plot(g1)
网络是这样的:
在这个网络中,E、C、B、I 是城市。其他节点是最初来自道路网络的点。当我在 igraph 中使用介数函数时,它将包括网络中的所有节点。但我只需要计算城市节点。城市的关系应该像g2:
D <- read.table(
sep=',text=
'from,length
E,9
E,12
B,7
B,14
')
g2 <- graph.data.frame(D,directed=F)
plot(g2)
有谁知道一种方法来计算城市的介数?谢谢!
解决方法
您可以像下面这样尝试distances
D2$length <- distances(
set_edge_attr(g1,name = "weight",value = D$length
)
)[as.matrix(D2)]
给出
> D2
from to length
1 E C 9
2 E B 12
3 B C 7
4 B I 14
更新
如果你期待顶点的介数,你可以试试
> 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
数据
> dput(D2)
structure(list(from = c("E","E","B","B"),to = c("C","C","I")),class = "data.frame",row.names = c(NA,-4L))