用于稀疏矩阵的 R repmat 函数

R repmat function for sparse matrices

对于我的 r 项目,我需要重复几个大(即大于 1000x1000)矩阵。我在 r 中找到了两个版本的 matlab repmat-function,它们都可以工作,但有严重的限制,所以我无法使用它们。有没有人有其他方法来解决这个问题?


为了减少内存使用,我使用了 Matrix-Package 中的稀疏函数(Diagonal()Matrix(..., sparse=TRUE))。

> m <- Diagonal(10000)
> object.size(m)
1168 bytes

现在,为了重复这个矩阵,我使用了 matlab 函数 repmat(可以找到 here)的 r 翻译:

repmat <- function(X, m, n){
    mx <- dim(X)[1]
    nx <- dim(X)[2]
    return(matrix(t(matrix(X,mx,nx*n)),mx*m,nx*n,byrow=T))
}

不幸的是,此方法使用矩阵的 standard/dense 版本并且仅适用于特定的对象大小,这在我的项目中很快就会超过。简单地将 matrix(...) 函数与 Matrix(..., sparse=TRUE) 函数交换也行不通,因为矩阵维度的参数定义不同。

唯一的其他解决方案是 pcaMethods-Package 的 repmat 版本,我可以在其中使用稀疏矩阵:

repmat <- function(mat, M, N) {
    ## Check if all input parameters are correct
    if( !all(M > 0, N > 0) ) {
        stop("M and N must be > 0")
    }    

    ## Convert array to matrix
    ma <- mat
    if(!is.matrix(mat)) {
        ma <- Matrix(mat, nrow=1, sparse=TRUE)
    }

    rows <- nrow(ma)
    cols <- ncol(ma)
    replicate <- Matrix(0, rows * M, cols * N, sparse=TRUE)

    for (i in 1:M) {
        for(j in 1:N) {
            start_row <- (i - 1) * rows + 1
            end_row <- i * rows
            start_col <- (j - 1) * cols + 1
            end_col <- j * cols
            replicate[start_row:end_row, start_col:end_col] <- ma
        }
    }

     return(replicate)
}

然而,这个函数可以完成工作,但需要大量的运行时间(可能是因为嵌套循环)。我剩下的唯一选择是增加整体 memory.limit,但这只会导致 运行 物理内存不足。


我已经无计可施了。任何帮助或建议将不胜感激。预先感谢您的回复。

rbindcbind 使用矩阵方法:

repMat <- function(X, m, n){
  Y <- do.call(rbind, rep(list(X), m))
  do.call(cbind, rep(list(Y), n))
}


system.time(res <- repMat(m, 20, 30))
#user  system elapsed 
#0.48    0.44    0.92
str(res)
#Formal class 'dgCMatrix' [package "Matrix"] with 6 slots
#  ..@ i       : int [1:6000000] 0 10000 20000 30000 40000 50000 60000 70000 80000 90000 ...
#  ..@ p       : int [1:300001] 0 20 40 60 80 100 120 140 160 180 ...
#  ..@ Dim     : int [1:2] 200000 300000
#  ..@ Dimnames:List of 2
#  .. ..$ : NULL
#  .. ..$ : NULL
#  ..@ x       : num [1:6000000] 1 1 1 1 1 1 1 1 1 1 ...
#  ..@ factors : list()

object.size(res)
#73201504 bytes