Search code examples
rmatrixsparse-matrixbigdatatriangular

Large Sparse Matrix to Triangular Matrix R


I have a very large (about 91 million non-zero entries) sparseMatrix() in R that looks like:

> myMatrix 
  a b c  
a . 1 2
b 1 . .
c 2 . .

I would like to convert it to a triangular matrix (upper or lower), but when I try myMatrix = myMatrix * lower.tri(myMatrix) there is an error that the 'problem is too large' for lower.tri(). Wondering if anyone might know of a solution. Thanks for any help!


Solution

  • Instead of working on the matrix itself, work on its summary:

    library(Matrix)
    myMatrix <- sparseMatrix(
        i = c(1,1,2,3),
        j = c(2,3,1,1),
        x = c(1,2,1,2))
    
    myMatrix
    # 3 x 3 sparse Matrix of class "dgCMatrix"
    #           
    # [1,] . 1 2
    # [2,] 1 . .
    # [3,] 2 . .
    
    mat.summ   <- summary(myMatrix)
    lower.summ <- subset(mat.summ, i >= j)
    
    sparseMatrix(i = lower.summ$i,
                 j = lower.summ$j,
                 x = lower.summ$x,
                 dims = dim(myMatrix))
    # 3 x 3 sparse Matrix of class "dgCMatrix"
    #           
    # [1,] . . .
    # [2,] 1 . .
    # [3,] 2 . .