将稀疏矩阵写入R中的CSV

时间:2010-12-29 22:05:48

标签: r statistics matrix sparse-matrix

我有一个稀疏矩阵(dgCMatrix)作为拟合glmnet的结果。我想将此结果写入.csv但不能使用write.table()矩阵,因为它无法强制转换为data.frame

有没有办法将稀疏矩阵强制为data.frame或常规矩阵?或者有没有办法将它写入文件,同时保持系数名称可能是行名?

4 个答案:

答案 0 :(得分:10)

如果稀疏矩阵大小太大,将稀疏矩阵转换为正常矩阵将是危险的。在我的情况下(文本分类任务),我得到了一个大小为22490×120,000的矩阵。如果你尝试获得密集矩阵,我认为这将超过20 GB。然后R会崩溃!

所以我的建议是,您可以简单地以有效且符合内存的方式存储稀疏矩阵,例如 Matrix Market Format ,它保留所有非零值及其坐标(行和放大器) ; col号)。在R中,您可以使用 writeMM

方法

答案 1 :(得分:5)

as.matrix()将转换为完整的密集表示形式:

> as.matrix(Matrix(0, 3, 2))
     [,1] [,2]
[1,]    0    0
[2,]    0    0
[3,]    0    0

您可以使用write.csvwrite.table编写结果对象。

答案 2 :(得分:4)

直接转换为密集矩阵可能会浪费大量内存。 R包Matrix允许使用summary()函数将稀疏矩阵转换为内存有效的坐标三元组格式数据帧,然后可以将其轻松写入csv。这可能比矩阵市场方法更简单,更容易。请参阅此相关问题的答案:Sparse matrix to a data frame in R

另外,以下是Matrix package documentation

的说明
## very simple export - in triplet format - to text file:
data(CAex)
s.CA <- summary(CAex)
s.CA # shows  (i, j, x)  [columns of a data frame]
message("writing to ", outf <- tempfile())
write.table(s.CA, file = outf, row.names=FALSE)
## and read it back -- showing off  sparseMatrix():
str(dd <- read.table(outf, header=TRUE))
## has columns (i, j, x) -> we can use via do.call() as arguments to sparseMatrix():
mm <- do.call(sparseMatrix, dd)
stopifnot(all.equal(mm, CAex, tolerance=1e-15))

答案 3 :(得分:3)

# input: a sparse matrix with named rows and columns (dimnames)
# returns: a data frame representing triplets (r, c, x) suitable for writing to a CSV file
sparse2triples <- function(m) {
 SM = summary(m)
 D1 = m@Dimnames[[1]][SM[,1]]
 D2 = m@Dimnames[[2]][SM[,2]]
 data.frame(row=D1, col=D2, x=m@x)
}

实施例

> library(Matrix)
> dn <- list(LETTERS[1:3], letters[1:5])
> m <- sparseMatrix(i = c(3,1,3,2,2,1), p= c(0:2, 4,4,6), x = 1:6, dimnames = dn)

> m
3 x 5 sparse Matrix of class "dgCMatrix"
  a b c d e
A . 2 . . 6
B . . 4 . 5
C 1 . 3 . .

> sparse2triples(m)
  row col x
1   C   a 1
2   A   b 2
3   B   c 4
4   C   c 3
5   A   e 6
6   B   e 5 

[编辑:使用data.frame]