Ehsan Shahriari - 1 year ago 54

R Question

I'm very new to R and trying to calculate the adjacent vertices of a graph, which is obtained from deleting certain nodes from an original graph.

However, the output of the result doesn't match with the plot of the graph.

For example:

`library(igraph)`

g <- make_ring(8)

g <- add_edges(g, c(1,2, 2,7, 3,6, 4,5, 8,2, 6,2))

V(g)$label <- 1:8

plot(g)

`h <- delete.vertices(g, c(1,2))`

plot(h)

If I compute:

`adjacent_vertices(h,6)= 5`

However, I want the output to be 3,5,7 as the plot shows. The problem lies in the fact that it doesn't know I'm trying to find the adjacent vertices of node labelled 6.

Could someone please help. Thanks.

Answer Source

The issue here is that when you delete the vertices, the indices for the remaining vertices are shifted down to [0,6]:

```
> V(h)
+ 6/6 vertices:
[1] 1 2 3 4 5 6
```

To find the neighbors, using the original vertex names, you could then simply offset the values by the number of vertices removed, e.g.:

```
> neighbors(h, 6 - offset) + offset
+ 3/6 vertices:
[1] 3 5 7
```

A better approach, however, would be to refer to the vertex *labels* instead of using the indices:

```
> V(g)$label
[1] 1 2 3 4 5 6 7 8
> V(h)$label
[1] 3 4 5 6 7 8
> V(h)[V(h)$label == 6]
+ 1/6 vertex:
[1] 4
```

To get the neighbors of your vertex of interest, you can modify your code to look like:

```
> vertex_of_interest <- V(h)[V(h)$label == 6]
> neighbors(h, vertex_of_interest)$label
[1] 3 5 7
```