【问题标题】:sparse outer product in R?R中的稀疏外积?
【发布时间】:2014-01-31 20:24:29
【问题描述】:

我正在尝试在 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)。

【问题讨论】:

  • 您是否查看过 Matrix 和/或 SparseM 包 - 它们确实支持稀疏矩阵运算。
  • @user102890 是的,我没有看到类似 outer( ..., '==') 的东西

标签: r


【解决方案1】:

我在下面的工作,虽然它很慢。

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

}

【讨论】:

    猜你喜欢
    • 2019-11-27
    • 2010-11-06
    • 2015-08-27
    • 2016-08-25
    • 2016-08-15
    • 2019-10-22
    • 1970-01-01
    • 2011-10-20
    • 2013-01-29
    相关资源
    最近更新 更多