如何以矩阵市场格式打印稀疏矩阵,但使用 0-index
How to print sparse matrix in matrix market format, but using 0-index
我想使用 R's Matrix 库的 writeMM 以矩阵市场格式将稀疏矩阵写入外部文件。
参见:https://stat.ethz.ch/R-manual/R-patched/library/Matrix/html/externalFormats.html
矩阵
4 0
2 4
library(Matrix)
writeMM(matrix, "./outfile.tsv")
outfile.tsv:
#rowindex #columnindex #value
1 1 4
2 1 2
2 2 4
但是,我希望输出文件中的打印索引实际上是 0 索引,这与 R 中的默认索引 1 形成对比。即我想从打印的每一行和列索引中减去 1。
如何在尽可能多地使用现有功能的同时做到这一点?
这是一个使用 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
Matrix
对象的 summary
函数 returns 具有列 i
、j
和 x
的数据框。每个非零条目都有一行。只需从 i
和 j
列中减去 1 就可以了——另外,您还没有浪费大量内存。
更新:
这不适用于 Matrix
包中的所有稀疏矩阵,但如果您这样做,它应该会起作用 summary(as(my_mat, "dgTMatrix"))
。
我想使用 R's Matrix 库的 writeMM 以矩阵市场格式将稀疏矩阵写入外部文件。 参见:https://stat.ethz.ch/R-manual/R-patched/library/Matrix/html/externalFormats.html
矩阵
4 0
2 4
library(Matrix)
writeMM(matrix, "./outfile.tsv")
outfile.tsv:
#rowindex #columnindex #value
1 1 4
2 1 2
2 2 4
但是,我希望输出文件中的打印索引实际上是 0 索引,这与 R 中的默认索引 1 形成对比。即我想从打印的每一行和列索引中减去 1。
如何在尽可能多地使用现有功能的同时做到这一点?
这是一个使用 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
Matrix
对象的 summary
函数 returns 具有列 i
、j
和 x
的数据框。每个非零条目都有一行。只需从 i
和 j
列中减去 1 就可以了——另外,您还没有浪费大量内存。
更新:
这不适用于 Matrix
包中的所有稀疏矩阵,但如果您这样做,它应该会起作用 summary(as(my_mat, "dgTMatrix"))
。