raK1
raK1

Reputation: 529

sparseMatrix command in R

How can I use the sparseMatrix command in R (Matrix package) to construct the matrix below

[1,] 1.002 0.210 0.002  .      .      .       2.943   0.051
[2,] 0.210 1.002 0.210  .      .      .       7.515   2.943
[3,] 0.002 0.210 1.002  .      .      .       0.843   7.515
[4,] .     .     .     16.003  3.354  0.031  18.691   1.122
[5,] .     .     .      3.354 16.003  3.354  13.675  18.691
[6,] .     .     .      0.031  3.354 16.003   0.440  13.675
[7,] 2.943 7.515 0.843 18.691 13.675  0.440 109.002  22.848
[8,] 0.051 2.943 7.515  1.122 18.691 13.675  22.848 109.002

I have also provided the dput command to be able to copy the matrix into your console

new("dsCMatrix"
    , i = c(0L, 0L, 1L, 0L, 1L, 2L, 3L, 3L, 4L, 3L, 4L, 5L, 0L, 1L, 2L, 
3L, 4L, 5L, 6L, 0L, 1L, 2L, 3L, 4L, 5L, 6L, 7L)
    , p = c(0L, 1L, 3L, 6L, 7L, 9L, 12L, 19L, 27L)
    , Dim = c(8L, 8L)
    , Dimnames = list(NULL, NULL)
    , x = c(1.002, 0.21, 1.002, 0.002, 0.21, 1.002, 16.003, 3.354, 16.003, 
0.031, 3.354, 16.003, 2.943, 7.515, 0.843, 18.691, 13.675, 0.44, 
109.002, 0.051, 2.943, 7.515, 1.122, 18.691, 13.675, 22.848, 
109.002)
    , uplo = "U"
    , factors = list()
)

Upvotes: 1

Views: 112

Answers (1)

IRTFM
IRTFM

Reputation: 263342

You have a CsparseMatrix and they don't have the column indices, but it's easy to coerce to a TsparseMatrix which do have them. The i and j parameters (of the values that are present in the x-values internally) are 0 based rather than 1 based so if you want to address something with them you will need to add 1.

 CSM <- new("dsCMatrix"
     , i = c(0L, 0L, 1L, 0L, 1L, 2L, 3L, 3L, 4L, 3L, 4L, 5L, 0L, 1L, 2L, 
 3L, 4L, 5L, 6L, 0L, 1L, 2L, 3L, 4L, 5L, 6L, 7L)
     , p = c(0L, 1L, 3L, 6L, 7L, 9L, 12L, 19L, 27L)
     , Dim = c(8L, 8L)
     , Dimnames = list(NULL, NULL)
     , x = c(1.002, 0.21, 1.002, 0.002, 0.21, 1.002, 16.003, 3.354, 16.003, 
 0.031, 3.354, 16.003, 2.943, 7.515, 0.843, 18.691, 13.675, 0.44, 
 109.002, 0.051, 2.943, 7.515, 1.122, 18.691, 13.675, 22.848, 
 109.002)
     , uplo = "U"
     , factors = list()
 )
 TSM <-as(CSM, "TsparseMatrix")
 TSM@i
# [1] 0 0 1 0 1 2 3 3 4 3 4 5 0 1 2 3 4 5 6 0 1 2 3 4 5 6 7
 TSM@j
# [1] 0 1 1 2 2 2 3 4 4 5 5 5 6 6 6 6 6 6 6 7 7 7 7 7 7 7 7
 TSM@j +1
# [1] 1 2 2 3 3 3 4 5 5 6 6 6 7 7 7 7 7 7 7 8 8 8 8 8 8 8 8
 TSM@i +1
# [1] 1 1 2 1 2 3 4 4 5 4 5 6 1 2 3 4 5 6 7 1 2 3 4 5 6 7 8

Upvotes: 1

Related Questions