Casting a Wide (and Sparse) Matrix in R
I routinely use
cast() from the reshape2 package as part of my data munging workflow. Recently I’ve noticed that the data frames I’ve been casting are often extremely sparse. Stashing these in a dense data structure just feels wasteful. And the dismal drone of page thrashing is unpleasant.
So I had a look around for an alternative. As it turns out, it’s remarkably easy to cast a sparse matrix using
sparseMatrix() from the Matrix package. Here’s an example.
First we’ll put together some test data.
It’s just a data.frame with two fields which will be transformed into the rows and columns of the matrix and a third field which gives the values to be stored in the matrix.
Doing the cast is pretty easy using
sparseMatrix() because you specify the row and column for every entry inserted into the matrix. Multiple entries for a single cell (like the highlighted records above) are simply summed, which is generally the behaviour that I am after anyway.
And here’s the result: