简体   繁体   中英

How to select a graph vertex with igraph in R?

In Python you can simply use graph.select() (atleast when reading the documentation: https://igraph.org/python/doc/api/igraph.VertexSeq.html ) to select a vertex based on a value. I have a huge graph connecting movies that share an actor. However I would simply like to select one vertex from that graph and then plot it with its direct neighbors. I'm running into issues when I want to select just that single vertex.

I had hoped something like worked

graph.movies.select('Snatch (2000)')

But no luck.

Another approach I took was grabbing the single Snatch vertex by filtering all others out and then adding the edges.

snatch.graph <- induced.subgraph(g.movies, vids=V(g.movies)$name == 'Snatch (2000)')
snatch.edges <- edges(g.movies, "Snatch (2000)")
add_edges(snatch.graph, snatch.edges$edges)

However this returns an empty graph with only the snatch vertex.

My goal is to grab the Snatch vertex and plot this vertex, its DIRECT neighbors and the edges amomng them. Any suggestions? Thanks alot:D Been stuck o nthis for a quite a while -.-

You can use ?ego to grab the neighbours or ?make_ego_graph to form the graph. (Depending on whether your graph is directed or not, you may need to use the mode argument).

An example:

library(igraph)

# create some data
set.seed(71085002)
n = 10
g = random.graph.game(n, 0.25)
V(g)$name = seq_len(n)

# grab neighbours of node "1"
# set mindist = 0 to include node itself
# set order for the stepsize of the neigbourhood; 
nb_g = make_ego_graph(g, order=1, node="1", mindist=0)[[1]]

# plot
# you could use the `layout` argument to 
# keep nodes in the same position
op = par(mfrow=c(1,2), oma=rep(0,4))
  plot(g, vertex.size=0, vertex.label.cex=3, main="Full graph")
  plot(nb_g, vertex.size=0, vertex.label.cex=3, main="Sub graph")
par(op) # reset

在此处输入图像描述

If you just need a list of the neighbouring nodes:

ego(g, order=1, node="1", mindist=0)
# [[1]]
# + 4/10 vertices, named, from 00cfa70:
# [1] 1 4 6 9

I think the method using ego (by @user20650) is comprehensive and efficient.

Here is another option if you would like to find the sub-graph built on direct neighbors, which applies distances + induced_subgraph

> induced_subgraph(g, which(distances(g, "1") <= 1))
IGRAPH 99f872b UN-- 4 3 -- Erdos renyi (gnp) graph
+ attr: name (g/c), type (g/c), loops (g/l), p (g/n), name (v/n)
+ edges from 99f872b (vertex names):
[1] 1--4 1--6 1--9

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