Search code examples
rlistmatrixsparse-matrix

Create sparse matrices from given LT indices but fill with values in other list


I have three lists:

"corMat"     "corMatPVAL" "index"

> head(corMat)
          [,1]
[1,] 0.7786662
[2,] 0.7536617
[3,] 0.7950954
[4,] 0.7950954
[5,] 0.7950954
[6,] 0.7388970


> head(corMatPVAL)
              [,1]
[1,] 6.166382e-155
[2,] 1.304651e-139
[3,] 3.756711e-166
[4,] 3.756711e-166
[5,] 3.756711e-166
[6,] 2.097761e-131

> head(index)
     [,1]
[1,]   82
[2,]  271
[3,]  441
[4,]  442
[5,]  443
[6,]  501

I have to make two matrices of the size 48389 rows and 48389 columns i-e one for corMat values (1st list) filling at the indices provided in the third list (index) and one corMatPVAL (2nd list) matrix filling the same indices as mentioned in the third list (index).

Note: The indexes are of only the lower triangle of a matrix. Kindly let me know how can I make a matrix and then map these list values in the matrix form. the indices as mentioned in the third list. the diagonal and upper.tri portion of the matrix can be NA


Solution

  • library(Matrix)
    sparseMatrix(index, seq_along(index), , corMat, c(48389,  48389))
    sparseMatrix(index, seq_along(index), , corMatPVAL, c(48389,  48389))
    

    That might be hard to visualise the output, so for a toy example:

    sparseMatrix(10:6, 1:5, , 1:5/10,  c(10,  10))
    #10 x 10 sparse Matrix of class "dgCMatrix"
    #                                   
    # [1,] .   .   .   .   .   . . . . .
    # [2,] .   .   .   .   .   . . . . .
    # [3,] .   .   .   .   .   . . . . .
    # [4,] .   .   .   .   .   . . . . .
    # [5,] .   .   .   .   .   . . . . .
    # [6,] .   .   .   .   0.5 . . . . .
    # [7,] .   .   .   0.4 .   . . . . .
    # [8,] .   .   0.3 .   .   . . . . .
    # [9,] .   0.2 .   .   .   . . . . .
    #[10,] 0.1 .   .   .   .   . . . . .