我正在尝试计算R中各种类型的邻接矩阵,以解决二元模型中的网络自相关问题。我可以使用outer()构造我需要的矩阵,但除非我能弄清楚如何让R以某种稀疏矩阵格式给出结果,否则这不会扩展:
N = 10
g = simplify(watts.strogatz.game(1, N, 2, 0.05))
EL = get.edgelist(g)
ego_out = outer(EL[,1], EL[,1], '==')
alter_out = outer(EL[,2], EL[,2], '==')
ea_out = outer(EL[,1], EL[,2], '==')
ae_out = outer(EL[,2], EL[,1], '==')
pair_out = ego_out | alter_out
opp_out = ea_out | ae_out
pair_out | opp_out
这显然不会扩展(如果你勇敢尝试设置N = 10000000)。
答案 0 :(得分:0)
我在下面的工作中,它很慢。
outer_Matrix = function(X, Y, FUN = '==', ...){
require('Matrix')
dX <- length(X)
no.nx <- is.null(names(X))
if (!no.nx)
nx <- list(names(X))
dY <- length(Y)
no.ny <- is.null(names(Y))
if (!no.ny)
ny <- list(names(Y))
# instead iterate over each item in X, check against Y
robj <- Matrix(FALSE, nrow = dX, ncol = dY)
rows = which(X %in% Y)
FUN <- match.fun(FUN)
for(i in rows){
robj[i,] <- FUN(X[i], Y, ...)
if(i %% 1000==0)
print(i)
}
if (!(no.nx && no.ny)) {
if (no.nx)
nx <- vector("list", length(dX))
else if (no.ny)
ny <- vector("list", length(dY))
dimnames(robj) <- c(nx, ny)
}
robj
}