View source: R/readSparseCSV.R
readSparseCSV | R Documentation |
Read/write a sparse matrix from/to a CSV (comma-separated values) file.
writeSparseCSV(x, filepath, sep=",", transpose=FALSE, write.zeros=FALSE,
chunknrow=250)
readSparseCSV(filepath, sep=",", transpose=FALSE)
x |
A matrix-like object, typically sparse. IMPORTANT: The object must have rownames and colnames! These will be written to the file. Another requirement is that the object must be subsettable. More
precisely: it must support 2D-style subsetting of the kind |
filepath |
The path (as a single string) to the file where to write the matrix-like object or to read it from. Compressed files are supported. If Note that |
sep |
The field separator character. Values on each line of the file are separated by this character. |
transpose |
Note that using |
write.zeros |
|
chunknrow |
|
writeSparseCSV
returns an invisible NULL
.
readSparseCSV
returns a SparseMatrix object of class
SVT_SparseMatrix.
SparseArray objects.
dgCMatrix objects implemented in the Matrix package.
## ---------------------------------------------------------------------
## writeSparseCSV()
## ---------------------------------------------------------------------
## Prepare toy matrix 'm0':
rownames0 <- LETTERS[1:6]
colnames0 <- letters[1:4]
m0 <- matrix(0L, nrow=length(rownames0), ncol=length(colnames0),
dimnames=list(rownames0, colnames0))
m0[c(1:2, 8, 10, 15:17, 24)] <- (1:8)*10L
m0
## writeSparseCSV():
writeSparseCSV(m0, filepath="", sep="\t")
writeSparseCSV(m0, filepath="", sep="\t", write.zeros=TRUE)
writeSparseCSV(m0, filepath="", sep="\t", transpose=TRUE)
## Note that writeSparseCSV() will automatically (and silently) coerce
## non-integer values to integer by passing them thru as.integer().
## Example where type(x) is "double":
m1 <- m0 * runif(length(m0))
m1
type(m1)
writeSparseCSV(m1, filepath="", sep="\t")
## Example where type(x) is "logical":
writeSparseCSV(m0 != 0, filepath="", sep="\t")
## Example where type(x) is "raw":
m2 <- m0
type(m2) <- "raw"
m2
writeSparseCSV(m2, filepath="", sep="\t")
## ---------------------------------------------------------------------
## readSparseCSV()
## ---------------------------------------------------------------------
csv_file <- tempfile()
writeSparseCSV(m0, csv_file)
svt1 <- readSparseCSV(csv_file)
svt1
svt2 <- readSparseCSV(csv_file, transpose=TRUE)
svt2
## If you need the sparse data as a dgCMatrix object, just coerce the
## returned object:
as(svt1, "dgCMatrix")
as(svt2, "dgCMatrix")
## Sanity checks:
stopifnot(identical(m0, as.matrix(svt1)))
stopifnot(identical(t(m0), as.matrix(svt2)))
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.