# 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")
``````

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!

1 Like

Tricky! It's because the nodes are not called "node 4" and "node 10", they are the first and 10th nodes of their graph, but they don't have names!

So, when you create the subgraph, each of the nodes gets a new node number within that subgraph:

``````> V(subgraph)
+ 10/10 vertices, from 6cac9e3:
  1  2  3  4  5  6  7  8  9 10
``````

To avoid that, you simply need to set the nodes names, for example:

``````set.seed(123)
library(igraph)
#>
#> Attaching package: 'igraph'
#> The following objects are masked from 'package:stats':
#>
#>     decompose, spectrum
#> The following object is masked from 'package:base':
#>
#>     union

# Create random graph
graph <- erdos.renyi.game(21, 0.3,
type=c("gnp", "gnm"),
directed = FALSE,
loops = FALSE)
names(V(graph))
#> NULL
V(graph)\$name <- as.character(1:21)
names(V(graph))
#>   "1"  "2"  "3"  "4"  "5"  "6"  "7"  "8"  "9"  "10" "11" "12" "13" "14" "15"
#>  "16" "17" "18" "19" "20" "21"

# 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)

# now the nodes names are not just 1:10
V(subgraph)
#> + 10/10 vertices, named, from b79d5da:
#>   1  3  5  10 14 15 16 17 18 20
``````

Created on 2023-03-09 with reprex v2.0.2

2 Likes

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.