[R] Matrix: How create a _row-oriented_ sparse Matrix (=dgRMatrix)?
Henrik Bengtsson
henrik.bengtsson at gmail.com
Tue Apr 19 23:04:11 CEST 2016
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:
> Cc <- Matrix(0, nrow=5, ncol=5, sparse=TRUE)
> Cc[1:3,1] <- 1
> Cc
5 x 5 sparse Matrix of class "dgCMatrix"
[1,] 1 . . . .
[2,] 1 . . . .
[3,] 1 . . . .
[4,] . . . . .
[5,] . . . . .
> str(Cc)
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":
> Cr <- Matrix(0, nrow=5, ncol=5, sparse=TRUE)
> Cr <- as(Cr, "dsRMatrix")
> Cr[1,1:3] <- 1
> Cr
5 x 5 sparse Matrix of class "dgTMatrix"
[1,] 1 1 1 . .
[2,] . . . . .
[3,] . . . . .
[4,] . . . . .
[5,] . . . . .
> str(Cr)
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:
> as(Cc, "dgRMatrix")
Error in as(Cc, "dgRMatrix") :
no method or default for coercing "dgCMatrix" to "dgRMatrix"
> as(Cr, "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
More information about the R-help
mailing list