Skip to content

Instantly share code, notes, and snippets.

@xie186
Last active May 16, 2024 01:42
Show Gist options
  • Save xie186/332eff13dcac50f101f91494402b4bd1 to your computer and use it in GitHub Desktop.
Save xie186/332eff13dcac50f101f91494402b4bd1 to your computer and use it in GitHub Desktop.
Convert gene expression table to matrix.mtx

MTX data

%%MatrixMarket matrix coordinate ***real*** general
%
32738 2700 2286884

This line 13406 1562 6512772 tells the matrix reader that your matrix has 13406 rows, 1562 columns and 6512772 non-zeros values.

Reference:

https://math.nist.gov/MatrixMarket/formats.html#MMformat

biostars.org/p/312933/

library(Matrix)
path = "YOUR_PATH"
setwd(path)
# generate single-cell RNA seq data
count <- read.csv("test.csv", header=T,row.names = 1)
gbm <- t(count)
# save sparse matrix
sparse.gbm <- Matrix(gbm , sparse = T )
head(sparse.gbm)
## Market Exchange Format (MEX) format
writeMM(obj = sparse.gbm, file="matrix.mtx")
# save genes and cells names
write(x = rownames(gbm), file = "genes.tsv")
write(x = colnames(gbm), file = "barcodes.tsv")
test<- Read10X(data.dir = path,
gene.column = 1, unique.features = TRUE)
# Initialize the Seurat object with the raw (non-normalized data).
test_seurat <- CreateSeuratObject(counts = test, project = "test", min.cells = 0, min.features = 0)
library(Matrix)
# generate single-cell RNA seq data
gbm <- replicate(10, rpois(10, 1))
rownames(gbm) <- paste0("gene_", 1:nrow(gbm))
colnames(gbm) <- paste0("cell_",1:ncol(gbm))
# save sparse matrix
sparse.gbm <- Matrix(gbm , sparse = T )
head(sparse.gbm)
writeMM(obj = sparse.gbm, file="matrix.mtx")
# save genes and cells names
write(x = rownames(gbm), file = "genes.tsv")
write(x = colnames(gbm), file = "barcodes.tsv")
#Reference: biostars.org/p/312933/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment