在R中将稀疏矩阵写入CSV文件

8
我有一个稀疏矩阵(dgCMatrix),是拟合glmnet的结果。我想将这个结果写入.csv文件,但无法使用write.table()函数因为该矩阵无法强制转换为data.frame
有没有一种方法可以将稀疏矩阵强制转换为data.frame或常规矩阵?或者有没有一种方法将其写入文件并保留系数名称(可能是行名称)?
4个回答

15
这将是危险的,如果稀疏矩阵的大小太大,将其转换为普通矩阵。在我的情况下(文本分类任务),我得到了一个大小为22490乘以120000的矩阵。如果您尝试获取密集矩阵,则会超过20 GB,我想。然后R将崩溃!因此,我的建议是,您可以简单地以高效和内存友好的方式存储稀疏矩阵,例如Matrix Market Format,它保留所有非零值及其坐标(行号和列号)。在R中,您可以使用方法writeMM。

7

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

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

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

我尝试了matrix(),但它没有起作用,我没有想到尝试as.matrix()。感谢您的帮助。 - Jared

6
直接转换为密集矩阵很可能会浪费大量内存。R包Matrix允许使用summary()函数将稀疏矩阵转换为内存高效的坐标三元组格式数据框,然后可以轻松地将其写入csv文件。这可能比矩阵市场方法更简单、更容易操作。参见下面这个相关问题的答案:Sparse matrix to a data frame in R
此外,《Matrix包文档》提供了以下插图: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))

4
# 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 
< p >[编辑:使用数据框架]

1
请在程序中添加注释,这样更容易理解。 - Haris
这对我有用(取自您的答案)SM = summary(mat0)D1 = nrow(mat0)D2 = nrow(mat0)a<-as.matrix(data.frame(row=D1, col=D2, x=SM)) - Omar Jaafor

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接