单细胞

[R语言]处理h5数据结构

2023-08-26  本文已影响0人  expgene

.h5 数据格式是一种基于层次结构设计用于存储和管理大型科学数据的文件格式,可以存储多种类型的数据,包括数值、图像、文本等。h5数据格式是由HDF Group开发的,是HDF5【层级数据存储格式(HierarchicalDataFormat 5)】的缩写。HDF5可以方便地存储和管理大型数据集,有效提高数据读写效率,同时也可以保证数据的安全性和跨平台兼容性,在数据科学领域应用广泛。如生物信息学领域中的单细胞数据,h5数据格式已经成为了一种比较的数据存储格式。

例如

library(Seurat)

Read10X_h5("GSE189889_acral_2101.debatched.iscva.h5",use.names = T)

a <- H5Fopen("/mnt/data/person/dxj/Melanoma/GSE189889_acral_2101.debatched.iscva.h5")

h5ls("GSE189889_acral_2101.debatched.iscva.h5")

参考:

https://developer.aliyun.com/article/1249408

但如果读不了成Seurat结构,那么我们就先读成矩阵的形式。例如:GSE189889_acral_2101.debatched.iscva.h5

library(rhdf5)

hd5 <- H5Fopen("GSE189889_acral_2101.debatched.iscva.h5")

执行hd5,可看到有artifacts和matrix。查看hd5$artifacts,速度比较慢。 is.list(hd5$artifacts),是TRUE。liebiao <- hd5$artifacts,将它赋值到变量liebiao中,以加快读取速度。

接下来我们要把矩阵保存成一个稀疏矩阵形式。hd5$matrix本质上是一个列表,我们通过names(hd5$matrix)可以查看到列表名。

barcodes <- hd5$matrix$barcodes

counts <- hd5$matrix$data

gene_id <- hd5$matrix$gene_names

indices <- hd5$matrix$indices

indptr <- hd5$matrix$indptr

shape <- hd5$matrix$shape

library(Matrix)

mat <- sparseMatrix(i = indices[], p = indptr[],x = as.numeric(x = counts[]), dims =shape[],dimnames=list(gene_id,barcodes), index1 = FALSE)

注意index1这个参数,文档解释为: logical. If TRUE (the default), then i and j are interpreted as 1-based indices, following the R convention. That is, counting of rows and columns starts at 1. If FALSE, then they are interpreted as 0-based indices.

本来默认是TRUE,但是我们执行后发现报错:

Error in sparseMatrix(i = indices[], p = indptr[], x = as.numeric(x = counts[]), :

  'i' and 'j' must be positive

于是将index1参数修改成FALSE即可

又例如,读取h5ad格式的

Convert("xxxxx.h5ad", dest="h5seurat",assay = "RNA",overwrite=F)

seurat_object <- LoadH5Seurat("xxxxx.h5seurat")

R语言中的Matrix包的sparseMatrix函数理解:

sparseMatrix(i = ep, j = ep, p, x, dims, dimnames,

            symmetric = FALSE, triangular = FALSE, index1 = TRUE,

            repr = "C", giveCsparse = (repr == "C"),

            check = TRUE, use.last.ij = FALSE)

案例介绍

i <- c(1,3:8); j <- c(2,9,6:10); x <- 7 * (1:7)

A <- sparseMatrix(i, j, x = x)                    ##  8 x 10 "dgCMatrix"

summary(A)

结果:

8 x 10 sparse Matrix of class "dgCMatrix", with 7 entries

  i  j  x

1 1  2  7

2 4  6 21

3 5  7 28

4 6  8 35

5 3  9 14

6 7  9 42

7 8 10 49

参考:

scRNAseq:h5文件转化为matrix表达矩阵

https://blog.csdn.net/jeffery0207/article/details/122507934

CSDN-稀疏矩阵(Sparse Matrix)

探序基因,生物信息解决方案提供商。

探序基因肿瘤研究院整理

上一篇下一篇

猜你喜欢

热点阅读