如何计算igraph中边属性的路径/直径?

如何计算igraph中边属性的路径/直径?,r,path,attributes,igraph,edge-list,R,Path,Attributes,Igraph,Edge List,下面是一个数据帧示例,您可以将其转换为边列表,然后再转换为图形。请注意,我已将“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

下面是一个数据帧示例,您可以将其转换为边列表,然后再转换为图形。请注意,我已将“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边属性已经存在。使用数据框()中的
graph\u时,
存储在第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)
#让我们再向网络添加两条边
#并在名为“2”的顶点和名为“7”的顶点之间创建新的更长路径
G