Giannis H. - 1 year ago 63

R Question

Is there a method or a class in igraph to do this procedure fast and efectively?

Answer Source

Let's assume that your graph is in `g`

and the set of vertices to be used is in `sampled`

(which is a vector consisting of zero-based vertex IDs).

First, we select the set of edges where at least one endpoint is in `sampled`

:

```
all.vertices <- (1:vcount(g)) - 1
es <- E(g) [ sampled %--% 1:n ]
```

`es`

is now an "edge sequence" object that consists of the edges of interest. Next, we take the edge list of the graph (which is an m x 2 matrix) and select the rows corresponding to the edges:

```
el <- get.edgelist(g)[as.vector(es)+1]
```

Here, `as.vector(es)`

converts the edge sequence into a vector consisting of the edge IDs of the edges in the edge sequence, and use it to select the appropriate subset of the edge list. Note that we had to add 1 to the edge IDs because R vectors are indexed from 1 but igraph edge IDs are from zero.

Next, we construct the result from the edge list:

```
g1 <- graph(el, vcount(g), directed=is.directed(g))
```

Note that `g1`

will contain exactly as many vertices as `g`

. You can take the subgraph consisting of the sampled vertices as follows:

```
g1 <- subgraph(g1, sampled)
```

**Note to users of igraph 0.6 and above**: igraph 0.6 will switch to 1-based indexing instead of 0-based, so there is no need to subtract 1 from `all.vertices`

and there is no need to add 1 to `as.vector(es)`

. Furthermore, igraph 0.6 will contain a function called `subgraph.edges`

, so one could simply use this:

```
g1 <- subgraph.edges(g, es)
```