2

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!

rfoley
  • 345
  • 3
  • 15

2 Answers2

7

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 . .
Josh O'Brien
  • 159,210
  • 26
  • 366
  • 455
flodel
  • 87,577
  • 21
  • 185
  • 223
0

This one is a little faster when you have a large sparse matrix:

ind <- which(myMatrix@i > myMatrix@j)
myMatrix_lower <- sparseMatrix(i = myMatrix@i[ind], 
                               j = myMatrix@j[ind],
                               x = myMatrix@x[ind] ,
                               dims = dim(myMatrix),
                               giveCsparse = F, index1 = FALSE)
Qibo
  • 1
  • 2