## 2008-07-15

### Symmetric sparse matrices with Matrix R package II

I have written about the size of created sparse matrices with Matrix R package here. After discussion with the developers of the package, I realized that one should not create sparse matrices in a way presented here i.e. setting up the matrix and then filling it is NOT OK. Instead one should either start with sparse design matrices and create the crossprods e.g.

`> library(Matrix)> tmp <- factor(rep(letters[1:3], each=4))   a a a a b b b b c c c c Levels: a b c > (x <- as(tmp, "sparseMatrix")) 3 x 12 sparse Matrix of class "dgCMatrix"                        a 1 1 1 1 . . . . . . . . b . . . . 1 1 1 1 . . . . c . . . . . . . . 1 1 1 1 > tcrossprod(x)3 x 3 sparse Matrix of class "dsCMatrix"a b ca 4 . .b . 4 .c . . 4`

or directly via the "triplets":

`i <- as.integer(c(1, 2, 3))j <- as.integer(c(1, 2, 3))x <- c(4, 4, 4)new("dsTMatrix", Dim=c(3L, 3L), i=(i - 1L), j=(j - 1L), x=x)`

The above code should of course be more "automagical" but shows the point. Additionally, creating a diagonal matrix is of course easy (there is a special class for them in Matrix), but the above code works in general setting.