Newbie Q: Creation of simple graphs with random nodes and edges

People,

After having been away from R for a couple of decades (I was never a guru by any means) but just having refamiliarised myself with vector manipulation, I realise what I really need are graphs. For the Bio Population model I have in mind, I would like to automatically create (in the first case) simple graphs with a limited number of nodes and edges eg:

  • 10 nodes
  • With nodes having a varied, random number of edges eg between 1 and 9

Can graphs be created like that in a somewhat similar way I can create vectors with random numbers in the elements?

Thanks!

Welcome back.

# Install and load the igraph package
if (!requireNamespace("igraph", quietly = TRUE)) {
  install.packages("igraph")
}
library(igraph)
#> 
#> Attaching package: 'igraph'
#> The following objects are masked from 'package:stats':
#> 
#>     decompose, spectrum
#> The following object is masked from 'package:base':
#> 
#>     union

# Set the number of nodes and edges
num_nodes <- 10
num_edges <- sample(1:9, 1)

# Generate a random graph with the specified number of nodes and edges
g <- sample_gnm(n = num_nodes, m = num_edges, directed = FALSE)

# Plot the graph
plot(g)

Created on 2023-06-21 with reprex v2.0.2

1 Like

Oh wow! - thanks so much! - I will get into it . .

1 Like

This topic was automatically closed 21 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.