Search code examples
rindexingigraphsubgraph

Creating a Random Connected Subgraph


I made this random graph/network in R:

set.seed(123)
library(igraph)

# Create random graph
graph <- erdos.renyi.game(21, 0.3, type=c("gnp", "gnm"), directed = FALSE, loops = FALSE)

Then, I tried to create a random connected subgraph:

# Get the edges of the random subgraph
random_edges <- sample(E(graph), 10)

# Create subgraph from the random edges
subgraph <- subgraph.edges(graph, random_edges)


par(mfrow = c(1,2))

# Plot the subgraph
plot(subgraph, main = "random subgraph")
plot(graph, main = "original graph")

enter image description here

My Question: When I look at the random subgraph, I see that "node 4" is connected to "node 10" - but in the original graph, "node 4" and "node 10" are not connected to each other.

Can someone please show me how to fix this?

Thanks!


Solution

  • I think a workaround is to add a name attribute to vertices before conducting induced.subgraph. Otherwise, the vertex "label" (to be shown in the plot of subgraph) is indexed differently, rather than keeping the same vid in the original graph.


    For example, you can do

    graph %>%
      set.vertex.attribute(name = "name", value = V(.)) %>%
      induced.subgraph(unique(c(ends(., random_edges))))
    

    then you will obtain a subgraph like below

    IGRAPH da87a26 UN-- 10 16 -- Erdos-Renyi (gnp) graph
    + attr: name (g/c), type (g/c), loops (g/l), p (g/n), name (v/n)
    + edges from da87a26 (vertex names):
     [1]  5--10  1--14  3--14  1--15 14--15  3--16 14--16 14--17  1--18  5--18
    [11] 14--18 15--18 17--18  3--20 10--20 16--20
    

    enter image description here