Obtain weight of a path with iGraph in R
Asked Answered
A

1

4

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

Annabal answered 6/4, 2018 at 14:48 Comment(0)
I
5

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)

Graph

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))])
Intine answered 6/4, 2018 at 16:21 Comment(5)
Wow, this is a really elegant solution! I was able to replicate your example, but I can't seem to make it work with my data. I added the data in the first post. I'm getting the error: Cannot get edge ids, invalid vertex id, Invalid vertex idAnnabal
Will look and add to answerIntine
Adding to answerIntine
@G5W, could you give an idea how to compute the weight of the circle c(2,7,6,2), i.e. the weigh of the triangle with double edge? The edges from vertex 2 to vertex 7 and from vertex 7 to vertex 2 should be in the sum.Postgraduate
@Intine I don't have any path sequence, I have node name/label (from) and (to). I have gone through this post but not getting any idea. Would you mind to check this question (#69860847)Guaiacol

© 2022 - 2024 — McMap. All rights reserved.