[R] assigning one value into a dspMatrix-class matrix

Robert Castelo robert.castelo at upf.edu
Mon Jul 19 12:13:25 CEST 2010


dear list,

I'm interested in using the 'dspMatrix' class of matrices, from the
R-project recommended package Matrix, to store large symmetric matrices.
I would like to know how to fill such a matrix cell by cell avoiding
coercion to a non-dspMatrix which might not be storing the symmetric
matrix so efficiently.

for instance, when i try to fill one cell in the two corresponding
triangles of a symmetric matrix:

library(Matrix)

m <- new("dspMatrix", Dim=as.integer(c(3,3)), x=rep(0, 6))
m
3 x 3 Matrix of class "dspMatrix"
     [,1] [,2] [,3]
[1,]    0    0    0
[2,]    0    0    0
[3,]    0    0    0
str(m)
Formal class 'dspMatrix' [package "Matrix"] with 5 slots
  ..@ x       : num [1:6] 0 0 0 0 0 0
  ..@ Dim     : int [1:2] 3 3
  ..@ Dimnames:List of 2
  .. ..$ : NULL
  .. ..$ : NULL
  ..@ uplo    : chr "U"
  ..@ factors : list()

m[1,2] <- m[2,1] <- 1
m
3 x 3 Matrix of class "dgeMatrix"
     [,1] [,2] [,3]
[1,]    0    1    0
[2,]    1    0    0
[3,]    0    0    0
str(m)
Formal class 'dgeMatrix' [package "Matrix"] with 4 slots
  ..@ x       : num [1:9] 0 1 0 1 0 0 0 0 0
  ..@ Dim     : int [1:2] 3 3
  ..@ Dimnames:List of 2
  .. ..$ : NULL
  .. ..$ : NULL
  ..@ factors : list()


however, when i do a subset assignment of a submatrix, then it works as
expected, i.e., i get a dspMatrix as a result:

m <- new("dspMatrix", Dim=as.integer(c(3,3)), x=rep(0, 6))
m[1:2,1:2] <- 1
m
3 x 3 Matrix of class "dspMatrix"
     [,1] [,2] [,3]
[1,]    1    1    0
[2,]    1    1    0
[3,]    0    0    0
str(m)
Formal class 'dspMatrix' [package "Matrix"] with 5 slots
  ..@ x       : num [1:6] 1 1 1 0 0 0
  ..@ Dim     : int [1:2] 3 3
  ..@ Dimnames:List of 2
  .. ..$ : NULL
  .. ..$ : NULL
  ..@ uplo    : chr "U"
  ..@ factors : list()


i guess there must be some way of doing a "symmetric" assignment of a
value but I have not been able to figure it out myself from the
documentation nor searching the list nor googling.

thanks!
robert.



More information about the R-help mailing list