lynnyi lynnyi - 28 days ago 18
R Question

How to print sparse matrix in matrix market format, but using 0-index

I want to use R's Matrix library's writeMM to write a sparse matrix to external file in matrix market format.
see: https://stat.ethz.ch/R-manual/R-patched/library/Matrix/html/externalFormats.html

matrix

4 0
2 4


library(Matrix)
writeMM(matrix, "./outfile.tsv")


outfile.tsv:

#rowindex #columnindex #value

1 1 4
2 1 2
2 2 4


However, I want the printed indices in the output file to be effectively 0 indexed, in contrast to the default in R which is 1-indexed. i.e. I want to subtract 1 from every row and column index that is printed.

How can I do that while using as much of pre-existing functionality as possible?

Answer

Here is a solution using reshape2:

m <- matrix(c(4,2,3,4), ncol = 2);

# Reshape
library(reshape2);
m.long <- melt(m);

# 0-based indices
m.long[, 1:2] <- m.long[, 1:2] - 1;

# Optionally sort
m.long <- m.long[order(m.long[, 1],  m.long[, 2]) ,]
print(m.long);
  Var1 Var2 value
1    0    0     4
3    0    1     3
2    1    0     2
4    1    1     4
Comments