Skip to content
Prev 360253 / 398503 Next

Matrix: How create a _row-oriented_ sparse Matrix (=dgRMatrix)?

Using the Matrix package, how can I create a row-oriented sparse
Matrix from scratch populated with some data?  By default a
column-oriented one is created and I'm aware of the note that the
package is optimized for column-oriented ones, but I'm only interested
in using it for holding my sparse row-oriented data and doing basic
subsetting by rows (even using drop=FALSE).

Here is what I get when I set up a column-oriented sparse Matrix:
5 x 5 sparse Matrix of class "dgCMatrix"

[1,] 1 . . . .
[2,] 1 . . . .
[3,] 1 . . . .
[4,] . . . . .
[5,] . . . . .
Formal class 'dgCMatrix' [package "Matrix"] with 6 slots
  ..@ i       : int [1:3] 0 1 2
  ..@ p       : int [1:6] 0 3 3 3 3 3
  ..@ Dim     : int [1:2] 5 5
  ..@ Dimnames:List of 2
  .. ..$ : NULL
  .. ..$ : NULL
  ..@ x       : num [1:3] 1 1 1
  ..@ factors : list()

When I try to do the analogue for a row-oriented matrix, I get a
"dgTMatrix", whereas I would expect a "dgRMatrix":
5 x 5 sparse Matrix of class "dgTMatrix"

[1,] 1 1 1 . .
[2,] . . . . .
[3,] . . . . .
[4,] . . . . .
[5,] . . . . .
Formal class 'dgTMatrix' [package "Matrix"] with 6 slots
  ..@ i       : int [1:3] 0 0 0
  ..@ j       : int [1:3] 0 1 2
  ..@ Dim     : int [1:2] 5 5
  ..@ Dimnames:List of 2
  .. ..$ : NULL
  .. ..$ : NULL
  ..@ x       : num [1:3] 1 1 1
  ..@ factors : list()


Trying with explicit coercion does not work:
Error in as(Cc, "dgRMatrix") :
  no method or default for coercing "dgCMatrix" to "dgRMatrix"
Error in as(Cr, "dgRMatrix") :
  no method or default for coercing "dgTMatrix" to "dgRMatrix"


Am I doing some wrong here?  Or is this what means that the package is
optimized for the column-oriented representation and I shouldn't
really work with row-oriented ones?  I'm really only interested in
access to efficient Cr[row,,drop=FALSE] subsetting (and a small memory
footprint).

Thanks,

Henrik