tommy chheng
tommy chheng

Reputation: 9228

How do I find the edges of a vertex using igraph and R?

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'.

Upvotes: 34

Views: 15900

Answers (4)

Dr_K_Lo
Dr_K_Lo

Reputation: 21

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])]))

Upvotes: 2

jtclaypool
jtclaypool

Reputation: 190

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

E(g)[from(V(g)["name"])]

Upvotes: 6

cannin
cannin

Reputation: 3325

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) ]

Upvotes: 7

neilfws
neilfws

Reputation: 33802

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

Upvotes: 33

Related Questions