---
title: "Using anndataR to read and convert"
shorttitle: "Using anndataR"
author:
  - name: Robrecht Cannoodt
  - name: Luke Zappia
  - name: Martin Morgan
  - name: Louise Deconinck
package: anndataR
output: BiocStyle::html_document
vignette: >
  %\VignetteIndexEntry{Using anndataR to read and convert}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r, include = FALSE}
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>"
)

# already load SeuratObject and SingleCellExperiment
# so warnings generated by these packages are not shown
library(SeuratObject)
library(SingleCellExperiment)
```

# Introduction

This package allows users to work with `.h5ad` files, access various slots in the datasets and convert these files to `SingleCellExperiment` objects and `SeuratObject`s, and vice versa.

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

# Installation

Install using:
```{r, eval = FALSE}
if (!require("BiocManager", quietly = TRUE)) {
  install.packages("BiocManager")
}
BiocManager::install("anndataR")
```

# Usage

This package provides an abstract interface for `AnnData` objects. This abstract interface models its Python counterpart closely, and stores a data matrix `X` and annotations corresponding to observations (`obs`, `obsm`, `obsp`) and variables (`var`, `varm`, `varp`) and unstructured metadata `uns`.


This abstract interface is implemented by different backends. Currently, the following backends are implemented:

1. `InMemoryAnnData`

2. `HDF5AnnData`

The `InMemoryAnnData` backend allows you to construct an `AnnData` object in memory.
The `HDF5AnnData` backend allows you to read in an `AnnData` object from an `.h5ad` file.

## `HDF5AnnData` backend

Here is an example of how to read in an `.h5ad` file.

```{r setup}
library(anndataR)
```

```{r show_anndata_hdf5}
file <- system.file("extdata", "example.h5ad", package = "anndataR")
adata <- read_h5ad(file, to = "InMemoryAnnData")
```

The contents can be accessed as well:
```{r access_hdf5}
X <- adata$X
layers <- adata$layers
obs <- adata$obs
var <- adata$var
```

## `InMemoryAnnData` backend

The following example details how to construct an InMemoryAnnData and access its contents.

```{r inmemory_construct}
adata <- AnnData(
  X = matrix(1:15, 3L, 5L),
  layers = list(
    A = matrix(5:1, 3L, 5L),
    B = matrix(letters[1:5], 3L, 5L)
  ),
  obs = data.frame(row.names = LETTERS[1:3], cell = 1:3),
  var = data.frame(row.names = letters[1:5], gene = 1:5)
)
adata
```

The contents can be accessed as well:
```{r access_construct}
X <- adata$X
layers <- adata$layers
obs <- adata$obs
var <- adata$var
```

You can convert the AnnData object to a SingleCellExperiment object or to a SeuratObject in the following way:

```{r convert}
sce <- adata$to_SingleCellExperiment()
seurat <- adata$to_Seurat()
```

# Session info

```{r}
sessionInfo()
```

