【发布时间】:2016-04-16 04:54:36
【问题描述】:
我在需要n 节点和优先附件参数beta 的函数中有一个很好的随机图形模拟。我使用 for 循环,但是当您将 n 设为非常大时,代码需要很长时间才能运行。我想知道是否可以使用 apply 系列来提高效率。
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)
}
它可以用于:
set.seed(123)
random_graph(10, 0.5)
【问题讨论】:
-
你能提供一个reproducible example吗?
-
@VincentBonhomme 这是一个随机模拟。只需将
n和beta输入random_graph。 (保持beta小,即在 0 和 2 之间) -
好吧,我编辑了你的问题。
-
好东西,谢谢
-
仅使用
j <- binfunction(colSums(mat[ , (1:(i-1))])^beta)即可获得 5% 的收益,但不足以解决您的问题。