1

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

我不确定如何将“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)

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

4

1 回答 1

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非常强大。绝对值得花时间探索它的文档。此外,Katherine Ognyanova 创建了一个绝对值得每个人花时间的很棒的教程。

于 2017-12-04T17:13:49.257 回答