[R] Reshape a sparse matrix

Martin Maechler maechler at stat.math.ethz.ch
Wed May 16 09:32:44 CEST 2007

>>>>> "Scott" == Scott Hyde <hydes at byuh.edu>
>>>>>     on Tue, 15 May 2007 17:03:13 -1000 (HST) writes:

    Scott> Hi,

    Scott> I'd like to reshape a sparse matrix generated from the Matrix package.  I can't seem to do it with the command

    Scott> dim(A) <- c(6,9)

    Scott> which works perfectly with the base package matrices, but with the sparse matrices it errors with

    Scott> Error in dim(A) = c(6, 9) : dim<- : invalid first argument

This *does* work in the current version of Matrix (0.99875-1), actually
already in version 0.99875-0 .

In the next version of Matrix, it will not only work, but also
work "sparsely" internally via the new class "sparseVector" and
its daughter classes, on which I've been working during the last
10 days or so...
Interesting that you bring the topic up right now ...

    Scott> Manipulating the Dim attribute of the sparse Matrix does not produce the desired effect. A at Dim <- c(as.integer(9),as.integer(6)) does not produce a column ordering result, which I am assuming is because the data is stored in a row (i) and column (j) format instead (class dgTMatrix)

You should not have manipulate slots of S4 classes in general.
Some  people say that you should not even access them directly.

    Scott> Does a function for this exist?

yes, as I said above  dim(.) <- ..  works in the newest versions
of "Matrix".

Martin Maechler, ETH Zurich

More information about the R-help mailing list