如何计算igraph(R)中边缘属性的路径/直径?

时间:2017-12-04 16:58:30

标签: r path attributes igraph edge

这是一个数据框的示例,您可以将其转换为边缘列表,然后转换为图形。请注意,我已将'km'作为属性添加到edgelist。

我不确定如何添加'km'作为边缘属性(所以两个节点之间的距离),但假装它已经完成。

inst2 = c(2, 3, 4, 5, 6) 
motherinst2 = c(7, 8, 9, 10, 11) 
km = c(20, 30, 40, 25, 60)
df2 = data.frame(inst2, motherinst2)
edgelist = cbind(df2, km)
g = graph_from_data_frame(edgelist)

现在,我如何根据这些km距离计算路径长度?我对路径中的边或顶点的数量不感兴趣,只是从根到叶子的那些km的总和。

1 个答案:

答案 0 :(得分:1)

km边缘属性已存在。使用graph_from_data_frame()时,存储在第3列及以上的任何信息都存储在边缘。您可以使用igraph::E()功能从边缘提取信息。

E(g) #identifies all of the edges
E(g)$km #identifies all of the `km` attributes for each edge
E(g)$km[1] #identifies the `km` attribute for the first edge (connecting 2 -> 7)

为完整起见,我们假设您的节点路径大于1.

#lets add two more edges to the network 
#and create a new and longer path between vertex named '2', and vertex named '7'
g <- g + 
  edge('2', '6', km = 10) +
  edge('6', '7', km = 120)


#find all paths between 2 and 7
#don't forget that the names of vertices are strings, not numbers
paths <- igraph::all_simple_paths(g, '2', '7')
paths

#find the edge id for each of the connecting edges
#the below function accepts a vector of pairwise vectors. 
#the ids are the edges between each pair of vectors
connecting_267 <- igraph::get.edge.ids(g, c('2','6' , '6','7'))
connecting_267

#get the km attribute for each of the edges
connecting_kms <- igraph::E(g)[connecting_267]$km
connecting_kms

sum(connecting_kms)

igraph非常强大。绝对值得花时间和exploring its documentation。此外,Katherine Ognyanova创造了an AWESOME tutorial,这绝对值得每个人的时间。