29

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
  • 8,680
  • 9
  • 53
  • 69

4 Answers4

32

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
  • 26,280
  • 5
  • 44
  • 53
  • 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
5

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
  • 1,402
  • 2
  • 17
  • 28
5

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

E(g)[from(V(g)["name"])]
jtclaypool
  • 91
  • 1
  • 5
1

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
  • 12,271
  • 14
  • 71
  • 107
Dr_K_Lo
  • 11
  • 1