Obtain weight of a path with iGraph in R

為{幸葍}努か 提交于 2019-12-11 04:14:13

问题


I have a graph I created from a data frame, in the form of from, to, cost columns. I also have a path (as a succession of vertexes, in the vpath format of igraph) which is valid (my graph is directed).

Is there any function that, given my graph and my path, would give me the cost of that path?

I'm not asking for the shortest path, as I obtained the path from all_shortest_paths. However, I only get the node succession and not the weight of the path, which I also need.

Edit: Data

This is my dataframe which I turn into the graph: http://www.sharecsv.com/s/47209742f0052a37e17db37ea3af63ac/arcsWithCost.csv

And my path is 15 4 50 212 183 112 114 37 228 119


回答1:


You have the path as a sequence of vertices. If you had the sequence of edges, this would be easy - just add up the weights for each edge. So what you need to do is convert the sequence of vertices to a sequence of edges. That is what get.edge.ids does, although you need to get the data into the right format.

Since you do not provide any data, I will illustrate with a random example.

library(igraph)
set.seed(1234)
g = erdos.renyi.game(10,0.15, directed=TRUE)
E(g)$weight = sample(5, length(E(g)), replace=TRUE)
plot(g)

OK, now suppose we want to sum the weights along the path from nodes 1-4-10-3. I assume that you have a list c(1,4,10,3)

VP = c(1,4,10,3)
EP = rep(VP, each=2)[-1]
EP = EP[-length(EP)]
E(g)$weight[get.edge.ids(g, EP)]
[1] 1 5 4
sum(E(g)$weight[get.edge.ids(g, EP)])
[1] 10

Addition:

In the data added to the question, there are 110 nodes but they are numbered up to 281. These numbers are labels for the nodes, but not the node IDs. You can use the labels to access the nodes, but you must convert them to strings for them to be treated as the labels. This code worked on your example.

VP = c(15, 4, 50, 212, 183, 112, 114, 37, 228, 119)
EP = rep(VP, each=2)[-1]
EP = EP[-length(EP)]
E(g)$cost[get.edge.ids(g, as.character(EP))]
sum(E(g)$cost[get.edge.ids(g, as.character(EP))])


来源:https://stackoverflow.com/questions/49695445/obtain-weight-of-a-path-with-igraph-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!