簡體   English   中英

將一個非常大的稀疏矩陣寫入 R 中的文件

[英]Writing a very large sparse matrix to file in R

我有一個尺寸為 ~400K x ~8k 的稀疏矩陣。

我想將它保存為制表符分隔或 csv 文件,因為我需要它作為另一個程序的輸入。

我按照這篇文章的建議使用了 MASS 包中的 write.matrix 函數: How to save an adjacency matrix as a CSV file?

但是,我收到以下錯誤:

library(MASS)
write.matrix(data,"data_sparseMat.txt",sep="\t")  
#Error in asMethod(object) : Cholmod error 'problem too large' at file ../Core/cholmod_dense.c, line 105

查看幫助,然后我嘗試提供 blocksize 參數。 我嘗試了 1000、10000、100000。都給了我同樣的錯誤

write.matrix(data,"data_sparseMat.txt",sep="\t", blocksize=1000)  
Error in asMethod(object) : 
  Cholmod error 'problem too large' at file ../Core/cholmod_dense.c, line 105

我很感激任何見解,我忽略了什么?

R版:

R version 3.5.2 (2018-12-20)
Platform: x86_64-apple-darwin15.6.0 (64-bit)
Running under: macOS High Sierra 10.13.6

例子:

w <- data.table( "id" = 1:300000 , "code" = paste(letters,1:9000,sep=""), "measure"=1:3000)
w$id <- factor(w$id)
w$code <- factor(w$code)

z<- sparseMatrix(as.integer(w$id),as.integer(w$code),x=w$measure,dimnames=list(levels(w$id),levels(w$code)))
write.matrix(z,"sparseTest.txt",sep="\t")
write.matrix(z,"sparseTest.txt",sep="\t",blocksize=100000)

注意:當代碼只是 1000 或 3000 而不是 9000 時,它似乎被寫入文件,盡管速度很慢。

非常感謝。

這是使用 Python 的解決方法。 我設法導出了一個在 R 中太大的矩陣。

將 R 中的數據導出為稀疏矩陣:

library(Matrix)
write(colnames(sparsematrix), file = "colnames.txt")
write(rownames(sparsematrix), file = "rownames.txt")
writeMM(sparsematrix, file = "sparsematrix.txt")

閱讀然后在 Python 中轉換:

from scipy import sparse, io
import pandas as pd
import numpy as np

sparsematrix = io.mmread('sparsematrix.txt')

m_dense = sparsematrix.toarray()

var_names = np.genfromtxt('rownames.txt', dtype=str)
col_names = np.genfromtxt('colnames.txt', dtype=str)

# Export to txt:
df = pd.DataFrame(m_dense, columns=col_names, index=var_names)
df.to_csv('export_sparsematrix.txt', sep='\t', header=True, index=True, index_label='Somelabel')

您可以省略行和列名稱部分,僅使用np.savetxt('m_dense.txt', m_dense, delimiter='\\t')導出值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM