Using anndataR

{anndataR} allows users to work with .h5ad files, access various slots in the datasets and convert these files to SingleCellExperiment objects and SeuratObjects, and vice versa.

Check out ?anndataR for a full list of the functions provided by this package.

Installation

Install using:

if (!require("pak", quietly = TRUE)) {
  install.packages("pak")
}
pak::pak("scverse/anndataR")

Usage

Here’s a quick example of how to use {anndataR}.

First, we fetch an example .h5ad file included in the package:

library(anndataR)

h5ad_path <- system.file("extdata", "example.h5ad", package = "anndataR")

Read an h5ad file in memory:

adata <- read_h5ad(h5ad_path)

Read an h5ad file on disk:

adata <- read_h5ad(h5ad_path, to = "HDF5AnnData")

View structure:

adata
#> AnnData object with n_obs × n_vars = 50 × 100
#>     obs: 'Float', 'FloatNA', 'Int', 'IntNA', 'Bool', 'BoolNA', 'n_genes_by_counts', 'log1p_n_genes_by_counts', 'total_counts', 'log1p_total_counts', 'leiden'
#>     var: 'String', 'n_cells_by_counts', 'mean_counts', 'log1p_mean_counts', 'pct_dropout_by_counts', 'total_counts', 'log1p_total_counts', 'highly_variable', 'means', 'dispersions', 'dispersions_norm'
#>     uns: 'Bool', 'BoolNA', 'Category', 'DataFrameEmpty', 'Int', 'IntNA', 'IntScalar', 'Sparse1D', 'String', 'String2D', 'StringScalar', 'hvg', 'leiden', 'log1p', 'neighbors', 'pca', 'rank_genes_groups', 'umap'
#>     obsm: 'X_pca', 'X_umap'
#>     varm: 'PCs'
#>     layers: 'counts', 'csc_counts', 'dense_X', 'dense_counts'
#>     obsp: 'connectivities', 'distances'

Access AnnData slots:

dim(adata$X)
#> [1]  50 100
adata$obs[1:5, 1:6]
#>         Float FloatNA Int IntNA  Bool BoolNA
#> Cell000 42.42     NaN   0    NA FALSE  FALSE
#> Cell001 42.42   42.42   1    42  TRUE     NA
#> Cell002 42.42   42.42   2    42  TRUE   TRUE
#> Cell003 42.42   42.42   3    42  TRUE   TRUE
#> Cell004 42.42   42.42   4    42  TRUE   TRUE
adata$var[1:5, 1:6]
#>          String n_cells_by_counts mean_counts log1p_mean_counts
#> Gene000 String0                44        1.94          1.078410
#> Gene001 String1                42        2.04          1.111858
#> Gene002 String2                43        2.12          1.137833
#> Gene003 String3                41        1.72          1.000632
#> Gene004 String4                42        2.06          1.118415
#>         pct_dropout_by_counts total_counts
#> Gene000                    12           97
#> Gene001                    16          102
#> Gene002                    14          106
#> Gene003                    18           86
#> Gene004                    16          103

Interoperability

Convert the AnnData object to a SingleCellExperiment object:

sce <- adata$to_SingleCellExperiment()
sce
#> class: SingleCellExperiment 
#> dim: 100 50 
#> metadata(18): Bool BoolNA ... rank_genes_groups umap
#> assays(5): data counts csc_counts dense_X dense_counts
#> rownames(100): Gene000 Gene001 ... Gene098 Gene099
#> rowData names(11): String n_cells_by_counts ... dispersions
#>   dispersions_norm
#> colnames(50): Cell000 Cell001 ... Cell048 Cell049
#> colData names(11): Float FloatNA ... log1p_total_counts leiden
#> reducedDimNames(2): pca umap
#> mainExpName: NULL
#> altExpNames(0):

Convert the AnnData object to a Seurat object:

obj <- adata$to_Seurat()
#> Warning: Data is of class dgRMatrix. Coercing to dgCMatrix.
#> Warning: No columnames present in cell embeddings, setting to 'PC_1:38'
#> Warning: No columnames present in cell embeddings, setting to 'umap_1:2'
obj
#> An object of class Seurat 
#> 100 features across 50 samples within 1 assay 
#> Active assay: RNA (100 features, 0 variable features)
#>  5 layers present: counts, data, csc_counts, dense_X, dense_counts
#>  2 dimensional reductions calculated: pca, umap

Manually create an object

adata <- AnnData(
  X = matrix(rnorm(100), nrow = 10),
  obs = data.frame(
    cell_type = factor(rep(c("A", "B"), each = 5))
  ),
  var = data.frame(
    gene_name = paste0("gene_", 1:10)
  )
)

adata
#> AnnData object with n_obs × n_vars = 10 × 10
#>     obs: 'cell_type'
#>     var: 'gene_name'

Session info

