Reputation: 89
A have code that creates a random graph in the form of a matrix. Now I would like it to create many, say m
, random graphs so the output is m
matrices. I am trying to do this with a for loop. This would be my preferred method however I am open to other suggestions (apply family?). Here is my code, where n is the number of nodes/vertices the graph has and beta is the amount of preferential attachment (keep this between 0 and 1.5)
multiplerandomgraphs <- function(n, beta, m) {
for(k in 1:m) {
randomgraph <- function(n, beta) {
binfunction <- function(y) {
L <- length(y)
x <- c(0, cumsum(y))
U <- runif(1, min = 0 , max = sum(y))
for(i in 1:L) {
if(x[i] <= U && x[i+1] > U){
return(i)
}
}
}
mat <- matrix(0,n,n)
mat[1,2] <- 1
mat[2,1] <- 1
for(i in 3:n) {
degvect <- colSums(mat[ , (1:(i-1))])
degvect <- degvect^(beta)
j <- binfunction(degvect)
mat[i,j] <- 1
mat[j,i] <- 1
}
return(mat)
}
}
}
Upvotes: 0
Views: 62
Reputation: 214957
You can define your randomgraph function as randomgraph <- function(i, n, beta) {}
with the body the same as your definition, leaves the parameter i
as a dummy parameter. And then use apply function as listOfMatrix <- lapply(1:m, randomgraph, n, beta)
which return a list of matrix.
Upvotes: 1