Induce a subgraph while keeping nodes' name/id

Viewed 175

Suppose I have a graph like this:

library(igraph)
gtest <- graph(c(1,2,1,3,2,3,3,4), directed = FALSE)

Now, I want the induced subgraph from gtest with nodes 1, 3, 4. When I run the following command, it seems that is generating a new graph, with 3 nodes 1, 2, and 3.

induced.subgraph(graph = gtest,vids = c(1,3,4), impl = "copy_and_delete")

IGRAPH 17d00a4 U--- 3 2 -- 
+ edges from 17d00a4: [1] 1--2 2--3

But I need to keep the node name/id. Is there any solution for this?

1 Answers

You can add name attribute to gtest before running inducded.graph, i.e.,

gtest <- graph(c(1, 2, 1, 3, 2, 3, 3, 4), directed = FALSE) %>%
  set_vertex_attr(name = "name", value = seq_along(V(.)))

and then

> induced.subgraph(graph = gtest, vids = c(1, 3, 4))
IGRAPH 76ee13e UN-- 3 2 --
+ attr: name (v/n)
+ edges from 76ee13e (vertex names):
[1] 1--3 3--4
Related