sessionInfo()
#> R version 4.4.2 (2024-10-31)
#> Platform: x86_64-pc-linux-gnu
#> Running under: Ubuntu 24.04.1 LTS
#> 
#> Matrix products: default
#> BLAS:   /usr/lib/x86_64-linux-gnu/openblas-pthread/libblas.so.3 
#> LAPACK: /usr/lib/x86_64-linux-gnu/openblas-pthread/libopenblasp-r0.3.26.so;  LAPACK version 3.12.0
#> 
#> locale:
#>  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
#>  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=C              
#>  [5] LC_MONETARY=en_US.UTF-8    LC_MESSAGES=en_US.UTF-8   
#>  [7] LC_PAPER=en_US.UTF-8       LC_NAME=C                 
#>  [9] LC_ADDRESS=C               LC_TELEPHONE=C            
#> [11] LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C       
#> 
#> time zone: Etc/UTC
#> tzcode source: system (glibc)
#> 
#> attached base packages:
#> [1] stats4    stats     graphics  grDevices utils     datasets  methods  
#> [8] base     
#> 
#> other attached packages:
#>  [1] anndataR_0.99.0             SingleCellExperiment_1.29.1
#>  [3] SummarizedExperiment_1.37.0 Biobase_2.67.0             
#>  [5] GenomicRanges_1.59.1        GenomeInfoDb_1.43.4        
#>  [7] IRanges_2.41.2              S4Vectors_0.45.2           
#>  [9] BiocGenerics_0.53.6         generics_0.1.3             
#> [11] MatrixGenerics_1.19.1       matrixStats_1.5.0          
#> [13] SeuratObject_5.0.2          sp_2.2-0                   
#> [15] BiocStyle_2.35.0           
#> 
#> loaded via a namespace (and not attached):
#>   [1] RColorBrewer_1.1-3      sys_3.4.3               jsonlite_1.8.9         
#>   [4] magrittr_2.0.3          spatstat.utils_3.1-2    farver_2.1.2           
#>   [7] rmarkdown_2.29          vctrs_0.6.5             ROCR_1.0-11            
#>  [10] spatstat.explore_3.3-4  htmltools_0.5.8.1       S4Arrays_1.7.2         
#>  [13] SparseArray_1.7.5       sass_0.4.9              sctransform_0.4.1      
#>  [16] parallelly_1.42.0       KernSmooth_2.23-26      bslib_0.9.0            
#>  [19] htmlwidgets_1.6.4       ica_1.0-3               plyr_1.8.9             
#>  [22] plotly_4.10.4           zoo_1.8-12              cachem_1.1.0           
#>  [25] buildtools_1.0.0        igraph_2.1.4            mime_0.12              
#>  [28] lifecycle_1.0.4         pkgconfig_2.0.3         Matrix_1.7-2           
#>  [31] R6_2.5.1                fastmap_1.2.0           GenomeInfoDbData_1.2.13
#>  [34] fitdistrplus_1.2-2      future_1.34.0           shiny_1.10.0           
#>  [37] digest_0.6.37           colorspace_2.1-1        patchwork_1.3.0        
#>  [40] tensor_1.5              Seurat_5.2.1            RSpectra_0.16-2        
#>  [43] irlba_2.3.5.1           progressr_0.15.1        spatstat.sparse_3.1-0  
#>  [46] polyclip_1.10-7         httr_1.4.7              abind_1.4-8            
#>  [49] compiler_4.4.2          bit64_4.6.0-1           fastDummies_1.7.5      
#>  [52] MASS_7.3-64             DelayedArray_0.33.5     tools_4.4.2            
#>  [55] lmtest_0.9-40           httpuv_1.6.15           future.apply_1.11.3    
#>  [58] goftest_1.2-3           glue_1.8.0              nlme_3.1-167           
#>  [61] promises_1.3.2          grid_4.4.2              Rtsne_0.17             
#>  [64] cluster_2.1.8           reshape2_1.4.4          hdf5r_1.3.12           
#>  [67] spatstat.data_3.1-4     gtable_0.3.6            tidyr_1.3.1            
#>  [70] data.table_1.16.4       XVector_0.47.2          spatstat.geom_3.3-5    
#>  [73] RcppAnnoy_0.0.22        ggrepel_0.9.6           RANN_2.6.2             
#>  [76] pillar_1.10.1           stringr_1.5.1           spam_2.11-1            
#>  [79] RcppHNSW_0.6.0          later_1.4.1             splines_4.4.2          
#>  [82] dplyr_1.1.4             lattice_0.22-6          deldir_2.0-4           
#>  [85] survival_3.8-3          bit_4.5.0.1             tidyselect_1.2.1       
#>  [88] maketools_1.3.1         miniUI_0.1.1.1          pbapply_1.7-2          
#>  [91] knitr_1.49              gridExtra_2.3           scattermore_1.2        
#>  [94] xfun_0.50               stringi_1.8.4           UCSC.utils_1.3.1       
#>  [97] lazyeval_0.2.2          yaml_2.3.10             evaluate_1.0.3         
#> [100] codetools_0.2-20        tibble_3.2.1            BiocManager_1.30.25    
#> [103] cli_3.6.3               uwot_0.2.2              xtable_1.8-4           
#> [106] reticulate_1.40.0       munsell_0.5.1           jquerylib_0.1.4        
#> [109] Rcpp_1.0.14             spatstat.random_3.3-2   globals_0.16.3         
#> [112] png_0.1-8               spatstat.univar_3.1-1   parallel_4.4.2         
#> [115] ggplot2_3.5.1           dotCall64_1.2           listenv_0.9.1          
#> [118] viridisLite_0.4.2       scales_1.3.0            ggridges_0.5.6         
#> [121] purrr_1.0.4             crayon_1.5.3            rlang_1.1.5            
#> [124] cowplot_1.1.3