简体   繁体   中英

How to find shortest paths between two nodes based on certain edge attribute using igraph in R?

I have made a directed graph in Rstudio using igraph package. For each edge I have set an edge attribute called edge_ids. Multiple edges are there with the same edge_id. Now I want to find if there exists a path between 2 nodes with a particular edge_id?

So basically, suppose I have a graph of trips covered by 10 vehicles and each vehicle has its own vehicle_id. Now if I want to find the shortest distance between 2 nodes in this graph, then it will consider all 10 vehicles, but what I want is that it should consider only that vehicle whose vehicle_id will be given by me.

shortest.paths(total_network, 'ttn85jv', 'ttn9rjy')
E(total_network)[edge_id=="0358511023767613_132.csv"]

First line will give me shortest path between node ttn85jv and ttn9rjy. Second line will give me edge sequence vector having edge id=0358511023767613_132.csv.

If edge id=0358511023767613_132.csv has created a path in the (total_network) graph, then I want to find if nodes ttn85jv and ttn9rjy are coming in between the path or not.

If both the nodes exist in the path, then what is the path length between these two nodes for that id(0358511023767613_132.csv)

I have got an answer for this. But it is not an optimal way, also it is taking very long time to execute because first it is making subgraph of the given graph(total_network).

s1 <- subgraph.edges(total_network, E(total_network)[edge_id=="0358511023767613_132.csv"])
shortest.paths(s1,'ttn9rjy','ttn85jv')

You already provide a functioning solution to your question, but Tthere are faster ways than subgraph.edges() for checking edges by edge-id.

Try, for example to define n <- make_empty_graph(n = length(V(total_network))) as an empty network and then find distances with this:

#s1 <- subgraph.edges(total_network, E(total_network)[edge_id=="0358511023767613_132.csv"])
s1 <- n %>% add_edges( as.vector(ends(total_network, E(total_network)[edge_id=="0358511023767613_132.csv"])) )

My version creates the subgraph much quicker. On my 2017 Mac, the speed advantages seem to be about 2x, but depend on network size. Maybe the advantages are different for you size of network?

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM