10

I am looping through the edges of a graph with:

 for es in graph.es:
         .... 
         # v = []
         # v = es.vertices()?
         ...

What method can I use to get the source and the target vertices for each edge?

giorgioca
  • 713
  • 1
  • 8
  • 21

2 Answers2

15

These are the very basic functionalities of igraph, described here thoroughly. If you iterate the <EdgeSeq> object (graph.es), you will go through all <Edge> objects (here edge). <Edge> has properties source and target. These are vertex ids, simply integers. You can get the corresponding <Vertex> object by graph.vs[]:

for edge in graph.es:
  source_vertex_id = edge.source
  target_vertex_id = edge.target
  source_vertex = graph.vs[source_vertex_id]
  target_vertex = graph.vs[target_vertex_id]
  # using get_eid() you can do the opposite:
  same_edge_id = graph.get_eid(source_vertex_id, target_vertex_id)
  same_edge = graph.es[same_edge_id]
  # by .index you get the id from the Vertex or Edge object:
  source_vertex.index == source_vertex_id
  # True
  edge.index == same_edge_id
  # True

Be aware if you have directed graph, otherwise source and target are simply two equivalent endpoints. With directed graphs you may use error = False with get_eid(), which then returns -1 in case there is no edge in the given direction between the vertices.

deeenes
  • 4,148
  • 5
  • 43
  • 59
  • what if I have a large graph and do not want to go through a for loop but just want the vertices that have a certain degree – user3067923 Nov 09 '17 at 20:01
  • you can do either `graph.vs[(i for i, d in enumerate(graph.vs.degree()) if d > 3)]` or `graph.vs[(v.index for v in graph.vs if v.degree() > 3)]` – deeenes Nov 10 '17 at 10:38
2

Here is one simple way to get edge information from an igraph object using built-in function get.data.frame() in R (I did not notice the question was asking about python, sorry):

edges_data_frame <- get.data.frame(your_igraph, what = "edges")

The first two columns of edges_data_frame will be "from" and "to". The following columns will be other attributes of the edges if there are.

TianLe Ma
  • 41
  • 3