34

Say I have this example graph, i want to find the edges connected to vertex 'a'

 d <- data.frame(p1=c('a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'd'),
                 p2=c('b', 'c', 'd', 'c', 'd', 'e', 'd', 'e', 'e'))

library(igraph)
g <- graph.data.frame(d, directed=FALSE)
print(g, e=TRUE, v=TRUE)

I can easily find a vertex:

 V(g)[V(g)$name == 'a' ]

But i need to reference all the edges connected to the vertex 'a'.

tommy chheng
  • 9,108
  • 9
  • 55
  • 72

4 Answers4

33

See the documentation on igraph iterators; in particular the from() and to() functions.

In your example, "a" is V(g)[0], so to find all edges connected to "a":

E(g) [ from(0) ]

Result:

[0] b -- a
[1] c -- a
[2] d -- a
neilfws
  • 32,751
  • 5
  • 50
  • 63
  • Note to Python-igraph users: Equivalent to this solution is to use EdgeSeq's [select](http://igraph.org/python/doc/igraph.EdgeSeq-class.html#select) function, but it is currently buggy as mentioned in this [bug report](https://github.com/igraph/python-igraph/issues/30). Suggested workaround to get edge IDs of vertex X is to use `g.es[g.incident(x)]`. – Manavalan Gajapathy Mar 24 '17 at 18:39
  • 1
    The `from`, `to`, and `adj` iterators behave the same for non-directional graphs, but for directional graphs, the `adj` iterator is required to get all links attached to a vertex. For directional graphs, `from` returns only edges that start at the supplied vertex; `to` returns only edges that end at the supplied vertex. For both directional and non-directional graphs, `adj` will return all edges associated with the vertex. – Geoffrey Poole Mar 03 '19 at 21:24
7

If you do not know the index of the vertex, you can find it using match() before using the from() function.

idx <- match("a", V(g)$name)
E(g) [ from(idx) ]
cannin
  • 2,735
  • 2
  • 25
  • 32
6

Found a simpler version combining the two efforts above that may be useful too.

E(g)[from(V(g)["name"])]
jtclaypool
  • 131
  • 1
  • 5
  • This gave me an index, but not the actual name as in tuple of (Source_Node -> Destination_Node) (I am using directed graphs) – Timbus Calin Nov 07 '21 at 14:32
  • 1
    I would need more to help with what you're seeing. I seem to be able to pull out the to/from nodes. require(igraph) g1 <- graph( edges=c(1,2, 2,3, 3, 1), n=3, directed=T ) plot(g1) E(g1)[from(V(g1)[2])] > E(g1)[to(V(g1)[2])] + 1/3 edge from 74d9064: [1] 1->2 > E(g1)[from(V(g1)[2])] + 1/3 edge from 74d9064: [1] 2->3 – jtclaypool Nov 07 '21 at 23:32
  • Thank you, will try when I have more time today or the next days. – Timbus Calin Nov 08 '21 at 08:49
2

I use this function for getting number of edges for all nodes:

sapply(V(g)$name, function(x) length(E(g)[from(V(g)[x])]))
Majid
  • 13,853
  • 15
  • 77
  • 113
Dr_K_Lo
  • 21
  • 1