Reputation: 203
I currently use a code like the following to generate random graphs:
set.seed(123); g <- erdos.renyi.game(30, 151 , type = "gnm" , directed = F , loops = F)
Is there a way to prevent the random generation of edges between the nodes 1, 7, 13, 19, and 25? I still want these 5 to be connected to the other 25 nodes by random edges, just not to each other.
Upvotes: 1
Views: 58
Reputation: 37641
Your model
erdos.renyi.game(30, 151 , type = "gnm" , directed = F , loops = F)`
can be considered as taking a random sample of 151 edges from all possible edges between 30 nodes. What you want is like that except certain edges are excluded. It is easy to generate all links and also the excluded links. So you can just generate all possible links, remove the excluded ones to get a list of acceptable links and sample those. Then, generate the graph from the list of links.
library(igraph)
AllEdges = as.data.frame(t(matrix(combn(30,2), ncol=2, byrow=TRUE)))
SpecialNodes = c(1, 7, 13, 19, 25)
ForbiddenEdges =
as.data.frame(t(matrix(combn(SpecialNodes,2), ncol=2, byrow=TRUE)))
AcceptableEdges = setdiff(AllEdges, ForbiddenEdges)
set.seed(123)
EL = t(as.matrix(sample(AcceptableEdges, 151)))
g = graph_from_edgelist(EL, directed=FALSE)
par(mar=rep(0,4))
plot(g)
You can check that there are no undesirable connections
EL[EL[,1] %in% SpecialNodes, ]
any(EL[EL[,1] %in% SpecialNodes, 2] %in% SpecialNodes)
[1] FALSE
This solution works fine for a modest number of nodes. It may be too inefficient for very large graphs.
Upvotes: 1