Lewkrr Lewkrr - 4 months ago 37
R Question

Convert a data.frame in "sparse matrix" COO format into an actual sparse-matrix class?

I am representing the following matrix:

6 5 0
0 5 4
0 0 4

as a data.frame. The data.frame in R has three columns. The COO format is as follows:

i j Xij
1 1 6
1 2 5
2 2 6
2 3 5
3 3 6

Note that there is no row
[1 3 0]
row, as it is omitted for having a value of zero. The same applied for the lower-triangular values, which are also zero.

What I want to do is convert it into a
class object from the
package in R.

I do NOT want to convert it to a regular matrix first, as the dataset I am working with is very large, and writing a loop to convert it to a standard R matrix would take too long.


Looking at ?Matrix::sparseMatrix we can use the already-coded function as follows:

myMatrix <- Matrix::sparseMatrix(i = coo$i, j = coo$j, x = coo$Xij, dims = c(42, 42))