Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In R how do you randomly generate edges between nodes?

Tags:

random

r

igraph

So currently I use the following code to randomly generate 30 nodes and 151 connections.

g <- erdos.renyi.game(30, 151 , type = "gnm" , directed = F , loops = F)

But, I want to generate an empty graph then randomly generate 151 edges. How would I go about doing that? Is there a code that I can add to the one below?

g <- g <- graph.empty(30, directed = F)
like image 338
Bill Avatar asked Dec 13 '25 23:12

Bill


1 Answers

You could do the following as demonstrated at the bottom of this page

g <- graph.empty(30, directed = F)
number_of_edges = 151

g <- g + edges(sample(V(g), number_of_edges*2, replace = T), color = "red")

However, it seems you want to exclude loops. You could do that by sampling 2 nodes 151 times without replacement, for example as follows:

my_edges <- sapply(seq(number_of_edges),function(x) {sample(V(g),2,replace=F)})
g <- g + edges(my_edges, color = "red")

Hope this helps!

EDIT: no duplicates edges.

To create a graph with no duplicate edges, you could first create all combinations, and then sample from those:

x <- combn(V(g),2)
my_edges <- x[,sample(seq(dim(x)[2]),number_of_edges,replace=F)]
g <- g + edges(my_edges, color = "red")
like image 151
Florian Avatar answered Dec 16 '25 17:12

Florian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!