I have a nice random graphing simulation in a function that requires n
nodes and a preferential attachment parameter beta
. I use for loops, however when you take n
to be very large, the code takes a long while to run. I was wondering if it was possible to use the apply family to make this more efficient.
binfunction <- function(y) { #Set up bins to create preferential attachment
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)
}
}
}
random_graph <- function(n, beta) { #Random graphing function
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)
}
And it can be used with:
set.seed(123)
random_graph(10, 0.5)