# Seurat-Local - Articles

**Pages:** 141

---

## Analysis, visualization, and integration of Visium HD spatial datasets with Seurat • Seurat

**URL:** http://127.0.0.1:9173/articles_seurat5_atacseq_integration_vignette.html

**Contents:**
- Integrating scRNA-seq and scATAC-seq data
    - Compiled: October 31, 2023
- Load in data and process each modality individually
- Identifying anchors between scRNA-seq and scATAC-seq datasets
- Annotate scATAC-seq cells via label transfer
- Co-embedding scRNA-seq and scATAC-seq datasets
- Contents

Single-cell transcriptomics has transformed our ability to characterize cell states, but deep biological understanding requires more than a taxonomic listing of clusters. As new methods arise to measure distinct cellular modalities, a key analytical challenge is to integrate these datasets to better understand cellular identity and function. For example, users may perform scRNA-seq and scATAC-seq experiments on the same biological system and to consistently annotate both datasets with the same set of cell type labels. This analysis is particularly challenging as scATAC-seq datasets are difficult to annotate, due to both the sparsity of genomic data collected at single-cell resolution, and the lack of interpretable gene markers in scRNA-seq data.

In Stuart*, Butler* et al, 2019, we introduce methods to integrate scRNA-seq and scATAC-seq datasets collected from the same biological system, and demonstrate these methods in this vignette. In particular, we demonstrate the following analyses:

This vignette makes extensive use of the Signac package, recently developed for the analysis of chromatin datasets collected at single-cell resolution, including scATAC-seq. Please see the Signac website for additional vignettes and documentation for analyzing scATAC-seq data.

We demonstrate these methods using a publicly available ~12,000 human PBMC ‘multiome’ dataset from 10x Genomics. In this dataset, scRNA-seq and scATAC-seq profiles were simultaneously collected in the same cells. For the purposes of this vignette, we treat the datasets as originating from two different experiments and integrate them together. Since they were originally measured in the same cells, this provides a ground truth that we can use to assess the accuracy of integration. We emphasize that our use of the multiome dataset here is for demonstration and evaluation purposes, and that users should apply these methods to scRNA-seq and scATAC-seq datasets that are collected separately. We provide a separate weighted nearest neighbors vignette (WNN) that describes analysis strategies for multi-omic single-cell data.

The PBMC multiome dataset is available from 10x genomics. To facilitate easy loading and exploration, it is also available as part of our SeuratData package. We load the RNA and ATAC data in separately, and pretend that these profiles were measured in separate experiments. We annotated these cells in our WNN vignette, and the annotations are also included in SeuratData.

Now we plot the results from both modalities. Cells have been previously annotated based on transcriptomic state. We will predict annotations for the scATAC-seq cells.

In order to identify ‘anchors’ between scRNA-seq and scATAC-seq experiments, we first generate a rough estimate of the transcriptional activity of each gene by quantifying ATAC-seq counts in the 2 kb-upstream region and gene body, using the GeneActivity() function in the Signac package. The ensuing gene activity scores from the scATAC-seq data are then used as input for canonical correlation analysis, along with the gene expression quantifications from scRNA-seq. We perform this quantification for all genes identified as being highly variable from the scRNA-seq dataset.

After identifying anchors, we can transfer annotations from the scRNA-seq dataset onto the scATAC-seq cells. The annotations are stored in the seurat_annotations field, and are provided as input to the refdata parameter. The output will contain a matrix with predictions and confidence scores for each ATAC-seq cell.

Why do you choose different (non-default) values for reduction and weight.reduction?

In FindTransferAnchors(), we typically project the PCA structure from the reference onto the query when transferring between scRNA-seq datasets. However, when transferring across modalities we find that CCA better captures the shared feature correlation structure and therefore set reduction = 'cca' here. Additionally, by default in TransferData() we use the same projected PCA structure to compute the weights of the local neighborhood of anchors that influence each cell’s prediction. In the case of scRNA-seq to scATAC-seq transfer, we use the low dimensional space learned by computing an LSI on the ATAC-seq data to compute these weights as this better captures the internal structure of the ATAC-seq data.

After performing transfer, the ATAC-seq cells have predicted annotations (transferred from the scRNA-seq dataset) stored in the predicted.id field. Since these cells were measured with the multiome kit, we also have a ground-truth annotation that can be used for evaluation. You can see that the predicted and actual annotations are extremely similar.

In this example, the annotation for an scATAC-seq profile is correctly predicted via scRNA-seq integration ~90% of the time. In addition, the prediction.score.max field quantifies the uncertainty associated with our predicted annotations. We can see that cells that are correctly annotated are typically associated with high prediction scores (>90%), while cells that are incorrectly annotated are associated with sharply lower prediction scores (<50%). Incorrect assignments also tend to reflect closely related cell types (i.e. Intermediate vs. Naive B cells).

In addition to transferring labels across modalities, it is also possible to visualize scRNA-seq and scATAC-seq cells on the same plot. We emphasize that this step is primarily for visualization, and is an optional step. Typically, when we perform integrative analysis between scRNA-seq and scATAC-seq datasets, we focus primarily on label transfer as described above. We demonstrate our workflows for co-embedding below, and again highlight that this is for demonstration purposes, especially as in this particular case both the scRNA-seq profiles and scATAC-seq profiles were actually measured in the same cells.

In order to perform co-embedding, we first ‘impute’ RNA expression into the scATAC-seq cells based on the previously computed anchors, and then merge the datasets.

Developed by Rahul Satija, Satija Lab and Collaborators.

Site built with pkgdown 2.0.7.

**Examples:**

Example 1 (unknown):
```unknown
vignettes/seurat5_atacseq_integration_vignette.Rmd
```

Example 2 (unknown):
```unknown
seurat5_atacseq_integration_vignette.Rmd
```

Example 3 (unknown):
```unknown
library(SeuratData)
# install the dataset and load requirements
InstallData("pbmcMultiome")
```

Example 4 (r):
```r
library(SeuratData)
# install the dataset and load requirements
InstallData("pbmcMultiome")
```

Example 5 (r):
```r
library(SeuratData)
# install the dataset and load requirements
InstallData("pbmcMultiome")
```

Example 6 (unknown):
```unknown
library(Seurat)
library(Signac)
library(EnsDb.Hsapiens.v86)
library(ggplot2)
library(cowplot)
```

Example 7 (r):
```r
library(Seurat)
library(Signac)
library(EnsDb.Hsapiens.v86)
library(ggplot2)
library(cowplot)
```

Example 8 (r):
```r
library(Seurat)
library(Signac)
library(EnsDb.Hsapiens.v86)
library(ggplot2)
library(cowplot)
```

Example 9 (unknown):
```unknown
# load both modalities
pbmc.rna <- LoadData("pbmcMultiome", "pbmc.rna")
pbmc.atac <- LoadData("pbmcMultiome", "pbmc.atac")

pbmc.rna[["RNA"]] <- as(pbmc.rna[["RNA"]], Class = "Assay5")
# repeat QC steps performed in the WNN vignette
pbmc.rna <- subset(pbmc.rna, seurat_annotations != "filtered")
pbmc.atac <- subset(pbmc.atac, seurat_annotations != "filtered")

# Perform standard analysis of each modality independently RNA analysis
pbmc.rna <- NormalizeData(pbmc.rna)
pbmc.rna <- FindVariableFeatures(pbmc.rna)
pbmc.rna <- ScaleData(pbmc.rna)
pbmc.rna <- RunPCA(pbmc.rna)
pbmc.rna <- RunUMAP(pbmc.rna, dims = 1:30)

# ATAC analysis add gene annotation information
annotations <- GetGRangesFromEnsDb(ensdb = EnsDb.Hsapiens.v86)
seqlevelsStyle(annotations) <- "UCSC"
genome(annotations) <- "hg38"
Annotation(pbmc.atac) <- annotations

# We exclude the first dimension as this is typically correlated with sequencing depth
pbmc.atac <- RunTFIDF(pbmc.atac)
pbmc.atac <- FindTopFeatures(pbmc.atac, min.cutoff = "q0")
pbmc.atac <- RunSVD(pbmc.atac)
pbmc.atac <- RunUMAP(pbmc.atac, reduction = "lsi", dims = 2:30, reduction.name = "umap.atac", reduction.key = "atacUMAP_")
```

Example 10 (r):
```r
# load both modalities
pbmc.rna <- LoadData("pbmcMultiome", "pbmc.rna")
pbmc.atac <- LoadData("pbmcMultiome", "pbmc.atac")

pbmc.rna[["RNA"]] <- as(pbmc.rna[["RNA"]], Class = "Assay5")
# repeat QC steps performed in the WNN vignette
pbmc.rna <- subset(pbmc.rna, seurat_annotations != "filtered")
pbmc.atac <- subset(pbmc.atac, seurat_annotations != "filtered")

# Perform standard analysis of each modality independently RNA analysis
pbmc.rna <- NormalizeData(pbmc.rna)
pbmc.rna <- FindVariableFeatures(pbmc.rna)
pbmc.rna <- ScaleData(pbmc.rna)
pbmc.rna <- RunPCA(pbmc.rna)
pbmc.rna <- RunUMAP(pbmc.rna, dims = 1:30)

# ATAC analysis add gene annotation information
annotations <- GetGRangesFromEnsDb(ensdb = EnsDb.Hsapiens.v86)
seqlevelsStyle(annotations) <- "UCSC"
genome(annotations) <- "hg38"
Annotation(pbmc.atac) <- annotations

# We exclude the first dimension as this is typically correlated with sequencing depth
pbmc.atac <- RunTFIDF(pbmc.atac)
pbmc.atac <- FindTopFeatures(pbmc.atac, min.cutoff = "q0")
pbmc.atac <- RunSVD(pbmc.atac)
pbmc.atac <- RunUMAP(pbmc.atac, reduction = "lsi", dims = 2:30, reduction.name = "umap.atac", reduction.key = "atacUMAP_")
```

Example 11 (r):
```r
# load both modalities
pbmc.rna <- LoadData("pbmcMultiome", "pbmc.rna")
pbmc.atac <- LoadData("pbmcMultiome", "pbmc.atac")

pbmc.rna[["RNA"]] <- as(pbmc.rna[["RNA"]], Class = "Assay5")
# repeat QC steps performed in the WNN vignette
pbmc.rna <- subset(pbmc.rna, seurat_annotations != "filtered")
pbmc.atac <- subset(pbmc.atac, seurat_annotations != "filtered")

# Perform standard analysis of each modality independently RNA analysis
pbmc.rna <- NormalizeData(pbmc.rna)
pbmc.rna <- FindVariableFeatures(pbmc.rna)
pbmc.rna <- ScaleData(pbmc.rna)
pbmc.rna <- RunPCA(pbmc.rna)
pbmc.rna <- RunUMAP(pbmc.rna, dims = 1:30)

# ATAC analysis add gene annotation information
annotations <- GetGRangesFromEnsDb(ensdb = EnsDb.Hsapiens.v86)
seqlevelsStyle(annotations) <- "UCSC"
genome(annotations) <- "hg38"
Annotation(pbmc.atac) <- annotations

# We exclude the first dimension as this is typically correlated with sequencing depth
pbmc.atac <- RunTFIDF(pbmc.atac)
pbmc.atac <- FindTopFeatures(pbmc.atac, min.cutoff = "q0")
pbmc.atac <- RunSVD(pbmc.atac)
pbmc.atac <- RunUMAP(pbmc.atac, reduction = "lsi", dims = 2:30, reduction.name = "umap.atac", reduction.key = "atacUMAP_")
```

Example 12 (unknown):
```unknown
p1 <- DimPlot(pbmc.rna, group.by = "seurat_annotations", label = TRUE) + NoLegend() + ggtitle("RNA")
p2 <- DimPlot(pbmc.atac, group.by = "orig.ident", label = FALSE) + NoLegend() + ggtitle("ATAC")
p1 + p2
```

Example 13 (r):
```r
p1 <- DimPlot(pbmc.rna, group.by = "seurat_annotations", label = TRUE) + NoLegend() + ggtitle("RNA")
p2 <- DimPlot(pbmc.atac, group.by = "orig.ident", label = FALSE) + NoLegend() + ggtitle("ATAC")
p1 + p2
```

Example 14 (r):
```r
p1 <- DimPlot(pbmc.rna, group.by = "seurat_annotations", label = TRUE) + NoLegend() + ggtitle("RNA")
p2 <- DimPlot(pbmc.atac, group.by = "orig.ident", label = FALSE) + NoLegend() + ggtitle("ATAC")
p1 + p2
```

Example 15 (unknown):
```unknown
plot <- (p1 + p2) & xlab("UMAP 1") & ylab("UMAP 2") & theme(axis.title = element_text(size = 18))
ggsave(filename = "../output/images/atacseq_integration_vignette.jpg", height = 7, width = 12, plot = plot,
    quality = 50)
```

Example 16 (r):
```r
plot <- (p1 + p2) & xlab("UMAP 1") & ylab("UMAP 2") & theme(axis.title = element_text(size = 18))
ggsave(filename = "../output/images/atacseq_integration_vignette.jpg", height = 7, width = 12, plot = plot,
    quality = 50)
```

Example 17 (r):
```r
plot <- (p1 + p2) & xlab("UMAP 1") & ylab("UMAP 2") & theme(axis.title = element_text(size = 18))
ggsave(filename = "../output/images/atacseq_integration_vignette.jpg", height = 7, width = 12, plot = plot,
    quality = 50)
```

Example 18 (unknown):
```unknown
GeneActivity()
```

Example 19 (unknown):
```unknown
# quantify gene activity
gene.activities <- GeneActivity(pbmc.atac, features = VariableFeatures(pbmc.rna))
```

Example 20 (r):
```r
# quantify gene activity
gene.activities <- GeneActivity(pbmc.atac, features = VariableFeatures(pbmc.rna))
```

Example 21 (r):
```r
# quantify gene activity
gene.activities <- GeneActivity(pbmc.atac, features = VariableFeatures(pbmc.rna))
```

Example 22 (unknown):
```unknown
# add gene activities as a new assay
pbmc.atac[["ACTIVITY"]] <- CreateAssayObject(counts = gene.activities)

# normalize gene activities
DefaultAssay(pbmc.atac) <- "ACTIVITY"
pbmc.atac <- NormalizeData(pbmc.atac)
pbmc.atac <- ScaleData(pbmc.atac, features = rownames(pbmc.atac))
```

Example 23 (r):
```r
# add gene activities as a new assay
pbmc.atac[["ACTIVITY"]] <- CreateAssayObject(counts = gene.activities)

# normalize gene activities
DefaultAssay(pbmc.atac) <- "ACTIVITY"
pbmc.atac <- NormalizeData(pbmc.atac)
pbmc.atac <- ScaleData(pbmc.atac, features = rownames(pbmc.atac))
```

Example 24 (r):
```r
# add gene activities as a new assay
pbmc.atac[["ACTIVITY"]] <- CreateAssayObject(counts = gene.activities)

# normalize gene activities
DefaultAssay(pbmc.atac) <- "ACTIVITY"
pbmc.atac <- NormalizeData(pbmc.atac)
pbmc.atac <- ScaleData(pbmc.atac, features = rownames(pbmc.atac))
```

Example 25 (unknown):
```unknown
# Identify anchors
transfer.anchors <- FindTransferAnchors(reference = pbmc.rna, query = pbmc.atac, features = VariableFeatures(object = pbmc.rna),
    reference.assay = "RNA", query.assay = "ACTIVITY", reduction = "cca")
```

Example 26 (r):
```r
# Identify anchors
transfer.anchors <- FindTransferAnchors(reference = pbmc.rna, query = pbmc.atac, features = VariableFeatures(object = pbmc.rna),
    reference.assay = "RNA", query.assay = "ACTIVITY", reduction = "cca")
```

Example 27 (r):
```r
# Identify anchors
transfer.anchors <- FindTransferAnchors(reference = pbmc.rna, query = pbmc.atac, features = VariableFeatures(object = pbmc.rna),
    reference.assay = "RNA", query.assay = "ACTIVITY", reduction = "cca")
```

Example 28 (unknown):
```unknown
seurat_annotations
```

Example 29 (python):
```python
celltype.predictions <- TransferData(anchorset = transfer.anchors, refdata = pbmc.rna$seurat_annotations,
    weight.reduction = pbmc.atac[["lsi"]], dims = 2:30)

pbmc.atac <- AddMetaData(pbmc.atac, metadata = celltype.predictions)
```

Example 30 (r):
```r
celltype.predictions <- TransferData(anchorset = transfer.anchors, refdata = pbmc.rna$seurat_annotations,
    weight.reduction = pbmc.atac[["lsi"]], dims = 2:30)

pbmc.atac <- AddMetaData(pbmc.atac, metadata = celltype.predictions)
```

Example 31 (r):
```r
celltype.predictions <- TransferData(anchorset = transfer.anchors, refdata = pbmc.rna$seurat_annotations,
    weight.reduction = pbmc.atac[["lsi"]], dims = 2:30)

pbmc.atac <- AddMetaData(pbmc.atac, metadata = celltype.predictions)
```

Example 32 (unknown):
```unknown
FindTransferAnchors()
```

Example 33 (unknown):
```unknown
reduction = 'cca'
```

Example 34 (unknown):
```unknown
TransferData()
```

Example 35 (unknown):
```unknown
predicted.id
```

Example 36 (unknown):
```unknown
pbmc.atac$annotation_correct <- pbmc.atac$predicted.id == pbmc.atac$seurat_annotations
p1 <- DimPlot(pbmc.atac, group.by = "predicted.id", label = TRUE) + NoLegend() + ggtitle("Predicted annotation")
p2 <- DimPlot(pbmc.atac, group.by = "seurat_annotations", label = TRUE) + NoLegend() + ggtitle("Ground-truth annotation")
p1 | p2
```

Example 37 (r):
```r
pbmc.atac$annotation_correct <- pbmc.atac$predicted.id == pbmc.atac$seurat_annotations
p1 <- DimPlot(pbmc.atac, group.by = "predicted.id", label = TRUE) + NoLegend() + ggtitle("Predicted annotation")
p2 <- DimPlot(pbmc.atac, group.by = "seurat_annotations", label = TRUE) + NoLegend() + ggtitle("Ground-truth annotation")
p1 | p2
```

Example 38 (r):
```r
pbmc.atac$annotation_correct <- pbmc.atac$predicted.id == pbmc.atac$seurat_annotations
p1 <- DimPlot(pbmc.atac, group.by = "predicted.id", label = TRUE) + NoLegend() + ggtitle("Predicted annotation")
p2 <- DimPlot(pbmc.atac, group.by = "seurat_annotations", label = TRUE) + NoLegend() + ggtitle("Ground-truth annotation")
p1 | p2
```

Example 39 (unknown):
```unknown
prediction.score.max
```

Example 40 (unknown):
```unknown
predictions <- table(pbmc.atac$seurat_annotations, pbmc.atac$predicted.id)
predictions <- predictions/rowSums(predictions)  # normalize for number of cells in each cell type
predictions <- as.data.frame(predictions)
p1 <- ggplot(predictions, aes(Var1, Var2, fill = Freq)) + geom_tile() + scale_fill_gradient(name = "Fraction of cells",
    low = "#ffffc8", high = "#7d0025") + xlab("Cell type annotation (RNA)") + ylab("Predicted cell type label (ATAC)") +
    theme_cowplot() + theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust = 1))

correct <- length(which(pbmc.atac$seurat_annotations == pbmc.atac$predicted.id))
incorrect <- length(which(pbmc.atac$seurat_annotations != pbmc.atac$predicted.id))
data <- FetchData(pbmc.atac, vars = c("prediction.score.max", "annotation_correct"))
p2 <- ggplot(data, aes(prediction.score.max, fill = annotation_correct, colour = annotation_correct)) +
    geom_density(alpha = 0.5) + theme_cowplot() + scale_fill_discrete(name = "Annotation Correct",
    labels = c(paste0("FALSE (n = ", incorrect, ")"), paste0("TRUE (n = ", correct, ")"))) + scale_color_discrete(name = "Annotation Correct",
    labels = c(paste0("FALSE (n = ", incorrect, ")"), paste0("TRUE (n = ", correct, ")"))) + xlab("Prediction Score")
p1 + p2
```

Example 41 (r):
```r
predictions <- table(pbmc.atac$seurat_annotations, pbmc.atac$predicted.id)
predictions <- predictions/rowSums(predictions)  # normalize for number of cells in each cell type
predictions <- as.data.frame(predictions)
p1 <- ggplot(predictions, aes(Var1, Var2, fill = Freq)) + geom_tile() + scale_fill_gradient(name = "Fraction of cells",
    low = "#ffffc8", high = "#7d0025") + xlab("Cell type annotation (RNA)") + ylab("Predicted cell type label (ATAC)") +
    theme_cowplot() + theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust = 1))

correct <- length(which(pbmc.atac$seurat_annotations == pbmc.atac$predicted.id))
incorrect <- length(which(pbmc.atac$seurat_annotations != pbmc.atac$predicted.id))
data <- FetchData(pbmc.atac, vars = c("prediction.score.max", "annotation_correct"))
p2 <- ggplot(data, aes(prediction.score.max, fill = annotation_correct, colour = annotation_correct)) +
    geom_density(alpha = 0.5) + theme_cowplot() + scale_fill_discrete(name = "Annotation Correct",
    labels = c(paste0("FALSE (n = ", incorrect, ")"), paste0("TRUE (n = ", correct, ")"))) + scale_color_discrete(name = "Annotation Correct",
    labels = c(paste0("FALSE (n = ", incorrect, ")"), paste0("TRUE (n = ", correct, ")"))) + xlab("Prediction Score")
p1 + p2
```

Example 42 (r):
```r
predictions <- table(pbmc.atac$seurat_annotations, pbmc.atac$predicted.id)
predictions <- predictions/rowSums(predictions)  # normalize for number of cells in each cell type
predictions <- as.data.frame(predictions)
p1 <- ggplot(predictions, aes(Var1, Var2, fill = Freq)) + geom_tile() + scale_fill_gradient(name = "Fraction of cells",
    low = "#ffffc8", high = "#7d0025") + xlab("Cell type annotation (RNA)") + ylab("Predicted cell type label (ATAC)") +
    theme_cowplot() + theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust = 1))

correct <- length(which(pbmc.atac$seurat_annotations == pbmc.atac$predicted.id))
incorrect <- length(which(pbmc.atac$seurat_annotations != pbmc.atac$predicted.id))
data <- FetchData(pbmc.atac, vars = c("prediction.score.max", "annotation_correct"))
p2 <- ggplot(data, aes(prediction.score.max, fill = annotation_correct, colour = annotation_correct)) +
    geom_density(alpha = 0.5) + theme_cowplot() + scale_fill_discrete(name = "Annotation Correct",
    labels = c(paste0("FALSE (n = ", incorrect, ")"), paste0("TRUE (n = ", correct, ")"))) + scale_color_discrete(name = "Annotation Correct",
    labels = c(paste0("FALSE (n = ", incorrect, ")"), paste0("TRUE (n = ", correct, ")"))) + xlab("Prediction Score")
p1 + p2
```

Example 43 (python):
```python
# note that we restrict the imputation to variable genes from scRNA-seq, but could impute the
# full transcriptome if we wanted to
genes.use <- VariableFeatures(pbmc.rna)
refdata <- GetAssayData(pbmc.rna, assay = "RNA", slot = "data")[genes.use, ]

# refdata (input) contains a scRNA-seq expression matrix for the scRNA-seq cells.  imputation
# (output) will contain an imputed scRNA-seq matrix for each of the ATAC cells
imputation <- TransferData(anchorset = transfer.anchors, refdata = refdata, weight.reduction = pbmc.atac[["lsi"]],
    dims = 2:30)
pbmc.atac[["RNA"]] <- imputation

coembed <- merge(x = pbmc.rna, y = pbmc.atac)

# Finally, we run PCA and UMAP on this combined object, to visualize the co-embedding of both
# datasets
coembed <- ScaleData(coembed, features = genes.use, do.scale = FALSE)
coembed <- RunPCA(coembed, features = genes.use, verbose = FALSE)
coembed <- RunUMAP(coembed, dims = 1:30)

DimPlot(coembed, group.by = c("orig.ident", "seurat_annotations"))
```

Example 44 (r):
```r
# note that we restrict the imputation to variable genes from scRNA-seq, but could impute the
# full transcriptome if we wanted to
genes.use <- VariableFeatures(pbmc.rna)
refdata <- GetAssayData(pbmc.rna, assay = "RNA", slot = "data")[genes.use, ]

# refdata (input) contains a scRNA-seq expression matrix for the scRNA-seq cells.  imputation
# (output) will contain an imputed scRNA-seq matrix for each of the ATAC cells
imputation <- TransferData(anchorset = transfer.anchors, refdata = refdata, weight.reduction = pbmc.atac[["lsi"]],
    dims = 2:30)
pbmc.atac[["RNA"]] <- imputation

coembed <- merge(x = pbmc.rna, y = pbmc.atac)

# Finally, we run PCA and UMAP on this combined object, to visualize the co-embedding of both
# datasets
coembed <- ScaleData(coembed, features = genes.use, do.scale = FALSE)
coembed <- RunPCA(coembed, features = genes.use, verbose = FALSE)
coembed <- RunUMAP(coembed, dims = 1:30)

DimPlot(coembed, group.by = c("orig.ident", "seurat_annotations"))
```

Example 45 (r):
```r
# note that we restrict the imputation to variable genes from scRNA-seq, but could impute the
# full transcriptome if we wanted to
genes.use <- VariableFeatures(pbmc.rna)
refdata <- GetAssayData(pbmc.rna, assay = "RNA", slot = "data")[genes.use, ]

# refdata (input) contains a scRNA-seq expression matrix for the scRNA-seq cells.  imputation
# (output) will contain an imputed scRNA-seq matrix for each of the ATAC cells
imputation <- TransferData(anchorset = transfer.anchors, refdata = refdata, weight.reduction = pbmc.atac[["lsi"]],
    dims = 2:30)
pbmc.atac[["RNA"]] <- imputation

coembed <- merge(x = pbmc.rna, y = pbmc.atac)

# Finally, we run PCA and UMAP on this combined object, to visualize the co-embedding of both
# datasets
coembed <- ScaleData(coembed, features = genes.use, do.scale = FALSE)
coembed <- RunPCA(coembed, features = genes.use, verbose = FALSE)
coembed <- RunUMAP(coembed, dims = 1:30)

DimPlot(coembed, group.by = c("orig.ident", "seurat_annotations"))
```

Example 46 (unknown):
```unknown
sessionInfo()
```

Example 47 (r):
```r
sessionInfo()
```

Example 48 (r):
```r
sessionInfo()
```

Example 49 (unknown):
```unknown
## R version 4.2.2 Patched (2022-11-10 r83330)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.6 LTS
## 
## Matrix products: default
## BLAS:   /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.9.0
## LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.9.0
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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       
## 
## attached base packages:
## [1] stats4    stats     graphics  grDevices utils     datasets  methods  
## [8] base     
## 
## other attached packages:
##  [1] cowplot_1.1.1                 ggplot2_3.4.4                
##  [3] EnsDb.Hsapiens.v86_2.99.0     ensembldb_2.22.0             
##  [5] AnnotationFilter_1.22.0       GenomicFeatures_1.50.4       
##  [7] AnnotationDbi_1.60.2          Biobase_2.58.0               
##  [9] GenomicRanges_1.50.2          GenomeInfoDb_1.34.9          
## [11] IRanges_2.32.0                S4Vectors_0.36.2             
## [13] BiocGenerics_0.44.0           Signac_1.12.9000             
## [15] Seurat_5.0.1                  SeuratObject_5.0.1           
## [17] sp_2.1-1                      thp1.eccite.SeuratData_3.1.5 
## [19] stxBrain.SeuratData_0.1.1     ssHippo.SeuratData_3.1.4     
## [21] pbmcsca.SeuratData_3.0.0      pbmcref.SeuratData_1.0.0     
## [23] pbmcMultiome.SeuratData_0.1.4 pbmc3k.SeuratData_3.1.4      
## [25] panc8.SeuratData_3.0.2        ifnb.SeuratData_3.0.0        
## [27] hcabm40k.SeuratData_3.0.0     cbmc.SeuratData_3.1.4        
## [29] bmcite.SeuratData_0.3.0       SeuratData_0.2.2.9001        
## 
## loaded via a namespace (and not attached):
##   [1] rappdirs_0.3.3              rtracklayer_1.58.0         
##   [3] scattermore_1.2             ragg_1.2.5                 
##   [5] tidyr_1.3.0                 bit64_4.0.5                
##   [7] knitr_1.45                  irlba_2.3.5.1              
##   [9] DelayedArray_0.24.0         data.table_1.14.8          
##  [11] rpart_4.1.19                KEGGREST_1.38.0            
##  [13] RCurl_1.98-1.12             generics_0.1.3             
##  [15] RSQLite_2.3.1               RANN_2.6.1                 
##  [17] future_1.33.0               bit_4.0.5                  
##  [19] spatstat.data_3.0-3         xml2_1.3.5                 
##  [21] httpuv_1.6.12               SummarizedExperiment_1.28.0
##  [23] xfun_0.40                   hms_1.1.3                  
##  [25] jquerylib_0.1.4             evaluate_0.22              
##  [27] promises_1.2.1              fansi_1.0.5                
##  [29] restfulr_0.0.15             progress_1.2.2             
##  [31] dbplyr_2.3.4                igraph_1.5.1               
##  [33] DBI_1.1.3                   htmlwidgets_1.6.2          
##  [35] spatstat.geom_3.2-7         purrr_1.0.2                
##  [37] ellipsis_0.3.2              RSpectra_0.16-1            
##  [39] dplyr_1.1.3                 backports_1.4.1            
##  [41] biomaRt_2.54.1              deldir_1.0-9               
##  [43] MatrixGenerics_1.10.0       vctrs_0.6.4                
##  [45] ROCR_1.0-11                 abind_1.4-5                
##  [47] cachem_1.0.8                withr_2.5.2                
##  [49] BSgenome_1.66.3             progressr_0.14.0           
##  [51] checkmate_2.2.0             sctransform_0.4.1          
##  [53] GenomicAlignments_1.34.1    prettyunits_1.1.1          
##  [55] goftest_1.2-3               cluster_2.1.4              
##  [57] dotCall64_1.1-0             lazyeval_0.2.2             
##  [59] crayon_1.5.2                spatstat.explore_3.2-5     
##  [61] labeling_0.4.3              pkgconfig_2.0.3            
##  [63] nlme_3.1-162                ProtGenerics_1.30.0        
##  [65] nnet_7.3-18                 rlang_1.1.1                
##  [67] globals_0.16.2              lifecycle_1.0.3            
##  [69] miniUI_0.1.1.1              filelock_1.0.2             
##  [71] fastDummies_1.7.3           BiocFileCache_2.6.1        
##  [73] dichromat_2.0-0.1           rprojroot_2.0.3            
##  [75] polyclip_1.10-6             RcppHNSW_0.5.0             
##  [77] matrixStats_1.0.0           lmtest_0.9-40              
##  [79] Matrix_1.6-1.1              zoo_1.8-12                 
##  [81] base64enc_0.1-3             ggridges_0.5.4             
##  [83] png_0.1-8                   viridisLite_0.4.2          
##  [85] rjson_0.2.21                bitops_1.0-7               
##  [87] KernSmooth_2.23-22          spam_2.10-0                
##  [89] Biostrings_2.66.0           blob_1.2.4                 
##  [91] stringr_1.5.0               parallelly_1.36.0          
##  [93] spatstat.random_3.2-1       scales_1.2.1               
##  [95] memoise_2.0.1               magrittr_2.0.3             
##  [97] plyr_1.8.9                  ica_1.0-3                  
##  [99] zlibbioc_1.44.0             compiler_4.2.2             
## [101] BiocIO_1.8.0                RColorBrewer_1.1-3         
## [103] fitdistrplus_1.1-11         Rsamtools_2.14.0           
## [105] cli_3.6.1                   XVector_0.38.0             
## [107] listenv_0.9.0               patchwork_1.1.3            
## [109] pbapply_1.7-2               htmlTable_2.4.1            
## [111] formatR_1.14                Formula_1.2-5              
## [113] MASS_7.3-58.2               tidyselect_1.2.0           
## [115] stringi_1.7.12              textshaping_0.3.6          
## [117] highr_0.10                  yaml_2.3.7                 
## [119] ggrepel_0.9.4               grid_4.2.2                 
## [121] VariantAnnotation_1.44.1    sass_0.4.7                 
## [123] fastmatch_1.1-4             tools_4.2.2                
## [125] future.apply_1.11.0         parallel_4.2.2             
## [127] rstudioapi_0.14             foreign_0.8-84             
## [129] gridExtra_2.3               farver_2.1.1               
## [131] Rtsne_0.16                  digest_0.6.33              
## [133] shiny_1.7.5.1               Rcpp_1.0.11                
## [135] later_1.3.1                 RcppAnnoy_0.0.21           
## [137] httr_1.4.7                  biovizBase_1.46.0          
## [139] colorspace_2.1-0            XML_3.99-0.14              
## [141] fs_1.6.3                    tensor_1.5                 
## [143] reticulate_1.34.0           splines_4.2.2              
## [145] uwot_0.1.16                 RcppRoll_0.3.0             
## [147] spatstat.utils_3.0-4        pkgdown_2.0.7              
## [149] plotly_4.10.3               systemfonts_1.0.4          
## [151] xtable_1.8-4                jsonlite_1.8.7             
## [153] R6_2.5.1                    Hmisc_5.1-1                
## [155] pillar_1.9.0                htmltools_0.5.6.1          
## [157] mime_0.12                   glue_1.6.2                 
## [159] fastmap_1.1.1               BiocParallel_1.32.6        
## [161] codetools_0.2-19            utf8_1.2.4                 
## [163] lattice_0.21-9              bslib_0.5.1                
## [165] spatstat.sparse_3.0-3       tibble_3.2.1               
## [167] curl_5.1.0                  leiden_0.4.3               
## [169] survival_3.5-7              rmarkdown_2.25             
## [171] desc_1.4.2                  munsell_0.5.0              
## [173] GenomeInfoDbData_1.2.9      reshape2_1.4.4             
## [175] gtable_0.3.4
```

Example 50 (unknown):
```unknown
## R version 4.2.2 Patched (2022-11-10 r83330)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.6 LTS
## 
## Matrix products: default
## BLAS:   /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.9.0
## LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.9.0
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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       
## 
## attached base packages:
## [1] stats4    stats     graphics  grDevices utils     datasets  methods  
## [8] base     
## 
## other attached packages:
##  [1] cowplot_1.1.1                 ggplot2_3.4.4                
##  [3] EnsDb.Hsapiens.v86_2.99.0     ensembldb_2.22.0             
##  [5] AnnotationFilter_1.22.0       GenomicFeatures_1.50.4       
##  [7] AnnotationDbi_1.60.2          Biobase_2.58.0               
##  [9] GenomicRanges_1.50.2          GenomeInfoDb_1.34.9          
## [11] IRanges_2.32.0                S4Vectors_0.36.2             
## [13] BiocGenerics_0.44.0           Signac_1.12.9000             
## [15] Seurat_5.0.1                  SeuratObject_5.0.1           
## [17] sp_2.1-1                      thp1.eccite.SeuratData_3.1.5 
## [19] stxBrain.SeuratData_0.1.1     ssHippo.SeuratData_3.1.4     
## [21] pbmcsca.SeuratData_3.0.0      pbmcref.SeuratData_1.0.0     
## [23] pbmcMultiome.SeuratData_0.1.4 pbmc3k.SeuratData_3.1.4      
## [25] panc8.SeuratData_3.0.2        ifnb.SeuratData_3.0.0        
## [27] hcabm40k.SeuratData_3.0.0     cbmc.SeuratData_3.1.4        
## [29] bmcite.SeuratData_0.3.0       SeuratData_0.2.2.9001        
## 
## loaded via a namespace (and not attached):
##   [1] rappdirs_0.3.3              rtracklayer_1.58.0         
##   [3] scattermore_1.2             ragg_1.2.5                 
##   [5] tidyr_1.3.0                 bit64_4.0.5                
##   [7] knitr_1.45                  irlba_2.3.5.1              
##   [9] DelayedArray_0.24.0         data.table_1.14.8          
##  [11] rpart_4.1.19                KEGGREST_1.38.0            
##  [13] RCurl_1.98-1.12             generics_0.1.3             
##  [15] RSQLite_2.3.1               RANN_2.6.1                 
##  [17] future_1.33.0               bit_4.0.5                  
##  [19] spatstat.data_3.0-3         xml2_1.3.5                 
##  [21] httpuv_1.6.12               SummarizedExperiment_1.28.0
##  [23] xfun_0.40                   hms_1.1.3                  
##  [25] jquerylib_0.1.4             evaluate_0.22              
##  [27] promises_1.2.1              fansi_1.0.5                
##  [29] restfulr_0.0.15             progress_1.2.2             
##  [31] dbplyr_2.3.4                igraph_1.5.1               
##  [33] DBI_1.1.3                   htmlwidgets_1.6.2          
##  [35] spatstat.geom_3.2-7         purrr_1.0.2                
##  [37] ellipsis_0.3.2              RSpectra_0.16-1            
##  [39] dplyr_1.1.3                 backports_1.4.1            
##  [41] biomaRt_2.54.1              deldir_1.0-9               
##  [43] MatrixGenerics_1.10.0       vctrs_0.6.4                
##  [45] ROCR_1.0-11                 abind_1.4-5                
##  [47] cachem_1.0.8                withr_2.5.2                
##  [49] BSgenome_1.66.3             progressr_0.14.0           
##  [51] checkmate_2.2.0             sctransform_0.4.1          
##  [53] GenomicAlignments_1.34.1    prettyunits_1.1.1          
##  [55] goftest_1.2-3               cluster_2.1.4              
##  [57] dotCall64_1.1-0             lazyeval_0.2.2             
##  [59] crayon_1.5.2                spatstat.explore_3.2-5     
##  [61] labeling_0.4.3              pkgconfig_2.0.3            
##  [63] nlme_3.1-162                ProtGenerics_1.30.0        
##  [65] nnet_7.3-18                 rlang_1.1.1                
##  [67] globals_0.16.2              lifecycle_1.0.3            
##  [69] miniUI_0.1.1.1              filelock_1.0.2             
##  [71] fastDummies_1.7.3           BiocFileCache_2.6.1        
##  [73] dichromat_2.0-0.1           rprojroot_2.0.3            
##  [75] polyclip_1.10-6             RcppHNSW_0.5.0             
##  [77] matrixStats_1.0.0           lmtest_0.9-40              
##  [79] Matrix_1.6-1.1              zoo_1.8-12                 
##  [81] base64enc_0.1-3             ggridges_0.5.4             
##  [83] png_0.1-8                   viridisLite_0.4.2          
##  [85] rjson_0.2.21                bitops_1.0-7               
##  [87] KernSmooth_2.23-22          spam_2.10-0                
##  [89] Biostrings_2.66.0           blob_1.2.4                 
##  [91] stringr_1.5.0               parallelly_1.36.0          
##  [93] spatstat.random_3.2-1       scales_1.2.1               
##  [95] memoise_2.0.1               magrittr_2.0.3             
##  [97] plyr_1.8.9                  ica_1.0-3                  
##  [99] zlibbioc_1.44.0             compiler_4.2.2             
## [101] BiocIO_1.8.0                RColorBrewer_1.1-3         
## [103] fitdistrplus_1.1-11         Rsamtools_2.14.0           
## [105] cli_3.6.1                   XVector_0.38.0             
## [107] listenv_0.9.0               patchwork_1.1.3            
## [109] pbapply_1.7-2               htmlTable_2.4.1            
## [111] formatR_1.14                Formula_1.2-5              
## [113] MASS_7.3-58.2               tidyselect_1.2.0           
## [115] stringi_1.7.12              textshaping_0.3.6          
## [117] highr_0.10                  yaml_2.3.7                 
## [119] ggrepel_0.9.4               grid_4.2.2                 
## [121] VariantAnnotation_1.44.1    sass_0.4.7                 
## [123] fastmatch_1.1-4             tools_4.2.2                
## [125] future.apply_1.11.0         parallel_4.2.2             
## [127] rstudioapi_0.14             foreign_0.8-84             
## [129] gridExtra_2.3               farver_2.1.1               
## [131] Rtsne_0.16                  digest_0.6.33              
## [133] shiny_1.7.5.1               Rcpp_1.0.11                
## [135] later_1.3.1                 RcppAnnoy_0.0.21           
## [137] httr_1.4.7                  biovizBase_1.46.0          
## [139] colorspace_2.1-0            XML_3.99-0.14              
## [141] fs_1.6.3                    tensor_1.5                 
## [143] reticulate_1.34.0           splines_4.2.2              
## [145] uwot_0.1.16                 RcppRoll_0.3.0             
## [147] spatstat.utils_3.0-4        pkgdown_2.0.7              
## [149] plotly_4.10.3               systemfonts_1.0.4          
## [151] xtable_1.8-4                jsonlite_1.8.7             
## [153] R6_2.5.1                    Hmisc_5.1-1                
## [155] pillar_1.9.0                htmltools_0.5.6.1          
## [157] mime_0.12                   glue_1.6.2                 
## [159] fastmap_1.1.1               BiocParallel_1.32.6        
## [161] codetools_0.2-19            utf8_1.2.4                 
## [163] lattice_0.21-9              bslib_0.5.1                
## [165] spatstat.sparse_3.0-3       tibble_3.2.1               
## [167] curl_5.1.0                  leiden_0.4.3               
## [169] survival_3.5-7              rmarkdown_2.25             
## [171] desc_1.4.2                  munsell_0.5.0              
## [173] GenomeInfoDbData_1.2.9      reshape2_1.4.4             
## [175] gtable_0.3.4
```

---

## Analysis, visualization, and integration of Visium HD spatial datasets with Seurat • Seurat

**URL:** http://127.0.0.1:9173/seurat/articles/install_v5/index.html

**Contents:**
- Installation Instructions for Seurat
- Seurat 5: Install from CRAN
- Install previous versions of Seurat
  - Install Seurat v4
  - Older versions of Seurat
- Install the development version of Seurat
- Docker
- Contents

To install Seurat, R version 4.0 or greater is required. We also recommend installing R Studio.

Seurat is available on CRAN for all platforms. To install, run:

Seurat does not require, but makes use of, packages developed by other labs that can substantially enhance speed and performance. These include presto (Korunsky/Raychaudhari labs), BPCells (Greenleaf Lab), and glmGamPoi (Huber Lab). We recommend users install these along with Seurat:

We also recommend installing these additional packages, which are used in our vignettes, and enhance the functionality of Seurat:

Seurat v4.4.0 can be installed with the following commands:

Old versions of Seurat, from Seurat v2.0.1 and up, are hosted in CRAN’s archive. To install an old version of Seurat, run:

For versions of Seurat older than those not hosted on CRAN (versions 1.3.0 and 1.4.0), please download the packaged source code from our releases page and install from the tarball.

Install the development version of Seurat - directly from GitHub.

We provide docker images for Seurat via dockerhub.

To pull the latest image from the command line:

To use as a base image in a new Dockerfile:

Developed by Rahul Satija, Satija Lab and Collaborators.

Site built with pkgdown 2.0.7.

**Examples:**

Example 1 (unknown):
```unknown
vignettes/install_v5.Rmd
```

Example 2 (unknown):
```unknown
install_v5.Rmd
```

Example 3 (unknown):
```unknown
# Enter commands in R (or R studio, if installed)
install.packages('Seurat')
library(Seurat)
```

Example 4 (r):
```r
# Enter commands in R (or R studio, if installed)
install.packages('Seurat')
library(Seurat)
```

Example 5 (r):
```r
# Enter commands in R (or R studio, if installed)
install.packages('Seurat')
library(Seurat)
```

Example 6 (unknown):
```unknown
setRepositories(ind = 1:3, addURLs = c('https://satijalab.r-universe.dev', 'https://bnprks.r-universe.dev/'))
install.packages(c("BPCells", "presto", "glmGamPoi"))
```

Example 7 (r):
```r
setRepositories(ind = 1:3, addURLs = c('https://satijalab.r-universe.dev', 'https://bnprks.r-universe.dev/'))
install.packages(c("BPCells", "presto", "glmGamPoi"))
```

Example 8 (r):
```r
setRepositories(ind = 1:3, addURLs = c('https://satijalab.r-universe.dev', 'https://bnprks.r-universe.dev/'))
install.packages(c("BPCells", "presto", "glmGamPoi"))
```

Example 9 (unknown):
```unknown
# Install the remotes package
if (!requireNamespace("remotes", quietly = TRUE)) {
  install.packages("remotes")
}
install.packages('Signac')
remotes::install_github("satijalab/seurat-data", quiet = TRUE)
remotes::install_github("satijalab/azimuth", quiet = TRUE)
remotes::install_github("satijalab/seurat-wrappers", quiet = TRUE)
```

Example 10 (r):
```r
# Install the remotes package
if (!requireNamespace("remotes", quietly = TRUE)) {
  install.packages("remotes")
}
install.packages('Signac')
remotes::install_github("satijalab/seurat-data", quiet = TRUE)
remotes::install_github("satijalab/azimuth", quiet = TRUE)
remotes::install_github("satijalab/seurat-wrappers", quiet = TRUE)
```

Example 11 (r):
```r
# Install the remotes package
if (!requireNamespace("remotes", quietly = TRUE)) {
  install.packages("remotes")
}
install.packages('Signac')
remotes::install_github("satijalab/seurat-data", quiet = TRUE)
remotes::install_github("satijalab/azimuth", quiet = TRUE)
remotes::install_github("satijalab/seurat-wrappers", quiet = TRUE)
```

Example 12 (unknown):
```unknown
remotes::install_version("SeuratObject", "4.1.4", repos = c("https://satijalab.r-universe.dev", getOption("repos")))
remotes::install_version("Seurat", "4.4.0", repos = c("https://satijalab.r-universe.dev", getOption("repos")))
```

Example 13 (r):
```r
remotes::install_version("SeuratObject", "4.1.4", repos = c("https://satijalab.r-universe.dev", getOption("repos")))
remotes::install_version("Seurat", "4.4.0", repos = c("https://satijalab.r-universe.dev", getOption("repos")))
```

Example 14 (r):
```r
remotes::install_version("SeuratObject", "4.1.4", repos = c("https://satijalab.r-universe.dev", getOption("repos")))
remotes::install_version("Seurat", "4.4.0", repos = c("https://satijalab.r-universe.dev", getOption("repos")))
```

Example 15 (unknown):
```unknown
# Install the remotes package 
install.packages('remotes')
# Replace 'X.X.X' with your desired version
remotes::install_version(package = 'Seurat', version = package_version('X.X.X'))
```

Example 16 (r):
```r
# Install the remotes package 
install.packages('remotes')
# Replace 'X.X.X' with your desired version
remotes::install_version(package = 'Seurat', version = package_version('X.X.X'))
```

Example 17 (r):
```r
# Install the remotes package 
install.packages('remotes')
# Replace 'X.X.X' with your desired version
remotes::install_version(package = 'Seurat', version = package_version('X.X.X'))
```

Example 18 (unknown):
```unknown
# Enter commands in R (or R studio, if installed)
# Install the remotes package
install.packages('remotes')
remotes::install_github(repo = 'satijalab/seurat', ref = 'develop')
library(Seurat)
```

Example 19 (r):
```r
# Enter commands in R (or R studio, if installed)
# Install the remotes package
install.packages('remotes')
remotes::install_github(repo = 'satijalab/seurat', ref = 'develop')
library(Seurat)
```

Example 20 (r):
```r
# Enter commands in R (or R studio, if installed)
# Install the remotes package
install.packages('remotes')
remotes::install_github(repo = 'satijalab/seurat', ref = 'develop')
library(Seurat)
```

Example 21 (unknown):
```unknown
docker pull satijalab/seurat:latest
```

Example 22 (unknown):
```unknown
docker pull satijalab/seurat:latest
```

Example 23 (bash):
```bash
docker pull satijalab/seurat:latest
```

Example 24 (unknown):
```unknown
FROM satijalab/seurat:latest
```

Example 25 (unknown):
```unknown
FROM satijalab/seurat:latest
```

Example 26 (bash):
```bash
FROM satijalab/seurat:latest
```

---

## Integration and Label Transfer

**URL:** http://127.0.0.1:9173/seurat/archive/v3.1/integration/index.html

**Contents:**
- Integration and Label Transfer
    - Compiled: 2020-04-17
  - Intro: Seurat v3 Integration
  - Standard Workflow
    - Dataset preprocessing
    - Integration of 3 pancreatic islet cell datasets
    - Cell type classification using an integrated reference
  - SCTransform
  - Reference-based
  - Reciprocal PCA

As described in Stuart*, Butler*, et al. Cell 2019, Seurat v3 introduces new methods for the integration of multiple single-cell datasets. These methods aim to identify shared cell states that are present across different datasets, even if they were collected from different individuals, experimental conditions, technologies, or even species.

Our method aims to first identify ‘anchors’ between pairs of datasets. These represent pairwise correspondences between individual cells (one in each dataset), that we hypothesize originate from the same biological state. These ‘anchors’ are then used to harmonize the datasets, or transfer information from one dataset to another. Below, we demonstrate multiple applications of integrative analysis, and also introduce new functionality beyond what was described in the 2019 manuscript. To help guide users, we briefly introduce these vignettes below:

In this example workflow, we demonstrate two new methods we recently introduced in our paper, Comprehensive Integration of Single Cell Data:

For the purposes of this example, we’ve chosen human pancreatic islet cell datasets produced across four technologies, CelSeq (GSE81076) CelSeq2 (GSE85241), Fluidigm C1 (GSE86469), and SMART-Seq2 (E-MTAB-5061). For convienence, we distribute this dataset through our SeuratData package.

The code for the new methodology is implemented in Seurat v3. You can download and install from CRAN with install.packages.

In addition to new methods, Seurat v3 includes a number of improvements aiming to improve the Seurat object and user interaction. To help users familiarize themselves with these changes, we put together a command cheat sheet for common tasks.

Load in the dataset. The metadata contains the technology (tech column) and cell type annotations (celltype column) for each cell in the four datasets.

To construct a reference, we will identify ‘anchors’ between the individual datasets. First, we split the combined object into a list, with each dataset as an element.

Prior to finding anchors, we perform standard preprocessing (log-normalization), and identify variable features individually for each. Note that Seurat v3 implements an improved method for variable feature selection based on a variance stabilizing transformation ("vst")

Next, we identify anchors using the FindIntegrationAnchors function, which takes a list of Seurat objects as input. Here, we integrate three of the objects into a reference (we will use the fourth later in this vignette)

We then pass these anchors to the IntegrateData function, which returns a Seurat object.

After running IntegrateData, the Seurat object will contain a new Assay with the integrated expression matrix. Note that the original (uncorrected values) are still stored in the object in the “RNA” assay, so you can switch back and forth.

We can then use this new integrated matrix for downstream analysis and visualization. Here we scale the integrated data, run PCA, and visualize the results with UMAP. The integrated datasets cluster by cell type, instead of by technology.

Seurat v3 also supports the projection of reference data (or meta data) onto a query object. While many of the methods are conserved (both procedures begin by identifying anchors), there are two important distinctions between data transfer and integration:

After finding anchors, we use the TransferData function to classify the query cells based on reference data (a vector of reference cell type labels). TransferData returns a matrix with predicted IDs and prediction scores, which we can add to the query metadata.

Because we have the original label annotations from our full integrated analysis, we can evaluate how well our predicted cell type annotations match the full reference. In this example, we find that there is a high agreement in cell type classification, with over 97% of cells being labeled correctly.

To verify this further, we can examine some canonical cell type markers for specific pancreatic islet cell populations. Note that even though some of these cell types are only represented by one or two cells (e.g. epsilon cells), we are still able to classify them correctly.

On the previous tab, we demonstrate how to integrate datasets after each has been pre-processed using standard log-normalization. Here, we modify the workflow to take advantage of our improved pre-processing and normalization workflow: SCTransform. You can read more about SCTransform in our recent preprint, and see how to apply it to a single dataset in a separate vignette. We suggest exploring these resources before proceeding.

Conceptually, this workflow is very similar to what we have previously introduced, where we ‘correct’ (or harmonize) log-normalized expression values across datasets. Here, instead, we will harmonize the Pearson residuals that are output from SCTransform. As demonstrated below, the workflow consists of the following steps:

First, setup the Seurat object list, and run SCTransform on each object separately:

Next, select features for downstream integration, and run PrepSCTIntegration, which ensures that all necessary Pearson residuals have been calculated.

Next, identify anchors and integrate the datasets. Commands are identical to the standard workflow, but make sure to set normalization.method = 'SCT':

Now proceed with downstream analysis (i.e. visualization, clustering) on the integrated dataset. Commands are identical to the standard workflow, but do not run the ScaleData function after integration. You can see that after integration, cells group by their biological cell type (which has been pre-annotated), instead of by their underlying technology.

To further demonstrate this workflow, we next apply it to a series of human PBMC datasets from eight different technologies, produced as a systematic technology benchmark by the Human Cell Atlas. Data was downloaded from the Broad Single Cell Portal. For convienence, we distribute this dataset through our SeuratData package.

Note that again, cells are grouped together by shared biological subtype, instead of by technology. In this case, the authors labeled “CellType” in each dataset independently, and you can see that this is consistent with our integrated analysis:

However, our integrated analysis reveals finer subdivisions amongst these broad cell types, since the combined dataset has substantially greater statistical power. We don’t do a full clustering here on the integrated dataset, but note that we can observe subpopulations of CD4+ (Memory/Naive), CD8 (multiple cytotoxic populations), and B cells (multiple developmental stages). Below, we visualize the expression of the original measurements on our integrated visualization (note that you can add split.by = 'Method to make these plots for each technology independently)"

Here, we present an additional modification to the Seurat integration workflow, which we refer to as ‘Reference-based’ integration. In the previous workflows, we identify anchors between all pairs of datasets. While this gives datasets equal weight in downstream integration, it can also become computationally intensive. For example, when integrating 10 different datasets, we perform 45 different pairwise comparisons.

As an alternative, we introduce here the possibility of specifying one or more of the datasets as the ‘reference’ for integrated analysis, with the remainder designated as ‘query’ datasets. In this workflow, we do not identify anchors between pairs of query datasets, reducing the number of comparisons. For example, when integrating 10 datasets with one specified as a reference, we perform only 9 comparisons. Reference-based integration can be applied to either log-normalized or SCTransform-normalized datasets.

In practice, we often observe very similar results between the approaches, but with substantially reduced computational time. We demonstrate this using the same PBMC analysis as in the previous tab with highly concordant outputs. We therefore recommend this workflow for users who are integrating a large number of datasets, and desire increased computational efficiency.

This approach does require users to pre-select datasets to serve as a reference. In this example, we use the 10X v3 dataset, as the dataset contains both high cell number and high sensitivity. Users can apply similar criteria when selecting a reference. Furthermore, you can change this setting in the workflow below (for example, try selecting the 10X v2, or Drop-seq datasets as a reference), with only very minor differences in the final result.

The workflow is demonstrated below. Commands are identical to the previous tab, except that we specify a reference argument in the FindIntegrationAnchors function. Data was originally downloaded from the Broad Single Cell Portal but for convienence, we distribute this dataset through our SeuratData package.

For very large datasets, Canonical Correlation Analysis can sometimes become a prohibitively computationally expensive step. In this workflow, we introduce an alternate form of dimension reduction, reciprocal PCA, to identify an effective space in which to find anchors. When determining anchors between any two datasets using reciprocal PCA, we project each dataset into the other’s PCA space and constrain the anchors by the same mutual neighborhood requirement. All downstream integration steps remain the same and we are able to ‘correct’ (or harmonize) the datasets.

As demonstrated below, the workflow consists of the following steps:

In general, we observe strikingly similar results between the two workflows, but with substantial reduction in compute time and memory when using reciprocal PCA. However, if the datasets are highly divergent (for example, cross-modality mapping or cross-species mapping), where only a small subset of features can be used to facilitate integration, and you may observe superior results using CCA.

For large studies with many datasets, we recommend also combining reciprocal PCA with reference-based integration, or SCTransform normalization (see details on previous tab).

For these examples, we will be using the “Immune Cell Atlas” data from the Human Cell Atlas which can be found here. First, we will integrate a randomly downsampled version of this dataset and then the full dataset. The randomly downsampled version contains 40K cells (5K from each donor) and is available through our new SeuratData package.

After acquiring the data, we first perform standard normalization and variable feature selection.

Next, select features for downstream integration, and run PCA on each object in the list, which is required for running the reciprocal PCA workflow.

Since this dataset contains both men and women, we will chose one male and one female (BM1 and BM2) to use in the reference-based workflow. We determined donor sex by examining the expression of the XIST gene. Next, identify anchors and integrate the datasets. Commands are identical to the standard workflow, but make sure to set reduction = 'rpca':

Now proceed with downstream analysis (i.e. visualization, clustering) on the integrated dataset. Commands are identical to the standard workflow.

To further demonstrate this workflow, we next apply it to the full dataset. While we do not provide this through SeuratData, you can find the counts matrix on the HCA Data Portal site. The commands below are identical to the 40k integration except we’ve increased the dimensionality to 50 to reflect the increased cell number and diversity.

**Examples:**

Example 1 (unknown):
```unknown
install.packages
```

Example 2 (r):
```r
install.packages("Seurat")
```

Example 3 (r):
```r
install.packages("Seurat")
```

Example 4 (r):
```r
library(Seurat)
library(SeuratData)
```

Example 5 (r):
```r
library(Seurat)
library(SeuratData)
```

Example 6 (r):
```r
InstallData("panc8")
```

Example 7 (r):
```r
InstallData("panc8")
```

Example 8 (r):
```r
data("panc8")
pancreas.list <- SplitObject(panc8, split.by = "tech")
pancreas.list <- pancreas.list[c("celseq", "celseq2", "fluidigmc1", "smartseq2")]
```

Example 9 (r):
```r
data("panc8")
pancreas.list <- SplitObject(panc8, split.by = "tech")
pancreas.list <- pancreas.list[c("celseq", "celseq2", "fluidigmc1", "smartseq2")]
```

Example 10 (r):
```r
for (i in 1:length(pancreas.list)) {
    pancreas.list[[i]] <- NormalizeData(pancreas.list[[i]], verbose = FALSE)
    pancreas.list[[i]] <- FindVariableFeatures(pancreas.list[[i]], selection.method = "vst", 
        nfeatures = 2000, verbose = FALSE)
}
```

Example 11 (r):
```r
for (i in 1:length(pancreas.list)) {
    pancreas.list[[i]] <- NormalizeData(pancreas.list[[i]], verbose = FALSE)
    pancreas.list[[i]] <- FindVariableFeatures(pancreas.list[[i]], selection.method = "vst", 
        nfeatures = 2000, verbose = FALSE)
}
```

Example 12 (unknown):
```unknown
FindIntegrationAnchors
```

Example 13 (r):
```r
reference.list <- pancreas.list[c("celseq", "celseq2", "smartseq2")]
pancreas.anchors <- FindIntegrationAnchors(object.list = reference.list, dims = 1:30)
```

Example 14 (r):
```r
reference.list <- pancreas.list[c("celseq", "celseq2", "smartseq2")]
pancreas.anchors <- FindIntegrationAnchors(object.list = reference.list, dims = 1:30)
```

Example 15 (unknown):
```unknown
IntegrateData
```

Example 16 (r):
```r
pancreas.integrated <- IntegrateData(anchorset = pancreas.anchors, dims = 1:30)
```

Example 17 (r):
```r
pancreas.integrated <- IntegrateData(anchorset = pancreas.anchors, dims = 1:30)
```

Example 18 (unknown):
```unknown
IntegrateData
```

Example 19 (r):
```r
library(ggplot2)
library(cowplot)
library(patchwork)
# switch to integrated assay. The variable features of this assay are automatically
# set during IntegrateData
DefaultAssay(pancreas.integrated) <- "integrated"

# Run the standard workflow for visualization and clustering
pancreas.integrated <- ScaleData(pancreas.integrated, verbose = FALSE)
pancreas.integrated <- RunPCA(pancreas.integrated, npcs = 30, verbose = FALSE)
pancreas.integrated <- RunUMAP(pancreas.integrated, reduction = "pca", dims = 1:30)
p1 <- DimPlot(pancreas.integrated, reduction = "umap", group.by = "tech")
p2 <- DimPlot(pancreas.integrated, reduction = "umap", group.by = "celltype", label = TRUE, 
    repel = TRUE) + NoLegend()
p1 + p2
```

Example 20 (r):
```r
library(ggplot2)
library(cowplot)
library(patchwork)
# switch to integrated assay. The variable features of this assay are automatically
# set during IntegrateData
DefaultAssay(pancreas.integrated) <- "integrated"

# Run the standard workflow for visualization and clustering
pancreas.integrated <- ScaleData(pancreas.integrated, verbose = FALSE)
pancreas.integrated <- RunPCA(pancreas.integrated, npcs = 30, verbose = FALSE)
pancreas.integrated <- RunUMAP(pancreas.integrated, reduction = "pca", dims = 1:30)
p1 <- DimPlot(pancreas.integrated, reduction = "umap", group.by = "tech")
p2 <- DimPlot(pancreas.integrated, reduction = "umap", group.by = "celltype", label = TRUE, 
    repel = TRUE) + NoLegend()
p1 + p2
```

Example 21 (unknown):
```unknown
TransferData
```

Example 22 (unknown):
```unknown
TransferData
```

Example 23 (r):
```r
pancreas.query <- pancreas.list[["fluidigmc1"]]
pancreas.anchors <- FindTransferAnchors(reference = pancreas.integrated, query = pancreas.query, 
    dims = 1:30)
predictions <- TransferData(anchorset = pancreas.anchors, refdata = pancreas.integrated$celltype, 
    dims = 1:30)
pancreas.query <- AddMetaData(pancreas.query, metadata = predictions)
```

Example 24 (r):
```r
pancreas.query <- pancreas.list[["fluidigmc1"]]
pancreas.anchors <- FindTransferAnchors(reference = pancreas.integrated, query = pancreas.query, 
    dims = 1:30)
predictions <- TransferData(anchorset = pancreas.anchors, refdata = pancreas.integrated$celltype, 
    dims = 1:30)
pancreas.query <- AddMetaData(pancreas.query, metadata = predictions)
```

Example 25 (r):
```r
pancreas.query$prediction.match <- pancreas.query$predicted.id == pancreas.query$celltype
table(pancreas.query$prediction.match)
```

Example 26 (r):
```r
pancreas.query$prediction.match <- pancreas.query$predicted.id == pancreas.query$celltype
table(pancreas.query$prediction.match)
```

Example 27 (unknown):
```unknown
## 
## FALSE  TRUE 
##    18   620
```

Example 28 (unknown):
```unknown
## 
## FALSE  TRUE 
##    18   620
```

Example 29 (r):
```r
table(pancreas.query$predicted.id)
```

Example 30 (r):
```r
table(pancreas.query$predicted.id)
```

Example 31 (unknown):
```unknown
## 
##             acinar activated_stellate              alpha               beta 
##                 21                 17                248                258 
##              delta             ductal        endothelial            epsilon 
##                 22                 33                 13                  1 
##              gamma         macrophage               mast            schwann 
##                 17                  1                  2                  5
```

Example 32 (unknown):
```unknown
## 
##             acinar activated_stellate              alpha               beta 
##                 21                 17                248                258 
##              delta             ductal        endothelial            epsilon 
##                 22                 33                 13                  1 
##              gamma         macrophage               mast            schwann 
##                 17                  1                  2                  5
```

Example 33 (r):
```r
VlnPlot(pancreas.query, c("REG1A", "PPY", "SST", "GHRL", "VWF", "SOX10"), group.by = "predicted.id")
```

Example 34 (r):
```r
VlnPlot(pancreas.query, c("REG1A", "PPY", "SST", "GHRL", "VWF", "SOX10"), group.by = "predicted.id")
```

Example 35 (r):
```r
library(Seurat)
library(ggplot2)
library(patchwork)
options(future.globals.maxSize = 4000 * 1024^2)
data("panc8")
pancreas.list <- SplitObject(panc8, split.by = "tech")
pancreas.list <- pancreas.list[c("celseq", "celseq2", "fluidigmc1", "smartseq2")]
for (i in 1:length(pancreas.list)) {
    pancreas.list[[i]] <- SCTransform(pancreas.list[[i]], verbose = FALSE)
}
```

Example 36 (r):
```r
library(Seurat)
library(ggplot2)
library(patchwork)
options(future.globals.maxSize = 4000 * 1024^2)
data("panc8")
pancreas.list <- SplitObject(panc8, split.by = "tech")
pancreas.list <- pancreas.list[c("celseq", "celseq2", "fluidigmc1", "smartseq2")]
for (i in 1:length(pancreas.list)) {
    pancreas.list[[i]] <- SCTransform(pancreas.list[[i]], verbose = FALSE)
}
```

Example 37 (unknown):
```unknown
PrepSCTIntegration
```

Example 38 (r):
```r
pancreas.features <- SelectIntegrationFeatures(object.list = pancreas.list, nfeatures = 3000)
pancreas.list <- PrepSCTIntegration(object.list = pancreas.list, anchor.features = pancreas.features, 
    verbose = FALSE)
```

Example 39 (r):
```r
pancreas.features <- SelectIntegrationFeatures(object.list = pancreas.list, nfeatures = 3000)
pancreas.list <- PrepSCTIntegration(object.list = pancreas.list, anchor.features = pancreas.features, 
    verbose = FALSE)
```

Example 40 (unknown):
```unknown
normalization.method = 'SCT'
```

Example 41 (r):
```r
pancreas.anchors <- FindIntegrationAnchors(object.list = pancreas.list, normalization.method = "SCT", 
    anchor.features = pancreas.features, verbose = FALSE)
pancreas.integrated <- IntegrateData(anchorset = pancreas.anchors, normalization.method = "SCT", 
    verbose = FALSE)
```

Example 42 (r):
```r
pancreas.anchors <- FindIntegrationAnchors(object.list = pancreas.list, normalization.method = "SCT", 
    anchor.features = pancreas.features, verbose = FALSE)
pancreas.integrated <- IntegrateData(anchorset = pancreas.anchors, normalization.method = "SCT", 
    verbose = FALSE)
```

Example 43 (r):
```r
pancreas.integrated <- RunPCA(pancreas.integrated, verbose = FALSE)
pancreas.integrated <- RunUMAP(pancreas.integrated, dims = 1:30)
plots <- DimPlot(pancreas.integrated, group.by = c("tech", "celltype"))
plots & theme(legend.position = "top") & guides(color = guide_legend(nrow = 3, byrow = TRUE, 
    override.aes = list(size = 3)))
```

Example 44 (r):
```r
pancreas.integrated <- RunPCA(pancreas.integrated, verbose = FALSE)
pancreas.integrated <- RunUMAP(pancreas.integrated, dims = 1:30)
plots <- DimPlot(pancreas.integrated, group.by = c("tech", "celltype"))
plots & theme(legend.position = "top") & guides(color = guide_legend(nrow = 3, byrow = TRUE, 
    override.aes = list(size = 3)))
```

Example 45 (r):
```r
InstallData("pbmcsca")
```

Example 46 (r):
```r
InstallData("pbmcsca")
```

Example 47 (r):
```r
data("pbmcsca")
pbmc.list <- SplitObject(pbmcsca, split.by = "Method")
for (i in names(pbmc.list)) {
    pbmc.list[[i]] <- SCTransform(pbmc.list[[i]], verbose = FALSE)
}
pbmc.features <- SelectIntegrationFeatures(object.list = pbmc.list, nfeatures = 3000)
pbmc.list <- PrepSCTIntegration(object.list = pbmc.list, anchor.features = pbmc.features)
pbmc.anchors <- FindIntegrationAnchors(object.list = pbmc.list, normalization.method = "SCT", 
    anchor.features = pbmc.features)
pbmc.integrated <- IntegrateData(anchorset = pbmc.anchors, normalization.method = "SCT")

pbmc.integrated <- RunPCA(object = pbmc.integrated, verbose = FALSE)
pbmc.integrated <- RunUMAP(object = pbmc.integrated, dims = 1:30)
```

Example 48 (r):
```r
data("pbmcsca")
pbmc.list <- SplitObject(pbmcsca, split.by = "Method")
for (i in names(pbmc.list)) {
    pbmc.list[[i]] <- SCTransform(pbmc.list[[i]], verbose = FALSE)
}
pbmc.features <- SelectIntegrationFeatures(object.list = pbmc.list, nfeatures = 3000)
pbmc.list <- PrepSCTIntegration(object.list = pbmc.list, anchor.features = pbmc.features)
pbmc.anchors <- FindIntegrationAnchors(object.list = pbmc.list, normalization.method = "SCT", 
    anchor.features = pbmc.features)
pbmc.integrated <- IntegrateData(anchorset = pbmc.anchors, normalization.method = "SCT")

pbmc.integrated <- RunPCA(object = pbmc.integrated, verbose = FALSE)
pbmc.integrated <- RunUMAP(object = pbmc.integrated, dims = 1:30)
```

Example 49 (r):
```r
plots <- DimPlot(pbmc.integrated, group.by = c("Method", "CellType"))
plots & theme(legend.position = "top") & guides(color = guide_legend(nrow = 4, byrow = TRUE, 
    override.aes = list(size = 2.5)))
```

Example 50 (r):
```r
plots <- DimPlot(pbmc.integrated, group.by = c("Method", "CellType"))
plots & theme(legend.position = "top") & guides(color = guide_legend(nrow = 4, byrow = TRUE, 
    override.aes = list(size = 2.5)))
```

Example 51 (r):
```r
DimPlot(pbmc.integrated, group.by = "CellType", split.by = "Method", ncol = 3)
```

Example 52 (r):
```r
DimPlot(pbmc.integrated, group.by = "CellType", split.by = "Method", ncol = 3)
```

Example 53 (unknown):
```unknown
split.by = 'Method
```

Example 54 (r):
```r
DefaultAssay(pbmc.integrated) <- "RNA"
# Normalize RNA data for visualization purposes
pbmc.integrated <- NormalizeData(pbmc.integrated, verbose = FALSE)
FeaturePlot(pbmc.integrated, c("CCR7", "S100A4", "GZMB", "GZMK", "GZMH", "TCL1A"))
```

Example 55 (r):
```r
DefaultAssay(pbmc.integrated) <- "RNA"
# Normalize RNA data for visualization purposes
pbmc.integrated <- NormalizeData(pbmc.integrated, verbose = FALSE)
FeaturePlot(pbmc.integrated, c("CCR7", "S100A4", "GZMB", "GZMK", "GZMH", "TCL1A"))
```

Example 56 (unknown):
```unknown
FindIntegrationAnchors
```

Example 57 (r):
```r
library(Seurat)
library(SeuratData)
library(ggplot2)
library(patchwork)
```

Example 58 (r):
```r
library(Seurat)
library(SeuratData)
library(ggplot2)
library(patchwork)
```

Example 59 (r):
```r
InstallData("pbmcsca")
```

Example 60 (r):
```r
InstallData("pbmcsca")
```

Example 61 (r):
```r
data("pbmcsca")
pbmc.list <- SplitObject(pbmcsca, split.by = "Method")
for (i in names(pbmc.list)) {
    pbmc.list[[i]] <- SCTransform(pbmc.list[[i]], verbose = FALSE)
}
pbmc.features <- SelectIntegrationFeatures(object.list = pbmc.list, nfeatures = 3000)
pbmc.list <- PrepSCTIntegration(object.list = pbmc.list, anchor.features = pbmc.features)

# This command returns dataset 5.  We can also specify multiple refs. (i.e. c(5,6))
reference_dataset <- which(names(pbmc.list) == "10x Chromium (v3)")

pbmc.anchors <- FindIntegrationAnchors(object.list = pbmc.list, normalization.method = "SCT", 
    anchor.features = pbmc.features, reference = reference_dataset)
pbmc.integrated <- IntegrateData(anchorset = pbmc.anchors, normalization.method = "SCT")

pbmc.integrated <- RunPCA(object = pbmc.integrated, verbose = FALSE)
pbmc.integrated <- RunUMAP(object = pbmc.integrated, dims = 1:30)
```

Example 62 (r):
```r
data("pbmcsca")
pbmc.list <- SplitObject(pbmcsca, split.by = "Method")
for (i in names(pbmc.list)) {
    pbmc.list[[i]] <- SCTransform(pbmc.list[[i]], verbose = FALSE)
}
pbmc.features <- SelectIntegrationFeatures(object.list = pbmc.list, nfeatures = 3000)
pbmc.list <- PrepSCTIntegration(object.list = pbmc.list, anchor.features = pbmc.features)

# This command returns dataset 5.  We can also specify multiple refs. (i.e. c(5,6))
reference_dataset <- which(names(pbmc.list) == "10x Chromium (v3)")

pbmc.anchors <- FindIntegrationAnchors(object.list = pbmc.list, normalization.method = "SCT", 
    anchor.features = pbmc.features, reference = reference_dataset)
pbmc.integrated <- IntegrateData(anchorset = pbmc.anchors, normalization.method = "SCT")

pbmc.integrated <- RunPCA(object = pbmc.integrated, verbose = FALSE)
pbmc.integrated <- RunUMAP(object = pbmc.integrated, dims = 1:30)
```

Example 63 (r):
```r
plots <- DimPlot(pbmc.integrated, group.by = c("Method", "CellType"))
plots & theme(legend.position = "top") & guides(color = guide_legend(nrow = 4, byrow = TRUE, 
    override.aes = list(size = 2.5)))
```

Example 64 (r):
```r
plots <- DimPlot(pbmc.integrated, group.by = c("Method", "CellType"))
plots & theme(legend.position = "top") & guides(color = guide_legend(nrow = 4, byrow = TRUE, 
    override.aes = list(size = 2.5)))
```

Example 65 (r):
```r
DefaultAssay(pbmc.integrated) <- "RNA"
# Normalize RNA data for visualization purposes
pbmc.integrated <- NormalizeData(pbmc.integrated, verbose = FALSE)
FeaturePlot(pbmc.integrated, c("CCR7", "S100A4", "GZMB", "GZMK", "GZMH", "TCL1A"))
```

Example 66 (r):
```r
DefaultAssay(pbmc.integrated) <- "RNA"
# Normalize RNA data for visualization purposes
pbmc.integrated <- NormalizeData(pbmc.integrated, verbose = FALSE)
FeaturePlot(pbmc.integrated, c("CCR7", "S100A4", "GZMB", "GZMK", "GZMH", "TCL1A"))
```

Example 67 (r):
```r
library(Seurat)
library(SeuratData)
```

Example 68 (r):
```r
library(Seurat)
library(SeuratData)
```

Example 69 (r):
```r
# Get data from seurat-data
InstallData(pkgs = "bm40k.SeuratData")
```

Example 70 (r):
```r
# Get data from seurat-data
InstallData(pkgs = "bm40k.SeuratData")
```

Example 71 (r):
```r
library(ggplot2)
# set up future for parallelization
library(future)
library(future.apply)
plan("multiprocess", workers = 4)
options(future.globals.maxSize = 20000 * 1024^2)
# load in the data
data(hcabm40k)
bm40k.list <- SplitObject(hcabm40k, split.by = "orig.ident")
bm40k.list <- lapply(X = bm40k.list, FUN = function(x) {
    x <- NormalizeData(x, verbose = FALSE)
    x <- FindVariableFeatures(x, verbose = FALSE)
})
```

Example 72 (r):
```r
library(ggplot2)
# set up future for parallelization
library(future)
library(future.apply)
plan("multiprocess", workers = 4)
options(future.globals.maxSize = 20000 * 1024^2)
# load in the data
data(hcabm40k)
bm40k.list <- SplitObject(hcabm40k, split.by = "orig.ident")
bm40k.list <- lapply(X = bm40k.list, FUN = function(x) {
    x <- NormalizeData(x, verbose = FALSE)
    x <- FindVariableFeatures(x, verbose = FALSE)
})
```

Example 73 (r):
```r
features <- SelectIntegrationFeatures(object.list = bm40k.list)
bm40k.list <- lapply(X = bm40k.list, FUN = function(x) {
    x <- ScaleData(x, features = features, verbose = FALSE)
    x <- RunPCA(x, features = features, verbose = FALSE)
})
```

Example 74 (r):
```r
features <- SelectIntegrationFeatures(object.list = bm40k.list)
bm40k.list <- lapply(X = bm40k.list, FUN = function(x) {
    x <- ScaleData(x, features = features, verbose = FALSE)
    x <- RunPCA(x, features = features, verbose = FALSE)
})
```

Example 75 (unknown):
```unknown
reduction = 'rpca'
```

Example 76 (r):
```r
anchors <- FindIntegrationAnchors(object.list = bm40k.list, reference = c(1, 2), reduction = "rpca", 
    dims = 1:30)
bm40k.integrated <- IntegrateData(anchorset = anchors, dims = 1:30)
```

Example 77 (r):
```r
anchors <- FindIntegrationAnchors(object.list = bm40k.list, reference = c(1, 2), reduction = "rpca", 
    dims = 1:30)
bm40k.integrated <- IntegrateData(anchorset = anchors, dims = 1:30)
```

Example 78 (r):
```r
bm40k.integrated <- ScaleData(bm40k.integrated, verbose = FALSE)
bm40k.integrated <- RunPCA(bm40k.integrated, verbose = FALSE)
bm40k.integrated <- RunUMAP(bm40k.integrated, dims = 1:30)
```

Example 79 (r):
```r
bm40k.integrated <- ScaleData(bm40k.integrated, verbose = FALSE)
bm40k.integrated <- RunPCA(bm40k.integrated, verbose = FALSE)
bm40k.integrated <- RunUMAP(bm40k.integrated, dims = 1:30)
```

Example 80 (r):
```r
DimPlot(bm40k.integrated, group.by = "orig.ident")
```

Example 81 (r):
```r
DimPlot(bm40k.integrated, group.by = "orig.ident")
```

Example 82 (r):
```r
bm280k.data <- Read10X_h5("../data/ica_bone_marrow_h5.h5")
bm280k <- CreateSeuratObject(counts = bm280k.data, min.cells = 100, min.features = 500)
bm280k.list <- SplitObject(bm280k, split.by = "orig.ident")
bm280k.list <- future_lapply(X = bm280k.list, FUN = function(x) {
    x <- NormalizeData(x, verbose = FALSE)
    x <- FindVariableFeatures(x, verbose = FALSE)
})
```

Example 83 (r):
```r
bm280k.data <- Read10X_h5("../data/ica_bone_marrow_h5.h5")
bm280k <- CreateSeuratObject(counts = bm280k.data, min.cells = 100, min.features = 500)
bm280k.list <- SplitObject(bm280k, split.by = "orig.ident")
bm280k.list <- future_lapply(X = bm280k.list, FUN = function(x) {
    x <- NormalizeData(x, verbose = FALSE)
    x <- FindVariableFeatures(x, verbose = FALSE)
})
```

Example 84 (r):
```r
features <- SelectIntegrationFeatures(object.list = bm280k.list)
bm280k.list <- future_lapply(X = bm280k.list, FUN = function(x) {
    x <- ScaleData(x, features = features, verbose = FALSE)
    x <- RunPCA(x, features = features, verbose = FALSE)
})
```

Example 85 (r):
```r
features <- SelectIntegrationFeatures(object.list = bm280k.list)
bm280k.list <- future_lapply(X = bm280k.list, FUN = function(x) {
    x <- ScaleData(x, features = features, verbose = FALSE)
    x <- RunPCA(x, features = features, verbose = FALSE)
})
```

Example 86 (r):
```r
anchors <- FindIntegrationAnchors(object.list = bm280k.list, reference = c(1, 2), reduction = "rpca", 
    dims = 1:50)
bm280k.integrated <- IntegrateData(anchorset = anchors, dims = 1:50)
```

Example 87 (r):
```r
anchors <- FindIntegrationAnchors(object.list = bm280k.list, reference = c(1, 2), reduction = "rpca", 
    dims = 1:50)
bm280k.integrated <- IntegrateData(anchorset = anchors, dims = 1:50)
```

Example 88 (r):
```r
bm280k.integrated <- ScaleData(bm280k.integrated, verbose = FALSE)
bm280k.integrated <- RunPCA(bm280k.integrated, verbose = FALSE)
bm280k.integrated <- RunUMAP(bm280k.integrated, dims = 1:50)
```

Example 89 (r):
```r
bm280k.integrated <- ScaleData(bm280k.integrated, verbose = FALSE)
bm280k.integrated <- RunPCA(bm280k.integrated, verbose = FALSE)
bm280k.integrated <- RunUMAP(bm280k.integrated, dims = 1:50)
```

Example 90 (r):
```r
DimPlot(bm280k.integrated, group.by = "orig.ident")
```

Example 91 (r):
```r
DimPlot(bm280k.integrated, group.by = "orig.ident")
```

---

## Seurat - Dimensional Reduction Vignette

**URL:** http://127.0.0.1:9173/seurat/archive/v3.1/dim_reduction_vignette/index.html

**Contents:**
- Seurat - Dimensional Reduction Vignette
    - Compiled: April 17, 2020
  - Load in the data
  - Explore the new dimensional reduction structure
  - Storing a custom dimensional reduction calculation

This vignette demonstrates how to store and interact with dimensional reduction information (such as the output from RunPCA) in Seurat v3.0. For demonstration purposes, we will be using the 2,700 PBMC object that is created in the first guided tutorial. You can download the pre-computed object here.

In Seurat v3.0, storing and interacting with dimensional reduction information has been generalized and formalized into the DimReduc object. Each dimensional reduction procedure is stored as a DimReduc object in the object@reductions slot as an element of a named list. Accessing these reductions can be done with the [[ operator, calling the name of the reduction desired. For example, after running a principle component analysis with RunPCA, object[['pca']] will contain the results of the PCA. By adding new elements to the list, users can add additional, and custom, dimensional reductions. Each stored dimensional reduction contains the following slots:

To access these slots, we provide the Embeddings,Loadings, and Stdev functions

Seurat provides RunPCA (pca), and RunTSNE (tsne), and representing dimensional reduction techniques commonly applied to scRNA-seq data. When using these functions, all slots are filled automatically.

We also allow users to add the results of a custom dimensional reduction technique (for example, multi-dimensional scaling (MDS), or zero-inflated factor analysis), that is computed separately. All you need is a matrix with each cell’s coordinates in low-dimensional space, as shown below.

Though not incorporated as part of the Seurat package, its easy to run multidimensional scaling (MDS) in R. If you were interested in running MDS and storing the output in your Seurat object:

**Examples:**

Example 1 (r):
```r
library(Seurat)
pbmc <- readRDS(file = "../data/pbmc3k_final.rds")
```

Example 2 (r):
```r
library(Seurat)
pbmc <- readRDS(file = "../data/pbmc3k_final.rds")
```

Example 3 (unknown):
```unknown
object@reductions
```

Example 4 (unknown):
```unknown
object[['pca']]
```

Example 5 (r):
```r
pbmc[["pca"]]
```

Example 6 (r):
```r
pbmc[["pca"]]
```

Example 7 (unknown):
```unknown
## A dimensional reduction object with key PC_ 
##  Number of dimensions: 50 
##  Projected dimensional reduction calculated:  FALSE 
##  Jackstraw run: TRUE 
##  Computed using assay: RNA
```

Example 8 (unknown):
```unknown
## A dimensional reduction object with key PC_ 
##  Number of dimensions: 50 
##  Projected dimensional reduction calculated:  FALSE 
##  Jackstraw run: TRUE 
##  Computed using assay: RNA
```

Example 9 (r):
```r
head(Embeddings(pbmc, reduction = "pca")[, 1:5])
```

Example 10 (r):
```r
head(Embeddings(pbmc, reduction = "pca")[, 1:5])
```

Example 11 (unknown):
```unknown
##                        PC_1       PC_2       PC_3       PC_4        PC_5
## AAACATACAACCAC-1 -4.7296855 -0.5184265 -0.7623220 -2.3156790 -0.07160006
## AAACATTGAGCTAC-1 -0.5174029  4.5918957  5.9091921  6.9118856 -1.96243034
## AAACATTGATCAGC-1 -3.1891063 -3.4695154 -0.8313710 -2.0019985 -5.10442765
## AAACCGTGCTTCCG-1 12.7933021  0.1007166  0.6310221 -0.3687338  0.21838204
## AAACCGTGTATGCG-1 -3.1288078 -6.3481412  1.2507776  3.0191026  7.84739502
## AAACGCACTGGTAC-1 -3.1088963  0.9262125 -0.6482331 -2.3244378 -2.00526763
```

Example 12 (unknown):
```unknown
##                        PC_1       PC_2       PC_3       PC_4        PC_5
## AAACATACAACCAC-1 -4.7296855 -0.5184265 -0.7623220 -2.3156790 -0.07160006
## AAACATTGAGCTAC-1 -0.5174029  4.5918957  5.9091921  6.9118856 -1.96243034
## AAACATTGATCAGC-1 -3.1891063 -3.4695154 -0.8313710 -2.0019985 -5.10442765
## AAACCGTGCTTCCG-1 12.7933021  0.1007166  0.6310221 -0.3687338  0.21838204
## AAACCGTGTATGCG-1 -3.1288078 -6.3481412  1.2507776  3.0191026  7.84739502
## AAACGCACTGGTAC-1 -3.1088963  0.9262125 -0.6482331 -2.3244378 -2.00526763
```

Example 13 (r):
```r
head(Loadings(pbmc, reduction = "pca")[, 1:5])
```

Example 14 (r):
```r
head(Loadings(pbmc, reduction = "pca")[, 1:5])
```

Example 15 (unknown):
```unknown
##                PC_1        PC_2        PC_3        PC_4        PC_5
## PPBP    0.010990202  0.01148426 -0.15176092  0.10403737 0.003299077
## LYZ     0.116231706  0.01472515 -0.01280613 -0.04414540 0.049906881
## S100A9  0.115414362  0.01895146 -0.02368853 -0.05787777 0.085382309
## IGLL5  -0.007987473  0.05454239  0.04901533  0.06694722 0.004603231
## GNLY   -0.015238762 -0.13375626  0.04101340  0.06912322 0.104558611
## FTL     0.118292572  0.01871142 -0.00984755 -0.01555269 0.038743505
```

Example 16 (unknown):
```unknown
##                PC_1        PC_2        PC_3        PC_4        PC_5
## PPBP    0.010990202  0.01148426 -0.15176092  0.10403737 0.003299077
## LYZ     0.116231706  0.01472515 -0.01280613 -0.04414540 0.049906881
## S100A9  0.115414362  0.01895146 -0.02368853 -0.05787777 0.085382309
## IGLL5  -0.007987473  0.05454239  0.04901533  0.06694722 0.004603231
## GNLY   -0.015238762 -0.13375626  0.04101340  0.06912322 0.104558611
## FTL     0.118292572  0.01871142 -0.00984755 -0.01555269 0.038743505
```

Example 17 (r):
```r
head(Stdev(pbmc, reduction = "pca"))
```

Example 18 (r):
```r
head(Stdev(pbmc, reduction = "pca"))
```

Example 19 (unknown):
```unknown
## [1] 7.098420 4.495493 3.872592 3.748859 3.171755 2.545292
```

Example 20 (unknown):
```unknown
## [1] 7.098420 4.495493 3.872592 3.748859 3.171755 2.545292
```

Example 21 (r):
```r
# Before running MDS, we first calculate a distance matrix between all pairs of cells.  Here we
# use a simple euclidean distance metric on all genes, using scale.data as input
d <- dist(t(GetAssayData(pbmc, slot = "scale.data")))
# Run the MDS procedure, k determines the number of dimensions
mds <- cmdscale(d = d, k = 2)
# cmdscale returns the cell embeddings, we first label the columns to ensure downstream
# consistency
colnames(mds) <- paste0("MDS_", 1:2)
# We will now store this as a custom dimensional reduction called 'mds'
pbmc[["mds"]] <- CreateDimReducObject(embeddings = mds, key = "MDS_", assay = DefaultAssay(pbmc))

# We can now use this as you would any other dimensional reduction in all downstream functions
DimPlot(pbmc, reduction = "mds", pt.size = 0.5)
```

Example 22 (r):
```r
# Before running MDS, we first calculate a distance matrix between all pairs of cells.  Here we
# use a simple euclidean distance metric on all genes, using scale.data as input
d <- dist(t(GetAssayData(pbmc, slot = "scale.data")))
# Run the MDS procedure, k determines the number of dimensions
mds <- cmdscale(d = d, k = 2)
# cmdscale returns the cell embeddings, we first label the columns to ensure downstream
# consistency
colnames(mds) <- paste0("MDS_", 1:2)
# We will now store this as a custom dimensional reduction called 'mds'
pbmc[["mds"]] <- CreateDimReducObject(embeddings = mds, key = "MDS_", assay = DefaultAssay(pbmc))

# We can now use this as you would any other dimensional reduction in all downstream functions
DimPlot(pbmc, reduction = "mds", pt.size = 0.5)
```

Example 23 (r):
```r
# If you wold like to observe genes that are strongly correlated with the first MDS coordinate
pbmc <- ProjectDim(pbmc, reduction = "mds")
```

Example 24 (r):
```r
# If you wold like to observe genes that are strongly correlated with the first MDS coordinate
pbmc <- ProjectDim(pbmc, reduction = "mds")
```

Example 25 (unknown):
```unknown
## MDS_ 1 
## Positive:  CST3, TYROBP, FCER1G, LST1, FTL, AIF1, FTH1, TYMP, FCN1, LYZ 
##     LGALS1, S100A9, CFD, CD68, SERPINA1, CTSS, IFITM3, SPI1, S100A8, LGALS2 
## Negative:  MALAT1, RPS27A, RPS27, RPL3, RPL23A, RPL21, RPL13A, RPS6, RPS3A, RPS3 
##     RPL9, LTB, RPSA, CD3D, RPS25, RPS18, PTPRCAP, RPS12, RPL30, RPL31 
## MDS_ 2 
## Positive:  NKG7, PRF1, CST7, GZMA, GZMB, B2M, FGFBP2, CTSW, GNLY, HLA-C 
##     GZMH, SPON2, CD247, FCGR3A, CCL5, HLA-A, CCL4, GZMM, KLRD1, CLIC3 
## Negative:  RPL32, RPL18A, HLA-DRA, CD79A, RPL13, MS4A1, RPL11, TCL1A, RPS9, RPL12 
##     LINC00926, HLA-DQB1, HLA-DQA1, HLA-DRB1, RPL28, RPS2, S100A8, HLA-DMA, RPL8, RPLP1
```

Example 26 (unknown):
```unknown
## MDS_ 1 
## Positive:  CST3, TYROBP, FCER1G, LST1, FTL, AIF1, FTH1, TYMP, FCN1, LYZ 
##     LGALS1, S100A9, CFD, CD68, SERPINA1, CTSS, IFITM3, SPI1, S100A8, LGALS2 
## Negative:  MALAT1, RPS27A, RPS27, RPL3, RPL23A, RPL21, RPL13A, RPS6, RPS3A, RPS3 
##     RPL9, LTB, RPSA, CD3D, RPS25, RPS18, PTPRCAP, RPS12, RPL30, RPL31 
## MDS_ 2 
## Positive:  NKG7, PRF1, CST7, GZMA, GZMB, B2M, FGFBP2, CTSW, GNLY, HLA-C 
##     GZMH, SPON2, CD247, FCGR3A, CCL5, HLA-A, CCL4, GZMM, KLRD1, CLIC3 
## Negative:  RPL32, RPL18A, HLA-DRA, CD79A, RPL13, MS4A1, RPL11, TCL1A, RPS9, RPL12 
##     LINC00926, HLA-DQB1, HLA-DQA1, HLA-DRB1, RPL28, RPS2, S100A8, HLA-DMA, RPL8, RPLP1
```

Example 27 (r):
```r
# Display the results as a heatmap
DimHeatmap(pbmc, reduction = "mds", dims = 1, cells = 500, projected = TRUE, balanced = TRUE)
```

Example 28 (r):
```r
# Display the results as a heatmap
DimHeatmap(pbmc, reduction = "mds", dims = 1, cells = 500, projected = TRUE, balanced = TRUE)
```

Example 29 (r):
```r
# Explore how the first MDS dimension is distributed across clusters
VlnPlot(pbmc, features = "MDS_1")
```

Example 30 (r):
```r
# Explore how the first MDS dimension is distributed across clusters
VlnPlot(pbmc, features = "MDS_1")
```

Example 31 (r):
```r
# See how the first MDS dimension is correlated with the first PC dimension
FeatureScatter(pbmc, feature1 = "MDS_1", feature2 = "PC_1")
```

Example 32 (r):
```r
# See how the first MDS dimension is correlated with the first PC dimension
FeatureScatter(pbmc, feature1 = "MDS_1", feature2 = "PC_1")
```

---

## Analysis, visualization, and integration of Visium HD spatial datasets with Seurat • Seurat

**URL:** http://127.0.0.1:9173/articles_seurat5_bpcells_interaction_vignette.html

**Contents:**
- Using BPCells with Seurat Objects
    - Compiled: October 20, 2023
- Load Data
  - Load Data from one h5 file
    - Example Analsyis
    - Saving Seurat objects with on-disk layers
  - Load data from multiple h5ad files
  - Parse Biosciences
- Contents

BPCells is an R package that allows for computationally efficient single-cell analysis. It utilizes bit-packing compression to store counts matrices on disk and C++ code to cache operations.

We leverage the high performance capabilities of BPCells to work with Seurat objects in memory while accessing the counts on disk. In this vignette, we show how to use BPCells to load data, work with a Seurat objects in a more memory-efficient way, and write out Seurat objects with BPCells matrices.

We will show the methods for interacting with both a single dataset in one file or multiple datasets across multiple files using BPCells. BPCells allows us to easily analyze these large datasets in memory, and we encourage users to check out some of our other vignettes here and here to see further applications.

We use BPCells functionality to both load in our data and write the counts layers to bitpacked compressed binary files on disk to improve computation speeds. BPCells has multiple functions for reading in files.

In this section, we will load a dataset of mouse brain cells freely available from 10x Genomics. This includes 1.3 Million single cells that were sequenced on the Illumina NovaSeq 6000. The raw data can be found here.

To read in the file, we will use open_matrix_10x_hdf5, a BPCells function written to read in feature matrices from 10x. We then write a matrix directory, load the matrix, and create a Seurat object.

What if I already have a Seurat Object?

You can use BPCells to convert the matrices in your already created Seurat objects to on-disk matrices. Note, that this is only possible for V5 assays. As an example, if you’d like to convert the counts matrix of your RNA assay to a BPCells matrix, you can use the following:

Once this conversion is done, you can perform typical Seurat functions on the object. For example, we can normalize data and visualize features by automatically accessing the on-disk counts.

If you save your object and load it in in the future, Seurat will access the on-disk matrices by their path, which is stored in the assay level data. saveRDS() can still be used to save your Seurat objects with on-disk matrices as shown below. Note, if you move the object across computers or to a place that no longer has access to the paths where the on-disk matrices are stored, you will have to move the folders that contain the on-disk matrices as well. We are actively working on functionality to make this process easier for users.

If needed, a layer with an on-disk matrix can be converted to an in-memory matrix using the as() function. For the purposes of this demo, we’ll subset the object so that it takes up less space in memory.

You can also download data from multiple matrices. In this section, we create a Seurat object using multiple peripheral blood mononuclear cell (PBMC) samples that are freely available for download from CZI here. We download data from Ahern et al. (2022) Nature, Jin et al. (2021) Science, and Yoshida et al. (2022) Nature. We use the BPCells function to read h5ad files.

When we create the Seurat object with the list of matrices from each publication, we can then see that multiple counts layers exist that represent each dataset. This object contains over a million cells, yet only takes up minimal space in memory!

Here, we show how to load a 1 million cell data set from Parse Biosciences and create a Seurat Object. The data is available for download here

Developed by Paul Hoffman, Satija Lab and Collaborators.

Site built with pkgdown 2.0.7.

**Examples:**

Example 1 (unknown):
```unknown
vignettes/v5/seurat5_bpcells_interaction_vignette.Rmd
```

Example 2 (unknown):
```unknown
seurat5_bpcells_interaction_vignette.Rmd
```

Example 3 (unknown):
```unknown
library(BPCells)
library(Seurat)
library(SeuratObject)
library(SeuratDisk)
library(Azimuth)
```

Example 4 (r):
```r
library(BPCells)
library(Seurat)
library(SeuratObject)
library(SeuratDisk)
library(Azimuth)
```

Example 5 (unknown):
```unknown
brain.data <- open_matrix_10x_hdf5(
  path = "/brahms/hartmana/vignette_data/1M_neurons_filtered_gene_bc_matrices_h5.h5"
)
# Write the matrix to a directory
 write_matrix_dir(
   mat = brain.data,
   dir = '/brahms/hartmana/vignette_data/bpcells/brain_counts')
# Now that we have the matrix on disk, we can load it
brain.mat <- open_matrix_dir(dir = "/brahms/hartmana/vignette_data/bpcells/brain_counts")
brain.mat <- Azimuth:::ConvertEnsembleToSymbol(mat = brain.mat, species = "mouse")

# Create Seurat Object
brain <- CreateSeuratObject(counts = brain.mat)
```

Example 6 (r):
```r
brain.data <- open_matrix_10x_hdf5(
  path = "/brahms/hartmana/vignette_data/1M_neurons_filtered_gene_bc_matrices_h5.h5"
)
# Write the matrix to a directory
 write_matrix_dir(
   mat = brain.data,
   dir = '/brahms/hartmana/vignette_data/bpcells/brain_counts')
# Now that we have the matrix on disk, we can load it
brain.mat <- open_matrix_dir(dir = "/brahms/hartmana/vignette_data/bpcells/brain_counts")
brain.mat <- Azimuth:::ConvertEnsembleToSymbol(mat = brain.mat, species = "mouse")

# Create Seurat Object
brain <- CreateSeuratObject(counts = brain.mat)
```

Example 7 (r):
```r
brain.data <- open_matrix_10x_hdf5(
  path = "/brahms/hartmana/vignette_data/1M_neurons_filtered_gene_bc_matrices_h5.h5"
)
# Write the matrix to a directory
 write_matrix_dir(
   mat = brain.data,
   dir = '/brahms/hartmana/vignette_data/bpcells/brain_counts')
# Now that we have the matrix on disk, we can load it
brain.mat <- open_matrix_dir(dir = "/brahms/hartmana/vignette_data/bpcells/brain_counts")
brain.mat <- Azimuth:::ConvertEnsembleToSymbol(mat = brain.mat, species = "mouse")

# Create Seurat Object
brain <- CreateSeuratObject(counts = brain.mat)
```

Example 8 (unknown):
```unknown
write_matrix_dir(
```

Example 9 (unknown):
```unknown
mat = brain.data,
```

Example 10 (unknown):
```unknown
dir = '/brahms/hartmana/vignette_data/bpcells/brain_counts')
```

Example 11 (unknown):
```unknown
# obj <- readRDS("/path/to/reference.rds")

# # Write the counts layer to a directory
 write_matrix_dir(mat = obj[["RNA"]]$counts, dir = '/brahms/hartmana/vignette_data/bpcells/brain_counts')
 counts.mat <- open_matrix_dir(dir = "/brahms/hartmana/vignette_data/bpcells/brain_counts")

# obj[["RNA"]]$counts <- counts.mat
```

Example 12 (r):
```r
# obj <- readRDS("/path/to/reference.rds")

# # Write the counts layer to a directory
 write_matrix_dir(mat = obj[["RNA"]]$counts, dir = '/brahms/hartmana/vignette_data/bpcells/brain_counts')
 counts.mat <- open_matrix_dir(dir = "/brahms/hartmana/vignette_data/bpcells/brain_counts")

# obj[["RNA"]]$counts <- counts.mat
```

Example 13 (r):
```r
# obj <- readRDS("/path/to/reference.rds")

# # Write the counts layer to a directory
 write_matrix_dir(mat = obj[["RNA"]]$counts, dir = '/brahms/hartmana/vignette_data/bpcells/brain_counts')
 counts.mat <- open_matrix_dir(dir = "/brahms/hartmana/vignette_data/bpcells/brain_counts")

# obj[["RNA"]]$counts <- counts.mat
```

Example 14 (unknown):
```unknown
write_matrix_dir(mat = obj[["RNA"]]$counts, dir = '/brahms/hartmana/vignette_data/bpcells/brain_counts')
```

Example 15 (unknown):
```unknown
counts.mat <- open_matrix_dir(dir = "/brahms/hartmana/vignette_data/bpcells/brain_counts")
```

Example 16 (unknown):
```unknown
VlnPlot(brain, features = c("Sox10", "Slc17a7", "Aif1"), ncol = 3, layer = "counts", alpha = 0.1)
```

Example 17 (r):
```r
VlnPlot(brain, features = c("Sox10", "Slc17a7", "Aif1"), ncol = 3, layer = "counts", alpha = 0.1)
```

Example 18 (r):
```r
VlnPlot(brain, features = c("Sox10", "Slc17a7", "Aif1"), ncol = 3, layer = "counts", alpha = 0.1)
```

Example 19 (unknown):
```unknown
# We then normalize and visualize again
brain <- NormalizeData(brain, normalization.method = "LogNormalize")
VlnPlot(brain, features = c("Sox10", "Slc17a7", "Aif1"), ncol = 3, layer = "data", alpha = 0.1)
```

Example 20 (r):
```r
# We then normalize and visualize again
brain <- NormalizeData(brain, normalization.method = "LogNormalize")
VlnPlot(brain, features = c("Sox10", "Slc17a7", "Aif1"), ncol = 3, layer = "data", alpha = 0.1)
```

Example 21 (r):
```r
# We then normalize and visualize again
brain <- NormalizeData(brain, normalization.method = "LogNormalize")
VlnPlot(brain, features = c("Sox10", "Slc17a7", "Aif1"), ncol = 3, layer = "data", alpha = 0.1)
```

Example 22 (unknown):
```unknown
saveRDS(
   object = brain,
   file = "obj.Rds"
)
```

Example 23 (r):
```r
saveRDS(
   object = brain,
   file = "obj.Rds"
)
```

Example 24 (r):
```r
saveRDS(
   object = brain,
   file = "obj.Rds"
)
```

Example 25 (unknown):
```unknown
object = brain,
```

Example 26 (unknown):
```unknown
file = "obj.Rds"
```

Example 27 (unknown):
```unknown
brain <- subset(brain, downsample = 1000)
brain[["RNA"]]$counts <- as(object = brain[["RNA"]]$counts, Class = "dgCMatrix")
```

Example 28 (r):
```r
brain <- subset(brain, downsample = 1000)
brain[["RNA"]]$counts <- as(object = brain[["RNA"]]$counts, Class = "dgCMatrix")
```

Example 29 (r):
```r
brain <- subset(brain, downsample = 1000)
brain[["RNA"]]$counts <- as(object = brain[["RNA"]]$counts, Class = "dgCMatrix")
```

Example 30 (python):
```python
file.dir <- "/brahms/hartmana/vignette_data/h5ad_files/"
files.set <- c("ahern_pbmc.h5ad", "jin_pbmc.h5ad", "yoshida_pbmc.h5ad")

# Loop through h5ad files and output BPCells matrices on-disk
data.list <- c()
metadata.list <- c()

for (i in 1:length(files.set)) {
  path <- paste0(file.dir, files.set[i])
  data <- open_matrix_anndata_hdf5(path)
   write_matrix_dir(
     mat = data,
     dir = paste0(gsub(".h5ad", "", path), "_BP")
   )
  # Load in BP matrices
  mat <- open_matrix_dir(dir = paste0(gsub(".h5ad", "", path), "_BP"))
  mat <- Azimuth:::ConvertEnsembleToSymbol(mat = mat, species = "human")
  # Get metadata
  metadata.list[[i]] <- LoadH5ADobs(path = path)
  data.list[[i]] <- mat
}
# Name layers
names(data.list) <- c("ahern", "jin", "yoshida")

# Add Metadata
for (i in 1:length(metadata.list)) {
  metadata.list[[i]]$publication <- names(data.list)[i]
}
metadata.list <- lapply(metadata.list, function(x) {
  x <- x[, c("publication", "sex", "cell_type", "donor_id", "disease")]
  return(x)
})
metadata <- Reduce(rbind, metadata.list)
```

Example 31 (r):
```r
file.dir <- "/brahms/hartmana/vignette_data/h5ad_files/"
files.set <- c("ahern_pbmc.h5ad", "jin_pbmc.h5ad", "yoshida_pbmc.h5ad")

# Loop through h5ad files and output BPCells matrices on-disk
data.list <- c()
metadata.list <- c()

for (i in 1:length(files.set)) {
  path <- paste0(file.dir, files.set[i])
  data <- open_matrix_anndata_hdf5(path)
   write_matrix_dir(
     mat = data,
     dir = paste0(gsub(".h5ad", "", path), "_BP")
   )
  # Load in BP matrices
  mat <- open_matrix_dir(dir = paste0(gsub(".h5ad", "", path), "_BP"))
  mat <- Azimuth:::ConvertEnsembleToSymbol(mat = mat, species = "human")
  # Get metadata
  metadata.list[[i]] <- LoadH5ADobs(path = path)
  data.list[[i]] <- mat
}
# Name layers
names(data.list) <- c("ahern", "jin", "yoshida")

# Add Metadata
for (i in 1:length(metadata.list)) {
  metadata.list[[i]]$publication <- names(data.list)[i]
}
metadata.list <- lapply(metadata.list, function(x) {
  x <- x[, c("publication", "sex", "cell_type", "donor_id", "disease")]
  return(x)
})
metadata <- Reduce(rbind, metadata.list)
```

Example 32 (r):
```r
file.dir <- "/brahms/hartmana/vignette_data/h5ad_files/"
files.set <- c("ahern_pbmc.h5ad", "jin_pbmc.h5ad", "yoshida_pbmc.h5ad")

# Loop through h5ad files and output BPCells matrices on-disk
data.list <- c()
metadata.list <- c()

for (i in 1:length(files.set)) {
  path <- paste0(file.dir, files.set[i])
  data <- open_matrix_anndata_hdf5(path)
   write_matrix_dir(
     mat = data,
     dir = paste0(gsub(".h5ad", "", path), "_BP")
   )
  # Load in BP matrices
  mat <- open_matrix_dir(dir = paste0(gsub(".h5ad", "", path), "_BP"))
  mat <- Azimuth:::ConvertEnsembleToSymbol(mat = mat, species = "human")
  # Get metadata
  metadata.list[[i]] <- LoadH5ADobs(path = path)
  data.list[[i]] <- mat
}
# Name layers
names(data.list) <- c("ahern", "jin", "yoshida")

# Add Metadata
for (i in 1:length(metadata.list)) {
  metadata.list[[i]]$publication <- names(data.list)[i]
}
metadata.list <- lapply(metadata.list, function(x) {
  x <- x[, c("publication", "sex", "cell_type", "donor_id", "disease")]
  return(x)
})
metadata <- Reduce(rbind, metadata.list)
```

Example 33 (unknown):
```unknown
write_matrix_dir(
```

Example 34 (unknown):
```unknown
mat = data,
```

Example 35 (unknown):
```unknown
dir = paste0(gsub(".h5ad", "", path), "_BP")
```

Example 36 (python):
```python
merged.object <- CreateSeuratObject(counts = data.list, meta.data = metadata)
merged.object
```

Example 37 (r):
```r
merged.object <- CreateSeuratObject(counts = data.list, meta.data = metadata)
merged.object
```

Example 38 (python):
```python
## An object of class Seurat 
## 26143 features across 1498064 samples within 1 assay 
## Active assay: RNA (26143 features, 0 variable features)
##  3 layers present: counts.ahern, counts.jin, counts.yoshida
```

Example 39 (python):
```python
## An object of class Seurat 
## 26143 features across 1498064 samples within 1 assay 
## Active assay: RNA (26143 features, 0 variable features)
##  3 layers present: counts.ahern, counts.jin, counts.yoshida
```

Example 40 (unknown):
```unknown
saveRDS(
  object = merged.object,
  file = "obj.Rds"
)
```

Example 41 (r):
```r
saveRDS(
  object = merged.object,
  file = "obj.Rds"
)
```

Example 42 (r):
```r
saveRDS(
  object = merged.object,
  file = "obj.Rds"
)
```

Example 43 (unknown):
```unknown
parse.data <- open_matrix_anndata_hdf5(
  "/brahms/hartmana/vignette_data/h5ad_files/ParseBio_PBMC.h5ad"
)
```

Example 44 (r):
```r
parse.data <- open_matrix_anndata_hdf5(
  "/brahms/hartmana/vignette_data/h5ad_files/ParseBio_PBMC.h5ad"
)
```

Example 45 (r):
```r
parse.data <- open_matrix_anndata_hdf5(
  "/brahms/hartmana/vignette_data/h5ad_files/ParseBio_PBMC.h5ad"
)
```

Example 46 (unknown):
```unknown
write_matrix_dir(mat = parse.data, dir = "/brahms/hartmana/vignette_data/bpcells/parse_1m_pbmc")
```

Example 47 (r):
```r
write_matrix_dir(mat = parse.data, dir = "/brahms/hartmana/vignette_data/bpcells/parse_1m_pbmc")
```

Example 48 (r):
```r
write_matrix_dir(mat = parse.data, dir = "/brahms/hartmana/vignette_data/bpcells/parse_1m_pbmc")
```

Example 49 (python):
```python
parse.mat <- open_matrix_dir(dir = "/brahms/hartmana/vignette_data/bpcells/parse_1m_pbmc")
metadata <- readRDS("/brahms/hartmana/vignette_data/ParseBio_PBMC_meta.rds")
metadata$disease <- sapply(strsplit(x = metadata$sample, split = "_"), "[", 1)
parse.object <- CreateSeuratObject(counts = parse.mat, meta.data = metadata)
```

Example 50 (r):
```r
parse.mat <- open_matrix_dir(dir = "/brahms/hartmana/vignette_data/bpcells/parse_1m_pbmc")
metadata <- readRDS("/brahms/hartmana/vignette_data/ParseBio_PBMC_meta.rds")
metadata$disease <- sapply(strsplit(x = metadata$sample, split = "_"), "[", 1)
parse.object <- CreateSeuratObject(counts = parse.mat, meta.data = metadata)
```

Example 51 (r):
```r
parse.mat <- open_matrix_dir(dir = "/brahms/hartmana/vignette_data/bpcells/parse_1m_pbmc")
metadata <- readRDS("/brahms/hartmana/vignette_data/ParseBio_PBMC_meta.rds")
metadata$disease <- sapply(strsplit(x = metadata$sample, split = "_"), "[", 1)
parse.object <- CreateSeuratObject(counts = parse.mat, meta.data = metadata)
```

Example 52 (unknown):
```unknown
saveRDS(
  object = parse.object,
  file = "obj.Rds"
)
```

Example 53 (r):
```r
saveRDS(
  object = parse.object,
  file = "obj.Rds"
)
```

Example 54 (r):
```r
saveRDS(
  object = parse.object,
  file = "obj.Rds"
)
```

Example 55 (unknown):
```unknown
sessionInfo()
```

Example 56 (r):
```r
sessionInfo()
```

Example 57 (r):
```r
sessionInfo()
```

Example 58 (unknown):
```unknown
## R version 4.2.2 Patched (2022-11-10 r83330)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.6 LTS
## 
## Matrix products: default
## BLAS:   /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.9.0
## LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.9.0
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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       
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
## [1] dplyr_1.1.3             biomaRt_2.54.1          Azimuth_0.4.6.9004     
## [4] shinyBS_0.61.1          SeuratDisk_0.0.0.9020   Seurat_4.9.9.9085      
## [7] SeuratObject_4.9.9.9092 sp_2.1-1                BPCells_0.1.0          
## 
## loaded via a namespace (and not attached):
##   [1] rappdirs_0.3.3                    rtracklayer_1.58.0               
##   [3] scattermore_1.2                   R.methodsS3_1.8.2                
##   [5] ragg_1.2.5                        tidyr_1.3.0                      
##   [7] JASPAR2020_0.99.10                ggplot2_3.4.4                    
##   [9] bit64_4.0.5                       knitr_1.44                       
##  [11] irlba_2.3.5.1                     DelayedArray_0.24.0              
##  [13] R.utils_2.12.2                    styler_1.10.2                    
##  [15] data.table_1.14.8                 KEGGREST_1.38.0                  
##  [17] TFBSTools_1.36.0                  RCurl_1.98-1.12                  
##  [19] AnnotationFilter_1.22.0           generics_0.1.3                   
##  [21] BiocGenerics_0.44.0               GenomicFeatures_1.50.4           
##  [23] cowplot_1.1.1                     RSQLite_2.3.1                    
##  [25] RANN_2.6.1                        future_1.33.0                    
##  [27] bit_4.0.5                         tzdb_0.4.0                       
##  [29] spatstat.data_3.0-1               xml2_1.3.5                       
##  [31] httpuv_1.6.11                     SummarizedExperiment_1.28.0      
##  [33] DirichletMultinomial_1.40.0       gargle_1.5.2                     
##  [35] xfun_0.40                         hms_1.1.3                        
##  [37] jquerylib_0.1.4                   evaluate_0.22                    
##  [39] promises_1.2.1                    fansi_1.0.5                      
##  [41] restfulr_0.0.15                   progress_1.2.2                   
##  [43] caTools_1.18.2                    dbplyr_2.3.4                     
##  [45] igraph_1.5.1                      DBI_1.1.3                        
##  [47] htmlwidgets_1.6.2                 spatstat.geom_3.2-5              
##  [49] googledrive_2.1.1                 stats4_4.2.2                     
##  [51] purrr_1.0.2                       ellipsis_0.3.2                   
##  [53] RSpectra_0.16-1                   annotate_1.76.0                  
##  [55] deldir_1.0-9                      MatrixGenerics_1.10.0            
##  [57] vctrs_0.6.4                       Biobase_2.58.0                   
##  [59] Cairo_1.6-0                       ensembldb_2.22.0                 
##  [61] ROCR_1.0-11                       abind_1.4-5                      
##  [63] cachem_1.0.8                      withr_2.5.1                      
##  [65] BSgenome.Hsapiens.UCSC.hg38_1.4.5 BSgenome_1.66.3                  
##  [67] progressr_0.14.0                  presto_1.0.0                     
##  [69] sctransform_0.4.1                 GenomicAlignments_1.34.1         
##  [71] prettyunits_1.1.1                 goftest_1.2-3                    
##  [73] cluster_2.1.4                     dotCall64_1.1-0                  
##  [75] lazyeval_0.2.2                    seqLogo_1.64.0                   
##  [77] crayon_1.5.2                      hdf5r_1.3.8                      
##  [79] spatstat.explore_3.2-3            labeling_0.4.3                   
##  [81] pkgconfig_2.0.3                   GenomeInfoDb_1.34.9              
##  [83] vipor_0.4.5                       nlme_3.1-162                     
##  [85] ProtGenerics_1.30.0               rlang_1.1.1                      
##  [87] globals_0.16.2                    lifecycle_1.0.3                  
##  [89] miniUI_0.1.1.1                    filelock_1.0.2                   
##  [91] fastDummies_1.7.3                 BiocFileCache_2.6.1              
##  [93] SeuratData_0.2.2.9001             ggrastr_1.0.1                    
##  [95] cellranger_1.1.0                  rprojroot_2.0.3                  
##  [97] polyclip_1.10-6                   RcppHNSW_0.5.0                   
##  [99] matrixStats_1.0.0                 lmtest_0.9-40                    
## [101] Matrix_1.6-1.1                    Rhdf5lib_1.20.0                  
## [103] zoo_1.8-12                        beeswarm_0.4.0                   
## [105] googlesheets4_1.1.1               ggridges_0.5.4                   
## [107] png_0.1-8                         viridisLite_0.4.2                
## [109] rjson_0.2.21                      shinydashboard_0.7.2             
## [111] bitops_1.0-7                      R.oo_1.25.0                      
## [113] rhdf5filters_1.10.1               KernSmooth_2.23-22               
## [115] spam_2.9-1                        Biostrings_2.66.0                
## [117] blob_1.2.4                        stringr_1.5.0                    
## [119] parallelly_1.36.0                 spatstat.random_3.1-6            
## [121] R.cache_0.16.0                    readr_2.1.4                      
## [123] S4Vectors_0.36.2                  CNEr_1.34.0                      
## [125] scales_1.2.1                      memoise_2.0.1                    
## [127] magrittr_2.0.3                    plyr_1.8.9                       
## [129] ica_1.0-3                         zlibbioc_1.44.0                  
## [131] compiler_4.2.2                    BiocIO_1.8.0                     
## [133] RColorBrewer_1.1-3                fitdistrplus_1.1-11              
## [135] Rsamtools_2.14.0                  cli_3.6.1                        
## [137] XVector_0.38.0                    listenv_0.9.0                    
## [139] patchwork_1.1.3                   pbapply_1.7-2                    
## [141] MASS_7.3-58.2                     tidyselect_1.2.0                 
## [143] stringi_1.7.12                    textshaping_0.3.6                
## [145] yaml_2.3.7                        ggrepel_0.9.4                    
## [147] grid_4.2.2                        sass_0.4.7                       
## [149] fastmatch_1.1-4                   EnsDb.Hsapiens.v86_2.99.0        
## [151] tools_4.2.2                       future.apply_1.11.0              
## [153] parallel_4.2.2                    rstudioapi_0.14                  
## [155] TFMPvalue_0.0.9                   gridExtra_2.3                    
## [157] farver_2.1.1                      Rtsne_0.16                       
## [159] digest_0.6.33                     pracma_2.4.2                     
## [161] shiny_1.7.5.1                     Rcpp_1.0.11                      
## [163] GenomicRanges_1.50.2              later_1.3.1                      
## [165] RcppAnnoy_0.0.21                  httr_1.4.7                       
## [167] AnnotationDbi_1.60.2              colorspace_2.1-0                 
## [169] XML_3.99-0.14                     fs_1.6.3                         
## [171] tensor_1.5                        reticulate_1.34.0                
## [173] IRanges_2.32.0                    splines_4.2.2                    
## [175] uwot_0.1.16                       RcppRoll_0.3.0                   
## [177] spatstat.utils_3.0-3              pkgdown_2.0.7                    
## [179] plotly_4.10.2                     systemfonts_1.0.4                
## [181] xtable_1.8-4                      jsonlite_1.8.7                   
## [183] poweRlaw_0.70.6                   R6_2.5.1                         
## [185] pillar_1.9.0                      htmltools_0.5.6.1                
## [187] mime_0.12                         glue_1.6.2                       
## [189] fastmap_1.1.1                     DT_0.30                          
## [191] BiocParallel_1.32.6               codetools_0.2-19                 
## [193] Signac_1.12.9000                  utf8_1.2.3                       
## [195] lattice_0.21-9                    bslib_0.5.1                      
## [197] spatstat.sparse_3.0-2             tibble_3.2.1                     
## [199] ggbeeswarm_0.7.1                  curl_5.1.0                       
## [201] leiden_0.4.3                      gtools_3.9.4                     
## [203] shinyjs_2.1.0                     GO.db_3.16.0                     
## [205] survival_3.5-7                    rmarkdown_2.25                   
## [207] desc_1.4.2                        munsell_0.5.0                    
## [209] rhdf5_2.42.1                      GenomeInfoDbData_1.2.9           
## [211] reshape2_1.4.4                    gtable_0.3.4
```

Example 59 (unknown):
```unknown
## R version 4.2.2 Patched (2022-11-10 r83330)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.6 LTS
## 
## Matrix products: default
## BLAS:   /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.9.0
## LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.9.0
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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       
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
## [1] dplyr_1.1.3             biomaRt_2.54.1          Azimuth_0.4.6.9004     
## [4] shinyBS_0.61.1          SeuratDisk_0.0.0.9020   Seurat_4.9.9.9085      
## [7] SeuratObject_4.9.9.9092 sp_2.1-1                BPCells_0.1.0          
## 
## loaded via a namespace (and not attached):
##   [1] rappdirs_0.3.3                    rtracklayer_1.58.0               
##   [3] scattermore_1.2                   R.methodsS3_1.8.2                
##   [5] ragg_1.2.5                        tidyr_1.3.0                      
##   [7] JASPAR2020_0.99.10                ggplot2_3.4.4                    
##   [9] bit64_4.0.5                       knitr_1.44                       
##  [11] irlba_2.3.5.1                     DelayedArray_0.24.0              
##  [13] R.utils_2.12.2                    styler_1.10.2                    
##  [15] data.table_1.14.8                 KEGGREST_1.38.0                  
##  [17] TFBSTools_1.36.0                  RCurl_1.98-1.12                  
##  [19] AnnotationFilter_1.22.0           generics_0.1.3                   
##  [21] BiocGenerics_0.44.0               GenomicFeatures_1.50.4           
##  [23] cowplot_1.1.1                     RSQLite_2.3.1                    
##  [25] RANN_2.6.1                        future_1.33.0                    
##  [27] bit_4.0.5                         tzdb_0.4.0                       
##  [29] spatstat.data_3.0-1               xml2_1.3.5                       
##  [31] httpuv_1.6.11                     SummarizedExperiment_1.28.0      
##  [33] DirichletMultinomial_1.40.0       gargle_1.5.2                     
##  [35] xfun_0.40                         hms_1.1.3                        
##  [37] jquerylib_0.1.4                   evaluate_0.22                    
##  [39] promises_1.2.1                    fansi_1.0.5                      
##  [41] restfulr_0.0.15                   progress_1.2.2                   
##  [43] caTools_1.18.2                    dbplyr_2.3.4                     
##  [45] igraph_1.5.1                      DBI_1.1.3                        
##  [47] htmlwidgets_1.6.2                 spatstat.geom_3.2-5              
##  [49] googledrive_2.1.1                 stats4_4.2.2                     
##  [51] purrr_1.0.2                       ellipsis_0.3.2                   
##  [53] RSpectra_0.16-1                   annotate_1.76.0                  
##  [55] deldir_1.0-9                      MatrixGenerics_1.10.0            
##  [57] vctrs_0.6.4                       Biobase_2.58.0                   
##  [59] Cairo_1.6-0                       ensembldb_2.22.0                 
##  [61] ROCR_1.0-11                       abind_1.4-5                      
##  [63] cachem_1.0.8                      withr_2.5.1                      
##  [65] BSgenome.Hsapiens.UCSC.hg38_1.4.5 BSgenome_1.66.3                  
##  [67] progressr_0.14.0                  presto_1.0.0                     
##  [69] sctransform_0.4.1                 GenomicAlignments_1.34.1         
##  [71] prettyunits_1.1.1                 goftest_1.2-3                    
##  [73] cluster_2.1.4                     dotCall64_1.1-0                  
##  [75] lazyeval_0.2.2                    seqLogo_1.64.0                   
##  [77] crayon_1.5.2                      hdf5r_1.3.8                      
##  [79] spatstat.explore_3.2-3            labeling_0.4.3                   
##  [81] pkgconfig_2.0.3                   GenomeInfoDb_1.34.9              
##  [83] vipor_0.4.5                       nlme_3.1-162                     
##  [85] ProtGenerics_1.30.0               rlang_1.1.1                      
##  [87] globals_0.16.2                    lifecycle_1.0.3                  
##  [89] miniUI_0.1.1.1                    filelock_1.0.2                   
##  [91] fastDummies_1.7.3                 BiocFileCache_2.6.1              
##  [93] SeuratData_0.2.2.9001             ggrastr_1.0.1                    
##  [95] cellranger_1.1.0                  rprojroot_2.0.3                  
##  [97] polyclip_1.10-6                   RcppHNSW_0.5.0                   
##  [99] matrixStats_1.0.0                 lmtest_0.9-40                    
## [101] Matrix_1.6-1.1                    Rhdf5lib_1.20.0                  
## [103] zoo_1.8-12                        beeswarm_0.4.0                   
## [105] googlesheets4_1.1.1               ggridges_0.5.4                   
## [107] png_0.1-8                         viridisLite_0.4.2                
## [109] rjson_0.2.21                      shinydashboard_0.7.2             
## [111] bitops_1.0-7                      R.oo_1.25.0                      
## [113] rhdf5filters_1.10.1               KernSmooth_2.23-22               
## [115] spam_2.9-1                        Biostrings_2.66.0                
## [117] blob_1.2.4                        stringr_1.5.0                    
## [119] parallelly_1.36.0                 spatstat.random_3.1-6            
## [121] R.cache_0.16.0                    readr_2.1.4                      
## [123] S4Vectors_0.36.2                  CNEr_1.34.0                      
## [125] scales_1.2.1                      memoise_2.0.1                    
## [127] magrittr_2.0.3                    plyr_1.8.9                       
## [129] ica_1.0-3                         zlibbioc_1.44.0                  
## [131] compiler_4.2.2                    BiocIO_1.8.0                     
## [133] RColorBrewer_1.1-3                fitdistrplus_1.1-11              
## [135] Rsamtools_2.14.0                  cli_3.6.1                        
## [137] XVector_0.38.0                    listenv_0.9.0                    
## [139] patchwork_1.1.3                   pbapply_1.7-2                    
## [141] MASS_7.3-58.2                     tidyselect_1.2.0                 
## [143] stringi_1.7.12                    textshaping_0.3.6                
## [145] yaml_2.3.7                        ggrepel_0.9.4                    
## [147] grid_4.2.2                        sass_0.4.7                       
## [149] fastmatch_1.1-4                   EnsDb.Hsapiens.v86_2.99.0        
## [151] tools_4.2.2                       future.apply_1.11.0              
## [153] parallel_4.2.2                    rstudioapi_0.14                  
## [155] TFMPvalue_0.0.9                   gridExtra_2.3                    
## [157] farver_2.1.1                      Rtsne_0.16                       
## [159] digest_0.6.33                     pracma_2.4.2                     
## [161] shiny_1.7.5.1                     Rcpp_1.0.11                      
## [163] GenomicRanges_1.50.2              later_1.3.1                      
## [165] RcppAnnoy_0.0.21                  httr_1.4.7                       
## [167] AnnotationDbi_1.60.2              colorspace_2.1-0                 
## [169] XML_3.99-0.14                     fs_1.6.3                         
## [171] tensor_1.5                        reticulate_1.34.0                
## [173] IRanges_2.32.0                    splines_4.2.2                    
## [175] uwot_0.1.16                       RcppRoll_0.3.0                   
## [177] spatstat.utils_3.0-3              pkgdown_2.0.7                    
## [179] plotly_4.10.2                     systemfonts_1.0.4                
## [181] xtable_1.8-4                      jsonlite_1.8.7                   
## [183] poweRlaw_0.70.6                   R6_2.5.1                         
## [185] pillar_1.9.0                      htmltools_0.5.6.1                
## [187] mime_0.12                         glue_1.6.2                       
## [189] fastmap_1.1.1                     DT_0.30                          
## [191] BiocParallel_1.32.6               codetools_0.2-19                 
## [193] Signac_1.12.9000                  utf8_1.2.3                       
## [195] lattice_0.21-9                    bslib_0.5.1                      
## [197] spatstat.sparse_3.0-2             tibble_3.2.1                     
## [199] ggbeeswarm_0.7.1                  curl_5.1.0                       
## [201] leiden_0.4.3                      gtools_3.9.4                     
## [203] shinyjs_2.1.0                     GO.db_3.16.0                     
## [205] survival_3.5-7                    rmarkdown_2.25                   
## [207] desc_1.4.2                        munsell_0.5.0                    
## [209] rhdf5_2.42.1                      GenomeInfoDbData_1.2.9           
## [211] reshape2_1.4.4                    gtable_0.3.4
```

---

## Analysis, visualization, and integration of spatial datasets with Seurat • Seurat

**URL:** http://127.0.0.1:9173/articles_spatial_vignette.html

**Contents:**
- Analysis, visualization, and integration of spatial datasets with Seurat
    - Compiled: 2025-06-17
- Overview
- 10x Visium
  - Dataset
  - Data preprocessing
  - Gene expression visualization
  - Dimensionality reduction, clustering, and visualization
  - Interactive plotting
  - Identification of Spatially Variable Features
  - Subset out anatomical regions
  - Integration with single-cell data
  - Working with multiple slices in Seurat
  - Acknowledgments
- Slide-seq
  - Dataset
  - Data preprocessing
  - Integration with a scRNA-seq reference
  - Identification of Spatially Variable Features
  - Spatial deconvolution using RCTD

This tutorial demonstrates how to use Seurat (>=3.2) to analyze spatially-resolved RNA-seq data. While the analytical pipelines are similar to the Seurat workflow for single-cell RNA-seq analysis, we introduce updated interaction and visualization tools, with a particular emphasis on the integration of spatial and molecular information. This tutorial will cover the following tasks, which we believe will be common for many spatial analyses:

For our first vignette, we analyze a dataset generated with the Visium technology from 10x Genomics. We will be extending Seurat to work with additional data types in the near-future, including SLIDE-Seq, STARmap, and MERFISH.

First, we load Seurat and the other packages necessary for this vignette.

Here, we will be using a recently released dataset of sagital mouse brain slices generated using the Visium v1 chemistry. There are two serial anterior sections, and two (matched) serial posterior sections.

You can download the data here, and load it into Seurat using the Load10X_Spatial() function. This reads in the output of the spaceranger pipeline, and returns a Seurat object that contains both the spot-level expression data along with the associated image of the tissue slice. You can also use our SeuratData package for easy data access, as demonstrated below. After installing the dataset, you can type ?stxBrain to learn more.

The visium data from 10x consists of the following data types:

The initial preprocessing steps that we perform on the spot by gene expression data are similar to a typical scRNA-seq experiment. We first need to normalize the data in order to account for variance in sequencing depth across data points. We note that the variance in molecular counts / spot can be substantial for spatial datasets, particularly if there are differences in cell density across the tissue. We see substantial heterogeneity here, which requires effective normalization.

These plots demonstrate that the variance in molecular counts across spots is not just technical in nature, but also is dependent on the tissue anatomy. For example, regions of the tissue that are depleted for neurons (such as the cortical white matter), reproducibly exhibit lower molecular counts. As a result, standard approaches (such as the LogNormalize() function), which force each data point to have the same underlying ‘size’ after normalization, can be problematic.

As an alternative, we recommend using sctransform (Hafemeister and Satija, Genome Biology 2019), which which builds regularized negative binomial models of gene expression in order to account for technical artifacts while preserving biological variance. For more details on sctransform, please see the paper here and the Seurat vignette here. sctransform normalizes the data, detects high-variance features, and stores the data in the SCT assay.

To explore the differences in normalization methods, we examine how both the sctransform and log normalization results correlate with the number of UMIs. For this comparison, we first rerun sctransform to store values for all genes and run a log-normalization procedure via NormalizeData().

In Seurat, we have functionality to explore and interact with the inherently visual nature of spatial data. The SpatialFeaturePlot() function in Seurat extends FeaturePlot(), and can overlay molecular data on top of tissue histology. For example, in this data set of the mouse brain, the gene Hpca is a strong hippocampus marker and Ttr is a marker of the choroid plexus.

The default parameters in Seurat emphasize the visualization of molecular data. However, you can also adjust the size of the spots (and their transparency) to improve the visualization of the histology image, by changing the following parameters:

We can then proceed to run dimensionality reduction and clustering on the RNA expression data, using the same workflow as we use for scRNA-seq analysis.

We can then visualize the results of the clustering either in UMAP space (with DimPlot()) or overlaid on the image with SpatialDimPlot().

As there are many colors, it can be challenging to visualize which voxel belongs to which cluster. We have a few strategies to help with this. Setting the label parameter places a colored box at the median of each cluster (see the plot above).

You can also use the cells.highlight parameter to demarcate particular cells of interest on a SpatialDimPlot(). This can be very useful for distinguishing the spatial localization of individual clusters, as we show below:

We have also built in a number of interactive plotting capabilities. Both SpatialDimPlot() and SpatialFeaturePlot() now have an interactive parameter, that when set to TRUE, will open up the Rstudio viewer pane with an interactive Shiny plot. The example below demonstrates an interactive SpatialDimPlot() in which you can hover over spots and view the cell name and current identity class (analogous to the previous do.hover behavior).

For SpatialFeaturePlot(), setting interactive to TRUE brings up an interactive pane in which you can adjust the transparency of the spots, the point size, as well as the Assay and feature being plotted. After exploring the data, selecting the done button will return the last active plot as a ggplot object.

The LinkedDimPlot() function links the UMAP representation to the tissue image representation and allows for interactive selection. For example, you can select a region in the UMAP plot and the corresponding spots in the image representation will be highlighted.

Seurat offers two workflows to identify molecular features that correlate with spatial location within a tissue. The first is to perform differential expression based on pre-annotated anatomical regions within the tissue, which may be determined either from unsupervised clustering or prior knowledge. This strategy works will in this case, as the clusters above exhibit clear spatial restriction.

An alternative approach, implemented in FindSpatiallyVariables(), is to search for features exhibiting spatial patterning in the absence of pre-annotation. The default method (method = 'markvariogram), is inspired by the Trendsceek, which models spatial transcriptomics data as a mark point process and computes a ‘variogram’, which identifies genes whose expression level is dependent on their spatial location. More specifically, this process calculates gamma(r) values measuring the dependence between two spots a certain “r” distance apart. By default, we use an r-value of ‘5’ in these analyses, and only compute these values for variable genes (where variation is calculated independently of spatial location) to save time.

We note that there are multiple methods in the literature to accomplish this task, including SpatialDE, and Splotch. We encourage interested users to explore these methods, and hope to add support for them in the near future.

Now we visualize the expression of the top 6 features identified by this measure.

As with single-cell objects, you can subset the object to focus on a subset of data. Here, we approximately subset the frontal cortex. This process also facilitates the integration of these data with a cortical scRNA-seq dataset in the next section. First, we take a subset of clusters, and then further segment based on exact positions. After subsetting, we can visualize the cortical cells either on the full image, or a cropped image.

In SeuratObject v5.1.0, spatial coordinates are no longer stored directly in the metadata and are instead located in the spatial image structure. To perform spatial filtering, we need to extract the x (image column) and y (image row) positions from the spatial centroids and manually attach them to the metadata prior to subsetting.

At ~50um, spots from the visium assay will encompass the expression profiles of multiple cells. For the growing list of systems where scRNA-seq data is available, users may be interested to ‘deconvolute’ each of the spatial voxels to predict the underlying composition of cell types. In preparing this vignette, we tested a wide variety of decovonlution and integration methods, using a reference scRNA-seq dataset of ~14,000 adult mouse cortical cell taxonomy from the Allen Institute, generated with the SMART-Seq2 protocol. We consistently found superior performance using integration methods (as opposed to deconvolution methods), likely because of substantially different noise models that characterize spatial and single-cell datasets, and integration methods are specifiically designed to be robust to these differences. We therefore apply the ‘anchor’-based integration workflow introduced in Seurat v3, that enables the probabilistic transfer of annotations from a reference to a query set. We therefore follow the label transfer workflow introduced here, taking advantage of sctransform normalization, but anticipate new methods to be developed to accomplish this task.

We first load the data (download available here), pre-process the scRNA-seq reference, and then perform label transfer. The procedure outputs, for each spot, a probabilistic classification for each of the scRNA-seq derived classes. We add these predictions as a new assay in the Seurat object.

Now we get prediction scores for each spot for each class. Of particular interest in the frontal cortex region are the laminar excitatory neurons. Here we can distinguish between distinct sequential layers of these neuronal subtypes, for example:

Based on these prediction scores, we can also predict cell types whose location is spatially restricted. We use the same methods based on marked point processes to define spatially variable features, but use the cell type prediction scores as the “marks” rather than gene expression.

Finally, we show that our integrative procedure is capable of recovering the known spatial localization patterns of both neuronal and non-neuronal subsets, including laminar excitatory, layer-1 astrocytes, and the cortical grey matter.

This dataset of the mouse brain contains another slice corresponding to the other half of the brain. Here we read it in and perform the same initial normalization.

In order to work with multiple slices in the same Seurat object, we provide the merge function.

This then enables joint dimensional reduction and clustering on the underlying RNA expression data.

Finally, the data can be jointly visualized in a single UMAP plot. SpatialDimPlot() and SpatialFeaturePlot() will by default plot all slices as columns and groupings/features as rows.

We would like to thank Nigel Delaney and Stephen Williams for their helpful feedback and contributions to the new spatial Seurat code.

Here, we will be analyzing a dataset generated using Slide-seq v2 of the mouse hippocampus. This tutorial will follow much of the same structure as the spatial vignette for 10x Visium data but is tailored to give a demonstration specific to Slide-seq data.

You can use our SeuratData package for easy data access, as demonstrated below. After installing the dataset, you can type ?ssHippo to see the commands used to create the Seurat object.

The initial preprocessing steps for the bead by gene expression data are similar to other spatial Seurat analyses and to typical scRNA-seq experiments. Here, we note that many beads contain particularly low UMI counts but choose to keep all detected beads for downstream analysis.

We then normalize the data using sctransform and perform a standard scRNA-seq dimensionality reduction and clustering workflow.

We can then visualize the results of the clustering either in UMAP space (with DimPlot()) or in the bead coordinate space with SpatialDimPlot().

To facilitate cell-type annotation of the Slide-seq dataset, we are leveraging an existing mouse single-cell RNA-seq hippocampus dataset, produced in Saunders*, Macosko*, et al. 2018. The data is available for download as a processed Seurat object here, with the raw count matrices available on the DropViz website.

The original annotations from the paper are provided in the cell metadata of the Seurat object. These annotations are provided at several “resolutions”, from broad classes (ref$class) to subclusters within celltypes (ref$subcluster). For the purposes of this vignette, we’ll work off of a modification of the celltype annotations (ref$celltype) which we felt struck a good balance.

We’ll start by running the Seurat label transfer method to predict the major celltype for each bead.

We can then visualize the prediction scores for some of the major expected classes.

As mentioned in the Visium vignette, we can identify spatially variable features in two general ways: differential expression testing between pre-annotated anatomical regions or statistics that measure the dependence of a feature on spatial location.

Here, we demonstrate the latter with an implementation of Moran’s I available via FindSpatiallyVariableFeatures() by setting method = 'moransi'. Moran’s I computes an overall spatial autocorrelation and gives a statistic (similar to a correlation coefficient) that measures the dependence of a feature on spatial location. This allows us to rank features based on how spatially variable their expression is. In order to facilitate quick estimation of this statistic, we implemented a basic binning strategy that will draw a rectangular grid over Slide-seq puck and average the feature and location within each bin. The number of bins in the x and y direction are controlled by the x.cuts and y.cuts parameters respectively. Additionally, while not required, installing the optional Rfast2 package(install.packages('Rfast2')), will significantly decrease the runtime via a more efficient implementation.

Now we visualize the expression of the top 6 features identified by Moran’s I.

While FindTransferAnchors can be used to integrate spot-level data from spatial transcriptomic datasets, Seurat v5 also includes support for the Robust Cell Type Decomposition, a computational approach to deconvolve spot-level data from spatial datasets, when provided with an scRNA-seq reference. RCTD has been shown to accurately annotate spatial data from a variety of technologies, including SLIDE-seq, Visium, and the 10x Xenium in-situ spatial platform.

To run RCTD, we first install the spacexr package from GitHub which implements RCTD.

Counts, cluster, and spot information is extracted from the Seurat query and reference objects to construct Reference and SpatialRNA objects used by RCTD for annotation.

Using the reference and query object, we annotate the dataset and add the cell type labels to the query Seurat object. RCTD parallelizes well, so multiple cores can be specified for faster performance.

Next, plot the RCTD annotations. Because we ran RCTD in doublet mode, the algorithm assigns a first_type and second_type for each barcode or spot.

Developed by Rahul Satija, Satija Lab and Collaborators.

Site built with pkgdown 2.1.3.

**Examples:**

Example 1 (unknown):
```unknown
vignettes/spatial_vignette.Rmd
```

Example 2 (unknown):
```unknown
spatial_vignette.Rmd
```

Example 3 (unknown):
```unknown
library(Seurat)
library(SeuratData)
library(ggplot2)
library(patchwork)
library(dplyr)
```

Example 4 (r):
```r
library(Seurat)
library(SeuratData)
library(ggplot2)
library(patchwork)
library(dplyr)
```

Example 5 (r):
```r
library(Seurat)
library(SeuratData)
library(ggplot2)
library(patchwork)
library(dplyr)
```

Example 6 (unknown):
```unknown
Load10X_Spatial()
```

Example 7 (unknown):
```unknown
InstallData("stxBrain")
```

Example 8 (r):
```r
InstallData("stxBrain")
```

Example 9 (r):
```r
InstallData("stxBrain")
```

Example 10 (unknown):
```unknown
brain <- LoadData("stxBrain", type = "anterior1")
```

Example 11 (r):
```r
brain <- LoadData("stxBrain", type = "anterior1")
```

Example 12 (r):
```r
brain <- LoadData("stxBrain", type = "anterior1")
```

Example 13 (unknown):
```unknown
plot1 <- VlnPlot(brain, features = "nCount_Spatial", pt.size = 0.1) + NoLegend()
plot2 <- SpatialFeaturePlot(brain, features = "nCount_Spatial") + theme(legend.position = "right")
wrap_plots(plot1, plot2)
```

Example 14 (r):
```r
plot1 <- VlnPlot(brain, features = "nCount_Spatial", pt.size = 0.1) + NoLegend()
plot2 <- SpatialFeaturePlot(brain, features = "nCount_Spatial") + theme(legend.position = "right")
wrap_plots(plot1, plot2)
```

Example 15 (r):
```r
plot1 <- VlnPlot(brain, features = "nCount_Spatial", pt.size = 0.1) + NoLegend()
plot2 <- SpatialFeaturePlot(brain, features = "nCount_Spatial") + theme(legend.position = "right")
wrap_plots(plot1, plot2)
```

Example 16 (unknown):
```unknown
LogNormalize()
```

Example 17 (unknown):
```unknown
brain <- SCTransform(brain, assay = "Spatial", verbose = FALSE)
```

Example 18 (r):
```r
brain <- SCTransform(brain, assay = "Spatial", verbose = FALSE)
```

Example 19 (r):
```r
brain <- SCTransform(brain, assay = "Spatial", verbose = FALSE)
```

Example 20 (unknown):
```unknown
NormalizeData()
```

Example 21 (unknown):
```unknown
# rerun normalization to store sctransform residuals for all genes
brain <- SCTransform(brain, assay = "Spatial", return.only.var.genes = FALSE, verbose = FALSE)
# also run standard log normalization for comparison
brain <- NormalizeData(brain, verbose = FALSE, assay = "Spatial")
```

Example 22 (r):
```r
# rerun normalization to store sctransform residuals for all genes
brain <- SCTransform(brain, assay = "Spatial", return.only.var.genes = FALSE, verbose = FALSE)
# also run standard log normalization for comparison
brain <- NormalizeData(brain, verbose = FALSE, assay = "Spatial")
```

Example 23 (r):
```r
# rerun normalization to store sctransform residuals for all genes
brain <- SCTransform(brain, assay = "Spatial", return.only.var.genes = FALSE, verbose = FALSE)
# also run standard log normalization for comparison
brain <- NormalizeData(brain, verbose = FALSE, assay = "Spatial")
```

Example 24 (unknown):
```unknown
# Computes the correlation of the log normalized data and sctransform residuals with the
# number of UMIs
brain <- GroupCorrelation(brain, group.assay = "Spatial", assay = "Spatial", slot = "data", do.plot = FALSE)
brain <- GroupCorrelation(brain, group.assay = "Spatial", assay = "SCT", slot = "scale.data", do.plot = FALSE)
```

Example 25 (r):
```r
# Computes the correlation of the log normalized data and sctransform residuals with the
# number of UMIs
brain <- GroupCorrelation(brain, group.assay = "Spatial", assay = "Spatial", slot = "data", do.plot = FALSE)
brain <- GroupCorrelation(brain, group.assay = "Spatial", assay = "SCT", slot = "scale.data", do.plot = FALSE)
```

Example 26 (r):
```r
# Computes the correlation of the log normalized data and sctransform residuals with the
# number of UMIs
brain <- GroupCorrelation(brain, group.assay = "Spatial", assay = "Spatial", slot = "data", do.plot = FALSE)
brain <- GroupCorrelation(brain, group.assay = "Spatial", assay = "SCT", slot = "scale.data", do.plot = FALSE)
```

Example 27 (unknown):
```unknown
p1 <- GroupCorrelationPlot(brain, assay = "Spatial", cor = "nCount_Spatial_cor") + ggtitle("Log Normalization") +
    theme(plot.title = element_text(hjust = 0.5))
p2 <- GroupCorrelationPlot(brain, assay = "SCT", cor = "nCount_Spatial_cor") + ggtitle("SCTransform Normalization") +
    theme(plot.title = element_text(hjust = 0.5))
p1 + p2
```

Example 28 (r):
```r
p1 <- GroupCorrelationPlot(brain, assay = "Spatial", cor = "nCount_Spatial_cor") + ggtitle("Log Normalization") +
    theme(plot.title = element_text(hjust = 0.5))
p2 <- GroupCorrelationPlot(brain, assay = "SCT", cor = "nCount_Spatial_cor") + ggtitle("SCTransform Normalization") +
    theme(plot.title = element_text(hjust = 0.5))
p1 + p2
```

Example 29 (r):
```r
p1 <- GroupCorrelationPlot(brain, assay = "Spatial", cor = "nCount_Spatial_cor") + ggtitle("Log Normalization") +
    theme(plot.title = element_text(hjust = 0.5))
p2 <- GroupCorrelationPlot(brain, assay = "SCT", cor = "nCount_Spatial_cor") + ggtitle("SCTransform Normalization") +
    theme(plot.title = element_text(hjust = 0.5))
p1 + p2
```

Example 30 (unknown):
```unknown
nCount_Spatial
```

Example 31 (unknown):
```unknown
SpatialFeaturePlot()
```

Example 32 (unknown):
```unknown
FeaturePlot()
```

Example 33 (unknown):
```unknown
SpatialFeaturePlot(brain, features = c("Hpca", "Ttr"))
```

Example 34 (r):
```r
SpatialFeaturePlot(brain, features = c("Hpca", "Ttr"))
```

Example 35 (r):
```r
SpatialFeaturePlot(brain, features = c("Hpca", "Ttr"))
```

Example 36 (python):
```python
library(ggplot2)
plot <- SpatialFeaturePlot(brain, features = c("Ttr")) + theme(legend.text = element_text(size = 0),
    legend.title = element_text(size = 20), legend.key.size = unit(1, "cm"))
jpeg(filename = "../output/images/spatial_vignette_ttr.jpg", height = 700, width = 1200, quality = 50)
print(plot)
```

Example 37 (r):
```r
library(ggplot2)
plot <- SpatialFeaturePlot(brain, features = c("Ttr")) + theme(legend.text = element_text(size = 0),
    legend.title = element_text(size = 20), legend.key.size = unit(1, "cm"))
jpeg(filename = "../output/images/spatial_vignette_ttr.jpg", height = 700, width = 1200, quality = 50)
print(plot)
```

Example 38 (r):
```r
library(ggplot2)
plot <- SpatialFeaturePlot(brain, features = c("Ttr")) + theme(legend.text = element_text(size = 0),
    legend.title = element_text(size = 20), legend.key.size = unit(1, "cm"))
jpeg(filename = "../output/images/spatial_vignette_ttr.jpg", height = 700, width = 1200, quality = 50)
print(plot)
```

Example 39 (unknown):
```unknown
## agg_png 
##       2
```

Example 40 (unknown):
```unknown
## agg_png 
##       2
```

Example 41 (unknown):
```unknown
pt.size.factor
```

Example 42 (unknown):
```unknown
p1 <- SpatialFeaturePlot(brain, features = "Ttr", pt.size.factor = 1)
p2 <- SpatialFeaturePlot(brain, features = "Ttr", alpha = c(0.1, 1))
p1 + p2
```

Example 43 (r):
```r
p1 <- SpatialFeaturePlot(brain, features = "Ttr", pt.size.factor = 1)
p2 <- SpatialFeaturePlot(brain, features = "Ttr", alpha = c(0.1, 1))
p1 + p2
```

Example 44 (r):
```r
p1 <- SpatialFeaturePlot(brain, features = "Ttr", pt.size.factor = 1)
p2 <- SpatialFeaturePlot(brain, features = "Ttr", alpha = c(0.1, 1))
p1 + p2
```

Example 45 (unknown):
```unknown
brain <- RunPCA(brain, assay = "SCT", verbose = FALSE)
brain <- FindNeighbors(brain, reduction = "pca", dims = 1:30)
brain <- FindClusters(brain, verbose = FALSE)
brain <- RunUMAP(brain, reduction = "pca", dims = 1:30)
```

Example 46 (r):
```r
brain <- RunPCA(brain, assay = "SCT", verbose = FALSE)
brain <- FindNeighbors(brain, reduction = "pca", dims = 1:30)
brain <- FindClusters(brain, verbose = FALSE)
brain <- RunUMAP(brain, reduction = "pca", dims = 1:30)
```

Example 47 (r):
```r
brain <- RunPCA(brain, assay = "SCT", verbose = FALSE)
brain <- FindNeighbors(brain, reduction = "pca", dims = 1:30)
brain <- FindClusters(brain, verbose = FALSE)
brain <- RunUMAP(brain, reduction = "pca", dims = 1:30)
```

Example 48 (unknown):
```unknown
SpatialDimPlot()
```

Example 49 (unknown):
```unknown
p1 <- DimPlot(brain, reduction = "umap", label = TRUE)
p2 <- SpatialDimPlot(brain, label = TRUE, label.size = 3)
p1 + p2
```

Example 50 (r):
```r
p1 <- DimPlot(brain, reduction = "umap", label = TRUE)
p2 <- SpatialDimPlot(brain, label = TRUE, label.size = 3)
p1 + p2
```

Example 51 (r):
```r
p1 <- DimPlot(brain, reduction = "umap", label = TRUE)
p2 <- SpatialDimPlot(brain, label = TRUE, label.size = 3)
p1 + p2
```

Example 52 (unknown):
```unknown
cells.highlight
```

Example 53 (unknown):
```unknown
SpatialDimPlot()
```

Example 54 (unknown):
```unknown
SpatialDimPlot(brain, cells.highlight = CellsByIdentities(object = brain, idents = c(2, 1, 4, 3,
    5, 8)), facet.highlight = TRUE, ncol = 3)
```

Example 55 (r):
```r
SpatialDimPlot(brain, cells.highlight = CellsByIdentities(object = brain, idents = c(2, 1, 4, 3,
    5, 8)), facet.highlight = TRUE, ncol = 3)
```

Example 56 (r):
```r
SpatialDimPlot(brain, cells.highlight = CellsByIdentities(object = brain, idents = c(2, 1, 4, 3,
    5, 8)), facet.highlight = TRUE, ncol = 3)
```

Example 57 (unknown):
```unknown
SpatialDimPlot()
```

Example 58 (unknown):
```unknown
SpatialFeaturePlot()
```

Example 59 (unknown):
```unknown
interactive
```

Example 60 (unknown):
```unknown
SpatialDimPlot()
```

Example 61 (unknown):
```unknown
SpatialDimPlot(brain, interactive = TRUE)
```

Example 62 (r):
```r
SpatialDimPlot(brain, interactive = TRUE)
```

Example 63 (r):
```r
SpatialDimPlot(brain, interactive = TRUE)
```

Example 64 (unknown):
```unknown
SpatialFeaturePlot()
```

Example 65 (unknown):
```unknown
SpatialFeaturePlot(brain, features = "Ttr", interactive = TRUE)
```

Example 66 (r):
```r
SpatialFeaturePlot(brain, features = "Ttr", interactive = TRUE)
```

Example 67 (r):
```r
SpatialFeaturePlot(brain, features = "Ttr", interactive = TRUE)
```

Example 68 (unknown):
```unknown
LinkedDimPlot()
```

Example 69 (unknown):
```unknown
LinkedDimPlot(brain)
```

Example 70 (r):
```r
LinkedDimPlot(brain)
```

Example 71 (r):
```r
LinkedDimPlot(brain)
```

Example 72 (unknown):
```unknown
de_markers <- FindMarkers(brain, ident.1 = 5, ident.2 = 6)
SpatialFeaturePlot(object = brain, features = rownames(de_markers)[1:3], alpha = c(0.1, 1), ncol = 3)
```

Example 73 (r):
```r
de_markers <- FindMarkers(brain, ident.1 = 5, ident.2 = 6)
SpatialFeaturePlot(object = brain, features = rownames(de_markers)[1:3], alpha = c(0.1, 1), ncol = 3)
```

Example 74 (r):
```r
de_markers <- FindMarkers(brain, ident.1 = 5, ident.2 = 6)
SpatialFeaturePlot(object = brain, features = rownames(de_markers)[1:3], alpha = c(0.1, 1), ncol = 3)
```

Example 75 (unknown):
```unknown
FindSpatiallyVariables()
```

Example 76 (unknown):
```unknown
method = 'markvariogram
```

Example 77 (unknown):
```unknown
brain <- FindSpatiallyVariableFeatures(brain, assay = "SCT", features = VariableFeatures(brain)[1:1000],
    selection.method = "moransi")
```

Example 78 (r):
```r
brain <- FindSpatiallyVariableFeatures(brain, assay = "SCT", features = VariableFeatures(brain)[1:1000],
    selection.method = "moransi")
```

Example 79 (r):
```r
brain <- FindSpatiallyVariableFeatures(brain, assay = "SCT", features = VariableFeatures(brain)[1:1000],
    selection.method = "moransi")
```

Example 80 (unknown):
```unknown
top.features <- head(SpatiallyVariableFeatures(brain, selection.method = "moransi"), 6)
SpatialFeaturePlot(brain, features = top.features, ncol = 3, alpha = c(0.1, 1))
```

Example 81 (r):
```r
top.features <- head(SpatiallyVariableFeatures(brain, selection.method = "moransi"), 6)
SpatialFeaturePlot(brain, features = top.features, ncol = 3, alpha = c(0.1, 1))
```

Example 82 (r):
```r
top.features <- head(SpatiallyVariableFeatures(brain, selection.method = "moransi"), 6)
SpatialFeaturePlot(brain, features = top.features, ncol = 3, alpha = c(0.1, 1))
```

Example 83 (python):
```python
# Subset to clusters of interest
cortex <- subset(brain, idents = c(1, 2, 3, 4, 6, 7))

# Extract and attach spatial coordinates from anterior1 image
centroids <- cortex[["anterior1"]]@boundaries$centroids
coords <- setNames(as.data.frame(centroids@coords), c("x", "y"))
rownames(coords) <- centroids@cells
cortex$x <- coords[colnames(cortex), "x"]
cortex$y <- coords[colnames(cortex), "y"]

# Perform spatial subsetting using image position Subset to upper right quadrant
cortex <- subset(cortex, y < 2719 | x > 7835, invert = TRUE)

# Further remove cells in lower right quadrant
m <- (9395 - 5747)/(4960 - 7715)
b <- 5747 - m * 7715
cortex <- subset(cortex, y > m * x + b, invert = TRUE)
```

Example 84 (r):
```r
# Subset to clusters of interest
cortex <- subset(brain, idents = c(1, 2, 3, 4, 6, 7))

# Extract and attach spatial coordinates from anterior1 image
centroids <- cortex[["anterior1"]]@boundaries$centroids
coords <- setNames(as.data.frame(centroids@coords), c("x", "y"))
rownames(coords) <- centroids@cells
cortex$x <- coords[colnames(cortex), "x"]
cortex$y <- coords[colnames(cortex), "y"]

# Perform spatial subsetting using image position Subset to upper right quadrant
cortex <- subset(cortex, y < 2719 | x > 7835, invert = TRUE)

# Further remove cells in lower right quadrant
m <- (9395 - 5747)/(4960 - 7715)
b <- 5747 - m * 7715
cortex <- subset(cortex, y > m * x + b, invert = TRUE)
```

Example 85 (r):
```r
# Subset to clusters of interest
cortex <- subset(brain, idents = c(1, 2, 3, 4, 6, 7))

# Extract and attach spatial coordinates from anterior1 image
centroids <- cortex[["anterior1"]]@boundaries$centroids
coords <- setNames(as.data.frame(centroids@coords), c("x", "y"))
rownames(coords) <- centroids@cells
cortex$x <- coords[colnames(cortex), "x"]
cortex$y <- coords[colnames(cortex), "y"]

# Perform spatial subsetting using image position Subset to upper right quadrant
cortex <- subset(cortex, y < 2719 | x > 7835, invert = TRUE)

# Further remove cells in lower right quadrant
m <- (9395 - 5747)/(4960 - 7715)
b <- 5747 - m * 7715
cortex <- subset(cortex, y > m * x + b, invert = TRUE)
```

Example 86 (unknown):
```unknown
# Visualize the subsetted data on full image vs cropped image
p1 <- SpatialDimPlot(cortex, crop = TRUE, label = TRUE)
p2 <- SpatialDimPlot(cortex, crop = FALSE, label = TRUE, pt.size.factor = 1, label.size = 3)
p1 + p2
```

Example 87 (r):
```r
# Visualize the subsetted data on full image vs cropped image
p1 <- SpatialDimPlot(cortex, crop = TRUE, label = TRUE)
p2 <- SpatialDimPlot(cortex, crop = FALSE, label = TRUE, pt.size.factor = 1, label.size = 3)
p1 + p2
```

Example 88 (r):
```r
# Visualize the subsetted data on full image vs cropped image
p1 <- SpatialDimPlot(cortex, crop = TRUE, label = TRUE)
p2 <- SpatialDimPlot(cortex, crop = FALSE, label = TRUE, pt.size.factor = 1, label.size = 3)
p1 + p2
```

Example 89 (unknown):
```unknown
allen_reference <- readRDS("/brahms/shared/vignette-data/allen_cortex.rds")
```

Example 90 (r):
```r
allen_reference <- readRDS("/brahms/shared/vignette-data/allen_cortex.rds")
```

Example 91 (r):
```r
allen_reference <- readRDS("/brahms/shared/vignette-data/allen_cortex.rds")
```

Example 92 (unknown):
```unknown
# note that setting ncells=3000 normalizes the full dataset but learns noise models on 3k
# cells this speeds up SCTransform dramatically with no loss in performance
library(dplyr)
allen_reference <- SCTransform(allen_reference, ncells = 3000, verbose = FALSE) %>%
    RunPCA(verbose = FALSE) %>%
    RunUMAP(dims = 1:30)
```

Example 93 (r):
```r
# note that setting ncells=3000 normalizes the full dataset but learns noise models on 3k
# cells this speeds up SCTransform dramatically with no loss in performance
library(dplyr)
allen_reference <- SCTransform(allen_reference, ncells = 3000, verbose = FALSE) %>%
    RunPCA(verbose = FALSE) %>%
    RunUMAP(dims = 1:30)
```

Example 94 (r):
```r
# note that setting ncells=3000 normalizes the full dataset but learns noise models on 3k
# cells this speeds up SCTransform dramatically with no loss in performance
library(dplyr)
allen_reference <- SCTransform(allen_reference, ncells = 3000, verbose = FALSE) %>%
    RunPCA(verbose = FALSE) %>%
    RunUMAP(dims = 1:30)
```

Example 95 (python):
```python
# After subsetting, we renormalize cortex
cortex <- SCTransform(cortex, assay = "Spatial", verbose = FALSE) %>%
    RunPCA(verbose = FALSE)
# the annotation is stored in the 'subclass' column of object metadata
DimPlot(allen_reference, group.by = "subclass", label = TRUE)
```

Example 96 (r):
```r
# After subsetting, we renormalize cortex
cortex <- SCTransform(cortex, assay = "Spatial", verbose = FALSE) %>%
    RunPCA(verbose = FALSE)
# the annotation is stored in the 'subclass' column of object metadata
DimPlot(allen_reference, group.by = "subclass", label = TRUE)
```

Example 97 (r):
```r
# After subsetting, we renormalize cortex
cortex <- SCTransform(cortex, assay = "Spatial", verbose = FALSE) %>%
    RunPCA(verbose = FALSE)
# the annotation is stored in the 'subclass' column of object metadata
DimPlot(allen_reference, group.by = "subclass", label = TRUE)
```

Example 98 (unknown):
```unknown
anchors <- FindTransferAnchors(reference = allen_reference, query = cortex, normalization.method = "SCT")
predictions.assay <- TransferData(anchorset = anchors, refdata = allen_reference$subclass, prediction.assay = TRUE,
    weight.reduction = cortex[["pca"]], dims = 1:30)
cortex[["predictions"]] <- predictions.assay
```

Example 99 (r):
```r
anchors <- FindTransferAnchors(reference = allen_reference, query = cortex, normalization.method = "SCT")
predictions.assay <- TransferData(anchorset = anchors, refdata = allen_reference$subclass, prediction.assay = TRUE,
    weight.reduction = cortex[["pca"]], dims = 1:30)
cortex[["predictions"]] <- predictions.assay
```

Example 100 (r):
```r
anchors <- FindTransferAnchors(reference = allen_reference, query = cortex, normalization.method = "SCT")
predictions.assay <- TransferData(anchorset = anchors, refdata = allen_reference$subclass, prediction.assay = TRUE,
    weight.reduction = cortex[["pca"]], dims = 1:30)
cortex[["predictions"]] <- predictions.assay
```

Example 101 (unknown):
```unknown
DefaultAssay(cortex) <- "predictions"
SpatialFeaturePlot(cortex, features = c("L2/3 IT", "L4"), pt.size.factor = 1.6, ncol = 2, crop = TRUE)
```

Example 102 (r):
```r
DefaultAssay(cortex) <- "predictions"
SpatialFeaturePlot(cortex, features = c("L2/3 IT", "L4"), pt.size.factor = 1.6, ncol = 2, crop = TRUE)
```

Example 103 (r):
```r
DefaultAssay(cortex) <- "predictions"
SpatialFeaturePlot(cortex, features = c("L2/3 IT", "L4"), pt.size.factor = 1.6, ncol = 2, crop = TRUE)
```

Example 104 (unknown):
```unknown
cortex <- FindSpatiallyVariableFeatures(cortex, assay = "predictions", selection.method = "moransi",
    features = rownames(cortex), r.metric = 5, slot = "data")
top.clusters <- head(SpatiallyVariableFeatures(cortex, selection.method = "moransi"), 4)
SpatialPlot(object = cortex, features = top.clusters, ncol = 2)
```

Example 105 (r):
```r
cortex <- FindSpatiallyVariableFeatures(cortex, assay = "predictions", selection.method = "moransi",
    features = rownames(cortex), r.metric = 5, slot = "data")
top.clusters <- head(SpatiallyVariableFeatures(cortex, selection.method = "moransi"), 4)
SpatialPlot(object = cortex, features = top.clusters, ncol = 2)
```

Example 106 (r):
```r
cortex <- FindSpatiallyVariableFeatures(cortex, assay = "predictions", selection.method = "moransi",
    features = rownames(cortex), r.metric = 5, slot = "data")
top.clusters <- head(SpatiallyVariableFeatures(cortex, selection.method = "moransi"), 4)
SpatialPlot(object = cortex, features = top.clusters, ncol = 2)
```

Example 107 (unknown):
```unknown
SpatialFeaturePlot(cortex, features = c("Astro", "L2/3 IT", "L4", "L5 PT", "L5 IT", "L6 CT", "L6 IT",
    "L6b", "Oligo"), pt.size.factor = 1, ncol = 2, crop = FALSE, alpha = c(0.1, 1))
```

Example 108 (r):
```r
SpatialFeaturePlot(cortex, features = c("Astro", "L2/3 IT", "L4", "L5 PT", "L5 IT", "L6 CT", "L6 IT",
    "L6b", "Oligo"), pt.size.factor = 1, ncol = 2, crop = FALSE, alpha = c(0.1, 1))
```

Example 109 (r):
```r
SpatialFeaturePlot(cortex, features = c("Astro", "L2/3 IT", "L4", "L5 PT", "L5 IT", "L6 CT", "L6 IT",
    "L6b", "Oligo"), pt.size.factor = 1, ncol = 2, crop = FALSE, alpha = c(0.1, 1))
```

Example 110 (unknown):
```unknown
brain2 <- LoadData("stxBrain", type = "posterior1")
brain2 <- SCTransform(brain2, assay = "Spatial", verbose = FALSE)
```

Example 111 (r):
```r
brain2 <- LoadData("stxBrain", type = "posterior1")
brain2 <- SCTransform(brain2, assay = "Spatial", verbose = FALSE)
```

Example 112 (r):
```r
brain2 <- LoadData("stxBrain", type = "posterior1")
brain2 <- SCTransform(brain2, assay = "Spatial", verbose = FALSE)
```

Example 113 (unknown):
```unknown
brain.merge <- merge(brain, brain2)
```

Example 114 (r):
```r
brain.merge <- merge(brain, brain2)
```

Example 115 (r):
```r
brain.merge <- merge(brain, brain2)
```

Example 116 (unknown):
```unknown
DefaultAssay(brain.merge) <- "SCT"
VariableFeatures(brain.merge) <- c(VariableFeatures(brain), VariableFeatures(brain2))
brain.merge <- RunPCA(brain.merge, verbose = FALSE)
brain.merge <- FindNeighbors(brain.merge, dims = 1:30)
brain.merge <- FindClusters(brain.merge, verbose = FALSE)
brain.merge <- RunUMAP(brain.merge, dims = 1:30)
```

Example 117 (r):
```r
DefaultAssay(brain.merge) <- "SCT"
VariableFeatures(brain.merge) <- c(VariableFeatures(brain), VariableFeatures(brain2))
brain.merge <- RunPCA(brain.merge, verbose = FALSE)
brain.merge <- FindNeighbors(brain.merge, dims = 1:30)
brain.merge <- FindClusters(brain.merge, verbose = FALSE)
brain.merge <- RunUMAP(brain.merge, dims = 1:30)
```

Example 118 (r):
```r
DefaultAssay(brain.merge) <- "SCT"
VariableFeatures(brain.merge) <- c(VariableFeatures(brain), VariableFeatures(brain2))
brain.merge <- RunPCA(brain.merge, verbose = FALSE)
brain.merge <- FindNeighbors(brain.merge, dims = 1:30)
brain.merge <- FindClusters(brain.merge, verbose = FALSE)
brain.merge <- RunUMAP(brain.merge, dims = 1:30)
```

Example 119 (unknown):
```unknown
SpatialDimPlot()
```

Example 120 (unknown):
```unknown
SpatialFeaturePlot()
```

Example 121 (unknown):
```unknown
DimPlot(brain.merge, reduction = "umap", group.by = c("ident", "orig.ident"))
```

Example 122 (r):
```r
DimPlot(brain.merge, reduction = "umap", group.by = c("ident", "orig.ident"))
```

Example 123 (r):
```r
DimPlot(brain.merge, reduction = "umap", group.by = c("ident", "orig.ident"))
```

Example 124 (unknown):
```unknown
SpatialDimPlot(brain.merge)
```

Example 125 (r):
```r
SpatialDimPlot(brain.merge)
```

Example 126 (r):
```r
SpatialDimPlot(brain.merge)
```

Example 127 (unknown):
```unknown
SpatialFeaturePlot(brain.merge, features = c("Hpca", "Plp1"))
```

Example 128 (r):
```r
SpatialFeaturePlot(brain.merge, features = c("Hpca", "Plp1"))
```

Example 129 (r):
```r
SpatialFeaturePlot(brain.merge, features = c("Hpca", "Plp1"))
```

Example 130 (unknown):
```unknown
InstallData("ssHippo")
```

Example 131 (r):
```r
InstallData("ssHippo")
```

Example 132 (r):
```r
InstallData("ssHippo")
```

Example 133 (unknown):
```unknown
slide.seq <- LoadData("ssHippo")
```

Example 134 (r):
```r
slide.seq <- LoadData("ssHippo")
```

Example 135 (r):
```r
slide.seq <- LoadData("ssHippo")
```

Example 136 (unknown):
```unknown
plot1 <- VlnPlot(slide.seq, features = "nCount_Spatial", pt.size = 0, log = TRUE) + NoLegend()
slide.seq$log_nCount_Spatial <- log(slide.seq$nCount_Spatial)
plot2 <- SpatialFeaturePlot(slide.seq, features = "log_nCount_Spatial") + theme(legend.position = "right")
wrap_plots(plot1, plot2)
```

Example 137 (r):
```r
plot1 <- VlnPlot(slide.seq, features = "nCount_Spatial", pt.size = 0, log = TRUE) + NoLegend()
slide.seq$log_nCount_Spatial <- log(slide.seq$nCount_Spatial)
plot2 <- SpatialFeaturePlot(slide.seq, features = "log_nCount_Spatial") + theme(legend.position = "right")
wrap_plots(plot1, plot2)
```

Example 138 (r):
```r
plot1 <- VlnPlot(slide.seq, features = "nCount_Spatial", pt.size = 0, log = TRUE) + NoLegend()
slide.seq$log_nCount_Spatial <- log(slide.seq$nCount_Spatial)
plot2 <- SpatialFeaturePlot(slide.seq, features = "log_nCount_Spatial") + theme(legend.position = "right")
wrap_plots(plot1, plot2)
```

Example 139 (unknown):
```unknown
slide.seq <- SCTransform(slide.seq, assay = "Spatial", ncells = 3000, verbose = FALSE)
slide.seq <- RunPCA(slide.seq)
slide.seq <- RunUMAP(slide.seq, dims = 1:30)
slide.seq <- FindNeighbors(slide.seq, dims = 1:30)
slide.seq <- FindClusters(slide.seq, resolution = 0.3, verbose = FALSE)
```

Example 140 (r):
```r
slide.seq <- SCTransform(slide.seq, assay = "Spatial", ncells = 3000, verbose = FALSE)
slide.seq <- RunPCA(slide.seq)
slide.seq <- RunUMAP(slide.seq, dims = 1:30)
slide.seq <- FindNeighbors(slide.seq, dims = 1:30)
slide.seq <- FindClusters(slide.seq, resolution = 0.3, verbose = FALSE)
```

Example 141 (r):
```r
slide.seq <- SCTransform(slide.seq, assay = "Spatial", ncells = 3000, verbose = FALSE)
slide.seq <- RunPCA(slide.seq)
slide.seq <- RunUMAP(slide.seq, dims = 1:30)
slide.seq <- FindNeighbors(slide.seq, dims = 1:30)
slide.seq <- FindClusters(slide.seq, resolution = 0.3, verbose = FALSE)
```

Example 142 (unknown):
```unknown
SpatialDimPlot()
```

Example 143 (unknown):
```unknown
plot1 <- DimPlot(slide.seq, reduction = "umap", label = TRUE)
plot2 <- SpatialDimPlot(slide.seq, stroke = 0)
plot1 + plot2
```

Example 144 (r):
```r
plot1 <- DimPlot(slide.seq, reduction = "umap", label = TRUE)
plot2 <- SpatialDimPlot(slide.seq, stroke = 0)
plot1 + plot2
```

Example 145 (r):
```r
plot1 <- DimPlot(slide.seq, reduction = "umap", label = TRUE)
plot2 <- SpatialDimPlot(slide.seq, stroke = 0)
plot1 + plot2
```

Example 146 (unknown):
```unknown
SpatialDimPlot(slide.seq, cells.highlight = CellsByIdentities(object = slide.seq, idents = c(1,
    6, 13)), facet.highlight = TRUE)
```

Example 147 (r):
```r
SpatialDimPlot(slide.seq, cells.highlight = CellsByIdentities(object = slide.seq, idents = c(1,
    6, 13)), facet.highlight = TRUE)
```

Example 148 (r):
```r
SpatialDimPlot(slide.seq, cells.highlight = CellsByIdentities(object = slide.seq, idents = c(1,
    6, 13)), facet.highlight = TRUE)
```

Example 149 (unknown):
```unknown
ref <- readRDS("/brahms/shared/vignette-data/mouse_hippocampus_reference.rds")
ref <- UpdateSeuratObject(ref)
```

Example 150 (r):
```r
ref <- readRDS("/brahms/shared/vignette-data/mouse_hippocampus_reference.rds")
ref <- UpdateSeuratObject(ref)
```

Example 151 (r):
```r
ref <- readRDS("/brahms/shared/vignette-data/mouse_hippocampus_reference.rds")
ref <- UpdateSeuratObject(ref)
```

Example 152 (unknown):
```unknown
ref$subcluster
```

Example 153 (unknown):
```unknown
ref$celltype
```

Example 154 (unknown):
```unknown
anchors <- FindTransferAnchors(reference = ref, query = slide.seq, normalization.method = "SCT",
    npcs = 50)
predictions.assay <- TransferData(anchorset = anchors, refdata = ref$celltype, prediction.assay = TRUE,
    weight.reduction = slide.seq[["pca"]], dims = 1:50)
slide.seq[["predictions"]] <- predictions.assay
```

Example 155 (r):
```r
anchors <- FindTransferAnchors(reference = ref, query = slide.seq, normalization.method = "SCT",
    npcs = 50)
predictions.assay <- TransferData(anchorset = anchors, refdata = ref$celltype, prediction.assay = TRUE,
    weight.reduction = slide.seq[["pca"]], dims = 1:50)
slide.seq[["predictions"]] <- predictions.assay
```

Example 156 (r):
```r
anchors <- FindTransferAnchors(reference = ref, query = slide.seq, normalization.method = "SCT",
    npcs = 50)
predictions.assay <- TransferData(anchorset = anchors, refdata = ref$celltype, prediction.assay = TRUE,
    weight.reduction = slide.seq[["pca"]], dims = 1:50)
slide.seq[["predictions"]] <- predictions.assay
```

Example 157 (unknown):
```unknown
DefaultAssay(slide.seq) <- "predictions"
SpatialFeaturePlot(slide.seq, features = c("Dentate Principal cells", "CA3 Principal cells", "Entorhinal cortex",
    "Endothelial tip", "Ependymal", "Oligodendrocyte"), alpha = c(0.1, 1))
```

Example 158 (r):
```r
DefaultAssay(slide.seq) <- "predictions"
SpatialFeaturePlot(slide.seq, features = c("Dentate Principal cells", "CA3 Principal cells", "Entorhinal cortex",
    "Endothelial tip", "Ependymal", "Oligodendrocyte"), alpha = c(0.1, 1))
```

Example 159 (r):
```r
DefaultAssay(slide.seq) <- "predictions"
SpatialFeaturePlot(slide.seq, features = c("Dentate Principal cells", "CA3 Principal cells", "Entorhinal cortex",
    "Endothelial tip", "Ependymal", "Oligodendrocyte"), alpha = c(0.1, 1))
```

Example 160 (unknown):
```unknown
slide.seq$predicted.id <- GetTransferPredictions(slide.seq)
Idents(slide.seq) <- "predicted.id"
SpatialDimPlot(slide.seq, cells.highlight = CellsByIdentities(object = slide.seq, idents = c("CA3 Principal cells",
    "Dentate Principal cells", "Endothelial tip")), facet.highlight = TRUE)
```

Example 161 (r):
```r
slide.seq$predicted.id <- GetTransferPredictions(slide.seq)
Idents(slide.seq) <- "predicted.id"
SpatialDimPlot(slide.seq, cells.highlight = CellsByIdentities(object = slide.seq, idents = c("CA3 Principal cells",
    "Dentate Principal cells", "Endothelial tip")), facet.highlight = TRUE)
```

Example 162 (r):
```r
slide.seq$predicted.id <- GetTransferPredictions(slide.seq)
Idents(slide.seq) <- "predicted.id"
SpatialDimPlot(slide.seq, cells.highlight = CellsByIdentities(object = slide.seq, idents = c("CA3 Principal cells",
    "Dentate Principal cells", "Endothelial tip")), facet.highlight = TRUE)
```

Example 163 (unknown):
```unknown
FindSpatiallyVariableFeatures()
```

Example 164 (unknown):
```unknown
method = 'moransi'
```

Example 165 (unknown):
```unknown
install.packages('Rfast2')
```

Example 166 (unknown):
```unknown
DefaultAssay(slide.seq) <- "SCT"
slide.seq <- FindSpatiallyVariableFeatures(slide.seq, assay = "SCT", slot = "scale.data", features = VariableFeatures(slide.seq)[1:1000],
    selection.method = "moransi", x.cuts = 100, y.cuts = 100)
```

Example 167 (r):
```r
DefaultAssay(slide.seq) <- "SCT"
slide.seq <- FindSpatiallyVariableFeatures(slide.seq, assay = "SCT", slot = "scale.data", features = VariableFeatures(slide.seq)[1:1000],
    selection.method = "moransi", x.cuts = 100, y.cuts = 100)
```

Example 168 (r):
```r
DefaultAssay(slide.seq) <- "SCT"
slide.seq <- FindSpatiallyVariableFeatures(slide.seq, assay = "SCT", slot = "scale.data", features = VariableFeatures(slide.seq)[1:1000],
    selection.method = "moransi", x.cuts = 100, y.cuts = 100)
```

Example 169 (unknown):
```unknown
SpatialFeaturePlot(slide.seq, features = head(SpatiallyVariableFeatures(slide.seq, selection.method = "moransi"),
    6), ncol = 3, alpha = c(0.1, 1), max.cutoff = "q95")
```

Example 170 (r):
```r
SpatialFeaturePlot(slide.seq, features = head(SpatiallyVariableFeatures(slide.seq, selection.method = "moransi"),
    6), ncol = 3, alpha = c(0.1, 1), max.cutoff = "q95")
```

Example 171 (r):
```r
SpatialFeaturePlot(slide.seq, features = head(SpatiallyVariableFeatures(slide.seq, selection.method = "moransi"),
    6), ncol = 3, alpha = c(0.1, 1), max.cutoff = "q95")
```

Example 172 (unknown):
```unknown
FindTransferAnchors
```

Example 173 (unknown):
```unknown
devtools::install_github("dmcable/spacexr", build_vignettes = FALSE)
```

Example 174 (r):
```r
devtools::install_github("dmcable/spacexr", build_vignettes = FALSE)
```

Example 175 (r):
```r
devtools::install_github("dmcable/spacexr", build_vignettes = FALSE)
```

Example 176 (unknown):
```unknown
library(spacexr)

# set up reference
ref <- readRDS("../data/mouse_hippocampus_reference.rds")
```

Example 177 (r):
```r
library(spacexr)

# set up reference
ref <- readRDS("../data/mouse_hippocampus_reference.rds")
```

Example 178 (r):
```r
library(spacexr)

# set up reference
ref <- readRDS("../data/mouse_hippocampus_reference.rds")
```

Example 179 (unknown):
```unknown
## Error in gzfile(file, "rb"): cannot open the connection
```

Example 180 (unknown):
```unknown
## Error in gzfile(file, "rb"): cannot open the connection
```

Example 181 (unknown):
```unknown
ref <- UpdateSeuratObject(ref)
Idents(ref) <- "celltype"

# extract information to pass to the RCTD Reference function
counts <- ref[["RNA"]]$counts
cluster <- as.factor(ref$celltype)
names(cluster) <- colnames(ref)
nUMI <- ref$nCount_RNA
names(nUMI) <- colnames(ref)
reference <- Reference(counts, cluster, nUMI)

# set up query with the RCTD function SpatialRNA
slide.seq <- SeuratData::LoadData("ssHippo")
counts <- slide.seq[["Spatial"]]$counts
coords <- GetTissueCoordinates(slide.seq)
colnames(coords) <- c("x", "y")
coords[is.na(colnames(coords))] <- NULL
query <- SpatialRNA(coords, counts, colSums(counts))
```

Example 182 (r):
```r
ref <- UpdateSeuratObject(ref)
Idents(ref) <- "celltype"

# extract information to pass to the RCTD Reference function
counts <- ref[["RNA"]]$counts
cluster <- as.factor(ref$celltype)
names(cluster) <- colnames(ref)
nUMI <- ref$nCount_RNA
names(nUMI) <- colnames(ref)
reference <- Reference(counts, cluster, nUMI)

# set up query with the RCTD function SpatialRNA
slide.seq <- SeuratData::LoadData("ssHippo")
counts <- slide.seq[["Spatial"]]$counts
coords <- GetTissueCoordinates(slide.seq)
colnames(coords) <- c("x", "y")
coords[is.na(colnames(coords))] <- NULL
query <- SpatialRNA(coords, counts, colSums(counts))
```

Example 183 (r):
```r
ref <- UpdateSeuratObject(ref)
Idents(ref) <- "celltype"

# extract information to pass to the RCTD Reference function
counts <- ref[["RNA"]]$counts
cluster <- as.factor(ref$celltype)
names(cluster) <- colnames(ref)
nUMI <- ref$nCount_RNA
names(nUMI) <- colnames(ref)
reference <- Reference(counts, cluster, nUMI)

# set up query with the RCTD function SpatialRNA
slide.seq <- SeuratData::LoadData("ssHippo")
counts <- slide.seq[["Spatial"]]$counts
coords <- GetTissueCoordinates(slide.seq)
colnames(coords) <- c("x", "y")
coords[is.na(colnames(coords))] <- NULL
query <- SpatialRNA(coords, counts, colSums(counts))
```

Example 184 (python):
```python
RCTD <- create.RCTD(query, reference, max_cores = 8)
RCTD <- run.RCTD(RCTD, doublet_mode = "doublet")
slide.seq <- AddMetaData(slide.seq, metadata = RCTD@results$results_df)
```

Example 185 (r):
```r
RCTD <- create.RCTD(query, reference, max_cores = 8)
RCTD <- run.RCTD(RCTD, doublet_mode = "doublet")
slide.seq <- AddMetaData(slide.seq, metadata = RCTD@results$results_df)
```

Example 186 (r):
```r
RCTD <- create.RCTD(query, reference, max_cores = 8)
RCTD <- run.RCTD(RCTD, doublet_mode = "doublet")
slide.seq <- AddMetaData(slide.seq, metadata = RCTD@results$results_df)
```

Example 187 (unknown):
```unknown
second_type
```

Example 188 (unknown):
```unknown
p1 <- SpatialDimPlot(slide.seq, group.by = "first_type")
p2 <- SpatialDimPlot(slide.seq, group.by = "second_type")
p1 | p2
```

Example 189 (r):
```r
p1 <- SpatialDimPlot(slide.seq, group.by = "first_type")
p2 <- SpatialDimPlot(slide.seq, group.by = "second_type")
p1 | p2
```

Example 190 (r):
```r
p1 <- SpatialDimPlot(slide.seq, group.by = "first_type")
p2 <- SpatialDimPlot(slide.seq, group.by = "second_type")
p1 | p2
```

Example 191 (unknown):
```unknown
sessionInfo()
```

Example 192 (r):
```r
sessionInfo()
```

Example 193 (r):
```r
sessionInfo()
```

Example 194 (unknown):
```unknown
## R version 4.4.2 (2024-10-31)
## Platform: x86_64-pc-linux-gnu
## Running under: Ubuntu 20.04.6 LTS
## 
## Matrix products: default
## BLAS:   /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.9.0 
## LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.9.0
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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: America/New_York
## tzcode source: system (glibc)
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
##  [1] spacexr_2.2.1             future_1.58.0            
##  [3] vembedr_0.1.5             htmltools_0.5.8.1        
##  [5] dplyr_1.1.4               patchwork_1.3.0          
##  [7] ggplot2_3.5.2             stxBrain.SeuratData_0.1.2
##  [9] ssHippo.SeuratData_3.1.4  pbmcsca.SeuratData_3.0.0 
## [11] pbmc3k.SeuratData_3.1.4   ifnb.SeuratData_3.1.0    
## [13] bmcite.SeuratData_0.3.0   SeuratData_0.2.2.9002    
## [15] Seurat_5.3.0              SeuratObject_5.1.0       
## [17] sp_2.2-0                 
## 
## loaded via a namespace (and not attached):
##   [1] RcppAnnoy_0.0.22            splines_4.4.2              
##   [3] later_1.4.2                 tibble_3.2.1               
##   [5] polyclip_1.10-7             fastDummies_1.7.5          
##   [7] lifecycle_1.0.4             doParallel_1.0.17          
##   [9] globals_0.18.0              lattice_0.22-7             
##  [11] MASS_7.3-65                 magrittr_2.0.3             
##  [13] plotly_4.10.4               sass_0.4.10                
##  [15] rmarkdown_2.29              jquerylib_0.1.4            
##  [17] yaml_2.3.10                 httpuv_1.6.16              
##  [19] glmGamPoi_1.18.0            sctransform_0.4.2          
##  [21] spam_2.11-1                 spatstat.sparse_3.1-0      
##  [23] reticulate_1.42.0           cowplot_1.1.3              
##  [25] pbapply_1.7-2               RColorBrewer_1.1-3         
##  [27] abind_1.4-8                 zlibbioc_1.52.0            
##  [29] quadprog_1.5-8              Rtsne_0.17                 
##  [31] GenomicRanges_1.58.0        purrr_1.0.4                
##  [33] presto_1.0.0                BiocGenerics_0.52.0        
##  [35] rappdirs_0.3.3              GenomeInfoDbData_1.2.13    
##  [37] IRanges_2.40.1              S4Vectors_0.44.0           
##  [39] ggrepel_0.9.6               irlba_2.3.5.1              
##  [41] listenv_0.9.1               spatstat.utils_3.1-4       
##  [43] goftest_1.2-3               RSpectra_0.16-2            
##  [45] spatstat.random_3.4-1       fitdistrplus_1.2-2         
##  [47] parallelly_1.45.0           pkgdown_2.1.3              
##  [49] DelayedMatrixStats_1.28.1   codetools_0.2-20           
##  [51] DelayedArray_0.32.0         tidyselect_1.2.1           
##  [53] UCSC.utils_1.2.0            farver_2.1.2               
##  [55] matrixStats_1.5.0           stats4_4.4.2               
##  [57] spatstat.explore_3.4-3      jsonlite_2.0.0             
##  [59] progressr_0.15.1            iterators_1.0.14           
##  [61] ggridges_0.5.6              survival_3.8-3             
##  [63] systemfonts_1.2.3           foreach_1.5.2              
##  [65] tools_4.4.2                 ragg_1.4.0                 
##  [67] ica_1.0-3                   Rcpp_1.0.14                
##  [69] glue_1.8.0                  gridExtra_2.3              
##  [71] SparseArray_1.6.2           xfun_0.52                  
##  [73] MatrixGenerics_1.18.1       GenomeInfoDb_1.42.3        
##  [75] withr_3.0.2                 formatR_1.14               
##  [77] fastmap_1.2.0               digest_0.6.37              
##  [79] R6_2.6.1                    mime_0.13                  
##  [81] textshaping_1.0.1           scattermore_1.2            
##  [83] tensor_1.5                  dichromat_2.0-0.1          
##  [85] spatstat.data_3.1-6         tidyr_1.3.1                
##  [87] generics_0.1.4              data.table_1.17.4          
##  [89] httr_1.4.7                  htmlwidgets_1.6.4          
##  [91] S4Arrays_1.6.0              uwot_0.2.3                 
##  [93] pkgconfig_2.0.3             gtable_0.3.6               
##  [95] lmtest_0.9-40               XVector_0.46.0             
##  [97] dotCall64_1.2               scales_1.4.0               
##  [99] Biobase_2.66.0              png_0.1-8                  
## [101] spatstat.univar_3.1-3       knitr_1.50                 
## [103] rstudioapi_0.17.1           reshape2_1.4.4             
## [105] nlme_3.1-168                cachem_1.1.0               
## [107] zoo_1.8-14                  stringr_1.5.1              
## [109] KernSmooth_2.23-26          parallel_4.4.2             
## [111] miniUI_0.1.2                vipor_0.4.7                
## [113] ggrastr_1.0.2               desc_1.4.3                 
## [115] pillar_1.10.2               grid_4.4.2                 
## [117] vctrs_0.6.5                 RANN_2.6.2                 
## [119] promises_1.3.3              xtable_1.8-4               
## [121] cluster_2.1.8.1             beeswarm_0.4.0             
## [123] evaluate_1.0.3              cli_3.6.5                  
## [125] compiler_4.4.2              rlang_1.1.6                
## [127] crayon_1.5.3                future.apply_1.11.3        
## [129] labeling_0.4.3              plyr_1.8.9                 
## [131] fs_1.6.6                    ggbeeswarm_0.7.2           
## [133] stringi_1.8.7               viridisLite_0.4.2          
## [135] deldir_2.0-4                assertthat_0.2.1           
## [137] lazyeval_0.2.2              spatstat.geom_3.4-1        
## [139] Matrix_1.7-3                RcppHNSW_0.6.0             
## [141] sparseMatrixStats_1.18.0    shiny_1.10.0               
## [143] SummarizedExperiment_1.36.0 ROCR_1.0-11                
## [145] igraph_2.1.4                bslib_0.9.0                
## [147] ape_5.8-1
```

Example 195 (unknown):
```unknown
## R version 4.4.2 (2024-10-31)
## Platform: x86_64-pc-linux-gnu
## Running under: Ubuntu 20.04.6 LTS
## 
## Matrix products: default
## BLAS:   /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.9.0 
## LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.9.0
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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: America/New_York
## tzcode source: system (glibc)
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
##  [1] spacexr_2.2.1             future_1.58.0            
##  [3] vembedr_0.1.5             htmltools_0.5.8.1        
##  [5] dplyr_1.1.4               patchwork_1.3.0          
##  [7] ggplot2_3.5.2             stxBrain.SeuratData_0.1.2
##  [9] ssHippo.SeuratData_3.1.4  pbmcsca.SeuratData_3.0.0 
## [11] pbmc3k.SeuratData_3.1.4   ifnb.SeuratData_3.1.0    
## [13] bmcite.SeuratData_0.3.0   SeuratData_0.2.2.9002    
## [15] Seurat_5.3.0              SeuratObject_5.1.0       
## [17] sp_2.2-0                 
## 
## loaded via a namespace (and not attached):
##   [1] RcppAnnoy_0.0.22            splines_4.4.2              
##   [3] later_1.4.2                 tibble_3.2.1               
##   [5] polyclip_1.10-7             fastDummies_1.7.5          
##   [7] lifecycle_1.0.4             doParallel_1.0.17          
##   [9] globals_0.18.0              lattice_0.22-7             
##  [11] MASS_7.3-65                 magrittr_2.0.3             
##  [13] plotly_4.10.4               sass_0.4.10                
##  [15] rmarkdown_2.29              jquerylib_0.1.4            
##  [17] yaml_2.3.10                 httpuv_1.6.16              
##  [19] glmGamPoi_1.18.0            sctransform_0.4.2          
##  [21] spam_2.11-1                 spatstat.sparse_3.1-0      
##  [23] reticulate_1.42.0           cowplot_1.1.3              
##  [25] pbapply_1.7-2               RColorBrewer_1.1-3         
##  [27] abind_1.4-8                 zlibbioc_1.52.0            
##  [29] quadprog_1.5-8              Rtsne_0.17                 
##  [31] GenomicRanges_1.58.0        purrr_1.0.4                
##  [33] presto_1.0.0                BiocGenerics_0.52.0        
##  [35] rappdirs_0.3.3              GenomeInfoDbData_1.2.13    
##  [37] IRanges_2.40.1              S4Vectors_0.44.0           
##  [39] ggrepel_0.9.6               irlba_2.3.5.1              
##  [41] listenv_0.9.1               spatstat.utils_3.1-4       
##  [43] goftest_1.2-3               RSpectra_0.16-2            
##  [45] spatstat.random_3.4-1       fitdistrplus_1.2-2         
##  [47] parallelly_1.45.0           pkgdown_2.1.3              
##  [49] DelayedMatrixStats_1.28.1   codetools_0.2-20           
##  [51] DelayedArray_0.32.0         tidyselect_1.2.1           
##  [53] UCSC.utils_1.2.0            farver_2.1.2               
##  [55] matrixStats_1.5.0           stats4_4.4.2               
##  [57] spatstat.explore_3.4-3      jsonlite_2.0.0             
##  [59] progressr_0.15.1            iterators_1.0.14           
##  [61] ggridges_0.5.6              survival_3.8-3             
##  [63] systemfonts_1.2.3           foreach_1.5.2              
##  [65] tools_4.4.2                 ragg_1.4.0                 
##  [67] ica_1.0-3                   Rcpp_1.0.14                
##  [69] glue_1.8.0                  gridExtra_2.3              
##  [71] SparseArray_1.6.2           xfun_0.52                  
##  [73] MatrixGenerics_1.18.1       GenomeInfoDb_1.42.3        
##  [75] withr_3.0.2                 formatR_1.14               
##  [77] fastmap_1.2.0               digest_0.6.37              
##  [79] R6_2.6.1                    mime_0.13                  
##  [81] textshaping_1.0.1           scattermore_1.2            
##  [83] tensor_1.5                  dichromat_2.0-0.1          
##  [85] spatstat.data_3.1-6         tidyr_1.3.1                
##  [87] generics_0.1.4              data.table_1.17.4          
##  [89] httr_1.4.7                  htmlwidgets_1.6.4          
##  [91] S4Arrays_1.6.0              uwot_0.2.3                 
##  [93] pkgconfig_2.0.3             gtable_0.3.6               
##  [95] lmtest_0.9-40               XVector_0.46.0             
##  [97] dotCall64_1.2               scales_1.4.0               
##  [99] Biobase_2.66.0              png_0.1-8                  
## [101] spatstat.univar_3.1-3       knitr_1.50                 
## [103] rstudioapi_0.17.1           reshape2_1.4.4             
## [105] nlme_3.1-168                cachem_1.1.0               
## [107] zoo_1.8-14                  stringr_1.5.1              
## [109] KernSmooth_2.23-26          parallel_4.4.2             
## [111] miniUI_0.1.2                vipor_0.4.7                
## [113] ggrastr_1.0.2               desc_1.4.3                 
## [115] pillar_1.10.2               grid_4.4.2                 
## [117] vctrs_0.6.5                 RANN_2.6.2                 
## [119] promises_1.3.3              xtable_1.8-4               
## [121] cluster_2.1.8.1             beeswarm_0.4.0             
## [123] evaluate_1.0.3              cli_3.6.5                  
## [125] compiler_4.4.2              rlang_1.1.6                
## [127] crayon_1.5.3                future.apply_1.11.3        
## [129] labeling_0.4.3              plyr_1.8.9                 
## [131] fs_1.6.6                    ggbeeswarm_0.7.2           
## [133] stringi_1.8.7               viridisLite_0.4.2          
## [135] deldir_2.0-4                assertthat_0.2.1           
## [137] lazyeval_0.2.2              spatstat.geom_3.4-1        
## [139] Matrix_1.7-3                RcppHNSW_0.6.0             
## [141] sparseMatrixStats_1.18.0    shiny_1.10.0               
## [143] SummarizedExperiment_1.36.0 ROCR_1.0-11                
## [145] igraph_2.1.4                bslib_0.9.0                
## [147] ape_5.8-1
```

---

## Differential expression testing • Seurat

**URL:** http://127.0.0.1:9173/seurat/archive/v4.3/de_vignette/index.html

**Contents:**
- Differential expression testing
    - Compiled: 2023-03-27
- Load in the data
- Perform default differential expression tests
- Prefilter features or cells to increase the speed of DE testing
- Perform DE analysis using alternative tests
- Acknowledgements
- Contents

This vignette highlights some example workflows for performing differential expression in Seurat. For demonstration purposes, we will be using the 2,700 PBMC object that is available via the SeuratData package). library(Seurat) library(SeuratData) pbmc <- LoadData("pbmc3k", type = "pbmc3k.final")

The bulk of Seurat’s differential expression features can be accessed through the FindMarkers() function. As a default, Seurat performs differential expression based on the non-parametric Wilcoxon rank sum test. This replaces the previous default test (‘bimod’). To test for differential expression between two specific groups of cells, specify the ident.1 and ident.2 parameters. # list options for groups to perform differential expression on levels(pbmc)## [1] "Naive CD4 T" "Memory CD4 T" "CD14+ Mono" "B" "CD8 T" ## [6] "FCGR3A+ Mono" "NK" "DC" "Platelet" # Find differentially expressed features between CD14+ and FCGR3A+ Monocytes monocyte.de.markers <- FindMarkers(pbmc, ident.1 = "CD14+ Mono", ident.2 = "FCGR3A+ Mono") # view results head(monocyte.de.markers)## p_val avg_log2FC pct.1 pct.2 p_val_adj ## FCGR3A 1.193617e-101 -3.776553 0.131 0.975 1.636926e-97 ## LYZ 8.134552e-75 2.614275 1.000 0.988 1.115572e-70 ## RHOC 4.479768e-68 -2.325013 0.162 0.864 6.143554e-64 ## S100A8 7.471811e-65 3.766437 0.975 0.500 1.024684e-60 ## S100A9 1.318422e-64 3.299060 0.996 0.870 1.808084e-60 ## IFITM2 4.821669e-64 -2.085807 0.677 1.000 6.612437e-60The results data frame has the following columns :p_val : p_val (unadjusted)avg_log2FC : log fold-change of the average expression between the two groups. Positive values indicate that the feature is more highly expressed in the first group.pct.1 : The percentage of cells where the feature is detected in the first grouppct.2 : The percentage of cells where the feature is detected in the second groupp_val_adj : Adjusted p-value, based on Bonferroni correction using all features in the dataset.If the ident.2 parameter is omitted or set to NULL, FindMarkers() will test for differentially expressed features between the group specified by ident.1 and all other cells. # Find differentially expressed features between CD14+ Monocytes and all other cells, only # search for positive markers monocyte.de.markers <- FindMarkers(pbmc, ident.1 = "CD14+ Mono", ident.2 = NULL, only.pos = TRUE) # view results head(monocyte.de.markers)## p_val avg_log2FC pct.1 pct.2 p_val_adj ## S100A9 0.000000e+00 5.570063 0.996 0.215 0.000000e+00 ## S100A8 0.000000e+00 5.477394 0.975 0.121 0.000000e+00 ## FCN1 0.000000e+00 3.394219 0.952 0.151 0.000000e+00 ## LGALS2 0.000000e+00 3.800484 0.908 0.059 0.000000e+00 ## CD14 2.856582e-294 2.815626 0.667 0.028 3.917516e-290 ## TYROBP 3.190467e-284 3.046798 0.994 0.265 4.375406e-280

The results data frame has the following columns :p_val : p_val (unadjusted)avg_log2FC : log fold-change of the average expression between the two groups. Positive values indicate that the feature is more highly expressed in the first group.pct.1 : The percentage of cells where the feature is detected in the first grouppct.2 : The percentage of cells where the feature is detected in the second groupp_val_adj : Adjusted p-value, based on Bonferroni correction using all features in the dataset.If the ident.2 parameter is omitted or set to NULL, FindMarkers() will test for differentially expressed features between the group specified by ident.1 and all other cells. # Find differentially expressed features between CD14+ Monocytes and all other cells, only # search for positive markers monocyte.de.markers <- FindMarkers(pbmc, ident.1 = "CD14+ Mono", ident.2 = NULL, only.pos = TRUE) # view results head(monocyte.de.markers)## p_val avg_log2FC pct.1 pct.2 p_val_adj ## S100A9 0.000000e+00 5.570063 0.996 0.215 0.000000e+00 ## S100A8 0.000000e+00 5.477394 0.975 0.121 0.000000e+00 ## FCN1 0.000000e+00 3.394219 0.952 0.151 0.000000e+00 ## LGALS2 0.000000e+00 3.800484 0.908 0.059 0.000000e+00 ## CD14 2.856582e-294 2.815626 0.667 0.028 3.917516e-290 ## TYROBP 3.190467e-284 3.046798 0.994 0.265 4.375406e-280

If the ident.2 parameter is omitted or set to NULL, FindMarkers() will test for differentially expressed features between the group specified by ident.1 and all other cells. # Find differentially expressed features between CD14+ Monocytes and all other cells, only # search for positive markers monocyte.de.markers <- FindMarkers(pbmc, ident.1 = "CD14+ Mono", ident.2 = NULL, only.pos = TRUE) # view results head(monocyte.de.markers)## p_val avg_log2FC pct.1 pct.2 p_val_adj ## S100A9 0.000000e+00 5.570063 0.996 0.215 0.000000e+00 ## S100A8 0.000000e+00 5.477394 0.975 0.121 0.000000e+00 ## FCN1 0.000000e+00 3.394219 0.952 0.151 0.000000e+00 ## LGALS2 0.000000e+00 3.800484 0.908 0.059 0.000000e+00 ## CD14 2.856582e-294 2.815626 0.667 0.028 3.917516e-290 ## TYROBP 3.190467e-284 3.046798 0.994 0.265 4.375406e-280

To increase the speed of marker discovery, particularly for large datasets, Seurat allows for pre-filtering of features or cells. For example, features that are very infrequently detected in either group of cells, or features that are expressed at similar average levels, are unlikely to be differentially expressed. Example use cases of the min.pct, logfc.threshold, min.diff.pct, and max.cells.per.ident parameters are demonstrated below. # Pre-filter features that are detected at <50% frequency in either CD14+ Monocytes or FCGR3A+ # Monocytes head(FindMarkers(pbmc, ident.1 = "CD14+ Mono", ident.2 = "FCGR3A+ Mono", min.pct = 0.5))## p_val avg_log2FC pct.1 pct.2 p_val_adj ## FCGR3A 1.193617e-101 -3.776553 0.131 0.975 1.636926e-97 ## LYZ 8.134552e-75 2.614275 1.000 0.988 1.115572e-70 ## RHOC 4.479768e-68 -2.325013 0.162 0.864 6.143554e-64 ## S100A8 7.471811e-65 3.766437 0.975 0.500 1.024684e-60 ## S100A9 1.318422e-64 3.299060 0.996 0.870 1.808084e-60 ## IFITM2 4.821669e-64 -2.085807 0.677 1.000 6.612437e-60 # Pre-filter features that have less than a two-fold change between the average expression of # CD14+ Monocytes vs FCGR3A+ Monocytes head(FindMarkers(pbmc, ident.1 = "CD14+ Mono", ident.2 = "FCGR3A+ Mono", logfc.threshold = log(2)))## p_val avg_log2FC pct.1 pct.2 p_val_adj ## FCGR3A 1.193617e-101 -3.776553 0.131 0.975 1.636926e-97 ## LYZ 8.134552e-75 2.614275 1.000 0.988 1.115572e-70 ## RHOC 4.479768e-68 -2.325013 0.162 0.864 6.143554e-64 ## S100A8 7.471811e-65 3.766437 0.975 0.500 1.024684e-60 ## S100A9 1.318422e-64 3.299060 0.996 0.870 1.808084e-60 ## IFITM2 4.821669e-64 -2.085807 0.677 1.000 6.612437e-60 # Pre-filter features whose detection percentages across the two groups are similar (within # 0.25) head(FindMarkers(pbmc, ident.1 = "CD14+ Mono", ident.2 = "FCGR3A+ Mono", min.diff.pct = 0.25))## p_val avg_log2FC pct.1 pct.2 p_val_adj ## FCGR3A 1.193617e-101 -3.776553 0.131 0.975 1.636926e-97 ## RHOC 4.479768e-68 -2.325013 0.162 0.864 6.143554e-64 ## S100A8 7.471811e-65 3.766437 0.975 0.500 1.024684e-60 ## IFITM2 4.821669e-64 -2.085807 0.677 1.000 6.612437e-60 ## LGALS2 1.034540e-57 2.956704 0.908 0.265 1.418768e-53 ## CDKN1C 2.886353e-48 -1.453845 0.029 0.506 3.958345e-44 # Increasing min.pct, logfc.threshold, and min.diff.pct, will increase the speed of DE # testing, but could also miss features that are prefiltered # Subsample each group to a maximum of 200 cells. Can be very useful for large clusters, or # computationally-intensive DE tests head(FindMarkers(pbmc, ident.1 = "CD14+ Mono", ident.2 = "FCGR3A+ Mono", max.cells.per.ident = 200))## p_val avg_log2FC pct.1 pct.2 p_val_adj ## FCGR3A 4.725441e-61 -3.776553 0.131 0.975 6.480470e-57 ## LYZ 6.442891e-56 2.614275 1.000 0.988 8.835781e-52 ## S100A8 8.983226e-49 3.766437 0.975 0.500 1.231960e-44 ## S100A9 1.812278e-47 3.299060 0.996 0.870 2.485358e-43 ## IFITM2 1.185202e-45 -2.085807 0.677 1.000 1.625386e-41 ## RPS19 1.685374e-44 -1.091150 0.990 1.000 2.311321e-40

The following differential expression tests are currently supported:“wilcox” : Wilcoxon rank sum test (default)“bimod” : Likelihood-ratio test for single cell feature expression, (McDavid et al., Bioinformatics, 2013)“roc” : Standard AUC classifier“t” : Student’s t-test“poisson” : Likelihood ratio test assuming an underlying negative binomial distribution. Use only for UMI-based datasets“negbinom” : Likelihood ratio test assuming an underlying negative binomial distribution. Use only for UMI-based datasets“LR” : Uses a logistic regression framework to determine differentially expressed genes. Constructs a logistic regression model predicting group membership based on each feature individually and compares this to a null model with a likelihood ratio test.“MAST” : GLM-framework that treates cellular detection rate as a covariate (Finak et al, Genome Biology, 2015) (Installation instructions)“DESeq2” : DE based on a model using the negative binomial distribution (Love et al, Genome Biology, 2014) (Installation instructions)For MAST and DESeq2, please ensure that these packages are installed separately in order to use them as part of Seurat. Once installed, use the test.use parameter can be used to specify which DE test to use. # Test for DE features using the MAST package head(FindMarkers(pbmc, ident.1 = "CD14+ Mono", ident.2 = "FCGR3A+ Mono", test.use = "MAST"))## p_val avg_log2FC pct.1 pct.2 p_val_adj ## LYZ 7.653066e-145 2.614275 1.000 0.988 1.049541e-140 ## FCGR3A 2.897172e-119 -3.776553 0.131 0.975 3.973182e-115 ## S100A9 2.123928e-95 3.299060 0.996 0.870 2.912755e-91 ## S100A8 3.279521e-92 3.766437 0.975 0.500 4.497535e-88 ## IFITM2 5.591175e-87 -2.085807 0.677 1.000 7.667737e-83 ## LGALS2 1.132854e-75 2.956704 0.908 0.265 1.553596e-71 # Test for DE features using the DESeq2 package. Throws an error if DESeq2 has not already # been installed Note that the DESeq2 workflows can be computationally intensive for large # datasets, but are incompatible with some feature pre-filtering options We therefore suggest # initially limiting the number of cells used for testing head(FindMarkers(pbmc, ident.1 = "CD14+ Mono", ident.2 = "FCGR3A+ Mono", test.use = "DESeq2", max.cells.per.ident = 50))## p_val avg_log2FC pct.1 pct.2 p_val_adj ## S100A9 1.887262e-58 2.538360 0.996 0.870 2.588191e-54 ## LYZ 4.198394e-52 1.987962 1.000 0.988 5.757678e-48 ## S100A8 5.747352e-49 2.784248 0.975 0.500 7.881918e-45 ## FCGR3A 1.315842e-35 -2.949992 0.131 0.975 1.804546e-31 ## RPS19 1.514561e-33 -1.614892 0.990 1.000 2.077068e-29 ## IFITM2 1.227042e-26 -2.212583 0.677 1.000 1.682765e-22

For MAST and DESeq2, please ensure that these packages are installed separately in order to use them as part of Seurat. Once installed, use the test.use parameter can be used to specify which DE test to use. # Test for DE features using the MAST package head(FindMarkers(pbmc, ident.1 = "CD14+ Mono", ident.2 = "FCGR3A+ Mono", test.use = "MAST"))## p_val avg_log2FC pct.1 pct.2 p_val_adj ## LYZ 7.653066e-145 2.614275 1.000 0.988 1.049541e-140 ## FCGR3A 2.897172e-119 -3.776553 0.131 0.975 3.973182e-115 ## S100A9 2.123928e-95 3.299060 0.996 0.870 2.912755e-91 ## S100A8 3.279521e-92 3.766437 0.975 0.500 4.497535e-88 ## IFITM2 5.591175e-87 -2.085807 0.677 1.000 7.667737e-83 ## LGALS2 1.132854e-75 2.956704 0.908 0.265 1.553596e-71 # Test for DE features using the DESeq2 package. Throws an error if DESeq2 has not already # been installed Note that the DESeq2 workflows can be computationally intensive for large # datasets, but are incompatible with some feature pre-filtering options We therefore suggest # initially limiting the number of cells used for testing head(FindMarkers(pbmc, ident.1 = "CD14+ Mono", ident.2 = "FCGR3A+ Mono", test.use = "DESeq2", max.cells.per.ident = 50))## p_val avg_log2FC pct.1 pct.2 p_val_adj ## S100A9 1.887262e-58 2.538360 0.996 0.870 2.588191e-54 ## LYZ 4.198394e-52 1.987962 1.000 0.988 5.757678e-48 ## S100A8 5.747352e-49 2.784248 0.975 0.500 7.881918e-45 ## FCGR3A 1.315842e-35 -2.949992 0.131 0.975 1.804546e-31 ## RPS19 1.514561e-33 -1.614892 0.990 1.000 2.077068e-29 ## IFITM2 1.227042e-26 -2.212583 0.677 1.000 1.682765e-22

We thank the authors of the MAST and DESeq2 packages for their kind assistance and advice. We also point users to the following study by Charlotte Soneson and Mark Robinson, which performs careful and extensive evaluation of methods for single cell differential expression testing.Session Info sessionInfo()## R version 4.2.0 (2022-04-22) ## Platform: x86_64-pc-linux-gnu (64-bit) ## Running under: Ubuntu 20.04.5 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/liblapack.so.3 ## ## locale: ## [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C ## [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8 ## [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 ## ## attached base packages: ## [1] stats4 stats graphics grDevices utils datasets methods ## [8] base ## ## other attached packages: ## [1] SingleCellExperiment_1.20.0 SummarizedExperiment_1.28.0 ## [3] Biobase_2.58.0 GenomicRanges_1.50.2 ## [5] GenomeInfoDb_1.35.16 IRanges_2.32.0 ## [7] S4Vectors_0.36.2 BiocGenerics_0.44.0 ## [9] MatrixGenerics_1.10.0 matrixStats_0.63.0 ## [11] thp1.eccite.SeuratData_3.1.5 stxBrain.SeuratData_0.1.1 ## [13] ssHippo.SeuratData_3.1.4 pbmcsca.SeuratData_3.0.0 ## [15] pbmcMultiome.SeuratData_0.1.2 pbmc3k.SeuratData_3.1.4 ## [17] panc8.SeuratData_3.0.2 ifnb.SeuratData_3.1.0 ## [19] hcabm40k.SeuratData_3.0.0 bmcite.SeuratData_0.3.0 ## [21] SeuratData_0.2.2 SeuratObject_4.1.3 ## [23] Seurat_4.3.0 ## ## loaded via a namespace (and not attached): ## [1] utf8_1.2.3 spatstat.explore_3.0-6 reticulate_1.28 ## [4] tidyselect_1.2.0 RSQLite_2.3.0 AnnotationDbi_1.60.0 ## [7] htmlwidgets_1.6.1 grid_4.2.0 BiocParallel_1.32.5 ## [10] Rtsne_0.16 munsell_0.5.0 codetools_0.2-18 ## [13] ragg_1.2.5 ica_1.0-3 future_1.31.0 ## [16] miniUI_0.1.1.1 spatstat.random_3.1-3 colorspace_2.1-0 ## [19] progressr_0.13.0 knitr_1.42 ROCR_1.0-11 ## [22] tensor_1.5 listenv_0.9.0 GenomeInfoDbData_1.2.9 ## [25] polyclip_1.10-4 bit64_4.0.5 rprojroot_2.0.3 ## [28] parallelly_1.34.0 vctrs_0.5.2 generics_0.1.3 ## [31] xfun_0.37 R6_2.5.1 locfit_1.5-9.7 ## [34] bitops_1.0-7 spatstat.utils_3.0-1 cachem_1.0.7 ## [37] DelayedArray_0.24.0 promises_1.2.0.1 scales_1.2.1 ## [40] gtable_0.3.1 globals_0.16.2 goftest_1.2-3 ## [43] rlang_1.0.6 systemfonts_1.0.4 splines_4.2.0 ## [46] lazyeval_0.2.2 spatstat.geom_3.0-6 yaml_2.3.7 ## [49] reshape2_1.4.4 abind_1.4-5 httpuv_1.6.9 ## [52] tools_4.2.0 ggplot2_3.4.1 ellipsis_0.3.2 ## [55] jquerylib_0.1.4 RColorBrewer_1.1-3 ggridges_0.5.4 ## [58] Rcpp_1.0.10 plyr_1.8.8 progress_1.2.2 ## [61] zlibbioc_1.44.0 purrr_1.0.1 RCurl_1.98-1.12 ## [64] prettyunits_1.1.1 deldir_1.0-6 pbapply_1.7-0 ## [67] cowplot_1.1.1 zoo_1.8-11 ggrepel_0.9.3 ## [70] cluster_2.1.3 fs_1.6.1 magrittr_2.0.3 ## [73] data.table_1.14.8 scattermore_0.8 lmtest_0.9-40 ## [76] RANN_2.6.1 fitdistrplus_1.1-8 hms_1.1.2 ## [79] patchwork_1.1.2 mime_0.12 evaluate_0.20 ## [82] xtable_1.8-4 XML_3.99-0.13 gridExtra_2.3 ## [85] compiler_4.2.0 tibble_3.1.8 KernSmooth_2.23-20 ## [88] crayon_1.5.2 htmltools_0.5.4 later_1.3.0 ## [91] tidyr_1.3.0 geneplotter_1.76.0 DBI_1.1.3 ## [94] formatR_1.14 MASS_7.3-56 rappdirs_0.3.3 ## [97] MAST_1.24.1 Matrix_1.5-3 cli_3.6.0 ## [100] parallel_4.2.0 igraph_1.4.1 pkgconfig_2.0.3 ## [103] pkgdown_2.0.7 sp_1.6-0 plotly_4.10.1 ## [106] spatstat.sparse_3.0-0 annotate_1.76.0 bslib_0.4.2 ## [109] XVector_0.38.0 stringr_1.5.0 digest_0.6.31 ## [112] sctransform_0.3.5 RcppAnnoy_0.0.20 Biostrings_2.66.0 ## [115] spatstat.data_3.0-0 rmarkdown_2.20 leiden_0.4.3 ## [118] uwot_0.1.14 shiny_1.7.4 lifecycle_1.0.3 ## [121] nlme_3.1-157 jsonlite_1.8.4 desc_1.4.2 ## [124] viridisLite_0.4.1 limma_3.54.1 fansi_1.0.4 ## [127] pillar_1.8.1 lattice_0.20-45 KEGGREST_1.38.0 ## [130] fastmap_1.1.1 httr_1.4.5 survival_3.3-1 ## [133] glue_1.6.2 png_0.1-8 bit_4.0.5 ## [136] stringi_1.7.12 sass_0.4.5 blob_1.2.3 ## [139] textshaping_0.3.6 DESeq2_1.38.3 memoise_2.0.1 ## [142] dplyr_1.1.0 irlba_2.3.5.1 future.apply_1.10.0

sessionInfo()## R version 4.2.0 (2022-04-22) ## Platform: x86_64-pc-linux-gnu (64-bit) ## Running under: Ubuntu 20.04.5 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/liblapack.so.3 ## ## locale: ## [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C ## [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8 ## [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 ## ## attached base packages: ## [1] stats4 stats graphics grDevices utils datasets methods ## [8] base ## ## other attached packages: ## [1] SingleCellExperiment_1.20.0 SummarizedExperiment_1.28.0 ## [3] Biobase_2.58.0 GenomicRanges_1.50.2 ## [5] GenomeInfoDb_1.35.16 IRanges_2.32.0 ## [7] S4Vectors_0.36.2 BiocGenerics_0.44.0 ## [9] MatrixGenerics_1.10.0 matrixStats_0.63.0 ## [11] thp1.eccite.SeuratData_3.1.5 stxBrain.SeuratData_0.1.1 ## [13] ssHippo.SeuratData_3.1.4 pbmcsca.SeuratData_3.0.0 ## [15] pbmcMultiome.SeuratData_0.1.2 pbmc3k.SeuratData_3.1.4 ## [17] panc8.SeuratData_3.0.2 ifnb.SeuratData_3.1.0 ## [19] hcabm40k.SeuratData_3.0.0 bmcite.SeuratData_0.3.0 ## [21] SeuratData_0.2.2 SeuratObject_4.1.3 ## [23] Seurat_4.3.0 ## ## loaded via a namespace (and not attached): ## [1] utf8_1.2.3 spatstat.explore_3.0-6 reticulate_1.28 ## [4] tidyselect_1.2.0 RSQLite_2.3.0 AnnotationDbi_1.60.0 ## [7] htmlwidgets_1.6.1 grid_4.2.0 BiocParallel_1.32.5 ## [10] Rtsne_0.16 munsell_0.5.0 codetools_0.2-18 ## [13] ragg_1.2.5 ica_1.0-3 future_1.31.0 ## [16] miniUI_0.1.1.1 spatstat.random_3.1-3 colorspace_2.1-0 ## [19] progressr_0.13.0 knitr_1.42 ROCR_1.0-11 ## [22] tensor_1.5 listenv_0.9.0 GenomeInfoDbData_1.2.9 ## [25] polyclip_1.10-4 bit64_4.0.5 rprojroot_2.0.3 ## [28] parallelly_1.34.0 vctrs_0.5.2 generics_0.1.3 ## [31] xfun_0.37 R6_2.5.1 locfit_1.5-9.7 ## [34] bitops_1.0-7 spatstat.utils_3.0-1 cachem_1.0.7 ## [37] DelayedArray_0.24.0 promises_1.2.0.1 scales_1.2.1 ## [40] gtable_0.3.1 globals_0.16.2 goftest_1.2-3 ## [43] rlang_1.0.6 systemfonts_1.0.4 splines_4.2.0 ## [46] lazyeval_0.2.2 spatstat.geom_3.0-6 yaml_2.3.7 ## [49] reshape2_1.4.4 abind_1.4-5 httpuv_1.6.9 ## [52] tools_4.2.0 ggplot2_3.4.1 ellipsis_0.3.2 ## [55] jquerylib_0.1.4 RColorBrewer_1.1-3 ggridges_0.5.4 ## [58] Rcpp_1.0.10 plyr_1.8.8 progress_1.2.2 ## [61] zlibbioc_1.44.0 purrr_1.0.1 RCurl_1.98-1.12 ## [64] prettyunits_1.1.1 deldir_1.0-6 pbapply_1.7-0 ## [67] cowplot_1.1.1 zoo_1.8-11 ggrepel_0.9.3 ## [70] cluster_2.1.3 fs_1.6.1 magrittr_2.0.3 ## [73] data.table_1.14.8 scattermore_0.8 lmtest_0.9-40 ## [76] RANN_2.6.1 fitdistrplus_1.1-8 hms_1.1.2 ## [79] patchwork_1.1.2 mime_0.12 evaluate_0.20 ## [82] xtable_1.8-4 XML_3.99-0.13 gridExtra_2.3 ## [85] compiler_4.2.0 tibble_3.1.8 KernSmooth_2.23-20 ## [88] crayon_1.5.2 htmltools_0.5.4 later_1.3.0 ## [91] tidyr_1.3.0 geneplotter_1.76.0 DBI_1.1.3 ## [94] formatR_1.14 MASS_7.3-56 rappdirs_0.3.3 ## [97] MAST_1.24.1 Matrix_1.5-3 cli_3.6.0 ## [100] parallel_4.2.0 igraph_1.4.1 pkgconfig_2.0.3 ## [103] pkgdown_2.0.7 sp_1.6-0 plotly_4.10.1 ## [106] spatstat.sparse_3.0-0 annotate_1.76.0 bslib_0.4.2 ## [109] XVector_0.38.0 stringr_1.5.0 digest_0.6.31 ## [112] sctransform_0.3.5 RcppAnnoy_0.0.20 Biostrings_2.66.0 ## [115] spatstat.data_3.0-0 rmarkdown_2.20 leiden_0.4.3 ## [118] uwot_0.1.14 shiny_1.7.4 lifecycle_1.0.3 ## [121] nlme_3.1-157 jsonlite_1.8.4 desc_1.4.2 ## [124] viridisLite_0.4.1 limma_3.54.1 fansi_1.0.4 ## [127] pillar_1.8.1 lattice_0.20-45 KEGGREST_1.38.0 ## [130] fastmap_1.1.1 httr_1.4.5 survival_3.3-1 ## [133] glue_1.6.2 png_0.1-8 bit_4.0.5 ## [136] stringi_1.7.12 sass_0.4.5 blob_1.2.3 ## [139] textshaping_0.3.6 DESeq2_1.38.3 memoise_2.0.1 ## [142] dplyr_1.1.0 irlba_2.3.5.1 future.apply_1.10.0

Developed by Paul Hoffman, Satija Lab and Collaborators.

Developed by Paul Hoffman, Satija Lab and Collaborators.

Site built with pkgdown 2.0.7.

Site built with pkgdown 2.0.7.

**Examples:**

Example 1 (unknown):
```unknown
vignettes/de_vignette.Rmd
```

Example 2 (unknown):
```unknown
de_vignette.Rmd
```

Example 3 (unknown):
```unknown
library(Seurat)
library(SeuratData)
pbmc <- LoadData("pbmc3k", type = "pbmc3k.final")
```

Example 4 (r):
```r
library(Seurat)
library(SeuratData)
pbmc <- LoadData("pbmc3k", type = "pbmc3k.final")
```

Example 5 (r):
```r
library(Seurat)
library(SeuratData)
pbmc <- LoadData("pbmc3k", type = "pbmc3k.final")
```

Example 6 (unknown):
```unknown
FindMarkers()
```

Example 7 (unknown):
```unknown
# list options for groups to perform differential expression on
levels(pbmc)
```

Example 8 (r):
```r
# list options for groups to perform differential expression on
levels(pbmc)
```

Example 9 (r):
```r
# list options for groups to perform differential expression on
levels(pbmc)
```

Example 10 (unknown):
```unknown
## [1] "Naive CD4 T"  "Memory CD4 T" "CD14+ Mono"   "B"            "CD8 T"       
## [6] "FCGR3A+ Mono" "NK"           "DC"           "Platelet"
```

Example 11 (unknown):
```unknown
## [1] "Naive CD4 T"  "Memory CD4 T" "CD14+ Mono"   "B"            "CD8 T"       
## [6] "FCGR3A+ Mono" "NK"           "DC"           "Platelet"
```

Example 12 (unknown):
```unknown
# Find differentially expressed features between CD14+ and FCGR3A+ Monocytes
monocyte.de.markers <- FindMarkers(pbmc, ident.1 = "CD14+ Mono", ident.2 = "FCGR3A+ Mono")
# view results
head(monocyte.de.markers)
```

Example 13 (r):
```r
# Find differentially expressed features between CD14+ and FCGR3A+ Monocytes
monocyte.de.markers <- FindMarkers(pbmc, ident.1 = "CD14+ Mono", ident.2 = "FCGR3A+ Mono")
# view results
head(monocyte.de.markers)
```

Example 14 (r):
```r
# Find differentially expressed features between CD14+ and FCGR3A+ Monocytes
monocyte.de.markers <- FindMarkers(pbmc, ident.1 = "CD14+ Mono", ident.2 = "FCGR3A+ Mono")
# view results
head(monocyte.de.markers)
```

Example 15 (unknown):
```unknown
##                p_val avg_log2FC pct.1 pct.2    p_val_adj
## FCGR3A 1.193617e-101  -3.776553 0.131 0.975 1.636926e-97
## LYZ     8.134552e-75   2.614275 1.000 0.988 1.115572e-70
## RHOC    4.479768e-68  -2.325013 0.162 0.864 6.143554e-64
## S100A8  7.471811e-65   3.766437 0.975 0.500 1.024684e-60
## S100A9  1.318422e-64   3.299060 0.996 0.870 1.808084e-60
## IFITM2  4.821669e-64  -2.085807 0.677 1.000 6.612437e-60
```

Example 16 (unknown):
```unknown
##                p_val avg_log2FC pct.1 pct.2    p_val_adj
## FCGR3A 1.193617e-101  -3.776553 0.131 0.975 1.636926e-97
## LYZ     8.134552e-75   2.614275 1.000 0.988 1.115572e-70
## RHOC    4.479768e-68  -2.325013 0.162 0.864 6.143554e-64
## S100A8  7.471811e-65   3.766437 0.975 0.500 1.024684e-60
## S100A9  1.318422e-64   3.299060 0.996 0.870 1.808084e-60
## IFITM2  4.821669e-64  -2.085807 0.677 1.000 6.612437e-60
```

Example 17 (unknown):
```unknown
FindMarkers()
```

Example 18 (unknown):
```unknown
# Find differentially expressed features between CD14+ Monocytes and all other cells, only
# search for positive markers
monocyte.de.markers <- FindMarkers(pbmc, ident.1 = "CD14+ Mono", ident.2 = NULL, only.pos = TRUE)
# view results
head(monocyte.de.markers)
```

Example 19 (r):
```r
# Find differentially expressed features between CD14+ Monocytes and all other cells, only
# search for positive markers
monocyte.de.markers <- FindMarkers(pbmc, ident.1 = "CD14+ Mono", ident.2 = NULL, only.pos = TRUE)
# view results
head(monocyte.de.markers)
```

Example 20 (r):
```r
# Find differentially expressed features between CD14+ Monocytes and all other cells, only
# search for positive markers
monocyte.de.markers <- FindMarkers(pbmc, ident.1 = "CD14+ Mono", ident.2 = NULL, only.pos = TRUE)
# view results
head(monocyte.de.markers)
```

Example 21 (unknown):
```unknown
##                p_val avg_log2FC pct.1 pct.2     p_val_adj
## S100A9  0.000000e+00   5.570063 0.996 0.215  0.000000e+00
## S100A8  0.000000e+00   5.477394 0.975 0.121  0.000000e+00
## FCN1    0.000000e+00   3.394219 0.952 0.151  0.000000e+00
## LGALS2  0.000000e+00   3.800484 0.908 0.059  0.000000e+00
## CD14   2.856582e-294   2.815626 0.667 0.028 3.917516e-290
## TYROBP 3.190467e-284   3.046798 0.994 0.265 4.375406e-280
```

Example 22 (unknown):
```unknown
##                p_val avg_log2FC pct.1 pct.2     p_val_adj
## S100A9  0.000000e+00   5.570063 0.996 0.215  0.000000e+00
## S100A8  0.000000e+00   5.477394 0.975 0.121  0.000000e+00
## FCN1    0.000000e+00   3.394219 0.952 0.151  0.000000e+00
## LGALS2  0.000000e+00   3.800484 0.908 0.059  0.000000e+00
## CD14   2.856582e-294   2.815626 0.667 0.028 3.917516e-290
## TYROBP 3.190467e-284   3.046798 0.994 0.265 4.375406e-280
```

Example 23 (unknown):
```unknown
logfc.threshold
```

Example 24 (unknown):
```unknown
min.diff.pct
```

Example 25 (unknown):
```unknown
max.cells.per.ident
```

Example 26 (unknown):
```unknown
# Pre-filter features that are detected at <50% frequency in either CD14+ Monocytes or FCGR3A+
# Monocytes
head(FindMarkers(pbmc, ident.1 = "CD14+ Mono", ident.2 = "FCGR3A+ Mono", min.pct = 0.5))
```

Example 27 (r):
```r
# Pre-filter features that are detected at <50% frequency in either CD14+ Monocytes or FCGR3A+
# Monocytes
head(FindMarkers(pbmc, ident.1 = "CD14+ Mono", ident.2 = "FCGR3A+ Mono", min.pct = 0.5))
```

Example 28 (r):
```r
# Pre-filter features that are detected at <50% frequency in either CD14+ Monocytes or FCGR3A+
# Monocytes
head(FindMarkers(pbmc, ident.1 = "CD14+ Mono", ident.2 = "FCGR3A+ Mono", min.pct = 0.5))
```

Example 29 (unknown):
```unknown
##                p_val avg_log2FC pct.1 pct.2    p_val_adj
## FCGR3A 1.193617e-101  -3.776553 0.131 0.975 1.636926e-97
## LYZ     8.134552e-75   2.614275 1.000 0.988 1.115572e-70
## RHOC    4.479768e-68  -2.325013 0.162 0.864 6.143554e-64
## S100A8  7.471811e-65   3.766437 0.975 0.500 1.024684e-60
## S100A9  1.318422e-64   3.299060 0.996 0.870 1.808084e-60
## IFITM2  4.821669e-64  -2.085807 0.677 1.000 6.612437e-60
```

Example 30 (unknown):
```unknown
##                p_val avg_log2FC pct.1 pct.2    p_val_adj
## FCGR3A 1.193617e-101  -3.776553 0.131 0.975 1.636926e-97
## LYZ     8.134552e-75   2.614275 1.000 0.988 1.115572e-70
## RHOC    4.479768e-68  -2.325013 0.162 0.864 6.143554e-64
## S100A8  7.471811e-65   3.766437 0.975 0.500 1.024684e-60
## S100A9  1.318422e-64   3.299060 0.996 0.870 1.808084e-60
## IFITM2  4.821669e-64  -2.085807 0.677 1.000 6.612437e-60
```

Example 31 (unknown):
```unknown
# Pre-filter features that have less than a two-fold change between the average expression of
# CD14+ Monocytes vs FCGR3A+ Monocytes
head(FindMarkers(pbmc, ident.1 = "CD14+ Mono", ident.2 = "FCGR3A+ Mono", logfc.threshold = log(2)))
```

Example 32 (r):
```r
# Pre-filter features that have less than a two-fold change between the average expression of
# CD14+ Monocytes vs FCGR3A+ Monocytes
head(FindMarkers(pbmc, ident.1 = "CD14+ Mono", ident.2 = "FCGR3A+ Mono", logfc.threshold = log(2)))
```

Example 33 (r):
```r
# Pre-filter features that have less than a two-fold change between the average expression of
# CD14+ Monocytes vs FCGR3A+ Monocytes
head(FindMarkers(pbmc, ident.1 = "CD14+ Mono", ident.2 = "FCGR3A+ Mono", logfc.threshold = log(2)))
```

Example 34 (unknown):
```unknown
##                p_val avg_log2FC pct.1 pct.2    p_val_adj
## FCGR3A 1.193617e-101  -3.776553 0.131 0.975 1.636926e-97
## LYZ     8.134552e-75   2.614275 1.000 0.988 1.115572e-70
## RHOC    4.479768e-68  -2.325013 0.162 0.864 6.143554e-64
## S100A8  7.471811e-65   3.766437 0.975 0.500 1.024684e-60
## S100A9  1.318422e-64   3.299060 0.996 0.870 1.808084e-60
## IFITM2  4.821669e-64  -2.085807 0.677 1.000 6.612437e-60
```

Example 35 (unknown):
```unknown
##                p_val avg_log2FC pct.1 pct.2    p_val_adj
## FCGR3A 1.193617e-101  -3.776553 0.131 0.975 1.636926e-97
## LYZ     8.134552e-75   2.614275 1.000 0.988 1.115572e-70
## RHOC    4.479768e-68  -2.325013 0.162 0.864 6.143554e-64
## S100A8  7.471811e-65   3.766437 0.975 0.500 1.024684e-60
## S100A9  1.318422e-64   3.299060 0.996 0.870 1.808084e-60
## IFITM2  4.821669e-64  -2.085807 0.677 1.000 6.612437e-60
```

Example 36 (unknown):
```unknown
# Pre-filter features whose detection percentages across the two groups are similar (within
# 0.25)
head(FindMarkers(pbmc, ident.1 = "CD14+ Mono", ident.2 = "FCGR3A+ Mono", min.diff.pct = 0.25))
```

Example 37 (r):
```r
# Pre-filter features whose detection percentages across the two groups are similar (within
# 0.25)
head(FindMarkers(pbmc, ident.1 = "CD14+ Mono", ident.2 = "FCGR3A+ Mono", min.diff.pct = 0.25))
```

Example 38 (r):
```r
# Pre-filter features whose detection percentages across the two groups are similar (within
# 0.25)
head(FindMarkers(pbmc, ident.1 = "CD14+ Mono", ident.2 = "FCGR3A+ Mono", min.diff.pct = 0.25))
```

Example 39 (unknown):
```unknown
##                p_val avg_log2FC pct.1 pct.2    p_val_adj
## FCGR3A 1.193617e-101  -3.776553 0.131 0.975 1.636926e-97
## RHOC    4.479768e-68  -2.325013 0.162 0.864 6.143554e-64
## S100A8  7.471811e-65   3.766437 0.975 0.500 1.024684e-60
## IFITM2  4.821669e-64  -2.085807 0.677 1.000 6.612437e-60
## LGALS2  1.034540e-57   2.956704 0.908 0.265 1.418768e-53
## CDKN1C  2.886353e-48  -1.453845 0.029 0.506 3.958345e-44
```

Example 40 (unknown):
```unknown
##                p_val avg_log2FC pct.1 pct.2    p_val_adj
## FCGR3A 1.193617e-101  -3.776553 0.131 0.975 1.636926e-97
## RHOC    4.479768e-68  -2.325013 0.162 0.864 6.143554e-64
## S100A8  7.471811e-65   3.766437 0.975 0.500 1.024684e-60
## IFITM2  4.821669e-64  -2.085807 0.677 1.000 6.612437e-60
## LGALS2  1.034540e-57   2.956704 0.908 0.265 1.418768e-53
## CDKN1C  2.886353e-48  -1.453845 0.029 0.506 3.958345e-44
```

Example 41 (unknown):
```unknown
# Increasing min.pct, logfc.threshold, and min.diff.pct, will increase the speed of DE
# testing, but could also miss features that are prefiltered

# Subsample each group to a maximum of 200 cells. Can be very useful for large clusters, or
# computationally-intensive DE tests
head(FindMarkers(pbmc, ident.1 = "CD14+ Mono", ident.2 = "FCGR3A+ Mono", max.cells.per.ident = 200))
```

Example 42 (r):
```r
# Increasing min.pct, logfc.threshold, and min.diff.pct, will increase the speed of DE
# testing, but could also miss features that are prefiltered

# Subsample each group to a maximum of 200 cells. Can be very useful for large clusters, or
# computationally-intensive DE tests
head(FindMarkers(pbmc, ident.1 = "CD14+ Mono", ident.2 = "FCGR3A+ Mono", max.cells.per.ident = 200))
```

Example 43 (r):
```r
# Increasing min.pct, logfc.threshold, and min.diff.pct, will increase the speed of DE
# testing, but could also miss features that are prefiltered

# Subsample each group to a maximum of 200 cells. Can be very useful for large clusters, or
# computationally-intensive DE tests
head(FindMarkers(pbmc, ident.1 = "CD14+ Mono", ident.2 = "FCGR3A+ Mono", max.cells.per.ident = 200))
```

Example 44 (unknown):
```unknown
##               p_val avg_log2FC pct.1 pct.2    p_val_adj
## FCGR3A 4.725441e-61  -3.776553 0.131 0.975 6.480470e-57
## LYZ    6.442891e-56   2.614275 1.000 0.988 8.835781e-52
## S100A8 8.983226e-49   3.766437 0.975 0.500 1.231960e-44
## S100A9 1.812278e-47   3.299060 0.996 0.870 2.485358e-43
## IFITM2 1.185202e-45  -2.085807 0.677 1.000 1.625386e-41
## RPS19  1.685374e-44  -1.091150 0.990 1.000 2.311321e-40
```

Example 45 (unknown):
```unknown
##               p_val avg_log2FC pct.1 pct.2    p_val_adj
## FCGR3A 4.725441e-61  -3.776553 0.131 0.975 6.480470e-57
## LYZ    6.442891e-56   2.614275 1.000 0.988 8.835781e-52
## S100A8 8.983226e-49   3.766437 0.975 0.500 1.231960e-44
## S100A9 1.812278e-47   3.299060 0.996 0.870 2.485358e-43
## IFITM2 1.185202e-45  -2.085807 0.677 1.000 1.625386e-41
## RPS19  1.685374e-44  -1.091150 0.990 1.000 2.311321e-40
```

Example 46 (unknown):
```unknown
# Test for DE features using the MAST package
head(FindMarkers(pbmc, ident.1 = "CD14+ Mono", ident.2 = "FCGR3A+ Mono", test.use = "MAST"))
```

Example 47 (r):
```r
# Test for DE features using the MAST package
head(FindMarkers(pbmc, ident.1 = "CD14+ Mono", ident.2 = "FCGR3A+ Mono", test.use = "MAST"))
```

Example 48 (r):
```r
# Test for DE features using the MAST package
head(FindMarkers(pbmc, ident.1 = "CD14+ Mono", ident.2 = "FCGR3A+ Mono", test.use = "MAST"))
```

Example 49 (unknown):
```unknown
##                p_val avg_log2FC pct.1 pct.2     p_val_adj
## LYZ    7.653066e-145   2.614275 1.000 0.988 1.049541e-140
## FCGR3A 2.897172e-119  -3.776553 0.131 0.975 3.973182e-115
## S100A9  2.123928e-95   3.299060 0.996 0.870  2.912755e-91
## S100A8  3.279521e-92   3.766437 0.975 0.500  4.497535e-88
## IFITM2  5.591175e-87  -2.085807 0.677 1.000  7.667737e-83
## LGALS2  1.132854e-75   2.956704 0.908 0.265  1.553596e-71
```

Example 50 (unknown):
```unknown
##                p_val avg_log2FC pct.1 pct.2     p_val_adj
## LYZ    7.653066e-145   2.614275 1.000 0.988 1.049541e-140
## FCGR3A 2.897172e-119  -3.776553 0.131 0.975 3.973182e-115
## S100A9  2.123928e-95   3.299060 0.996 0.870  2.912755e-91
## S100A8  3.279521e-92   3.766437 0.975 0.500  4.497535e-88
## IFITM2  5.591175e-87  -2.085807 0.677 1.000  7.667737e-83
## LGALS2  1.132854e-75   2.956704 0.908 0.265  1.553596e-71
```

Example 51 (unknown):
```unknown
# Test for DE features using the DESeq2 package. Throws an error if DESeq2 has not already
# been installed Note that the DESeq2 workflows can be computationally intensive for large
# datasets, but are incompatible with some feature pre-filtering options We therefore suggest
# initially limiting the number of cells used for testing
head(FindMarkers(pbmc, ident.1 = "CD14+ Mono", ident.2 = "FCGR3A+ Mono", test.use = "DESeq2", max.cells.per.ident = 50))
```

Example 52 (r):
```r
# Test for DE features using the DESeq2 package. Throws an error if DESeq2 has not already
# been installed Note that the DESeq2 workflows can be computationally intensive for large
# datasets, but are incompatible with some feature pre-filtering options We therefore suggest
# initially limiting the number of cells used for testing
head(FindMarkers(pbmc, ident.1 = "CD14+ Mono", ident.2 = "FCGR3A+ Mono", test.use = "DESeq2", max.cells.per.ident = 50))
```

Example 53 (r):
```r
# Test for DE features using the DESeq2 package. Throws an error if DESeq2 has not already
# been installed Note that the DESeq2 workflows can be computationally intensive for large
# datasets, but are incompatible with some feature pre-filtering options We therefore suggest
# initially limiting the number of cells used for testing
head(FindMarkers(pbmc, ident.1 = "CD14+ Mono", ident.2 = "FCGR3A+ Mono", test.use = "DESeq2", max.cells.per.ident = 50))
```

Example 54 (unknown):
```unknown
##               p_val avg_log2FC pct.1 pct.2    p_val_adj
## S100A9 1.887262e-58   2.538360 0.996 0.870 2.588191e-54
## LYZ    4.198394e-52   1.987962 1.000 0.988 5.757678e-48
## S100A8 5.747352e-49   2.784248 0.975 0.500 7.881918e-45
## FCGR3A 1.315842e-35  -2.949992 0.131 0.975 1.804546e-31
## RPS19  1.514561e-33  -1.614892 0.990 1.000 2.077068e-29
## IFITM2 1.227042e-26  -2.212583 0.677 1.000 1.682765e-22
```

Example 55 (unknown):
```unknown
##               p_val avg_log2FC pct.1 pct.2    p_val_adj
## S100A9 1.887262e-58   2.538360 0.996 0.870 2.588191e-54
## LYZ    4.198394e-52   1.987962 1.000 0.988 5.757678e-48
## S100A8 5.747352e-49   2.784248 0.975 0.500 7.881918e-45
## FCGR3A 1.315842e-35  -2.949992 0.131 0.975 1.804546e-31
## RPS19  1.514561e-33  -1.614892 0.990 1.000 2.077068e-29
## IFITM2 1.227042e-26  -2.212583 0.677 1.000 1.682765e-22
```

Example 56 (unknown):
```unknown
sessionInfo()
```

Example 57 (r):
```r
sessionInfo()
```

Example 58 (r):
```r
sessionInfo()
```

Example 59 (unknown):
```unknown
## R version 4.2.0 (2022-04-22)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.5 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/liblapack.so.3
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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       
## 
## attached base packages:
## [1] stats4    stats     graphics  grDevices utils     datasets  methods  
## [8] base     
## 
## other attached packages:
##  [1] SingleCellExperiment_1.20.0   SummarizedExperiment_1.28.0  
##  [3] Biobase_2.58.0                GenomicRanges_1.50.2         
##  [5] GenomeInfoDb_1.35.16          IRanges_2.32.0               
##  [7] S4Vectors_0.36.2              BiocGenerics_0.44.0          
##  [9] MatrixGenerics_1.10.0         matrixStats_0.63.0           
## [11] thp1.eccite.SeuratData_3.1.5  stxBrain.SeuratData_0.1.1    
## [13] ssHippo.SeuratData_3.1.4      pbmcsca.SeuratData_3.0.0     
## [15] pbmcMultiome.SeuratData_0.1.2 pbmc3k.SeuratData_3.1.4      
## [17] panc8.SeuratData_3.0.2        ifnb.SeuratData_3.1.0        
## [19] hcabm40k.SeuratData_3.0.0     bmcite.SeuratData_0.3.0      
## [21] SeuratData_0.2.2              SeuratObject_4.1.3           
## [23] Seurat_4.3.0                 
## 
## loaded via a namespace (and not attached):
##   [1] utf8_1.2.3             spatstat.explore_3.0-6 reticulate_1.28       
##   [4] tidyselect_1.2.0       RSQLite_2.3.0          AnnotationDbi_1.60.0  
##   [7] htmlwidgets_1.6.1      grid_4.2.0             BiocParallel_1.32.5   
##  [10] Rtsne_0.16             munsell_0.5.0          codetools_0.2-18      
##  [13] ragg_1.2.5             ica_1.0-3              future_1.31.0         
##  [16] miniUI_0.1.1.1         spatstat.random_3.1-3  colorspace_2.1-0      
##  [19] progressr_0.13.0       knitr_1.42             ROCR_1.0-11           
##  [22] tensor_1.5             listenv_0.9.0          GenomeInfoDbData_1.2.9
##  [25] polyclip_1.10-4        bit64_4.0.5            rprojroot_2.0.3       
##  [28] parallelly_1.34.0      vctrs_0.5.2            generics_0.1.3        
##  [31] xfun_0.37              R6_2.5.1               locfit_1.5-9.7        
##  [34] bitops_1.0-7           spatstat.utils_3.0-1   cachem_1.0.7          
##  [37] DelayedArray_0.24.0    promises_1.2.0.1       scales_1.2.1          
##  [40] gtable_0.3.1           globals_0.16.2         goftest_1.2-3         
##  [43] rlang_1.0.6            systemfonts_1.0.4      splines_4.2.0         
##  [46] lazyeval_0.2.2         spatstat.geom_3.0-6    yaml_2.3.7            
##  [49] reshape2_1.4.4         abind_1.4-5            httpuv_1.6.9          
##  [52] tools_4.2.0            ggplot2_3.4.1          ellipsis_0.3.2        
##  [55] jquerylib_0.1.4        RColorBrewer_1.1-3     ggridges_0.5.4        
##  [58] Rcpp_1.0.10            plyr_1.8.8             progress_1.2.2        
##  [61] zlibbioc_1.44.0        purrr_1.0.1            RCurl_1.98-1.12       
##  [64] prettyunits_1.1.1      deldir_1.0-6           pbapply_1.7-0         
##  [67] cowplot_1.1.1          zoo_1.8-11             ggrepel_0.9.3         
##  [70] cluster_2.1.3          fs_1.6.1               magrittr_2.0.3        
##  [73] data.table_1.14.8      scattermore_0.8        lmtest_0.9-40         
##  [76] RANN_2.6.1             fitdistrplus_1.1-8     hms_1.1.2             
##  [79] patchwork_1.1.2        mime_0.12              evaluate_0.20         
##  [82] xtable_1.8-4           XML_3.99-0.13          gridExtra_2.3         
##  [85] compiler_4.2.0         tibble_3.1.8           KernSmooth_2.23-20    
##  [88] crayon_1.5.2           htmltools_0.5.4        later_1.3.0           
##  [91] tidyr_1.3.0            geneplotter_1.76.0     DBI_1.1.3             
##  [94] formatR_1.14           MASS_7.3-56            rappdirs_0.3.3        
##  [97] MAST_1.24.1            Matrix_1.5-3           cli_3.6.0             
## [100] parallel_4.2.0         igraph_1.4.1           pkgconfig_2.0.3       
## [103] pkgdown_2.0.7          sp_1.6-0               plotly_4.10.1         
## [106] spatstat.sparse_3.0-0  annotate_1.76.0        bslib_0.4.2           
## [109] XVector_0.38.0         stringr_1.5.0          digest_0.6.31         
## [112] sctransform_0.3.5      RcppAnnoy_0.0.20       Biostrings_2.66.0     
## [115] spatstat.data_3.0-0    rmarkdown_2.20         leiden_0.4.3          
## [118] uwot_0.1.14            shiny_1.7.4            lifecycle_1.0.3       
## [121] nlme_3.1-157           jsonlite_1.8.4         desc_1.4.2            
## [124] viridisLite_0.4.1      limma_3.54.1           fansi_1.0.4           
## [127] pillar_1.8.1           lattice_0.20-45        KEGGREST_1.38.0       
## [130] fastmap_1.1.1          httr_1.4.5             survival_3.3-1        
## [133] glue_1.6.2             png_0.1-8              bit_4.0.5             
## [136] stringi_1.7.12         sass_0.4.5             blob_1.2.3            
## [139] textshaping_0.3.6      DESeq2_1.38.3          memoise_2.0.1         
## [142] dplyr_1.1.0            irlba_2.3.5.1          future.apply_1.10.0
```

Example 60 (unknown):
```unknown
## R version 4.2.0 (2022-04-22)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.5 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/liblapack.so.3
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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       
## 
## attached base packages:
## [1] stats4    stats     graphics  grDevices utils     datasets  methods  
## [8] base     
## 
## other attached packages:
##  [1] SingleCellExperiment_1.20.0   SummarizedExperiment_1.28.0  
##  [3] Biobase_2.58.0                GenomicRanges_1.50.2         
##  [5] GenomeInfoDb_1.35.16          IRanges_2.32.0               
##  [7] S4Vectors_0.36.2              BiocGenerics_0.44.0          
##  [9] MatrixGenerics_1.10.0         matrixStats_0.63.0           
## [11] thp1.eccite.SeuratData_3.1.5  stxBrain.SeuratData_0.1.1    
## [13] ssHippo.SeuratData_3.1.4      pbmcsca.SeuratData_3.0.0     
## [15] pbmcMultiome.SeuratData_0.1.2 pbmc3k.SeuratData_3.1.4      
## [17] panc8.SeuratData_3.0.2        ifnb.SeuratData_3.1.0        
## [19] hcabm40k.SeuratData_3.0.0     bmcite.SeuratData_0.3.0      
## [21] SeuratData_0.2.2              SeuratObject_4.1.3           
## [23] Seurat_4.3.0                 
## 
## loaded via a namespace (and not attached):
##   [1] utf8_1.2.3             spatstat.explore_3.0-6 reticulate_1.28       
##   [4] tidyselect_1.2.0       RSQLite_2.3.0          AnnotationDbi_1.60.0  
##   [7] htmlwidgets_1.6.1      grid_4.2.0             BiocParallel_1.32.5   
##  [10] Rtsne_0.16             munsell_0.5.0          codetools_0.2-18      
##  [13] ragg_1.2.5             ica_1.0-3              future_1.31.0         
##  [16] miniUI_0.1.1.1         spatstat.random_3.1-3  colorspace_2.1-0      
##  [19] progressr_0.13.0       knitr_1.42             ROCR_1.0-11           
##  [22] tensor_1.5             listenv_0.9.0          GenomeInfoDbData_1.2.9
##  [25] polyclip_1.10-4        bit64_4.0.5            rprojroot_2.0.3       
##  [28] parallelly_1.34.0      vctrs_0.5.2            generics_0.1.3        
##  [31] xfun_0.37              R6_2.5.1               locfit_1.5-9.7        
##  [34] bitops_1.0-7           spatstat.utils_3.0-1   cachem_1.0.7          
##  [37] DelayedArray_0.24.0    promises_1.2.0.1       scales_1.2.1          
##  [40] gtable_0.3.1           globals_0.16.2         goftest_1.2-3         
##  [43] rlang_1.0.6            systemfonts_1.0.4      splines_4.2.0         
##  [46] lazyeval_0.2.2         spatstat.geom_3.0-6    yaml_2.3.7            
##  [49] reshape2_1.4.4         abind_1.4-5            httpuv_1.6.9          
##  [52] tools_4.2.0            ggplot2_3.4.1          ellipsis_0.3.2        
##  [55] jquerylib_0.1.4        RColorBrewer_1.1-3     ggridges_0.5.4        
##  [58] Rcpp_1.0.10            plyr_1.8.8             progress_1.2.2        
##  [61] zlibbioc_1.44.0        purrr_1.0.1            RCurl_1.98-1.12       
##  [64] prettyunits_1.1.1      deldir_1.0-6           pbapply_1.7-0         
##  [67] cowplot_1.1.1          zoo_1.8-11             ggrepel_0.9.3         
##  [70] cluster_2.1.3          fs_1.6.1               magrittr_2.0.3        
##  [73] data.table_1.14.8      scattermore_0.8        lmtest_0.9-40         
##  [76] RANN_2.6.1             fitdistrplus_1.1-8     hms_1.1.2             
##  [79] patchwork_1.1.2        mime_0.12              evaluate_0.20         
##  [82] xtable_1.8-4           XML_3.99-0.13          gridExtra_2.3         
##  [85] compiler_4.2.0         tibble_3.1.8           KernSmooth_2.23-20    
##  [88] crayon_1.5.2           htmltools_0.5.4        later_1.3.0           
##  [91] tidyr_1.3.0            geneplotter_1.76.0     DBI_1.1.3             
##  [94] formatR_1.14           MASS_7.3-56            rappdirs_0.3.3        
##  [97] MAST_1.24.1            Matrix_1.5-3           cli_3.6.0             
## [100] parallel_4.2.0         igraph_1.4.1           pkgconfig_2.0.3       
## [103] pkgdown_2.0.7          sp_1.6-0               plotly_4.10.1         
## [106] spatstat.sparse_3.0-0  annotate_1.76.0        bslib_0.4.2           
## [109] XVector_0.38.0         stringr_1.5.0          digest_0.6.31         
## [112] sctransform_0.3.5      RcppAnnoy_0.0.20       Biostrings_2.66.0     
## [115] spatstat.data_3.0-0    rmarkdown_2.20         leiden_0.4.3          
## [118] uwot_0.1.14            shiny_1.7.4            lifecycle_1.0.3       
## [121] nlme_3.1-157           jsonlite_1.8.4         desc_1.4.2            
## [124] viridisLite_0.4.1      limma_3.54.1           fansi_1.0.4           
## [127] pillar_1.8.1           lattice_0.20-45        KEGGREST_1.38.0       
## [130] fastmap_1.1.1          httr_1.4.5             survival_3.3-1        
## [133] glue_1.6.2             png_0.1-8              bit_4.0.5             
## [136] stringi_1.7.12         sass_0.4.5             blob_1.2.3            
## [139] textshaping_0.3.6      DESeq2_1.38.3          memoise_2.0.1         
## [142] dplyr_1.1.0            irlba_2.3.5.1          future.apply_1.10.0
```

---

## Analysis, visualization, and integration of Visium HD spatial datasets with Seurat • Seurat

**URL:** http://127.0.0.1:9173/seurat/pbmc3k_tutorial.html

**Contents:**
- Seurat - Guided Clustering Tutorial
    - Compiled: October 31, 2023
- Setup the Seurat Object
- Standard pre-processing workflow
  - QC and selecting cells for further analysis
- Normalizing the data
- Identification of highly variable features (feature selection)
- Scaling the data
- Perform linear dimensional reduction
- Determine the ‘dimensionality’ of the dataset
- Cluster the cells
- Run non-linear dimensional reduction (UMAP/tSNE)
- Finding differentially expressed features (cluster biomarkers)
- Assigning cell type identity to clusters
- Contents

For this tutorial, we will be analyzing the a dataset of Peripheral Blood Mononuclear Cells (PBMC) freely available from 10X Genomics. There are 2,700 single cells that were sequenced on the Illumina NextSeq 500. The raw data can be found here.

We start by reading in the data. The Read10X() function reads in the output of the cellranger pipeline from 10X, returning a unique molecular identified (UMI) count matrix. The values in this matrix represent the number of molecules for each feature (i.e. gene; row) that are detected in each cell (column). Note that more recent versions of cellranger now also output using the h5 file format, which can be read in using the Read10X_h5() function in Seurat.

We next use the count matrix to create a Seurat object. The object serves as a container that contains both data (like the count matrix) and analysis (like PCA, or clustering results) for a single-cell dataset. For more information, check out our [Seurat object interaction vignette], or our GitHub Wiki. For example, in Seurat v5, the count matrix is stored in pbmc[["RNA"]]$counts.

What does data in a count matrix look like?

The . values in the matrix represent 0s (no molecules detected). Since most values in an scRNA-seq matrix are 0, Seurat uses a sparse-matrix representation whenever possible. This results in significant memory and speed savings for Drop-seq/inDrop/10x data.

The steps below encompass the standard pre-processing workflow for scRNA-seq data in Seurat. These represent the selection and filtration of cells based on QC metrics, data normalization and scaling, and the detection of highly variable features.

Seurat allows you to easily explore QC metrics and filter cells based on any user-defined criteria. A few QC metrics commonly used by the community include

Where are QC metrics stored in Seurat?

In the example below, we visualize QC metrics, and use these to filter cells.

After removing unwanted cells from the dataset, the next step is to normalize the data. By default, we employ a global-scaling normalization method “LogNormalize” that normalizes the feature expression measurements for each cell by the total expression, multiplies this by a scale factor (10,000 by default), and log-transforms the result. In Seurat v5, Normalized values are stored in pbmc[["RNA"]]$data.

For clarity, in this previous line of code (and in future commands), we provide the default values for certain parameters in the function call. However, this isn’t required and the same behavior can be achieved with:

While this method of normalization is standard and widely used in scRNA-seq analysis, global-scaling relies on an assumption that each cell originally contains the same number of RNA molecules. We and others have developed alternative workflows for the single cell preprocessing that do not make these assumptions. For users who are interested, please check out our SCTransform() normalization workflow. The method is described in ourpaper, with a separate vignette using Seurat here. The use of SCTransform replaces the need to run NormalizeData, FindVariableFeatures, or ScaleData (described below.)

We next calculate a subset of features that exhibit high cell-to-cell variation in the dataset (i.e, they are highly expressed in some cells, and lowly expressed in others). We and others have found that focusing on these genes in downstream analysis helps to highlight biological signal in single-cell datasets.

Our procedure in Seurat is described in detail here, and improves on previous versions by directly modeling the mean-variance relationship inherent in single-cell data, and is implemented in the FindVariableFeatures() function. By default, we return 2,000 features per dataset. These will be used in downstream analysis, like PCA.

Next, we apply a linear transformation (‘scaling’) that is a standard pre-processing step prior to dimensional reduction techniques like PCA. The ScaleData() function:

How can I remove unwanted sources of variation

In Seurat, we also use the ScaleData() function to remove unwanted sources of variation from a single-cell dataset. For example, we could ‘regress out’ heterogeneity associated with (for example) cell cycle stage, or mitochondrial contamination i.e.:

Next we perform PCA on the scaled data. By default, only the previously determined variable features are used as input, but can be defined using features argument if you wish to choose a different subset (if you do want to use a custom subset of features, make sure you pass these to ScaleData first).

For the first principal components, Seurat outputs a list of genes with the most positive and negative loadings, representing modules of genes that exhibit either correlation (or anti-correlation) across single-cells in the dataset.

Seurat provides several useful ways of visualizing both cells and features that define the PCA, including VizDimReduction(), DimPlot(), and DimHeatmap()

In particular DimHeatmap() allows for easy exploration of the primary sources of heterogeneity in a dataset, and can be useful when trying to decide which PCs to include for further downstream analyses. Both cells and features are ordered according to their PCA scores. Setting cells to a number plots the ‘extreme’ cells on both ends of the spectrum, which dramatically speeds plotting for large datasets. Though clearly a supervised analysis, we find this to be a valuable tool for exploring correlated feature sets.

To overcome the extensive technical noise in any single feature for scRNA-seq data, Seurat clusters cells based on their PCA scores, with each PC essentially representing a ‘metafeature’ that combines information across a correlated feature set. The top principal components therefore represent a robust compression of the dataset. However, how many components should we choose to include? 10? 20? 100?

In Macosko et al, we implemented a resampling test inspired by the JackStraw procedure. While still available in Seurat (see previous vignette), this is a slow and computationally expensive procedure, and we is no longer routinely used in single cell analysis.

An alternative heuristic method generates an ‘Elbow plot’: a ranking of principle components based on the percentage of variance explained by each one (ElbowPlot() function). In this example, we can observe an ‘elbow’ around PC9-10, suggesting that the majority of true signal is captured in the first 10 PCs.

Identifying the true dimensionality of a dataset – can be challenging/uncertain for the user. We therefore suggest these multiple approaches for users. The first is more supervised, exploring PCs to determine relevant sources of heterogeneity, and could be used in conjunction with GSEA for example. The second (ElbowPlot) The third is a heuristic that is commonly used, and can be calculated instantly. In this example, we might have been justified in choosing anything between PC 7-12 as a cutoff.

We chose 10 here, but encourage users to consider the following:

Seurat applies a graph-based clustering approach, building upon initial strategies in (Macosko et al). Importantly, the distance metric which drives the clustering analysis (based on previously identified PCs) remains the same. However, our approach to partitioning the cellular distance matrix into clusters has dramatically improved. Our approach was heavily inspired by recent manuscripts which applied graph-based clustering approaches to scRNA-seq data [SNN-Cliq, Xu and Su, Bioinformatics, 2015] and CyTOF data [PhenoGraph, Levine et al., Cell, 2015]. Briefly, these methods embed cells in a graph structure - for example a K-nearest neighbor (KNN) graph, with edges drawn between cells with similar feature expression patterns, and then attempt to partition this graph into highly interconnected ‘quasi-cliques’ or ‘communities’.

As in PhenoGraph, we first construct a KNN graph based on the euclidean distance in PCA space, and refine the edge weights between any two cells based on the shared overlap in their local neighborhoods (Jaccard similarity). This step is performed using the FindNeighbors() function, and takes as input the previously defined dimensionality of the dataset (first 10 PCs).

To cluster the cells, we next apply modularity optimization techniques such as the Louvain algorithm (default) or SLM [SLM, Blondel et al., Journal of Statistical Mechanics], to iteratively group cells together, with the goal of optimizing the standard modularity function. The FindClusters() function implements this procedure, and contains a resolution parameter that sets the ‘granularity’ of the downstream clustering, with increased values leading to a greater number of clusters. We find that setting this parameter between 0.4-1.2 typically returns good results for single-cell datasets of around 3K cells. Optimal resolution often increases for larger datasets. The clusters can be found using the Idents() function.

Seurat offers several non-linear dimensional reduction techniques, such as tSNE and UMAP, to visualize and explore these datasets. The goal of these algorithms is to learn underlying structure in the dataset, in order to place similar cells together in low-dimensional space. Therefore, cells that are grouped together within graph-based clusters determined above should co-localize on these dimension reduction plots.

While we and others have routinely found 2D visualization techniques like tSNE and UMAP to be valuable tools for exploring datasets, all visualization techniques have limitations, and cannot fully represent the complexity of the underlying data. In particular, these methods aim to preserve local distances in the dataset (i.e. ensuring that cells with very similar gene expression profiles co-localize), but often do not preserve more global relationships. We encourage users to leverage techniques like UMAP for visualization, but to avoid drawing biological conclusions solely on the basis of visualization techniques.

You can save the object at this point so that it can easily be loaded back in without having to rerun the computationally intensive steps performed above, or easily shared with collaborators.

Seurat can help you find markers that define clusters via differential expression (DE). By default, it identifies positive and negative markers of a single cluster (specified in ident.1), compared to all other cells. FindAllMarkers() automates this process for all clusters, but you can also test groups of clusters vs. each other, or against all cells.

In Seurat v5, we use the presto package (as described here and available for installation here), to dramatically improve the speed of DE analysis, particularly for large datasets. For users who are not using presto, you can examine the documentation for this function (?FindMarkers) to explore the min.pct and logfc.threshold parameters, which can be increased in order to increase the speed of DE testing.

Seurat has several tests for differential expression which can be set with the test.use parameter (see our DE vignette for details). For example, the ROC test returns the ‘classification power’ for any individual marker (ranging from 0 - random, to 1 - perfect).

We include several tools for visualizing marker expression. VlnPlot() (shows expression probability distributions across clusters), and FeaturePlot() (visualizes feature expression on a tSNE or PCA plot) are our most commonly used visualizations. We also suggest exploring RidgePlot(), CellScatter(), and DotPlot() as additional methods to view your dataset.

DoHeatmap() generates an expression heatmap for given cells and features. In this case, we are plotting the top 20 markers (or all markers if less than 20) for each cluster.

Fortunately in the case of this dataset, we can use canonical markers to easily match the unbiased clustering to known cell types:

Developed by Rahul Satija, Satija Lab and Collaborators.

Site built with pkgdown 2.0.7.

**Examples:**

Example 1 (unknown):
```unknown
vignettes/pbmc3k_tutorial.Rmd
```

Example 2 (unknown):
```unknown
pbmc3k_tutorial.Rmd
```

Example 3 (unknown):
```unknown
Read10X_h5()
```

Example 4 (unknown):
```unknown
pbmc[["RNA"]]$counts
```

Example 5 (unknown):
```unknown
library(dplyr)
library(Seurat)
library(patchwork)

# Load the PBMC dataset
pbmc.data <- Read10X(data.dir = "/brahms/mollag/practice/filtered_gene_bc_matrices/hg19/")
# Initialize the Seurat object with the raw (non-normalized data).
pbmc <- CreateSeuratObject(counts = pbmc.data, project = "pbmc3k", min.cells = 3, min.features = 200)
pbmc
```

Example 6 (r):
```r
library(dplyr)
library(Seurat)
library(patchwork)

# Load the PBMC dataset
pbmc.data <- Read10X(data.dir = "/brahms/mollag/practice/filtered_gene_bc_matrices/hg19/")
# Initialize the Seurat object with the raw (non-normalized data).
pbmc <- CreateSeuratObject(counts = pbmc.data, project = "pbmc3k", min.cells = 3, min.features = 200)
pbmc
```

Example 7 (r):
```r
library(dplyr)
library(Seurat)
library(patchwork)

# Load the PBMC dataset
pbmc.data <- Read10X(data.dir = "/brahms/mollag/practice/filtered_gene_bc_matrices/hg19/")
# Initialize the Seurat object with the raw (non-normalized data).
pbmc <- CreateSeuratObject(counts = pbmc.data, project = "pbmc3k", min.cells = 3, min.features = 200)
pbmc
```

Example 8 (python):
```python
## An object of class Seurat 
## 13714 features across 2700 samples within 1 assay 
## Active assay: RNA (13714 features, 0 variable features)
##  1 layer present: counts
```

Example 9 (python):
```python
## An object of class Seurat 
## 13714 features across 2700 samples within 1 assay 
## Active assay: RNA (13714 features, 0 variable features)
##  1 layer present: counts
```

Example 10 (unknown):
```unknown
# Lets examine a few genes in the first thirty cells
pbmc.data[c("CD3D", "TCL1A", "MS4A1"), 1:30]
```

Example 11 (r):
```r
# Lets examine a few genes in the first thirty cells
pbmc.data[c("CD3D", "TCL1A", "MS4A1"), 1:30]
```

Example 12 (r):
```r
# Lets examine a few genes in the first thirty cells
pbmc.data[c("CD3D", "TCL1A", "MS4A1"), 1:30]
```

Example 13 (python):
```python
## 3 x 30 sparse Matrix of class "dgCMatrix"
##                                                                    
## CD3D  4 . 10 . . 1 2 3 1 . . 2 7 1 . . 1 3 . 2  3 . . . . . 3 4 1 5
## TCL1A . .  . . . . . . 1 . . . . . . . . . . .  . 1 . . . . . . . .
## MS4A1 . 6  . . . . . . 1 1 1 . . . . . . . . . 36 1 2 . . 2 . . . .
```

Example 14 (python):
```python
## 3 x 30 sparse Matrix of class "dgCMatrix"
##                                                                    
## CD3D  4 . 10 . . 1 2 3 1 . . 2 7 1 . . 1 3 . 2  3 . . . . . 3 4 1 5
## TCL1A . .  . . . . . . 1 . . . . . . . . . . .  . 1 . . . . . . . .
## MS4A1 . 6  . . . . . . 1 1 1 . . . . . . . . . 36 1 2 . . 2 . . . .
```

Example 15 (unknown):
```unknown
dense.size <- object.size(as.matrix(pbmc.data))
dense.size
```

Example 16 (r):
```r
dense.size <- object.size(as.matrix(pbmc.data))
dense.size
```

Example 17 (r):
```r
dense.size <- object.size(as.matrix(pbmc.data))
dense.size
```

Example 18 (unknown):
```unknown
## 709591472 bytes
```

Example 19 (unknown):
```unknown
## 709591472 bytes
```

Example 20 (unknown):
```unknown
sparse.size <- object.size(pbmc.data)
sparse.size
```

Example 21 (r):
```r
sparse.size <- object.size(pbmc.data)
sparse.size
```

Example 22 (r):
```r
sparse.size <- object.size(pbmc.data)
sparse.size
```

Example 23 (unknown):
```unknown
## 29905192 bytes
```

Example 24 (unknown):
```unknown
## 29905192 bytes
```

Example 25 (unknown):
```unknown
dense.size/sparse.size
```

Example 26 (r):
```r
dense.size/sparse.size
```

Example 27 (r):
```r
dense.size/sparse.size
```

Example 28 (unknown):
```unknown
## 23.7 bytes
```

Example 29 (unknown):
```unknown
## 23.7 bytes
```

Example 30 (unknown):
```unknown
PercentageFeatureSet()
```

Example 31 (python):
```python
# The [[ operator can add columns to object metadata. This is a great place to stash QC stats
pbmc[["percent.mt"]] <- PercentageFeatureSet(pbmc, pattern = "^MT-")
```

Example 32 (r):
```r
# The [[ operator can add columns to object metadata. This is a great place to stash QC stats
pbmc[["percent.mt"]] <- PercentageFeatureSet(pbmc, pattern = "^MT-")
```

Example 33 (r):
```r
# The [[ operator can add columns to object metadata. This is a great place to stash QC stats
pbmc[["percent.mt"]] <- PercentageFeatureSet(pbmc, pattern = "^MT-")
```

Example 34 (unknown):
```unknown
CreateSeuratObject()
```

Example 35 (unknown):
```unknown
# Show QC metrics for the first 5 cells
head(pbmc@meta.data, 5)
```

Example 36 (r):
```r
# Show QC metrics for the first 5 cells
head(pbmc@meta.data, 5)
```

Example 37 (r):
```r
# Show QC metrics for the first 5 cells
head(pbmc@meta.data, 5)
```

Example 38 (unknown):
```unknown
##                  orig.ident nCount_RNA nFeature_RNA percent.mt
## AAACATACAACCAC-1     pbmc3k       2419          779  3.0177759
## AAACATTGAGCTAC-1     pbmc3k       4903         1352  3.7935958
## AAACATTGATCAGC-1     pbmc3k       3147         1129  0.8897363
## AAACCGTGCTTCCG-1     pbmc3k       2639          960  1.7430845
## AAACCGTGTATGCG-1     pbmc3k        980          521  1.2244898
```

Example 39 (unknown):
```unknown
##                  orig.ident nCount_RNA nFeature_RNA percent.mt
## AAACATACAACCAC-1     pbmc3k       2419          779  3.0177759
## AAACATTGAGCTAC-1     pbmc3k       4903         1352  3.7935958
## AAACATTGATCAGC-1     pbmc3k       3147         1129  0.8897363
## AAACCGTGCTTCCG-1     pbmc3k       2639          960  1.7430845
## AAACCGTGTATGCG-1     pbmc3k        980          521  1.2244898
```

Example 40 (unknown):
```unknown
# Visualize QC metrics as a violin plot
VlnPlot(pbmc, features = c("nFeature_RNA", "nCount_RNA", "percent.mt"), ncol = 3)
```

Example 41 (r):
```r
# Visualize QC metrics as a violin plot
VlnPlot(pbmc, features = c("nFeature_RNA", "nCount_RNA", "percent.mt"), ncol = 3)
```

Example 42 (r):
```r
# Visualize QC metrics as a violin plot
VlnPlot(pbmc, features = c("nFeature_RNA", "nCount_RNA", "percent.mt"), ncol = 3)
```

Example 43 (python):
```python
# FeatureScatter is typically used to visualize feature-feature relationships, but can be used
# for anything calculated by the object, i.e. columns in object metadata, PC scores etc.

plot1 <- FeatureScatter(pbmc, feature1 = "nCount_RNA", feature2 = "percent.mt")
plot2 <- FeatureScatter(pbmc, feature1 = "nCount_RNA", feature2 = "nFeature_RNA")
plot1 + plot2
```

Example 44 (r):
```r
# FeatureScatter is typically used to visualize feature-feature relationships, but can be used
# for anything calculated by the object, i.e. columns in object metadata, PC scores etc.

plot1 <- FeatureScatter(pbmc, feature1 = "nCount_RNA", feature2 = "percent.mt")
plot2 <- FeatureScatter(pbmc, feature1 = "nCount_RNA", feature2 = "nFeature_RNA")
plot1 + plot2
```

Example 45 (r):
```r
# FeatureScatter is typically used to visualize feature-feature relationships, but can be used
# for anything calculated by the object, i.e. columns in object metadata, PC scores etc.

plot1 <- FeatureScatter(pbmc, feature1 = "nCount_RNA", feature2 = "percent.mt")
plot2 <- FeatureScatter(pbmc, feature1 = "nCount_RNA", feature2 = "nFeature_RNA")
plot1 + plot2
```

Example 46 (unknown):
```unknown
pbmc <- subset(pbmc, subset = nFeature_RNA > 200 & nFeature_RNA < 2500 & percent.mt < 5)
```

Example 47 (r):
```r
pbmc <- subset(pbmc, subset = nFeature_RNA > 200 & nFeature_RNA < 2500 & percent.mt < 5)
```

Example 48 (r):
```r
pbmc <- subset(pbmc, subset = nFeature_RNA > 200 & nFeature_RNA < 2500 & percent.mt < 5)
```

Example 49 (unknown):
```unknown
pbmc[["RNA"]]$data
```

Example 50 (unknown):
```unknown
pbmc <- NormalizeData(pbmc, normalization.method = "LogNormalize", scale.factor = 10000)
```

Example 51 (r):
```r
pbmc <- NormalizeData(pbmc, normalization.method = "LogNormalize", scale.factor = 10000)
```

Example 52 (r):
```r
pbmc <- NormalizeData(pbmc, normalization.method = "LogNormalize", scale.factor = 10000)
```

Example 53 (unknown):
```unknown
pbmc <- NormalizeData(pbmc)
```

Example 54 (r):
```r
pbmc <- NormalizeData(pbmc)
```

Example 55 (r):
```r
pbmc <- NormalizeData(pbmc)
```

Example 56 (unknown):
```unknown
SCTransform()
```

Example 57 (unknown):
```unknown
SCTransform
```

Example 58 (unknown):
```unknown
NormalizeData
```

Example 59 (unknown):
```unknown
FindVariableFeatures
```

Example 60 (unknown):
```unknown
FindVariableFeatures()
```

Example 61 (unknown):
```unknown
pbmc <- FindVariableFeatures(pbmc, selection.method = "vst", nfeatures = 2000)

# Identify the 10 most highly variable genes
top10 <- head(VariableFeatures(pbmc), 10)

# plot variable features with and without labels
plot1 <- VariableFeaturePlot(pbmc)
plot2 <- LabelPoints(plot = plot1, points = top10, repel = TRUE)
plot1 + plot2
```

Example 62 (r):
```r
pbmc <- FindVariableFeatures(pbmc, selection.method = "vst", nfeatures = 2000)

# Identify the 10 most highly variable genes
top10 <- head(VariableFeatures(pbmc), 10)

# plot variable features with and without labels
plot1 <- VariableFeaturePlot(pbmc)
plot2 <- LabelPoints(plot = plot1, points = top10, repel = TRUE)
plot1 + plot2
```

Example 63 (r):
```r
pbmc <- FindVariableFeatures(pbmc, selection.method = "vst", nfeatures = 2000)

# Identify the 10 most highly variable genes
top10 <- head(VariableFeatures(pbmc), 10)

# plot variable features with and without labels
plot1 <- VariableFeaturePlot(pbmc)
plot2 <- LabelPoints(plot = plot1, points = top10, repel = TRUE)
plot1 + plot2
```

Example 64 (unknown):
```unknown
ScaleData()
```

Example 65 (unknown):
```unknown
pbmc[["RNA"]]$scale.data
```

Example 66 (unknown):
```unknown
all.genes <- rownames(pbmc)
pbmc <- ScaleData(pbmc, features = all.genes)
```

Example 67 (r):
```r
all.genes <- rownames(pbmc)
pbmc <- ScaleData(pbmc, features = all.genes)
```

Example 68 (r):
```r
all.genes <- rownames(pbmc)
pbmc <- ScaleData(pbmc, features = all.genes)
```

Example 69 (unknown):
```unknown
ScaleData()
```

Example 70 (unknown):
```unknown
pbmc <- ScaleData(pbmc, vars.to.regress = "percent.mt")
```

Example 71 (r):
```r
pbmc <- ScaleData(pbmc, vars.to.regress = "percent.mt")
```

Example 72 (r):
```r
pbmc <- ScaleData(pbmc, vars.to.regress = "percent.mt")
```

Example 73 (unknown):
```unknown
SCTransform()
```

Example 74 (unknown):
```unknown
ScaleData()
```

Example 75 (unknown):
```unknown
SCTransform()
```

Example 76 (unknown):
```unknown
vars.to.regress
```

Example 77 (unknown):
```unknown
pbmc <- RunPCA(pbmc, features = VariableFeatures(object = pbmc))
```

Example 78 (r):
```r
pbmc <- RunPCA(pbmc, features = VariableFeatures(object = pbmc))
```

Example 79 (r):
```r
pbmc <- RunPCA(pbmc, features = VariableFeatures(object = pbmc))
```

Example 80 (unknown):
```unknown
VizDimReduction()
```

Example 81 (unknown):
```unknown
DimHeatmap()
```

Example 82 (python):
```python
# Examine and visualize PCA results a few different ways
print(pbmc[["pca"]], dims = 1:5, nfeatures = 5)
```

Example 83 (r):
```r
# Examine and visualize PCA results a few different ways
print(pbmc[["pca"]], dims = 1:5, nfeatures = 5)
```

Example 84 (r):
```r
# Examine and visualize PCA results a few different ways
print(pbmc[["pca"]], dims = 1:5, nfeatures = 5)
```

Example 85 (unknown):
```unknown
## PC_ 1 
## Positive:  CST3, TYROBP, LST1, AIF1, FTL 
## Negative:  MALAT1, LTB, IL32, IL7R, CD2 
## PC_ 2 
## Positive:  CD79A, MS4A1, TCL1A, HLA-DQA1, HLA-DQB1 
## Negative:  NKG7, PRF1, CST7, GZMB, GZMA 
## PC_ 3 
## Positive:  HLA-DQA1, CD79A, CD79B, HLA-DQB1, HLA-DPB1 
## Negative:  PPBP, PF4, SDPR, SPARC, GNG11 
## PC_ 4 
## Positive:  HLA-DQA1, CD79B, CD79A, MS4A1, HLA-DQB1 
## Negative:  VIM, IL7R, S100A6, IL32, S100A8 
## PC_ 5 
## Positive:  GZMB, NKG7, S100A8, FGFBP2, GNLY 
## Negative:  LTB, IL7R, CKB, VIM, MS4A7
```

Example 86 (unknown):
```unknown
## PC_ 1 
## Positive:  CST3, TYROBP, LST1, AIF1, FTL 
## Negative:  MALAT1, LTB, IL32, IL7R, CD2 
## PC_ 2 
## Positive:  CD79A, MS4A1, TCL1A, HLA-DQA1, HLA-DQB1 
## Negative:  NKG7, PRF1, CST7, GZMB, GZMA 
## PC_ 3 
## Positive:  HLA-DQA1, CD79A, CD79B, HLA-DQB1, HLA-DPB1 
## Negative:  PPBP, PF4, SDPR, SPARC, GNG11 
## PC_ 4 
## Positive:  HLA-DQA1, CD79B, CD79A, MS4A1, HLA-DQB1 
## Negative:  VIM, IL7R, S100A6, IL32, S100A8 
## PC_ 5 
## Positive:  GZMB, NKG7, S100A8, FGFBP2, GNLY 
## Negative:  LTB, IL7R, CKB, VIM, MS4A7
```

Example 87 (unknown):
```unknown
VizDimLoadings(pbmc, dims = 1:2, reduction = "pca")
```

Example 88 (r):
```r
VizDimLoadings(pbmc, dims = 1:2, reduction = "pca")
```

Example 89 (r):
```r
VizDimLoadings(pbmc, dims = 1:2, reduction = "pca")
```

Example 90 (unknown):
```unknown
DimPlot(pbmc, reduction = "pca") + NoLegend()
```

Example 91 (r):
```r
DimPlot(pbmc, reduction = "pca") + NoLegend()
```

Example 92 (r):
```r
DimPlot(pbmc, reduction = "pca") + NoLegend()
```

Example 93 (unknown):
```unknown
DimHeatmap()
```

Example 94 (unknown):
```unknown
DimHeatmap(pbmc, dims = 1, cells = 500, balanced = TRUE)
```

Example 95 (r):
```r
DimHeatmap(pbmc, dims = 1, cells = 500, balanced = TRUE)
```

Example 96 (r):
```r
DimHeatmap(pbmc, dims = 1, cells = 500, balanced = TRUE)
```

Example 97 (unknown):
```unknown
DimHeatmap(pbmc, dims = 1:15, cells = 500, balanced = TRUE)
```

Example 98 (r):
```r
DimHeatmap(pbmc, dims = 1:15, cells = 500, balanced = TRUE)
```

Example 99 (r):
```r
DimHeatmap(pbmc, dims = 1:15, cells = 500, balanced = TRUE)
```

Example 100 (unknown):
```unknown
ElbowPlot()
```

Example 101 (unknown):
```unknown
ElbowPlot(pbmc)
```

Example 102 (r):
```r
ElbowPlot(pbmc)
```

Example 103 (r):
```r
ElbowPlot(pbmc)
```

Example 104 (unknown):
```unknown
FindNeighbors()
```

Example 105 (unknown):
```unknown
FindClusters()
```

Example 106 (unknown):
```unknown
pbmc <- FindNeighbors(pbmc, dims = 1:10)
pbmc <- FindClusters(pbmc, resolution = 0.5)
```

Example 107 (r):
```r
pbmc <- FindNeighbors(pbmc, dims = 1:10)
pbmc <- FindClusters(pbmc, resolution = 0.5)
```

Example 108 (r):
```r
pbmc <- FindNeighbors(pbmc, dims = 1:10)
pbmc <- FindClusters(pbmc, resolution = 0.5)
```

Example 109 (unknown):
```unknown
## Modularity Optimizer version 1.3.0 by Ludo Waltman and Nees Jan van Eck
## 
## Number of nodes: 2638
## Number of edges: 95965
## 
## Running Louvain algorithm...
## Maximum modularity in 10 random starts: 0.8723
## Number of communities: 9
## Elapsed time: 0 seconds
```

Example 110 (unknown):
```unknown
## Modularity Optimizer version 1.3.0 by Ludo Waltman and Nees Jan van Eck
## 
## Number of nodes: 2638
## Number of edges: 95965
## 
## Running Louvain algorithm...
## Maximum modularity in 10 random starts: 0.8723
## Number of communities: 9
## Elapsed time: 0 seconds
```

Example 111 (unknown):
```unknown
# Look at cluster IDs of the first 5 cells
head(Idents(pbmc), 5)
```

Example 112 (r):
```r
# Look at cluster IDs of the first 5 cells
head(Idents(pbmc), 5)
```

Example 113 (r):
```r
# Look at cluster IDs of the first 5 cells
head(Idents(pbmc), 5)
```

Example 114 (unknown):
```unknown
## AAACATACAACCAC-1 AAACATTGAGCTAC-1 AAACATTGATCAGC-1 AAACCGTGCTTCCG-1 
##                2                3                2                1 
## AAACCGTGTATGCG-1 
##                6 
## Levels: 0 1 2 3 4 5 6 7 8
```

Example 115 (unknown):
```unknown
## AAACATACAACCAC-1 AAACATTGAGCTAC-1 AAACATTGATCAGC-1 AAACCGTGCTTCCG-1 
##                2                3                2                1 
## AAACCGTGTATGCG-1 
##                6 
## Levels: 0 1 2 3 4 5 6 7 8
```

Example 116 (unknown):
```unknown
pbmc <- RunUMAP(pbmc, dims = 1:10)
```

Example 117 (r):
```r
pbmc <- RunUMAP(pbmc, dims = 1:10)
```

Example 118 (r):
```r
pbmc <- RunUMAP(pbmc, dims = 1:10)
```

Example 119 (unknown):
```unknown
# note that you can set `label = TRUE` or use the LabelClusters function to help label
# individual clusters
DimPlot(pbmc, reduction = "umap")
```

Example 120 (r):
```r
# note that you can set `label = TRUE` or use the LabelClusters function to help label
# individual clusters
DimPlot(pbmc, reduction = "umap")
```

Example 121 (r):
```r
# note that you can set `label = TRUE` or use the LabelClusters function to help label
# individual clusters
DimPlot(pbmc, reduction = "umap")
```

Example 122 (unknown):
```unknown
saveRDS(pbmc, file = "../output/pbmc_tutorial.rds")
```

Example 123 (r):
```r
saveRDS(pbmc, file = "../output/pbmc_tutorial.rds")
```

Example 124 (r):
```r
saveRDS(pbmc, file = "../output/pbmc_tutorial.rds")
```

Example 125 (unknown):
```unknown
FindAllMarkers()
```

Example 126 (unknown):
```unknown
?FindMarkers
```

Example 127 (unknown):
```unknown
logfc.threshold
```

Example 128 (unknown):
```unknown
# find all markers of cluster 2
cluster2.markers <- FindMarkers(pbmc, ident.1 = 2)
head(cluster2.markers, n = 5)
```

Example 129 (r):
```r
# find all markers of cluster 2
cluster2.markers <- FindMarkers(pbmc, ident.1 = 2)
head(cluster2.markers, n = 5)
```

Example 130 (r):
```r
# find all markers of cluster 2
cluster2.markers <- FindMarkers(pbmc, ident.1 = 2)
head(cluster2.markers, n = 5)
```

Example 131 (unknown):
```unknown
##             p_val avg_log2FC pct.1 pct.2    p_val_adj
## IL32 2.593535e-91  1.3221171 0.949 0.466 3.556774e-87
## LTB  7.994465e-87  1.3450377 0.981 0.644 1.096361e-82
## CD3D 3.922451e-70  1.0562099 0.922 0.433 5.379250e-66
## IL7R 1.130870e-66  1.4256944 0.748 0.327 1.550876e-62
## LDHB 4.082189e-65  0.9765875 0.953 0.614 5.598314e-61
```

Example 132 (unknown):
```unknown
##             p_val avg_log2FC pct.1 pct.2    p_val_adj
## IL32 2.593535e-91  1.3221171 0.949 0.466 3.556774e-87
## LTB  7.994465e-87  1.3450377 0.981 0.644 1.096361e-82
## CD3D 3.922451e-70  1.0562099 0.922 0.433 5.379250e-66
## IL7R 1.130870e-66  1.4256944 0.748 0.327 1.550876e-62
## LDHB 4.082189e-65  0.9765875 0.953 0.614 5.598314e-61
```

Example 133 (python):
```python
# find all markers distinguishing cluster 5 from clusters 0 and 3
cluster5.markers <- FindMarkers(pbmc, ident.1 = 5, ident.2 = c(0, 3))
head(cluster5.markers, n = 5)
```

Example 134 (r):
```r
# find all markers distinguishing cluster 5 from clusters 0 and 3
cluster5.markers <- FindMarkers(pbmc, ident.1 = 5, ident.2 = c(0, 3))
head(cluster5.markers, n = 5)
```

Example 135 (r):
```r
# find all markers distinguishing cluster 5 from clusters 0 and 3
cluster5.markers <- FindMarkers(pbmc, ident.1 = 5, ident.2 = c(0, 3))
head(cluster5.markers, n = 5)
```

Example 136 (unknown):
```unknown
##                       p_val avg_log2FC pct.1 pct.2     p_val_adj
## FCGR3A        2.150929e-209   6.832372 0.975 0.039 2.949784e-205
## IFITM3        6.103366e-199   6.181000 0.975 0.048 8.370156e-195
## CFD           8.891428e-198   6.052575 0.938 0.037 1.219370e-193
## CD68          2.374425e-194   5.493138 0.926 0.035 3.256286e-190
## RP11-290F20.3 9.308287e-191   6.335402 0.840 0.016 1.276538e-186
```

Example 137 (unknown):
```unknown
##                       p_val avg_log2FC pct.1 pct.2     p_val_adj
## FCGR3A        2.150929e-209   6.832372 0.975 0.039 2.949784e-205
## IFITM3        6.103366e-199   6.181000 0.975 0.048 8.370156e-195
## CFD           8.891428e-198   6.052575 0.938 0.037 1.219370e-193
## CD68          2.374425e-194   5.493138 0.926 0.035 3.256286e-190
## RP11-290F20.3 9.308287e-191   6.335402 0.840 0.016 1.276538e-186
```

Example 138 (unknown):
```unknown
# find markers for every cluster compared to all remaining cells, report only the positive
# ones
pbmc.markers <- FindAllMarkers(pbmc, only.pos = TRUE)
pbmc.markers %>%
    group_by(cluster) %>%
    dplyr::filter(avg_log2FC > 1)
```

Example 139 (r):
```r
# find markers for every cluster compared to all remaining cells, report only the positive
# ones
pbmc.markers <- FindAllMarkers(pbmc, only.pos = TRUE)
pbmc.markers %>%
    group_by(cluster) %>%
    dplyr::filter(avg_log2FC > 1)
```

Example 140 (r):
```r
# find markers for every cluster compared to all remaining cells, report only the positive
# ones
pbmc.markers <- FindAllMarkers(pbmc, only.pos = TRUE)
pbmc.markers %>%
    group_by(cluster) %>%
    dplyr::filter(avg_log2FC > 1)
```

Example 141 (unknown):
```unknown
## # A tibble: 7,046 × 7
## # Groups:   cluster [9]
##        p_val avg_log2FC pct.1 pct.2 p_val_adj cluster gene     
##        <dbl>      <dbl> <dbl> <dbl>     <dbl> <fct>   <chr>    
##  1 1.74e-109       1.19 0.897 0.593 2.39e-105 0       LDHB     
##  2 1.17e- 83       2.37 0.435 0.108 1.60e- 79 0       CCR7     
##  3 8.94e- 79       1.09 0.838 0.403 1.23e- 74 0       CD3D     
##  4 3.05e- 53       1.02 0.722 0.399 4.19e- 49 0       CD3E     
##  5 3.28e- 49       2.10 0.333 0.103 4.50e- 45 0       LEF1     
##  6 6.66e- 49       1.25 0.623 0.358 9.13e- 45 0       NOSIP    
##  7 9.31e- 44       2.02 0.328 0.11  1.28e- 39 0       PRKCQ-AS1
##  8 4.69e- 43       1.53 0.435 0.184 6.43e- 39 0       PIK3IP1  
##  9 1.47e- 39       2.70 0.195 0.04  2.01e- 35 0       FHIT     
## 10 2.44e- 33       1.94 0.262 0.087 3.34e- 29 0       MAL      
## # ℹ 7,036 more rows
```

Example 142 (unknown):
```unknown
## # A tibble: 7,046 × 7
## # Groups:   cluster [9]
##        p_val avg_log2FC pct.1 pct.2 p_val_adj cluster gene     
##        <dbl>      <dbl> <dbl> <dbl>     <dbl> <fct>   <chr>    
##  1 1.74e-109       1.19 0.897 0.593 2.39e-105 0       LDHB     
##  2 1.17e- 83       2.37 0.435 0.108 1.60e- 79 0       CCR7     
##  3 8.94e- 79       1.09 0.838 0.403 1.23e- 74 0       CD3D     
##  4 3.05e- 53       1.02 0.722 0.399 4.19e- 49 0       CD3E     
##  5 3.28e- 49       2.10 0.333 0.103 4.50e- 45 0       LEF1     
##  6 6.66e- 49       1.25 0.623 0.358 9.13e- 45 0       NOSIP    
##  7 9.31e- 44       2.02 0.328 0.11  1.28e- 39 0       PRKCQ-AS1
##  8 4.69e- 43       1.53 0.435 0.184 6.43e- 39 0       PIK3IP1  
##  9 1.47e- 39       2.70 0.195 0.04  2.01e- 35 0       FHIT     
## 10 2.44e- 33       1.94 0.262 0.087 3.34e- 29 0       MAL      
## # ℹ 7,036 more rows
```

Example 143 (unknown):
```unknown
cluster0.markers <- FindMarkers(pbmc, ident.1 = 0, logfc.threshold = 0.25, test.use = "roc", only.pos = TRUE)
```

Example 144 (r):
```r
cluster0.markers <- FindMarkers(pbmc, ident.1 = 0, logfc.threshold = 0.25, test.use = "roc", only.pos = TRUE)
```

Example 145 (r):
```r
cluster0.markers <- FindMarkers(pbmc, ident.1 = 0, logfc.threshold = 0.25, test.use = "roc", only.pos = TRUE)
```

Example 146 (unknown):
```unknown
FeaturePlot()
```

Example 147 (unknown):
```unknown
RidgePlot()
```

Example 148 (unknown):
```unknown
CellScatter()
```

Example 149 (unknown):
```unknown
VlnPlot(pbmc, features = c("MS4A1", "CD79A"))
```

Example 150 (r):
```r
VlnPlot(pbmc, features = c("MS4A1", "CD79A"))
```

Example 151 (r):
```r
VlnPlot(pbmc, features = c("MS4A1", "CD79A"))
```

Example 152 (unknown):
```unknown
# you can plot raw counts as well
VlnPlot(pbmc, features = c("NKG7", "PF4"), slot = "counts", log = TRUE)
```

Example 153 (r):
```r
# you can plot raw counts as well
VlnPlot(pbmc, features = c("NKG7", "PF4"), slot = "counts", log = TRUE)
```

Example 154 (r):
```r
# you can plot raw counts as well
VlnPlot(pbmc, features = c("NKG7", "PF4"), slot = "counts", log = TRUE)
```

Example 155 (unknown):
```unknown
FeaturePlot(pbmc, features = c("MS4A1", "GNLY", "CD3E", "CD14", "FCER1A", "FCGR3A", "LYZ", "PPBP",
    "CD8A"))
```

Example 156 (r):
```r
FeaturePlot(pbmc, features = c("MS4A1", "GNLY", "CD3E", "CD14", "FCER1A", "FCGR3A", "LYZ", "PPBP",
    "CD8A"))
```

Example 157 (r):
```r
FeaturePlot(pbmc, features = c("MS4A1", "GNLY", "CD3E", "CD14", "FCER1A", "FCGR3A", "LYZ", "PPBP",
    "CD8A"))
```

Example 158 (unknown):
```unknown
DoHeatmap()
```

Example 159 (unknown):
```unknown
pbmc.markers %>%
    group_by(cluster) %>%
    dplyr::filter(avg_log2FC > 1) %>%
    slice_head(n = 10) %>%
    ungroup() -> top10
DoHeatmap(pbmc, features = top10$gene) + NoLegend()
```

Example 160 (r):
```r
pbmc.markers %>%
    group_by(cluster) %>%
    dplyr::filter(avg_log2FC > 1) %>%
    slice_head(n = 10) %>%
    ungroup() -> top10
DoHeatmap(pbmc, features = top10$gene) + NoLegend()
```

Example 161 (r):
```r
pbmc.markers %>%
    group_by(cluster) %>%
    dplyr::filter(avg_log2FC > 1) %>%
    slice_head(n = 10) %>%
    ungroup() -> top10
DoHeatmap(pbmc, features = top10$gene) + NoLegend()
```

Example 162 (unknown):
```unknown
new.cluster.ids <- c("Naive CD4 T", "CD14+ Mono", "Memory CD4 T", "B", "CD8 T", "FCGR3A+ Mono",
    "NK", "DC", "Platelet")
names(new.cluster.ids) <- levels(pbmc)
pbmc <- RenameIdents(pbmc, new.cluster.ids)
DimPlot(pbmc, reduction = "umap", label = TRUE, pt.size = 0.5) + NoLegend()
```

Example 163 (r):
```r
new.cluster.ids <- c("Naive CD4 T", "CD14+ Mono", "Memory CD4 T", "B", "CD8 T", "FCGR3A+ Mono",
    "NK", "DC", "Platelet")
names(new.cluster.ids) <- levels(pbmc)
pbmc <- RenameIdents(pbmc, new.cluster.ids)
DimPlot(pbmc, reduction = "umap", label = TRUE, pt.size = 0.5) + NoLegend()
```

Example 164 (r):
```r
new.cluster.ids <- c("Naive CD4 T", "CD14+ Mono", "Memory CD4 T", "B", "CD8 T", "FCGR3A+ Mono",
    "NK", "DC", "Platelet")
names(new.cluster.ids) <- levels(pbmc)
pbmc <- RenameIdents(pbmc, new.cluster.ids)
DimPlot(pbmc, reduction = "umap", label = TRUE, pt.size = 0.5) + NoLegend()
```

Example 165 (unknown):
```unknown
library(ggplot2)
plot <- DimPlot(pbmc, reduction = "umap", label = TRUE, label.size = 4.5) + xlab("UMAP 1") + ylab("UMAP 2") +
    theme(axis.title = element_text(size = 18), legend.text = element_text(size = 18)) + guides(colour = guide_legend(override.aes = list(size = 10)))
ggsave(filename = "../output/images/pbmc3k_umap.jpg", height = 7, width = 12, plot = plot, quality = 50)
```

Example 166 (r):
```r
library(ggplot2)
plot <- DimPlot(pbmc, reduction = "umap", label = TRUE, label.size = 4.5) + xlab("UMAP 1") + ylab("UMAP 2") +
    theme(axis.title = element_text(size = 18), legend.text = element_text(size = 18)) + guides(colour = guide_legend(override.aes = list(size = 10)))
ggsave(filename = "../output/images/pbmc3k_umap.jpg", height = 7, width = 12, plot = plot, quality = 50)
```

Example 167 (r):
```r
library(ggplot2)
plot <- DimPlot(pbmc, reduction = "umap", label = TRUE, label.size = 4.5) + xlab("UMAP 1") + ylab("UMAP 2") +
    theme(axis.title = element_text(size = 18), legend.text = element_text(size = 18)) + guides(colour = guide_legend(override.aes = list(size = 10)))
ggsave(filename = "../output/images/pbmc3k_umap.jpg", height = 7, width = 12, plot = plot, quality = 50)
```

Example 168 (unknown):
```unknown
saveRDS(pbmc, file = "../output/pbmc3k_final.rds")
```

Example 169 (r):
```r
saveRDS(pbmc, file = "../output/pbmc3k_final.rds")
```

Example 170 (r):
```r
saveRDS(pbmc, file = "../output/pbmc3k_final.rds")
```

Example 171 (unknown):
```unknown
sessionInfo()
```

Example 172 (r):
```r
sessionInfo()
```

Example 173 (r):
```r
sessionInfo()
```

Example 174 (unknown):
```unknown
## R version 4.2.2 Patched (2022-11-10 r83330)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.6 LTS
## 
## Matrix products: default
## BLAS:   /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.9.0
## LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.9.0
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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       
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
## [1] ggplot2_3.4.4      patchwork_1.1.3    Seurat_5.0.0       SeuratObject_5.0.0
## [5] sp_2.1-1           dplyr_1.1.3       
## 
## loaded via a namespace (and not attached):
##   [1] spam_2.10-0            systemfonts_1.0.4      plyr_1.8.9            
##   [4] igraph_1.5.1           lazyeval_0.2.2         splines_4.2.2         
##   [7] RcppHNSW_0.5.0         listenv_0.9.0          scattermore_1.2       
##  [10] digest_0.6.33          htmltools_0.5.6.1      fansi_1.0.5           
##  [13] magrittr_2.0.3         memoise_2.0.1          tensor_1.5            
##  [16] cluster_2.1.4          ROCR_1.0-11            limma_3.54.1          
##  [19] globals_0.16.2         matrixStats_1.0.0      R.utils_2.12.2        
##  [22] pkgdown_2.0.7          spatstat.sparse_3.0-3  colorspace_2.1-0      
##  [25] ggrepel_0.9.4          textshaping_0.3.6      xfun_0.40             
##  [28] jsonlite_1.8.7         progressr_0.14.0       spatstat.data_3.0-3   
##  [31] survival_3.5-7         zoo_1.8-12             glue_1.6.2            
##  [34] polyclip_1.10-6        gtable_0.3.4           leiden_0.4.3          
##  [37] future.apply_1.11.0    abind_1.4-5            scales_1.2.1          
##  [40] spatstat.random_3.2-1  miniUI_0.1.1.1         Rcpp_1.0.11           
##  [43] viridisLite_0.4.2      xtable_1.8-4           reticulate_1.34.0     
##  [46] dotCall64_1.1-0        htmlwidgets_1.6.2      httr_1.4.7            
##  [49] RColorBrewer_1.1-3     ellipsis_0.3.2         ica_1.0-3             
##  [52] pkgconfig_2.0.3        R.methodsS3_1.8.2      farver_2.1.1          
##  [55] sass_0.4.7             uwot_0.1.16            deldir_1.0-9          
##  [58] utf8_1.2.4             tidyselect_1.2.0       labeling_0.4.3        
##  [61] rlang_1.1.1            reshape2_1.4.4         later_1.3.1           
##  [64] munsell_0.5.0          tools_4.2.2            cachem_1.0.8          
##  [67] cli_3.6.1              generics_0.1.3         ggridges_0.5.4        
##  [70] evaluate_0.22          stringr_1.5.0          fastmap_1.1.1         
##  [73] yaml_2.3.7             ragg_1.2.5             goftest_1.2-3         
##  [76] knitr_1.45             fs_1.6.3               fitdistrplus_1.1-11   
##  [79] purrr_1.0.2            RANN_2.6.1             pbapply_1.7-2         
##  [82] future_1.33.0          nlme_3.1-162           mime_0.12             
##  [85] formatR_1.14           ggrastr_1.0.1          R.oo_1.25.0           
##  [88] compiler_4.2.2         beeswarm_0.4.0         plotly_4.10.3         
##  [91] png_0.1-8              spatstat.utils_3.0-4   tibble_3.2.1          
##  [94] bslib_0.5.1            stringi_1.7.12         highr_0.10            
##  [97] desc_1.4.2             RSpectra_0.16-1        lattice_0.21-9        
## [100] Matrix_1.6-1.1         vctrs_0.6.4            pillar_1.9.0          
## [103] lifecycle_1.0.3        spatstat.geom_3.2-7    lmtest_0.9-40         
## [106] jquerylib_0.1.4        RcppAnnoy_0.0.21       data.table_1.14.8     
## [109] cowplot_1.1.1          irlba_2.3.5.1          httpuv_1.6.12         
## [112] R6_2.5.1               promises_1.2.1         KernSmooth_2.23-22    
## [115] gridExtra_2.3          vipor_0.4.5            parallelly_1.36.0     
## [118] codetools_0.2-19       fastDummies_1.7.3      MASS_7.3-58.2         
## [121] rprojroot_2.0.3        withr_2.5.2            presto_1.0.0          
## [124] sctransform_0.4.1      parallel_4.2.2         grid_4.2.2            
## [127] tidyr_1.3.0            rmarkdown_2.25         Rtsne_0.16            
## [130] spatstat.explore_3.2-5 shiny_1.7.5.1          ggbeeswarm_0.7.1
```

Example 175 (unknown):
```unknown
## R version 4.2.2 Patched (2022-11-10 r83330)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.6 LTS
## 
## Matrix products: default
## BLAS:   /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.9.0
## LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.9.0
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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       
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
## [1] ggplot2_3.4.4      patchwork_1.1.3    Seurat_5.0.0       SeuratObject_5.0.0
## [5] sp_2.1-1           dplyr_1.1.3       
## 
## loaded via a namespace (and not attached):
##   [1] spam_2.10-0            systemfonts_1.0.4      plyr_1.8.9            
##   [4] igraph_1.5.1           lazyeval_0.2.2         splines_4.2.2         
##   [7] RcppHNSW_0.5.0         listenv_0.9.0          scattermore_1.2       
##  [10] digest_0.6.33          htmltools_0.5.6.1      fansi_1.0.5           
##  [13] magrittr_2.0.3         memoise_2.0.1          tensor_1.5            
##  [16] cluster_2.1.4          ROCR_1.0-11            limma_3.54.1          
##  [19] globals_0.16.2         matrixStats_1.0.0      R.utils_2.12.2        
##  [22] pkgdown_2.0.7          spatstat.sparse_3.0-3  colorspace_2.1-0      
##  [25] ggrepel_0.9.4          textshaping_0.3.6      xfun_0.40             
##  [28] jsonlite_1.8.7         progressr_0.14.0       spatstat.data_3.0-3   
##  [31] survival_3.5-7         zoo_1.8-12             glue_1.6.2            
##  [34] polyclip_1.10-6        gtable_0.3.4           leiden_0.4.3          
##  [37] future.apply_1.11.0    abind_1.4-5            scales_1.2.1          
##  [40] spatstat.random_3.2-1  miniUI_0.1.1.1         Rcpp_1.0.11           
##  [43] viridisLite_0.4.2      xtable_1.8-4           reticulate_1.34.0     
##  [46] dotCall64_1.1-0        htmlwidgets_1.6.2      httr_1.4.7            
##  [49] RColorBrewer_1.1-3     ellipsis_0.3.2         ica_1.0-3             
##  [52] pkgconfig_2.0.3        R.methodsS3_1.8.2      farver_2.1.1          
##  [55] sass_0.4.7             uwot_0.1.16            deldir_1.0-9          
##  [58] utf8_1.2.4             tidyselect_1.2.0       labeling_0.4.3        
##  [61] rlang_1.1.1            reshape2_1.4.4         later_1.3.1           
##  [64] munsell_0.5.0          tools_4.2.2            cachem_1.0.8          
##  [67] cli_3.6.1              generics_0.1.3         ggridges_0.5.4        
##  [70] evaluate_0.22          stringr_1.5.0          fastmap_1.1.1         
##  [73] yaml_2.3.7             ragg_1.2.5             goftest_1.2-3         
##  [76] knitr_1.45             fs_1.6.3               fitdistrplus_1.1-11   
##  [79] purrr_1.0.2            RANN_2.6.1             pbapply_1.7-2         
##  [82] future_1.33.0          nlme_3.1-162           mime_0.12             
##  [85] formatR_1.14           ggrastr_1.0.1          R.oo_1.25.0           
##  [88] compiler_4.2.2         beeswarm_0.4.0         plotly_4.10.3         
##  [91] png_0.1-8              spatstat.utils_3.0-4   tibble_3.2.1          
##  [94] bslib_0.5.1            stringi_1.7.12         highr_0.10            
##  [97] desc_1.4.2             RSpectra_0.16-1        lattice_0.21-9        
## [100] Matrix_1.6-1.1         vctrs_0.6.4            pillar_1.9.0          
## [103] lifecycle_1.0.3        spatstat.geom_3.2-7    lmtest_0.9-40         
## [106] jquerylib_0.1.4        RcppAnnoy_0.0.21       data.table_1.14.8     
## [109] cowplot_1.1.1          irlba_2.3.5.1          httpuv_1.6.12         
## [112] R6_2.5.1               promises_1.2.1         KernSmooth_2.23-22    
## [115] gridExtra_2.3          vipor_0.4.5            parallelly_1.36.0     
## [118] codetools_0.2-19       fastDummies_1.7.3      MASS_7.3-58.2         
## [121] rprojroot_2.0.3        withr_2.5.2            presto_1.0.0          
## [124] sctransform_0.4.1      parallel_4.2.2         grid_4.2.2            
## [127] tidyr_1.3.0            rmarkdown_2.25         Rtsne_0.16            
## [130] spatstat.explore_3.2-5 shiny_1.7.5.1          ggbeeswarm_0.7.1
```

---

## Using Seurat with multimodal data • Seurat

**URL:** http://127.0.0.1:9173/seurat/archive/v4.3/multimodal_vignette/index.html

**Contents:**
- Using Seurat with multimodal data
    - Compiled: 2023-03-27
- Load in the data
- Setup a Seurat object, add the RNA and protein data
- Cluster cells on the basis of their scRNA-seq profiles
- Visualize multiple modalities side-by-side
- Identify cell surface markers for scRNA-seq clusters
- Additional visualizations of multimodal data
- Loading data from 10X multi-modal experiments
- Additional functionality for multimodal data in Seurat
- Contents

The ability to make simultaneous measurements of multiple data types from the same cell, known as multimodal analysis, represents a new and exciting frontier for single-cell genomics. For example, CITE-seq enables the simultaneous measurements of transcriptomes and cell-surface proteins from the same cell. Other exciting multimodal technologies, such as the 10x multiome kit allow for the paired measurements of cellular transcriptome and chromatin accessibility (i.e scRNA-seq+scATAC-seq). Other modalities that can be measured alongside cellular transcriptomes include genetic perturbations, cellular methylomes, and hashtag oligos from Cell Hashing. We have designed Seurat4 to enable for the seamless storage, analysis, and exploration of diverse multimodal single-cell datasets.In this vignette, we present an introductory workflow for creating a multimodal Seurat object and performing an initial analysis. For example, we demonstrate how to cluster a CITE-seq dataset on the basis of the measured cellular transcriptomes, and subsequently discover cell surface proteins that are enriched in each cluster. We note that Seurat4 also enables more advanced techniques for the analysis of multimodal data, in particular the application of our Weighted Nearest Neighbors (WNN) approach that enables simultaneous clustering of cells based on a weighted combination of both modalities, and you can explore this functionality here.Here, we analyze a dataset of 8,617 cord blood mononuclear cells (CBMCs), where transcriptomic measurements are paired with abundance estimates for 11 surface proteins, whose levels are quantified with DNA-barcoded antibodies. First, we load in two count matrices : one for the RNA measurements, and one for the antibody-derived tags (ADT). You can download the ADT file here and the RNA file here library(Seurat) library(ggplot2) library(patchwork) # Load in the RNA UMI matrix # Note that this dataset also contains ~5% of mouse cells, which we can use as negative # controls for the protein measurements. For this reason, the gene expression matrix has # HUMAN_ or MOUSE_ appended to the beginning of each gene. cbmc.rna <- as.sparse(read.csv(file = "../data/GSE100866_CBMC_8K_13AB_10X-RNA_umi.csv.gz", sep = ",", header = TRUE, row.names = 1)) # To make life a bit easier going forward, we're going to discard all but the top 100 most # highly expressed mouse genes, and remove the 'HUMAN_' from the CITE-seq prefix cbmc.rna <- CollapseSpeciesExpressionMatrix(cbmc.rna) # Load in the ADT UMI matrix cbmc.adt <- as.sparse(read.csv(file = "../data/GSE100866_CBMC_8K_13AB_10X-ADT_umi.csv.gz", sep = ",", header = TRUE, row.names = 1)) # Note that since measurements were made in the same cells, the two matrices have identical # column names all.equal(colnames(cbmc.rna), colnames(cbmc.adt))## [1] TRUE

In this vignette, we present an introductory workflow for creating a multimodal Seurat object and performing an initial analysis. For example, we demonstrate how to cluster a CITE-seq dataset on the basis of the measured cellular transcriptomes, and subsequently discover cell surface proteins that are enriched in each cluster. We note that Seurat4 also enables more advanced techniques for the analysis of multimodal data, in particular the application of our Weighted Nearest Neighbors (WNN) approach that enables simultaneous clustering of cells based on a weighted combination of both modalities, and you can explore this functionality here.Here, we analyze a dataset of 8,617 cord blood mononuclear cells (CBMCs), where transcriptomic measurements are paired with abundance estimates for 11 surface proteins, whose levels are quantified with DNA-barcoded antibodies. First, we load in two count matrices : one for the RNA measurements, and one for the antibody-derived tags (ADT). You can download the ADT file here and the RNA file here library(Seurat) library(ggplot2) library(patchwork) # Load in the RNA UMI matrix # Note that this dataset also contains ~5% of mouse cells, which we can use as negative # controls for the protein measurements. For this reason, the gene expression matrix has # HUMAN_ or MOUSE_ appended to the beginning of each gene. cbmc.rna <- as.sparse(read.csv(file = "../data/GSE100866_CBMC_8K_13AB_10X-RNA_umi.csv.gz", sep = ",", header = TRUE, row.names = 1)) # To make life a bit easier going forward, we're going to discard all but the top 100 most # highly expressed mouse genes, and remove the 'HUMAN_' from the CITE-seq prefix cbmc.rna <- CollapseSpeciesExpressionMatrix(cbmc.rna) # Load in the ADT UMI matrix cbmc.adt <- as.sparse(read.csv(file = "../data/GSE100866_CBMC_8K_13AB_10X-ADT_umi.csv.gz", sep = ",", header = TRUE, row.names = 1)) # Note that since measurements were made in the same cells, the two matrices have identical # column names all.equal(colnames(cbmc.rna), colnames(cbmc.adt))## [1] TRUE

Here, we analyze a dataset of 8,617 cord blood mononuclear cells (CBMCs), where transcriptomic measurements are paired with abundance estimates for 11 surface proteins, whose levels are quantified with DNA-barcoded antibodies. First, we load in two count matrices : one for the RNA measurements, and one for the antibody-derived tags (ADT). You can download the ADT file here and the RNA file here library(Seurat) library(ggplot2) library(patchwork) # Load in the RNA UMI matrix # Note that this dataset also contains ~5% of mouse cells, which we can use as negative # controls for the protein measurements. For this reason, the gene expression matrix has # HUMAN_ or MOUSE_ appended to the beginning of each gene. cbmc.rna <- as.sparse(read.csv(file = "../data/GSE100866_CBMC_8K_13AB_10X-RNA_umi.csv.gz", sep = ",", header = TRUE, row.names = 1)) # To make life a bit easier going forward, we're going to discard all but the top 100 most # highly expressed mouse genes, and remove the 'HUMAN_' from the CITE-seq prefix cbmc.rna <- CollapseSpeciesExpressionMatrix(cbmc.rna) # Load in the ADT UMI matrix cbmc.adt <- as.sparse(read.csv(file = "../data/GSE100866_CBMC_8K_13AB_10X-ADT_umi.csv.gz", sep = ",", header = TRUE, row.names = 1)) # Note that since measurements were made in the same cells, the two matrices have identical # column names all.equal(colnames(cbmc.rna), colnames(cbmc.adt))## [1] TRUE

Now we create a Seurat object, and add the ADT data as a second assay # creates a Seurat object based on the scRNA-seq data cbmc <- CreateSeuratObject(counts = cbmc.rna) # We can see that by default, the cbmc object contains an assay storing RNA measurement Assays(cbmc)## [1] "RNA" # create a new assay to store ADT information adt_assay <- CreateAssayObject(counts = cbmc.adt) # add this assay to the previously created Seurat object cbmc[["ADT"]] <- adt_assay # Validate that the object now contains multiple assays Assays(cbmc)## [1] "RNA" "ADT" # Extract a list of features measured in the ADT assay rownames(cbmc[["ADT"]])## [1] "CD3" "CD4" "CD8" "CD45RA" "CD56" "CD16" "CD10" "CD11c" ## [9] "CD14" "CD19" "CD34" "CCR5" "CCR7" # Note that we can easily switch back and forth between the two assays to specify the default # for visualization and analysis # List the current default assay DefaultAssay(cbmc)## [1] "RNA" # Switch the default to ADT DefaultAssay(cbmc) <- "ADT" DefaultAssay(cbmc)## [1] "ADT"

The steps below represent a quick clustering of the PBMCs based on the scRNA-seq data. For more detail on individual steps or more advanced options, see our PBMC clustering guided tutorial here # Note that all operations below are performed on the RNA assay Set and verify that the # default assay is RNA DefaultAssay(cbmc) <- "RNA" DefaultAssay(cbmc)## [1] "RNA" # perform visualization and clustering steps cbmc <- NormalizeData(cbmc) cbmc <- FindVariableFeatures(cbmc) cbmc <- ScaleData(cbmc) cbmc <- RunPCA(cbmc, verbose = FALSE) cbmc <- FindNeighbors(cbmc, dims = 1:30) cbmc <- FindClusters(cbmc, resolution = 0.8, verbose = FALSE) cbmc <- RunUMAP(cbmc, dims = 1:30) DimPlot(cbmc, label = TRUE)

Now that we have obtained clusters from scRNA-seq profiles, we can visualize the expression of either protein or RNA molecules in our dataset. Importantly, Seurat provides a couple ways to switch between modalities, and specify which modality you are interested in analyzing or visualizing. This is particularly important as, in some cases, the same feature can be present in multiple modalities - for example this dataset contains independent measurements of the B cell marker CD19 (both protein and RNA levels). # Normalize ADT data, DefaultAssay(cbmc) <- "ADT" cbmc <- NormalizeData(cbmc, normalization.method = "CLR", margin = 2) DefaultAssay(cbmc) <- "RNA" # Note that the following command is an alternative but returns the same result cbmc <- NormalizeData(cbmc, normalization.method = "CLR", margin = 2, assay = "ADT") # Now, we will visualize CD14 levels for RNA and protein By setting the default assay, we can # visualize one or the other DefaultAssay(cbmc) <- "ADT" p1 <- FeaturePlot(cbmc, "CD19", cols = c("lightgrey", "darkgreen")) + ggtitle("CD19 protein") DefaultAssay(cbmc) <- "RNA" p2 <- FeaturePlot(cbmc, "CD19") + ggtitle("CD19 RNA") # place plots side-by-side p1 | p2 # Alternately, we can use specific assay keys to specify a specific modality Identify the key # for the RNA and protein assays Key(cbmc[["RNA"]])## [1] "rna_" Key(cbmc[["ADT"]])## [1] "adt_" # Now, we can include the key in the feature name, which overrides the default assay p1 <- FeaturePlot(cbmc, "adt_CD19", cols = c("lightgrey", "darkgreen")) + ggtitle("CD19 protein") p2 <- FeaturePlot(cbmc, "rna_CD19") + ggtitle("CD19 RNA") p1 | p2

# Alternately, we can use specific assay keys to specify a specific modality Identify the key # for the RNA and protein assays Key(cbmc[["RNA"]])## [1] "rna_" Key(cbmc[["ADT"]])## [1] "adt_" # Now, we can include the key in the feature name, which overrides the default assay p1 <- FeaturePlot(cbmc, "adt_CD19", cols = c("lightgrey", "darkgreen")) + ggtitle("CD19 protein") p2 <- FeaturePlot(cbmc, "rna_CD19") + ggtitle("CD19 RNA") p1 | p2

We can leverage our paired CITE-seq measurements to help annotate clusters derived from scRNA-seq, and to identify both protein and RNA markers. # as we know that CD19 is a B cell marker, we can identify cluster 6 as expressing CD19 on the # surface VlnPlot(cbmc, "adt_CD19") # we can also identify alternative protein and RNA markers for this cluster through # differential expression adt_markers <- FindMarkers(cbmc, ident.1 = 6, assay = "ADT") rna_markers <- FindMarkers(cbmc, ident.1 = 6, assay = "RNA") head(adt_markers)## p_val avg_log2FC pct.1 pct.2 p_val_adj ## CD19 2.067533e-215 1.2787751 1 1 2.687793e-214 ## CD45RA 8.106076e-109 0.4117172 1 1 1.053790e-107 ## CD4 1.123162e-107 -0.7255977 1 1 1.460110e-106 ## CD14 7.212876e-106 -0.5060496 1 1 9.376739e-105 ## CD3 1.639633e-87 -0.6565471 1 1 2.131523e-86 ## CD8 1.042859e-17 -0.3001131 1 1 1.355716e-16 head(rna_markers)## p_val avg_log2FC pct.1 pct.2 p_val_adj ## BANK1 0 1.963277 0.456 0.015 0 ## CD19 0 1.563124 0.351 0.004 0 ## CD22 0 1.503809 0.284 0.007 0 ## CD79A 0 4.177162 0.965 0.045 0 ## CD79B 0 3.774579 0.944 0.089 0 ## FCRL1 0 1.188813 0.222 0.002 0

# we can also identify alternative protein and RNA markers for this cluster through # differential expression adt_markers <- FindMarkers(cbmc, ident.1 = 6, assay = "ADT") rna_markers <- FindMarkers(cbmc, ident.1 = 6, assay = "RNA") head(adt_markers)## p_val avg_log2FC pct.1 pct.2 p_val_adj ## CD19 2.067533e-215 1.2787751 1 1 2.687793e-214 ## CD45RA 8.106076e-109 0.4117172 1 1 1.053790e-107 ## CD4 1.123162e-107 -0.7255977 1 1 1.460110e-106 ## CD14 7.212876e-106 -0.5060496 1 1 9.376739e-105 ## CD3 1.639633e-87 -0.6565471 1 1 2.131523e-86 ## CD8 1.042859e-17 -0.3001131 1 1 1.355716e-16 head(rna_markers)## p_val avg_log2FC pct.1 pct.2 p_val_adj ## BANK1 0 1.963277 0.456 0.015 0 ## CD19 0 1.563124 0.351 0.004 0 ## CD22 0 1.503809 0.284 0.007 0 ## CD79A 0 4.177162 0.965 0.045 0 ## CD79B 0 3.774579 0.944 0.089 0 ## FCRL1 0 1.188813 0.222 0.002 0

# view relationship between protein and RNA FeatureScatter(cbmc, feature1 = "adt_CD3", feature2 = "rna_CD3E") FeatureScatter(cbmc, feature1 = "adt_CD4", feature2 = "adt_CD8") # Let's look at the raw (non-normalized) ADT counts. You can see the values are quite high, # particularly in comparison to RNA values. This is due to the significantly higher protein # copy number in cells, which significantly reduces 'drop-out' in ADT data FeatureScatter(cbmc, feature1 = "adt_CD4", feature2 = "adt_CD8", slot = "counts")

FeatureScatter(cbmc, feature1 = "adt_CD4", feature2 = "adt_CD8") # Let's look at the raw (non-normalized) ADT counts. You can see the values are quite high, # particularly in comparison to RNA values. This is due to the significantly higher protein # copy number in cells, which significantly reduces 'drop-out' in ADT data FeatureScatter(cbmc, feature1 = "adt_CD4", feature2 = "adt_CD8", slot = "counts")

# Let's look at the raw (non-normalized) ADT counts. You can see the values are quite high, # particularly in comparison to RNA values. This is due to the significantly higher protein # copy number in cells, which significantly reduces 'drop-out' in ADT data FeatureScatter(cbmc, feature1 = "adt_CD4", feature2 = "adt_CD8", slot = "counts")

Seurat is also able to analyze data from multimodal 10X experiments processed using CellRanger v3; as an example, we recreate the plots above using a dataset of 7,900 peripheral blood mononuclear cells (PBMC), freely available from 10X Genomics here. pbmc10k.data <- Read10X(data.dir = "../data/pbmc10k/filtered_feature_bc_matrix/") rownames(x = pbmc10k.data[["Antibody Capture"]]) <- gsub(pattern = "_[control_]*TotalSeqB", replacement = "", x = rownames(x = pbmc10k.data[["Antibody Capture"]])) pbmc10k <- CreateSeuratObject(counts = pbmc10k.data[["Gene Expression"]], min.cells = 3, min.features = 200) pbmc10k <- NormalizeData(pbmc10k) pbmc10k[["ADT"]] <- CreateAssayObject(pbmc10k.data[["Antibody Capture"]][, colnames(x = pbmc10k)]) pbmc10k <- NormalizeData(pbmc10k, assay = "ADT", normalization.method = "CLR") plot1 <- FeatureScatter(pbmc10k, feature1 = "adt_CD19", feature2 = "adt_CD3", pt.size = 1) plot2 <- FeatureScatter(pbmc10k, feature1 = "adt_CD4", feature2 = "adt_CD8a", pt.size = 1) plot3 <- FeatureScatter(pbmc10k, feature1 = "adt_CD3", feature2 = "CD3E", pt.size = 1) (plot1 + plot2 + plot3) & NoLegend()

Seurat v4 also includes additional functionality for the analysis, visualization, and integration of multimodal datasets. For more information, please explore the resources below:Defining cellular identity from multimodal data using WNN analysis in Seurat v4 vignetteMapping scRNA-seq data onto CITE-seq references [vignette]Introduction to the analysis of spatial transcriptomics analysis [vignette]Analysis of 10x multiome (paired scRNA-seq + ATAC) using WNN analysis [vignette]Signac: Analysis, interpretation, and exploration of single-cell chromatin datasets [package]Mixscape: an analytical toolkit for pooled single-cell genetic screens [vignette]Session Info sessionInfo()## R version 4.2.0 (2022-04-22) ## Platform: x86_64-pc-linux-gnu (64-bit) ## Running under: Ubuntu 20.04.5 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/liblapack.so.3 ## ## locale: ## [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C ## [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8 ## [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 ## ## attached base packages: ## [1] stats graphics grDevices utils datasets methods base ## ## other attached packages: ## [1] patchwork_1.1.2 ggplot2_3.4.1 SeuratObject_4.1.3 Seurat_4.3.0 ## ## loaded via a namespace (and not attached): ## [1] Rtsne_0.16 colorspace_2.1-0 deldir_1.0-6 ## [4] ellipsis_0.3.2 ggridges_0.5.4 rprojroot_2.0.3 ## [7] fs_1.6.1 spatstat.data_3.0-0 farver_2.1.1 ## [10] leiden_0.4.3 listenv_0.9.0 ggrepel_0.9.3 ## [13] fansi_1.0.4 R.methodsS3_1.8.2 codetools_0.2-18 ## [16] splines_4.2.0 cachem_1.0.7 knitr_1.42 ## [19] polyclip_1.10-4 jsonlite_1.8.4 ica_1.0-3 ## [22] cluster_2.1.3 R.oo_1.25.0 png_0.1-8 ## [25] uwot_0.1.14 spatstat.sparse_3.0-0 shiny_1.7.4 ## [28] sctransform_0.3.5 compiler_4.2.0 httr_1.4.5 ## [31] Matrix_1.5-3 fastmap_1.1.1 lazyeval_0.2.2 ## [34] limma_3.54.1 cli_3.6.0 later_1.3.0 ## [37] formatR_1.14 htmltools_0.5.4 tools_4.2.0 ## [40] igraph_1.4.1 gtable_0.3.1 glue_1.6.2 ## [43] RANN_2.6.1 reshape2_1.4.4 dplyr_1.1.0 ## [46] Rcpp_1.0.10 scattermore_0.8 jquerylib_0.1.4 ## [49] pkgdown_2.0.7 vctrs_0.5.2 nlme_3.1-157 ## [52] spatstat.explore_3.0-6 progressr_0.13.0 lmtest_0.9-40 ## [55] spatstat.random_3.1-3 xfun_0.37 stringr_1.5.0 ## [58] globals_0.16.2 mime_0.12 miniUI_0.1.1.1 ## [61] lifecycle_1.0.3 irlba_2.3.5.1 goftest_1.2-3 ## [64] future_1.31.0 MASS_7.3-56 zoo_1.8-11 ## [67] scales_1.2.1 ragg_1.2.5 promises_1.2.0.1 ## [70] spatstat.utils_3.0-1 parallel_4.2.0 RColorBrewer_1.1-3 ## [73] yaml_2.3.7 memoise_2.0.1 reticulate_1.28 ## [76] pbapply_1.7-0 gridExtra_2.3 sass_0.4.5 ## [79] stringi_1.7.12 highr_0.10 desc_1.4.2 ## [82] rlang_1.0.6 pkgconfig_2.0.3 systemfonts_1.0.4 ## [85] matrixStats_0.63.0 evaluate_0.20 lattice_0.20-45 ## [88] tensor_1.5 ROCR_1.0-11 purrr_1.0.1 ## [91] labeling_0.4.2 htmlwidgets_1.6.1 cowplot_1.1.1 ## [94] tidyselect_1.2.0 parallelly_1.34.0 RcppAnnoy_0.0.20 ## [97] plyr_1.8.8 magrittr_2.0.3 R6_2.5.1 ## [100] generics_0.1.3 withr_2.5.0 pillar_1.8.1 ## [103] fitdistrplus_1.1-8 abind_1.4-5 survival_3.3-1 ## [106] sp_1.6-0 tibble_3.1.8 future.apply_1.10.0 ## [109] KernSmooth_2.23-20 utf8_1.2.3 spatstat.geom_3.0-6 ## [112] plotly_4.10.1 rmarkdown_2.20 grid_4.2.0 ## [115] data.table_1.14.8 digest_0.6.31 xtable_1.8-4 ## [118] tidyr_1.3.0 httpuv_1.6.9 R.utils_2.12.2 ## [121] textshaping_0.3.6 munsell_0.5.0 viridisLite_0.4.1 ## [124] bslib_0.4.2

sessionInfo()## R version 4.2.0 (2022-04-22) ## Platform: x86_64-pc-linux-gnu (64-bit) ## Running under: Ubuntu 20.04.5 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/liblapack.so.3 ## ## locale: ## [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C ## [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8 ## [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 ## ## attached base packages: ## [1] stats graphics grDevices utils datasets methods base ## ## other attached packages: ## [1] patchwork_1.1.2 ggplot2_3.4.1 SeuratObject_4.1.3 Seurat_4.3.0 ## ## loaded via a namespace (and not attached): ## [1] Rtsne_0.16 colorspace_2.1-0 deldir_1.0-6 ## [4] ellipsis_0.3.2 ggridges_0.5.4 rprojroot_2.0.3 ## [7] fs_1.6.1 spatstat.data_3.0-0 farver_2.1.1 ## [10] leiden_0.4.3 listenv_0.9.0 ggrepel_0.9.3 ## [13] fansi_1.0.4 R.methodsS3_1.8.2 codetools_0.2-18 ## [16] splines_4.2.0 cachem_1.0.7 knitr_1.42 ## [19] polyclip_1.10-4 jsonlite_1.8.4 ica_1.0-3 ## [22] cluster_2.1.3 R.oo_1.25.0 png_0.1-8 ## [25] uwot_0.1.14 spatstat.sparse_3.0-0 shiny_1.7.4 ## [28] sctransform_0.3.5 compiler_4.2.0 httr_1.4.5 ## [31] Matrix_1.5-3 fastmap_1.1.1 lazyeval_0.2.2 ## [34] limma_3.54.1 cli_3.6.0 later_1.3.0 ## [37] formatR_1.14 htmltools_0.5.4 tools_4.2.0 ## [40] igraph_1.4.1 gtable_0.3.1 glue_1.6.2 ## [43] RANN_2.6.1 reshape2_1.4.4 dplyr_1.1.0 ## [46] Rcpp_1.0.10 scattermore_0.8 jquerylib_0.1.4 ## [49] pkgdown_2.0.7 vctrs_0.5.2 nlme_3.1-157 ## [52] spatstat.explore_3.0-6 progressr_0.13.0 lmtest_0.9-40 ## [55] spatstat.random_3.1-3 xfun_0.37 stringr_1.5.0 ## [58] globals_0.16.2 mime_0.12 miniUI_0.1.1.1 ## [61] lifecycle_1.0.3 irlba_2.3.5.1 goftest_1.2-3 ## [64] future_1.31.0 MASS_7.3-56 zoo_1.8-11 ## [67] scales_1.2.1 ragg_1.2.5 promises_1.2.0.1 ## [70] spatstat.utils_3.0-1 parallel_4.2.0 RColorBrewer_1.1-3 ## [73] yaml_2.3.7 memoise_2.0.1 reticulate_1.28 ## [76] pbapply_1.7-0 gridExtra_2.3 sass_0.4.5 ## [79] stringi_1.7.12 highr_0.10 desc_1.4.2 ## [82] rlang_1.0.6 pkgconfig_2.0.3 systemfonts_1.0.4 ## [85] matrixStats_0.63.0 evaluate_0.20 lattice_0.20-45 ## [88] tensor_1.5 ROCR_1.0-11 purrr_1.0.1 ## [91] labeling_0.4.2 htmlwidgets_1.6.1 cowplot_1.1.1 ## [94] tidyselect_1.2.0 parallelly_1.34.0 RcppAnnoy_0.0.20 ## [97] plyr_1.8.8 magrittr_2.0.3 R6_2.5.1 ## [100] generics_0.1.3 withr_2.5.0 pillar_1.8.1 ## [103] fitdistrplus_1.1-8 abind_1.4-5 survival_3.3-1 ## [106] sp_1.6-0 tibble_3.1.8 future.apply_1.10.0 ## [109] KernSmooth_2.23-20 utf8_1.2.3 spatstat.geom_3.0-6 ## [112] plotly_4.10.1 rmarkdown_2.20 grid_4.2.0 ## [115] data.table_1.14.8 digest_0.6.31 xtable_1.8-4 ## [118] tidyr_1.3.0 httpuv_1.6.9 R.utils_2.12.2 ## [121] textshaping_0.3.6 munsell_0.5.0 viridisLite_0.4.1 ## [124] bslib_0.4.2

Developed by Paul Hoffman, Satija Lab and Collaborators.

Developed by Paul Hoffman, Satija Lab and Collaborators.

Site built with pkgdown 2.0.7.

Site built with pkgdown 2.0.7.

**Examples:**

Example 1 (unknown):
```unknown
vignettes/multimodal_vignette.Rmd
```

Example 2 (unknown):
```unknown
multimodal_vignette.Rmd
```

Example 3 (unknown):
```unknown
library(Seurat)
library(ggplot2)
library(patchwork)
```

Example 4 (r):
```r
library(Seurat)
library(ggplot2)
library(patchwork)
```

Example 5 (r):
```r
library(Seurat)
library(ggplot2)
library(patchwork)
```

Example 6 (python):
```python
# Load in the RNA UMI matrix

# Note that this dataset also contains ~5% of mouse cells, which we can use as negative
# controls for the protein measurements. For this reason, the gene expression matrix has
# HUMAN_ or MOUSE_ appended to the beginning of each gene.
cbmc.rna <- as.sparse(read.csv(file = "../data/GSE100866_CBMC_8K_13AB_10X-RNA_umi.csv.gz", sep = ",",
    header = TRUE, row.names = 1))

# To make life a bit easier going forward, we're going to discard all but the top 100 most
# highly expressed mouse genes, and remove the 'HUMAN_' from the CITE-seq prefix
cbmc.rna <- CollapseSpeciesExpressionMatrix(cbmc.rna)

# Load in the ADT UMI matrix
cbmc.adt <- as.sparse(read.csv(file = "../data/GSE100866_CBMC_8K_13AB_10X-ADT_umi.csv.gz", sep = ",",
    header = TRUE, row.names = 1))

# Note that since measurements were made in the same cells, the two matrices have identical
# column names
all.equal(colnames(cbmc.rna), colnames(cbmc.adt))
```

Example 7 (r):
```r
# Load in the RNA UMI matrix

# Note that this dataset also contains ~5% of mouse cells, which we can use as negative
# controls for the protein measurements. For this reason, the gene expression matrix has
# HUMAN_ or MOUSE_ appended to the beginning of each gene.
cbmc.rna <- as.sparse(read.csv(file = "../data/GSE100866_CBMC_8K_13AB_10X-RNA_umi.csv.gz", sep = ",",
    header = TRUE, row.names = 1))

# To make life a bit easier going forward, we're going to discard all but the top 100 most
# highly expressed mouse genes, and remove the 'HUMAN_' from the CITE-seq prefix
cbmc.rna <- CollapseSpeciesExpressionMatrix(cbmc.rna)

# Load in the ADT UMI matrix
cbmc.adt <- as.sparse(read.csv(file = "../data/GSE100866_CBMC_8K_13AB_10X-ADT_umi.csv.gz", sep = ",",
    header = TRUE, row.names = 1))

# Note that since measurements were made in the same cells, the two matrices have identical
# column names
all.equal(colnames(cbmc.rna), colnames(cbmc.adt))
```

Example 8 (r):
```r
# Load in the RNA UMI matrix

# Note that this dataset also contains ~5% of mouse cells, which we can use as negative
# controls for the protein measurements. For this reason, the gene expression matrix has
# HUMAN_ or MOUSE_ appended to the beginning of each gene.
cbmc.rna <- as.sparse(read.csv(file = "../data/GSE100866_CBMC_8K_13AB_10X-RNA_umi.csv.gz", sep = ",",
    header = TRUE, row.names = 1))

# To make life a bit easier going forward, we're going to discard all but the top 100 most
# highly expressed mouse genes, and remove the 'HUMAN_' from the CITE-seq prefix
cbmc.rna <- CollapseSpeciesExpressionMatrix(cbmc.rna)

# Load in the ADT UMI matrix
cbmc.adt <- as.sparse(read.csv(file = "../data/GSE100866_CBMC_8K_13AB_10X-ADT_umi.csv.gz", sep = ",",
    header = TRUE, row.names = 1))

# Note that since measurements were made in the same cells, the two matrices have identical
# column names
all.equal(colnames(cbmc.rna), colnames(cbmc.adt))
```

Example 9 (unknown):
```unknown
## [1] TRUE
```

Example 10 (unknown):
```unknown
## [1] TRUE
```

Example 11 (unknown):
```unknown
# creates a Seurat object based on the scRNA-seq data
cbmc <- CreateSeuratObject(counts = cbmc.rna)

# We can see that by default, the cbmc object contains an assay storing RNA measurement
Assays(cbmc)
```

Example 12 (r):
```r
# creates a Seurat object based on the scRNA-seq data
cbmc <- CreateSeuratObject(counts = cbmc.rna)

# We can see that by default, the cbmc object contains an assay storing RNA measurement
Assays(cbmc)
```

Example 13 (r):
```r
# creates a Seurat object based on the scRNA-seq data
cbmc <- CreateSeuratObject(counts = cbmc.rna)

# We can see that by default, the cbmc object contains an assay storing RNA measurement
Assays(cbmc)
```

Example 14 (unknown):
```unknown
## [1] "RNA"
```

Example 15 (unknown):
```unknown
## [1] "RNA"
```

Example 16 (unknown):
```unknown
# create a new assay to store ADT information
adt_assay <- CreateAssayObject(counts = cbmc.adt)

# add this assay to the previously created Seurat object
cbmc[["ADT"]] <- adt_assay

# Validate that the object now contains multiple assays
Assays(cbmc)
```

Example 17 (r):
```r
# create a new assay to store ADT information
adt_assay <- CreateAssayObject(counts = cbmc.adt)

# add this assay to the previously created Seurat object
cbmc[["ADT"]] <- adt_assay

# Validate that the object now contains multiple assays
Assays(cbmc)
```

Example 18 (r):
```r
# create a new assay to store ADT information
adt_assay <- CreateAssayObject(counts = cbmc.adt)

# add this assay to the previously created Seurat object
cbmc[["ADT"]] <- adt_assay

# Validate that the object now contains multiple assays
Assays(cbmc)
```

Example 19 (unknown):
```unknown
## [1] "RNA" "ADT"
```

Example 20 (unknown):
```unknown
## [1] "RNA" "ADT"
```

Example 21 (unknown):
```unknown
# Extract a list of features measured in the ADT assay
rownames(cbmc[["ADT"]])
```

Example 22 (r):
```r
# Extract a list of features measured in the ADT assay
rownames(cbmc[["ADT"]])
```

Example 23 (r):
```r
# Extract a list of features measured in the ADT assay
rownames(cbmc[["ADT"]])
```

Example 24 (unknown):
```unknown
##  [1] "CD3"    "CD4"    "CD8"    "CD45RA" "CD56"   "CD16"   "CD10"   "CD11c" 
##  [9] "CD14"   "CD19"   "CD34"   "CCR5"   "CCR7"
```

Example 25 (unknown):
```unknown
##  [1] "CD3"    "CD4"    "CD8"    "CD45RA" "CD56"   "CD16"   "CD10"   "CD11c" 
##  [9] "CD14"   "CD19"   "CD34"   "CCR5"   "CCR7"
```

Example 26 (unknown):
```unknown
# Note that we can easily switch back and forth between the two assays to specify the default
# for visualization and analysis

# List the current default assay
DefaultAssay(cbmc)
```

Example 27 (r):
```r
# Note that we can easily switch back and forth between the two assays to specify the default
# for visualization and analysis

# List the current default assay
DefaultAssay(cbmc)
```

Example 28 (r):
```r
# Note that we can easily switch back and forth between the two assays to specify the default
# for visualization and analysis

# List the current default assay
DefaultAssay(cbmc)
```

Example 29 (unknown):
```unknown
## [1] "RNA"
```

Example 30 (unknown):
```unknown
## [1] "RNA"
```

Example 31 (unknown):
```unknown
# Switch the default to ADT
DefaultAssay(cbmc) <- "ADT"
DefaultAssay(cbmc)
```

Example 32 (r):
```r
# Switch the default to ADT
DefaultAssay(cbmc) <- "ADT"
DefaultAssay(cbmc)
```

Example 33 (r):
```r
# Switch the default to ADT
DefaultAssay(cbmc) <- "ADT"
DefaultAssay(cbmc)
```

Example 34 (unknown):
```unknown
## [1] "ADT"
```

Example 35 (unknown):
```unknown
## [1] "ADT"
```

Example 36 (unknown):
```unknown
# Note that all operations below are performed on the RNA assay Set and verify that the
# default assay is RNA
DefaultAssay(cbmc) <- "RNA"
DefaultAssay(cbmc)
```

Example 37 (r):
```r
# Note that all operations below are performed on the RNA assay Set and verify that the
# default assay is RNA
DefaultAssay(cbmc) <- "RNA"
DefaultAssay(cbmc)
```

Example 38 (r):
```r
# Note that all operations below are performed on the RNA assay Set and verify that the
# default assay is RNA
DefaultAssay(cbmc) <- "RNA"
DefaultAssay(cbmc)
```

Example 39 (unknown):
```unknown
## [1] "RNA"
```

Example 40 (unknown):
```unknown
## [1] "RNA"
```

Example 41 (unknown):
```unknown
# perform visualization and clustering steps
cbmc <- NormalizeData(cbmc)
cbmc <- FindVariableFeatures(cbmc)
cbmc <- ScaleData(cbmc)
cbmc <- RunPCA(cbmc, verbose = FALSE)
cbmc <- FindNeighbors(cbmc, dims = 1:30)
cbmc <- FindClusters(cbmc, resolution = 0.8, verbose = FALSE)
cbmc <- RunUMAP(cbmc, dims = 1:30)
DimPlot(cbmc, label = TRUE)
```

Example 42 (r):
```r
# perform visualization and clustering steps
cbmc <- NormalizeData(cbmc)
cbmc <- FindVariableFeatures(cbmc)
cbmc <- ScaleData(cbmc)
cbmc <- RunPCA(cbmc, verbose = FALSE)
cbmc <- FindNeighbors(cbmc, dims = 1:30)
cbmc <- FindClusters(cbmc, resolution = 0.8, verbose = FALSE)
cbmc <- RunUMAP(cbmc, dims = 1:30)
DimPlot(cbmc, label = TRUE)
```

Example 43 (r):
```r
# perform visualization and clustering steps
cbmc <- NormalizeData(cbmc)
cbmc <- FindVariableFeatures(cbmc)
cbmc <- ScaleData(cbmc)
cbmc <- RunPCA(cbmc, verbose = FALSE)
cbmc <- FindNeighbors(cbmc, dims = 1:30)
cbmc <- FindClusters(cbmc, resolution = 0.8, verbose = FALSE)
cbmc <- RunUMAP(cbmc, dims = 1:30)
DimPlot(cbmc, label = TRUE)
```

Example 44 (unknown):
```unknown
# Normalize ADT data,
DefaultAssay(cbmc) <- "ADT"
cbmc <- NormalizeData(cbmc, normalization.method = "CLR", margin = 2)
DefaultAssay(cbmc) <- "RNA"

# Note that the following command is an alternative but returns the same result
cbmc <- NormalizeData(cbmc, normalization.method = "CLR", margin = 2, assay = "ADT")

# Now, we will visualize CD14 levels for RNA and protein By setting the default assay, we can
# visualize one or the other
DefaultAssay(cbmc) <- "ADT"
p1 <- FeaturePlot(cbmc, "CD19", cols = c("lightgrey", "darkgreen")) + ggtitle("CD19 protein")
DefaultAssay(cbmc) <- "RNA"
p2 <- FeaturePlot(cbmc, "CD19") + ggtitle("CD19 RNA")

# place plots side-by-side
p1 | p2
```

Example 45 (r):
```r
# Normalize ADT data,
DefaultAssay(cbmc) <- "ADT"
cbmc <- NormalizeData(cbmc, normalization.method = "CLR", margin = 2)
DefaultAssay(cbmc) <- "RNA"

# Note that the following command is an alternative but returns the same result
cbmc <- NormalizeData(cbmc, normalization.method = "CLR", margin = 2, assay = "ADT")

# Now, we will visualize CD14 levels for RNA and protein By setting the default assay, we can
# visualize one or the other
DefaultAssay(cbmc) <- "ADT"
p1 <- FeaturePlot(cbmc, "CD19", cols = c("lightgrey", "darkgreen")) + ggtitle("CD19 protein")
DefaultAssay(cbmc) <- "RNA"
p2 <- FeaturePlot(cbmc, "CD19") + ggtitle("CD19 RNA")

# place plots side-by-side
p1 | p2
```

Example 46 (r):
```r
# Normalize ADT data,
DefaultAssay(cbmc) <- "ADT"
cbmc <- NormalizeData(cbmc, normalization.method = "CLR", margin = 2)
DefaultAssay(cbmc) <- "RNA"

# Note that the following command is an alternative but returns the same result
cbmc <- NormalizeData(cbmc, normalization.method = "CLR", margin = 2, assay = "ADT")

# Now, we will visualize CD14 levels for RNA and protein By setting the default assay, we can
# visualize one or the other
DefaultAssay(cbmc) <- "ADT"
p1 <- FeaturePlot(cbmc, "CD19", cols = c("lightgrey", "darkgreen")) + ggtitle("CD19 protein")
DefaultAssay(cbmc) <- "RNA"
p2 <- FeaturePlot(cbmc, "CD19") + ggtitle("CD19 RNA")

# place plots side-by-side
p1 | p2
```

Example 47 (unknown):
```unknown
# Alternately, we can use specific assay keys to specify a specific modality Identify the key
# for the RNA and protein assays
Key(cbmc[["RNA"]])
```

Example 48 (r):
```r
# Alternately, we can use specific assay keys to specify a specific modality Identify the key
# for the RNA and protein assays
Key(cbmc[["RNA"]])
```

Example 49 (r):
```r
# Alternately, we can use specific assay keys to specify a specific modality Identify the key
# for the RNA and protein assays
Key(cbmc[["RNA"]])
```

Example 50 (unknown):
```unknown
## [1] "rna_"
```

Example 51 (unknown):
```unknown
## [1] "rna_"
```

Example 52 (unknown):
```unknown
Key(cbmc[["ADT"]])
```

Example 53 (r):
```r
Key(cbmc[["ADT"]])
```

Example 54 (r):
```r
Key(cbmc[["ADT"]])
```

Example 55 (unknown):
```unknown
## [1] "adt_"
```

Example 56 (unknown):
```unknown
## [1] "adt_"
```

Example 57 (unknown):
```unknown
# Now, we can include the key in the feature name, which overrides the default assay
p1 <- FeaturePlot(cbmc, "adt_CD19", cols = c("lightgrey", "darkgreen")) + ggtitle("CD19 protein")
p2 <- FeaturePlot(cbmc, "rna_CD19") + ggtitle("CD19 RNA")
p1 | p2
```

Example 58 (r):
```r
# Now, we can include the key in the feature name, which overrides the default assay
p1 <- FeaturePlot(cbmc, "adt_CD19", cols = c("lightgrey", "darkgreen")) + ggtitle("CD19 protein")
p2 <- FeaturePlot(cbmc, "rna_CD19") + ggtitle("CD19 RNA")
p1 | p2
```

Example 59 (r):
```r
# Now, we can include the key in the feature name, which overrides the default assay
p1 <- FeaturePlot(cbmc, "adt_CD19", cols = c("lightgrey", "darkgreen")) + ggtitle("CD19 protein")
p2 <- FeaturePlot(cbmc, "rna_CD19") + ggtitle("CD19 RNA")
p1 | p2
```

Example 60 (unknown):
```unknown
# as we know that CD19 is a B cell marker, we can identify cluster 6 as expressing CD19 on the
# surface
VlnPlot(cbmc, "adt_CD19")
```

Example 61 (r):
```r
# as we know that CD19 is a B cell marker, we can identify cluster 6 as expressing CD19 on the
# surface
VlnPlot(cbmc, "adt_CD19")
```

Example 62 (r):
```r
# as we know that CD19 is a B cell marker, we can identify cluster 6 as expressing CD19 on the
# surface
VlnPlot(cbmc, "adt_CD19")
```

Example 63 (unknown):
```unknown
# we can also identify alternative protein and RNA markers for this cluster through
# differential expression
adt_markers <- FindMarkers(cbmc, ident.1 = 6, assay = "ADT")
rna_markers <- FindMarkers(cbmc, ident.1 = 6, assay = "RNA")

head(adt_markers)
```

Example 64 (r):
```r
# we can also identify alternative protein and RNA markers for this cluster through
# differential expression
adt_markers <- FindMarkers(cbmc, ident.1 = 6, assay = "ADT")
rna_markers <- FindMarkers(cbmc, ident.1 = 6, assay = "RNA")

head(adt_markers)
```

Example 65 (r):
```r
# we can also identify alternative protein and RNA markers for this cluster through
# differential expression
adt_markers <- FindMarkers(cbmc, ident.1 = 6, assay = "ADT")
rna_markers <- FindMarkers(cbmc, ident.1 = 6, assay = "RNA")

head(adt_markers)
```

Example 66 (unknown):
```unknown
##                p_val avg_log2FC pct.1 pct.2     p_val_adj
## CD19   2.067533e-215  1.2787751     1     1 2.687793e-214
## CD45RA 8.106076e-109  0.4117172     1     1 1.053790e-107
## CD4    1.123162e-107 -0.7255977     1     1 1.460110e-106
## CD14   7.212876e-106 -0.5060496     1     1 9.376739e-105
## CD3     1.639633e-87 -0.6565471     1     1  2.131523e-86
## CD8     1.042859e-17 -0.3001131     1     1  1.355716e-16
```

Example 67 (unknown):
```unknown
##                p_val avg_log2FC pct.1 pct.2     p_val_adj
## CD19   2.067533e-215  1.2787751     1     1 2.687793e-214
## CD45RA 8.106076e-109  0.4117172     1     1 1.053790e-107
## CD4    1.123162e-107 -0.7255977     1     1 1.460110e-106
## CD14   7.212876e-106 -0.5060496     1     1 9.376739e-105
## CD3     1.639633e-87 -0.6565471     1     1  2.131523e-86
## CD8     1.042859e-17 -0.3001131     1     1  1.355716e-16
```

Example 68 (unknown):
```unknown
head(rna_markers)
```

Example 69 (r):
```r
head(rna_markers)
```

Example 70 (r):
```r
head(rna_markers)
```

Example 71 (unknown):
```unknown
##       p_val avg_log2FC pct.1 pct.2 p_val_adj
## BANK1     0   1.963277 0.456 0.015         0
## CD19      0   1.563124 0.351 0.004         0
## CD22      0   1.503809 0.284 0.007         0
## CD79A     0   4.177162 0.965 0.045         0
## CD79B     0   3.774579 0.944 0.089         0
## FCRL1     0   1.188813 0.222 0.002         0
```

Example 72 (unknown):
```unknown
##       p_val avg_log2FC pct.1 pct.2 p_val_adj
## BANK1     0   1.963277 0.456 0.015         0
## CD19      0   1.563124 0.351 0.004         0
## CD22      0   1.503809 0.284 0.007         0
## CD79A     0   4.177162 0.965 0.045         0
## CD79B     0   3.774579 0.944 0.089         0
## FCRL1     0   1.188813 0.222 0.002         0
```

Example 73 (unknown):
```unknown
# Draw ADT scatter plots (like biaxial plots for FACS). Note that you can even 'gate' cells if
# desired by using HoverLocator and FeatureLocator
FeatureScatter(cbmc, feature1 = "adt_CD19", feature2 = "adt_CD3")
```

Example 74 (r):
```r
# Draw ADT scatter plots (like biaxial plots for FACS). Note that you can even 'gate' cells if
# desired by using HoverLocator and FeatureLocator
FeatureScatter(cbmc, feature1 = "adt_CD19", feature2 = "adt_CD3")
```

Example 75 (r):
```r
# Draw ADT scatter plots (like biaxial plots for FACS). Note that you can even 'gate' cells if
# desired by using HoverLocator and FeatureLocator
FeatureScatter(cbmc, feature1 = "adt_CD19", feature2 = "adt_CD3")
```

Example 76 (unknown):
```unknown
# view relationship between protein and RNA
FeatureScatter(cbmc, feature1 = "adt_CD3", feature2 = "rna_CD3E")
```

Example 77 (r):
```r
# view relationship between protein and RNA
FeatureScatter(cbmc, feature1 = "adt_CD3", feature2 = "rna_CD3E")
```

Example 78 (r):
```r
# view relationship between protein and RNA
FeatureScatter(cbmc, feature1 = "adt_CD3", feature2 = "rna_CD3E")
```

Example 79 (unknown):
```unknown
FeatureScatter(cbmc, feature1 = "adt_CD4", feature2 = "adt_CD8")
```

Example 80 (r):
```r
FeatureScatter(cbmc, feature1 = "adt_CD4", feature2 = "adt_CD8")
```

Example 81 (r):
```r
FeatureScatter(cbmc, feature1 = "adt_CD4", feature2 = "adt_CD8")
```

Example 82 (unknown):
```unknown
# Let's look at the raw (non-normalized) ADT counts. You can see the values are quite high,
# particularly in comparison to RNA values. This is due to the significantly higher protein
# copy number in cells, which significantly reduces 'drop-out' in ADT data
FeatureScatter(cbmc, feature1 = "adt_CD4", feature2 = "adt_CD8", slot = "counts")
```

Example 83 (r):
```r
# Let's look at the raw (non-normalized) ADT counts. You can see the values are quite high,
# particularly in comparison to RNA values. This is due to the significantly higher protein
# copy number in cells, which significantly reduces 'drop-out' in ADT data
FeatureScatter(cbmc, feature1 = "adt_CD4", feature2 = "adt_CD8", slot = "counts")
```

Example 84 (r):
```r
# Let's look at the raw (non-normalized) ADT counts. You can see the values are quite high,
# particularly in comparison to RNA values. This is due to the significantly higher protein
# copy number in cells, which significantly reduces 'drop-out' in ADT data
FeatureScatter(cbmc, feature1 = "adt_CD4", feature2 = "adt_CD8", slot = "counts")
```

Example 85 (unknown):
```unknown
pbmc10k.data <- Read10X(data.dir = "../data/pbmc10k/filtered_feature_bc_matrix/")
rownames(x = pbmc10k.data[["Antibody Capture"]]) <- gsub(pattern = "_[control_]*TotalSeqB", replacement = "",
    x = rownames(x = pbmc10k.data[["Antibody Capture"]]))

pbmc10k <- CreateSeuratObject(counts = pbmc10k.data[["Gene Expression"]], min.cells = 3, min.features = 200)
pbmc10k <- NormalizeData(pbmc10k)
pbmc10k[["ADT"]] <- CreateAssayObject(pbmc10k.data[["Antibody Capture"]][, colnames(x = pbmc10k)])
pbmc10k <- NormalizeData(pbmc10k, assay = "ADT", normalization.method = "CLR")

plot1 <- FeatureScatter(pbmc10k, feature1 = "adt_CD19", feature2 = "adt_CD3", pt.size = 1)
plot2 <- FeatureScatter(pbmc10k, feature1 = "adt_CD4", feature2 = "adt_CD8a", pt.size = 1)
plot3 <- FeatureScatter(pbmc10k, feature1 = "adt_CD3", feature2 = "CD3E", pt.size = 1)
(plot1 + plot2 + plot3) & NoLegend()
```

Example 86 (r):
```r
pbmc10k.data <- Read10X(data.dir = "../data/pbmc10k/filtered_feature_bc_matrix/")
rownames(x = pbmc10k.data[["Antibody Capture"]]) <- gsub(pattern = "_[control_]*TotalSeqB", replacement = "",
    x = rownames(x = pbmc10k.data[["Antibody Capture"]]))

pbmc10k <- CreateSeuratObject(counts = pbmc10k.data[["Gene Expression"]], min.cells = 3, min.features = 200)
pbmc10k <- NormalizeData(pbmc10k)
pbmc10k[["ADT"]] <- CreateAssayObject(pbmc10k.data[["Antibody Capture"]][, colnames(x = pbmc10k)])
pbmc10k <- NormalizeData(pbmc10k, assay = "ADT", normalization.method = "CLR")

plot1 <- FeatureScatter(pbmc10k, feature1 = "adt_CD19", feature2 = "adt_CD3", pt.size = 1)
plot2 <- FeatureScatter(pbmc10k, feature1 = "adt_CD4", feature2 = "adt_CD8a", pt.size = 1)
plot3 <- FeatureScatter(pbmc10k, feature1 = "adt_CD3", feature2 = "CD3E", pt.size = 1)
(plot1 + plot2 + plot3) & NoLegend()
```

Example 87 (r):
```r
pbmc10k.data <- Read10X(data.dir = "../data/pbmc10k/filtered_feature_bc_matrix/")
rownames(x = pbmc10k.data[["Antibody Capture"]]) <- gsub(pattern = "_[control_]*TotalSeqB", replacement = "",
    x = rownames(x = pbmc10k.data[["Antibody Capture"]]))

pbmc10k <- CreateSeuratObject(counts = pbmc10k.data[["Gene Expression"]], min.cells = 3, min.features = 200)
pbmc10k <- NormalizeData(pbmc10k)
pbmc10k[["ADT"]] <- CreateAssayObject(pbmc10k.data[["Antibody Capture"]][, colnames(x = pbmc10k)])
pbmc10k <- NormalizeData(pbmc10k, assay = "ADT", normalization.method = "CLR")

plot1 <- FeatureScatter(pbmc10k, feature1 = "adt_CD19", feature2 = "adt_CD3", pt.size = 1)
plot2 <- FeatureScatter(pbmc10k, feature1 = "adt_CD4", feature2 = "adt_CD8a", pt.size = 1)
plot3 <- FeatureScatter(pbmc10k, feature1 = "adt_CD3", feature2 = "CD3E", pt.size = 1)
(plot1 + plot2 + plot3) & NoLegend()
```

Example 88 (unknown):
```unknown
sessionInfo()
```

Example 89 (r):
```r
sessionInfo()
```

Example 90 (r):
```r
sessionInfo()
```

Example 91 (unknown):
```unknown
## R version 4.2.0 (2022-04-22)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.5 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/liblapack.so.3
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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       
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
## [1] patchwork_1.1.2    ggplot2_3.4.1      SeuratObject_4.1.3 Seurat_4.3.0      
## 
## loaded via a namespace (and not attached):
##   [1] Rtsne_0.16             colorspace_2.1-0       deldir_1.0-6          
##   [4] ellipsis_0.3.2         ggridges_0.5.4         rprojroot_2.0.3       
##   [7] fs_1.6.1               spatstat.data_3.0-0    farver_2.1.1          
##  [10] leiden_0.4.3           listenv_0.9.0          ggrepel_0.9.3         
##  [13] fansi_1.0.4            R.methodsS3_1.8.2      codetools_0.2-18      
##  [16] splines_4.2.0          cachem_1.0.7           knitr_1.42            
##  [19] polyclip_1.10-4        jsonlite_1.8.4         ica_1.0-3             
##  [22] cluster_2.1.3          R.oo_1.25.0            png_0.1-8             
##  [25] uwot_0.1.14            spatstat.sparse_3.0-0  shiny_1.7.4           
##  [28] sctransform_0.3.5      compiler_4.2.0         httr_1.4.5            
##  [31] Matrix_1.5-3           fastmap_1.1.1          lazyeval_0.2.2        
##  [34] limma_3.54.1           cli_3.6.0              later_1.3.0           
##  [37] formatR_1.14           htmltools_0.5.4        tools_4.2.0           
##  [40] igraph_1.4.1           gtable_0.3.1           glue_1.6.2            
##  [43] RANN_2.6.1             reshape2_1.4.4         dplyr_1.1.0           
##  [46] Rcpp_1.0.10            scattermore_0.8        jquerylib_0.1.4       
##  [49] pkgdown_2.0.7          vctrs_0.5.2            nlme_3.1-157          
##  [52] spatstat.explore_3.0-6 progressr_0.13.0       lmtest_0.9-40         
##  [55] spatstat.random_3.1-3  xfun_0.37              stringr_1.5.0         
##  [58] globals_0.16.2         mime_0.12              miniUI_0.1.1.1        
##  [61] lifecycle_1.0.3        irlba_2.3.5.1          goftest_1.2-3         
##  [64] future_1.31.0          MASS_7.3-56            zoo_1.8-11            
##  [67] scales_1.2.1           ragg_1.2.5             promises_1.2.0.1      
##  [70] spatstat.utils_3.0-1   parallel_4.2.0         RColorBrewer_1.1-3    
##  [73] yaml_2.3.7             memoise_2.0.1          reticulate_1.28       
##  [76] pbapply_1.7-0          gridExtra_2.3          sass_0.4.5            
##  [79] stringi_1.7.12         highr_0.10             desc_1.4.2            
##  [82] rlang_1.0.6            pkgconfig_2.0.3        systemfonts_1.0.4     
##  [85] matrixStats_0.63.0     evaluate_0.20          lattice_0.20-45       
##  [88] tensor_1.5             ROCR_1.0-11            purrr_1.0.1           
##  [91] labeling_0.4.2         htmlwidgets_1.6.1      cowplot_1.1.1         
##  [94] tidyselect_1.2.0       parallelly_1.34.0      RcppAnnoy_0.0.20      
##  [97] plyr_1.8.8             magrittr_2.0.3         R6_2.5.1              
## [100] generics_0.1.3         withr_2.5.0            pillar_1.8.1          
## [103] fitdistrplus_1.1-8     abind_1.4-5            survival_3.3-1        
## [106] sp_1.6-0               tibble_3.1.8           future.apply_1.10.0   
## [109] KernSmooth_2.23-20     utf8_1.2.3             spatstat.geom_3.0-6   
## [112] plotly_4.10.1          rmarkdown_2.20         grid_4.2.0            
## [115] data.table_1.14.8      digest_0.6.31          xtable_1.8-4          
## [118] tidyr_1.3.0            httpuv_1.6.9           R.utils_2.12.2        
## [121] textshaping_0.3.6      munsell_0.5.0          viridisLite_0.4.1     
## [124] bslib_0.4.2
```

Example 92 (unknown):
```unknown
## R version 4.2.0 (2022-04-22)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.5 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/liblapack.so.3
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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       
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
## [1] patchwork_1.1.2    ggplot2_3.4.1      SeuratObject_4.1.3 Seurat_4.3.0      
## 
## loaded via a namespace (and not attached):
##   [1] Rtsne_0.16             colorspace_2.1-0       deldir_1.0-6          
##   [4] ellipsis_0.3.2         ggridges_0.5.4         rprojroot_2.0.3       
##   [7] fs_1.6.1               spatstat.data_3.0-0    farver_2.1.1          
##  [10] leiden_0.4.3           listenv_0.9.0          ggrepel_0.9.3         
##  [13] fansi_1.0.4            R.methodsS3_1.8.2      codetools_0.2-18      
##  [16] splines_4.2.0          cachem_1.0.7           knitr_1.42            
##  [19] polyclip_1.10-4        jsonlite_1.8.4         ica_1.0-3             
##  [22] cluster_2.1.3          R.oo_1.25.0            png_0.1-8             
##  [25] uwot_0.1.14            spatstat.sparse_3.0-0  shiny_1.7.4           
##  [28] sctransform_0.3.5      compiler_4.2.0         httr_1.4.5            
##  [31] Matrix_1.5-3           fastmap_1.1.1          lazyeval_0.2.2        
##  [34] limma_3.54.1           cli_3.6.0              later_1.3.0           
##  [37] formatR_1.14           htmltools_0.5.4        tools_4.2.0           
##  [40] igraph_1.4.1           gtable_0.3.1           glue_1.6.2            
##  [43] RANN_2.6.1             reshape2_1.4.4         dplyr_1.1.0           
##  [46] Rcpp_1.0.10            scattermore_0.8        jquerylib_0.1.4       
##  [49] pkgdown_2.0.7          vctrs_0.5.2            nlme_3.1-157          
##  [52] spatstat.explore_3.0-6 progressr_0.13.0       lmtest_0.9-40         
##  [55] spatstat.random_3.1-3  xfun_0.37              stringr_1.5.0         
##  [58] globals_0.16.2         mime_0.12              miniUI_0.1.1.1        
##  [61] lifecycle_1.0.3        irlba_2.3.5.1          goftest_1.2-3         
##  [64] future_1.31.0          MASS_7.3-56            zoo_1.8-11            
##  [67] scales_1.2.1           ragg_1.2.5             promises_1.2.0.1      
##  [70] spatstat.utils_3.0-1   parallel_4.2.0         RColorBrewer_1.1-3    
##  [73] yaml_2.3.7             memoise_2.0.1          reticulate_1.28       
##  [76] pbapply_1.7-0          gridExtra_2.3          sass_0.4.5            
##  [79] stringi_1.7.12         highr_0.10             desc_1.4.2            
##  [82] rlang_1.0.6            pkgconfig_2.0.3        systemfonts_1.0.4     
##  [85] matrixStats_0.63.0     evaluate_0.20          lattice_0.20-45       
##  [88] tensor_1.5             ROCR_1.0-11            purrr_1.0.1           
##  [91] labeling_0.4.2         htmlwidgets_1.6.1      cowplot_1.1.1         
##  [94] tidyselect_1.2.0       parallelly_1.34.0      RcppAnnoy_0.0.20      
##  [97] plyr_1.8.8             magrittr_2.0.3         R6_2.5.1              
## [100] generics_0.1.3         withr_2.5.0            pillar_1.8.1          
## [103] fitdistrplus_1.1-8     abind_1.4-5            survival_3.3-1        
## [106] sp_1.6-0               tibble_3.1.8           future.apply_1.10.0   
## [109] KernSmooth_2.23-20     utf8_1.2.3             spatstat.geom_3.0-6   
## [112] plotly_4.10.1          rmarkdown_2.20         grid_4.2.0            
## [115] data.table_1.14.8      digest_0.6.31          xtable_1.8-4          
## [118] tidyr_1.3.0            httpuv_1.6.9           R.utils_2.12.2        
## [121] textshaping_0.3.6      munsell_0.5.0          viridisLite_0.4.1     
## [124] bslib_0.4.2
```

---

## Interoperability between single-cell object formats

**URL:** http://127.0.0.1:9173/seurat/archive/v3.1/conversion_vignette/index.html

**Contents:**
- Interoperability between single-cell object formats
    - Compiled: 2020-04-17
  - Converting to/from SingleCellExperiment
  - Converting to/from loom
  - Converting to/from AnnData
- Acknowledgments

In this vignette, we demonstrate the ability to convert between Seurat objects, SingleCellExperiment objects, and anndata objects.

SingleCellExperiment is a class for storing single-cell experiment data, created by Davide Risso, Aaron Lun, and Keegan Korthauer, and is used by many Bioconductor analysis packages. Here we demonstrate converting the Seurat object produced in our 3k PBMC tutorial to SingleCellExperiment for use with Davis McCarthy’s scater package.

Seurat also allows conversion from SingleCellExperiment objects to Seurat objects; we demonstrate this on some publicly available data downloaded from a repository maintained by Martin Hemberg’s group.

The loom format is a file structure imposed on HDF5 files designed by Sten Linnarson’s group. It is designed to efficiently hold large single-cell genomics datasets. For more details about the loom format, please see the loom file format specification.

Seurat can also read in loom files connected via loomR into a Seurat object; we demonstrate this on a subset of the Mouse Brain Atlas created by the Linnarson lab.

For more details about interacting with loom files in R and Seurat, please see loomR on GitHub.

AnnData provides a Python class, created by Alex Wolf and Philipp Angerer, that can be used to store single-cell data. This data format is also use for storage in their Scanpy package for which we now support interoperability. Seurat has a new function ReadH5AD to read the data from the H5AD files that AnnData uses.

We currently do not support writing to an H5AD file at this time; however, transferring data from Seurat to Scanpy can be done via loom files

Many thanks to Davis McCarthy and Alex Wolf for their help in drafting the conversion functions.

**Examples:**

Example 1 (r):
```r
# install scater https://bioconductor.org/packages/release/bioc/html/scater.html
library(scater)
# install loomR from GitHub using the remotes package remotes::install_github(repo =
# 'mojaveazure/loomR', ref = 'develop')
library(loomR)
library(Seurat)
library(patchwork)
```

Example 2 (r):
```r
# install scater https://bioconductor.org/packages/release/bioc/html/scater.html
library(scater)
# install loomR from GitHub using the remotes package remotes::install_github(repo =
# 'mojaveazure/loomR', ref = 'develop')
library(loomR)
library(Seurat)
library(patchwork)
```

Example 3 (unknown):
```unknown
SingleCellExperiment
```

Example 4 (unknown):
```unknown
SingleCellExperiment
```

Example 5 (r):
```r
# download from satija lab https://www.dropbox.com/s/kwd3kcxkmpzqg6w/pbmc3k_final.rds?dl=0
pbmc <- readRDS(file = "../data/pbmc3k_final.rds")
pbmc.sce <- as.SingleCellExperiment(pbmc)
p1 <- plotExpression(pbmc.sce, features = "MS4A1", x = "ident") + theme(axis.text.x = element_text(angle = 45, 
    hjust = 1))
p2 <- plotPCA(pbmc.sce, colour_by = "ident")
p1 + p2
```

Example 6 (r):
```r
# download from satija lab https://www.dropbox.com/s/kwd3kcxkmpzqg6w/pbmc3k_final.rds?dl=0
pbmc <- readRDS(file = "../data/pbmc3k_final.rds")
pbmc.sce <- as.SingleCellExperiment(pbmc)
p1 <- plotExpression(pbmc.sce, features = "MS4A1", x = "ident") + theme(axis.text.x = element_text(angle = 45, 
    hjust = 1))
p2 <- plotPCA(pbmc.sce, colour_by = "ident")
p1 + p2
```

Example 7 (unknown):
```unknown
SingleCellExperiment
```

Example 8 (r):
```r
# download from hemberg lab
# https://scrnaseq-public-datasets.s3.amazonaws.com/scater-objects/manno_human.rds
manno <- readRDS(file = "../data/manno_human.rds")
manno <- runPCA(manno)
manno.seurat <- as.Seurat(manno, counts = "counts", data = "logcounts")
# gives the same results; but omits defaults provided in the last line
manno.seurat <- as.Seurat(manno)
Idents(manno.seurat) <- "cell_type1"
p1 <- DimPlot(manno.seurat, reduction = "PCA", group.by = "Source") + NoLegend()
p2 <- RidgePlot(manno.seurat, features = "ACTB", group.by = "Source")
p1 + p2
```

Example 9 (r):
```r
# download from hemberg lab
# https://scrnaseq-public-datasets.s3.amazonaws.com/scater-objects/manno_human.rds
manno <- readRDS(file = "../data/manno_human.rds")
manno <- runPCA(manno)
manno.seurat <- as.Seurat(manno, counts = "counts", data = "logcounts")
# gives the same results; but omits defaults provided in the last line
manno.seurat <- as.Seurat(manno)
Idents(manno.seurat) <- "cell_type1"
p1 <- DimPlot(manno.seurat, reduction = "PCA", group.by = "Source") + NoLegend()
p2 <- RidgePlot(manno.seurat, features = "ACTB", group.by = "Source")
p1 + p2
```

Example 10 (r):
```r
pbmc.loom <- as.loom(pbmc, filename = "../output/pbmc3k.loom", verbose = FALSE)
pbmc.loom
```

Example 11 (r):
```r
pbmc.loom <- as.loom(pbmc, filename = "../output/pbmc3k.loom", verbose = FALSE)
pbmc.loom
```

Example 12 (unknown):
```unknown
## Class: loom
## Filename: /__w/1/s/output/pbmc3k.loom
## Access type: H5F_ACC_RDWR
## Attributes: version, chunks, LOOM_SPEC_VERSION, assay, last_modified
## Listing:
##        name    obj_type dataset.dims dataset.type_class
##   col_attrs   H5I_GROUP         <NA>               <NA>
##  col_graphs   H5I_GROUP         <NA>               <NA>
##      layers   H5I_GROUP         <NA>               <NA>
##      matrix H5I_DATASET 2638 x 13714          H5T_FLOAT
##   row_attrs   H5I_GROUP         <NA>               <NA>
##  row_graphs   H5I_GROUP         <NA>               <NA>
```

Example 13 (unknown):
```unknown
## Class: loom
## Filename: /__w/1/s/output/pbmc3k.loom
## Access type: H5F_ACC_RDWR
## Attributes: version, chunks, LOOM_SPEC_VERSION, assay, last_modified
## Listing:
##        name    obj_type dataset.dims dataset.type_class
##   col_attrs   H5I_GROUP         <NA>               <NA>
##  col_graphs   H5I_GROUP         <NA>               <NA>
##      layers   H5I_GROUP         <NA>               <NA>
##      matrix H5I_DATASET 2638 x 13714          H5T_FLOAT
##   row_attrs   H5I_GROUP         <NA>               <NA>
##  row_graphs   H5I_GROUP         <NA>               <NA>
```

Example 14 (r):
```r
# Always remember to close loom files when done
pbmc.loom$close_all()
```

Example 15 (r):
```r
# Always remember to close loom files when done
pbmc.loom$close_all()
```

Example 16 (r):
```r
# download from linnarson lab
# https://storage.googleapis.com/linnarsson-lab-loom/l6_r1_immune_cells.loom
l6.immune <- connect(filename = "../data/l6_r1_immune_cells.loom", mode = "r")
l6.immune
```

Example 17 (r):
```r
# download from linnarson lab
# https://storage.googleapis.com/linnarsson-lab-loom/l6_r1_immune_cells.loom
l6.immune <- connect(filename = "../data/l6_r1_immune_cells.loom", mode = "r")
l6.immune
```

Example 18 (unknown):
```unknown
## Class: loom
## Filename: /__w/1/s/data/l6_r1_immune_cells.loom
## Access type: H5F_ACC_RDONLY
## Attributes: CreationDate, last_modified
## Listing:
##        name    obj_type  dataset.dims dataset.type_class
##   col_attrs   H5I_GROUP          <NA>               <NA>
##  col_graphs   H5I_GROUP          <NA>               <NA>
##      layers   H5I_GROUP          <NA>               <NA>
##      matrix H5I_DATASET 14908 x 27998          H5T_FLOAT
##   row_attrs   H5I_GROUP          <NA>               <NA>
##  row_graphs   H5I_GROUP          <NA>               <NA>
```

Example 19 (unknown):
```unknown
## Class: loom
## Filename: /__w/1/s/data/l6_r1_immune_cells.loom
## Access type: H5F_ACC_RDONLY
## Attributes: CreationDate, last_modified
## Listing:
##        name    obj_type  dataset.dims dataset.type_class
##   col_attrs   H5I_GROUP          <NA>               <NA>
##  col_graphs   H5I_GROUP          <NA>               <NA>
##      layers   H5I_GROUP          <NA>               <NA>
##      matrix H5I_DATASET 14908 x 27998          H5T_FLOAT
##   row_attrs   H5I_GROUP          <NA>               <NA>
##  row_graphs   H5I_GROUP          <NA>               <NA>
```

Example 20 (r):
```r
l6.seurat <- as.Seurat(l6.immune)
VlnPlot(l6.seurat, features = c("Sparc", "Ftl1", "Junb", "Ccl4"), ncol = 2, pt.size = 0.1)
```

Example 21 (r):
```r
l6.seurat <- as.Seurat(l6.immune)
VlnPlot(l6.seurat, features = c("Sparc", "Ftl1", "Junb", "Ccl4"), ncol = 2, pt.size = 0.1)
```

Example 22 (r):
```r
# Always remember to close loom files when done
l6.immune$close_all()
```

Example 23 (r):
```r
# Always remember to close loom files when done
l6.immune$close_all()
```

Example 24 (r):
```r
# download from satija lab https://www.dropbox.com/s/ngs3p8n2i8y33hj/pbmc3k.h5ad?dl=0
pbmc3k <- ReadH5AD(file = "../data/pbmc3k.h5ad")
Idents(pbmc3k) <- "louvain"
p1 <- DimPlot(pbmc3k, label = TRUE)
p2 <- VlnPlot(pbmc3k, features = c("CST3", "NKG7", "PPBP"), combine = FALSE)
wrap_plots(c(list(p1), p2), ncol = 2) & NoLegend()
```

Example 25 (r):
```r
# download from satija lab https://www.dropbox.com/s/ngs3p8n2i8y33hj/pbmc3k.h5ad?dl=0
pbmc3k <- ReadH5AD(file = "../data/pbmc3k.h5ad")
Idents(pbmc3k) <- "louvain"
p1 <- DimPlot(pbmc3k, label = TRUE)
p2 <- VlnPlot(pbmc3k, features = c("CST3", "NKG7", "PPBP"), combine = FALSE)
wrap_plots(c(list(p1), p2), ncol = 2) & NoLegend()
```

---

## Analysis, visualization, and integration of Visium HD spatial datasets with Seurat • Seurat

**URL:** http://127.0.0.1:9173/articles_mixscape_vignette.html

**Contents:**
- Mixscape Vignette
    - Compiled: October 31, 2023
- Overview
- Loading required packages
- Loading Seurat object containing ECCITE-seq dataset
- RNA-based clustering is driven by confounding sources of variation
- Calculating local perturbation signatures mitigates confounding effects
- Mixscape identifies cells with no detectable perturbation
- Inspecting mixscape results
- Visualizing perturbation responses with Linear Discriminant Analysis (LDA)
- Contents

This tutorial demonstrates how to use mixscape for the analyses of single-cell pooled CRISPR screens. We introduce new Seurat functions for:

We use a 111 gRNA ECCITE-seq dataset generated from stimulated THP-1 cells that was recently published from our lab in bioRxiv Papalexi et al. 2020. This dataset can be easily downloaded from the SeuratData package.

Here, we follow the standard Seurat workflow to cluster cells based on their gene expression profiles. We expected to obtain perturbation-specific clusters however we saw that clustering is primarily driven by cell cycle phase and replicate ID. We only observed one perturbation-specific cluster containing cells expression IFNgamma pathway gRNAs.

To calculate local perturbation signatures we set the number of non-targeting Nearest Neighbors (NNs) equal to k=20 and we recommend that the user picks a k from the following range: 20 < k < 30. Intuitively, the user does not want to set k to a very small or large number as this will most likely not remove the technical variation from the dataset. Using the PRTB signature to cluster cells removes all technical variation and reveals one additional perturbation-specific cluster.

Here, we are assuming each target gene class is a mixture of two Gaussian distributions one representing the knockout (KO) and the other the non-perturbed (NP) cells. We further assume that the distribution of the NP cells is identical to that of cells expressing non-targeting gRNAs (NT) and we try to estimate the distribution of KO cells using the function normalmixEM() from the mixtools package. Next, we calculate the posterior probability that a cell belongs to the KO distribution and classify cells with a probability higher than 0.5 as KOs. Applying this method we identify KOs in 11 target gene classes and detect variation in gRNA targeting efficiency within each class.

To ensure mixscape is assigning the correct perturbation status to cells we can use the functions below to look at the perturbation score distributions and the posterior probabilities of cells within a target gene class (for example IFNGR2) and compare it to those of the NT cells. In addition, we can perform differential expression (DE) analyses and show that only IFNGR2 KO cells have reduced expression of the IFNG-pathway genes. Finally, as an independent check, we can look at the PD-L1 protein expression values in NP and KO cells for target genes known to be PD-L1 regulators.

We use LDA as a dimensionality reduction method to visualize perturbation-specific clusters. LDA is trying to maximize the separability of known labels (mixscape classes) using both gene expression and the labels as input.

Developed by Rahul Satija, Satija Lab and Collaborators.

Site built with pkgdown 2.0.7.

**Examples:**

Example 1 (unknown):
```unknown
vignettes/mixscape_vignette.Rmd
```

Example 2 (unknown):
```unknown
mixscape_vignette.Rmd
```

Example 3 (unknown):
```unknown
# Load packages.
library(Seurat)
library(SeuratData)
library(ggplot2)
library(patchwork)
library(scales)
library(dplyr)
library(reshape2)

# Download dataset using SeuratData.
InstallData(ds = "thp1.eccite")

# Setup custom theme for plotting.
custom_theme <- theme(
  plot.title = element_text(size=16, hjust = 0.5), 
  legend.key.size = unit(0.7, "cm"), 
  legend.text = element_text(size = 14))
```

Example 4 (r):
```r
# Load packages.
library(Seurat)
library(SeuratData)
library(ggplot2)
library(patchwork)
library(scales)
library(dplyr)
library(reshape2)

# Download dataset using SeuratData.
InstallData(ds = "thp1.eccite")

# Setup custom theme for plotting.
custom_theme <- theme(
  plot.title = element_text(size=16, hjust = 0.5), 
  legend.key.size = unit(0.7, "cm"), 
  legend.text = element_text(size = 14))
```

Example 5 (r):
```r
# Load packages.
library(Seurat)
library(SeuratData)
library(ggplot2)
library(patchwork)
library(scales)
library(dplyr)
library(reshape2)

# Download dataset using SeuratData.
InstallData(ds = "thp1.eccite")

# Setup custom theme for plotting.
custom_theme <- theme(
  plot.title = element_text(size=16, hjust = 0.5), 
  legend.key.size = unit(0.7, "cm"), 
  legend.text = element_text(size = 14))
```

Example 6 (unknown):
```unknown
# Load object.
eccite <- LoadData(ds = "thp1.eccite")

# Normalize protein.
eccite <- NormalizeData(
  object = eccite, 
  assay = "ADT", 
  normalization.method = "CLR", 
  margin = 2)
```

Example 7 (r):
```r
# Load object.
eccite <- LoadData(ds = "thp1.eccite")

# Normalize protein.
eccite <- NormalizeData(
  object = eccite, 
  assay = "ADT", 
  normalization.method = "CLR", 
  margin = 2)
```

Example 8 (r):
```r
# Load object.
eccite <- LoadData(ds = "thp1.eccite")

# Normalize protein.
eccite <- NormalizeData(
  object = eccite, 
  assay = "ADT", 
  normalization.method = "CLR", 
  margin = 2)
```

Example 9 (unknown):
```unknown
# Prepare RNA assay for dimensionality reduction: 
# Normalize data, find variable features and scale data.
DefaultAssay(object = eccite) <- 'RNA'
eccite <- NormalizeData(object = eccite) %>% FindVariableFeatures() %>% ScaleData()

# Run Principle Component Analysis (PCA) to reduce the dimensionality of the data.
eccite <- RunPCA(object = eccite)

# Run Uniform Manifold Approximation and Projection (UMAP) to visualize clustering in 2-D.
eccite <- RunUMAP(object = eccite, dims = 1:40)

# Generate plots to check if clustering is driven by biological replicate ID, 
# cell cycle phase or target gene class.
p1 <- DimPlot(
  object = eccite, 
  group.by = 'replicate', 
  label = F, 
  pt.size = 0.2, 
  reduction = "umap", cols = "Dark2", repel = T) +
  scale_color_brewer(palette = "Dark2") +
  ggtitle("Biological Replicate") +
  xlab("UMAP 1") +
  ylab("UMAP 2") +
  custom_theme

p2 <- DimPlot(
  object = eccite, 
  group.by = 'Phase', 
  label = F, pt.size = 0.2, 
  reduction = "umap", repel = T) + 
  ggtitle("Cell Cycle Phase") +
  ylab("UMAP 2") +
  xlab("UMAP 1") +
  custom_theme

p3 <- DimPlot(
  object = eccite, 
  group.by = 'crispr', 
  pt.size = 0.2, 
  reduction = "umap", 
  split.by = "crispr", 
  ncol = 1, 
  cols = c("grey39","goldenrod3")) + 
  ggtitle("Perturbation Status") +
  ylab("UMAP 2") +
  xlab("UMAP 1") +
  custom_theme

# Visualize plots.
((p1 / p2 + plot_layout(guides = 'auto')) | p3 )
```

Example 10 (r):
```r
# Prepare RNA assay for dimensionality reduction: 
# Normalize data, find variable features and scale data.
DefaultAssay(object = eccite) <- 'RNA'
eccite <- NormalizeData(object = eccite) %>% FindVariableFeatures() %>% ScaleData()

# Run Principle Component Analysis (PCA) to reduce the dimensionality of the data.
eccite <- RunPCA(object = eccite)

# Run Uniform Manifold Approximation and Projection (UMAP) to visualize clustering in 2-D.
eccite <- RunUMAP(object = eccite, dims = 1:40)

# Generate plots to check if clustering is driven by biological replicate ID, 
# cell cycle phase or target gene class.
p1 <- DimPlot(
  object = eccite, 
  group.by = 'replicate', 
  label = F, 
  pt.size = 0.2, 
  reduction = "umap", cols = "Dark2", repel = T) +
  scale_color_brewer(palette = "Dark2") +
  ggtitle("Biological Replicate") +
  xlab("UMAP 1") +
  ylab("UMAP 2") +
  custom_theme

p2 <- DimPlot(
  object = eccite, 
  group.by = 'Phase', 
  label = F, pt.size = 0.2, 
  reduction = "umap", repel = T) + 
  ggtitle("Cell Cycle Phase") +
  ylab("UMAP 2") +
  xlab("UMAP 1") +
  custom_theme

p3 <- DimPlot(
  object = eccite, 
  group.by = 'crispr', 
  pt.size = 0.2, 
  reduction = "umap", 
  split.by = "crispr", 
  ncol = 1, 
  cols = c("grey39","goldenrod3")) + 
  ggtitle("Perturbation Status") +
  ylab("UMAP 2") +
  xlab("UMAP 1") +
  custom_theme

# Visualize plots.
((p1 / p2 + plot_layout(guides = 'auto')) | p3 )
```

Example 11 (r):
```r
# Prepare RNA assay for dimensionality reduction: 
# Normalize data, find variable features and scale data.
DefaultAssay(object = eccite) <- 'RNA'
eccite <- NormalizeData(object = eccite) %>% FindVariableFeatures() %>% ScaleData()

# Run Principle Component Analysis (PCA) to reduce the dimensionality of the data.
eccite <- RunPCA(object = eccite)

# Run Uniform Manifold Approximation and Projection (UMAP) to visualize clustering in 2-D.
eccite <- RunUMAP(object = eccite, dims = 1:40)

# Generate plots to check if clustering is driven by biological replicate ID, 
# cell cycle phase or target gene class.
p1 <- DimPlot(
  object = eccite, 
  group.by = 'replicate', 
  label = F, 
  pt.size = 0.2, 
  reduction = "umap", cols = "Dark2", repel = T) +
  scale_color_brewer(palette = "Dark2") +
  ggtitle("Biological Replicate") +
  xlab("UMAP 1") +
  ylab("UMAP 2") +
  custom_theme

p2 <- DimPlot(
  object = eccite, 
  group.by = 'Phase', 
  label = F, pt.size = 0.2, 
  reduction = "umap", repel = T) + 
  ggtitle("Cell Cycle Phase") +
  ylab("UMAP 2") +
  xlab("UMAP 1") +
  custom_theme

p3 <- DimPlot(
  object = eccite, 
  group.by = 'crispr', 
  pt.size = 0.2, 
  reduction = "umap", 
  split.by = "crispr", 
  ncol = 1, 
  cols = c("grey39","goldenrod3")) + 
  ggtitle("Perturbation Status") +
  ylab("UMAP 2") +
  xlab("UMAP 1") +
  custom_theme

# Visualize plots.
((p1 / p2 + plot_layout(guides = 'auto')) | p3 )
```

Example 12 (python):
```python
# Calculate perturbation signature (PRTB).
eccite<- CalcPerturbSig(
  object = eccite, 
  assay = "RNA", 
  slot = "data", 
  gd.class ="gene", 
  nt.cell.class = "NT", 
  reduction = "pca", 
  ndims = 40, 
  num.neighbors = 20, 
  split.by = "replicate", 
  new.assay.name = "PRTB")

# Prepare PRTB assay for dimensionality reduction: 
# Normalize data, find variable features and center data.
DefaultAssay(object = eccite) <- 'PRTB'

# Use variable features from RNA assay.
VariableFeatures(object = eccite) <- VariableFeatures(object = eccite[["RNA"]])
eccite <- ScaleData(object = eccite, do.scale = F, do.center = T)

# Run PCA to reduce the dimensionality of the data.
eccite <- RunPCA(object = eccite, reduction.key = 'prtbpca', reduction.name = 'prtbpca')

# Run UMAP to visualize clustering in 2-D.
eccite <- RunUMAP(
  object = eccite, 
  dims = 1:40, 
  reduction = 'prtbpca', 
  reduction.key = 'prtbumap', 
  reduction.name = 'prtbumap')

# Generate plots to check if clustering is driven by biological replicate ID, 
# cell cycle phase or target gene class.
q1 <- DimPlot(
  object = eccite, 
  group.by = 'replicate', 
  reduction = 'prtbumap', 
  pt.size = 0.2, cols = "Dark2", label = F, repel = T) +
  scale_color_brewer(palette = "Dark2") +
  ggtitle("Biological Replicate") +
  ylab("UMAP 2") +
  xlab("UMAP 1") +
  custom_theme

q2 <- DimPlot(
  object = eccite, 
  group.by = 'Phase', 
  reduction = 'prtbumap', 
  pt.size = 0.2, label = F, repel = T) +
  ggtitle("Cell Cycle Phase") +
  ylab("UMAP 2") +
  xlab("UMAP 1") + 
  custom_theme

q3 <- DimPlot(
  object = eccite,
  group.by = 'crispr',
  reduction = 'prtbumap', 
  split.by = "crispr", 
  ncol = 1, 
  pt.size = 0.2, 
  cols = c("grey39","goldenrod3")) +
  ggtitle("Perturbation Status") +
  ylab("UMAP 2") +
  xlab("UMAP 1") +
  custom_theme

# Visualize plots.
(q1 / q2 + plot_layout(guides = 'auto') | q3)
```

Example 13 (r):
```r
# Calculate perturbation signature (PRTB).
eccite<- CalcPerturbSig(
  object = eccite, 
  assay = "RNA", 
  slot = "data", 
  gd.class ="gene", 
  nt.cell.class = "NT", 
  reduction = "pca", 
  ndims = 40, 
  num.neighbors = 20, 
  split.by = "replicate", 
  new.assay.name = "PRTB")

# Prepare PRTB assay for dimensionality reduction: 
# Normalize data, find variable features and center data.
DefaultAssay(object = eccite) <- 'PRTB'

# Use variable features from RNA assay.
VariableFeatures(object = eccite) <- VariableFeatures(object = eccite[["RNA"]])
eccite <- ScaleData(object = eccite, do.scale = F, do.center = T)

# Run PCA to reduce the dimensionality of the data.
eccite <- RunPCA(object = eccite, reduction.key = 'prtbpca', reduction.name = 'prtbpca')

# Run UMAP to visualize clustering in 2-D.
eccite <- RunUMAP(
  object = eccite, 
  dims = 1:40, 
  reduction = 'prtbpca', 
  reduction.key = 'prtbumap', 
  reduction.name = 'prtbumap')

# Generate plots to check if clustering is driven by biological replicate ID, 
# cell cycle phase or target gene class.
q1 <- DimPlot(
  object = eccite, 
  group.by = 'replicate', 
  reduction = 'prtbumap', 
  pt.size = 0.2, cols = "Dark2", label = F, repel = T) +
  scale_color_brewer(palette = "Dark2") +
  ggtitle("Biological Replicate") +
  ylab("UMAP 2") +
  xlab("UMAP 1") +
  custom_theme

q2 <- DimPlot(
  object = eccite, 
  group.by = 'Phase', 
  reduction = 'prtbumap', 
  pt.size = 0.2, label = F, repel = T) +
  ggtitle("Cell Cycle Phase") +
  ylab("UMAP 2") +
  xlab("UMAP 1") + 
  custom_theme

q3 <- DimPlot(
  object = eccite,
  group.by = 'crispr',
  reduction = 'prtbumap', 
  split.by = "crispr", 
  ncol = 1, 
  pt.size = 0.2, 
  cols = c("grey39","goldenrod3")) +
  ggtitle("Perturbation Status") +
  ylab("UMAP 2") +
  xlab("UMAP 1") +
  custom_theme

# Visualize plots.
(q1 / q2 + plot_layout(guides = 'auto') | q3)
```

Example 14 (r):
```r
# Calculate perturbation signature (PRTB).
eccite<- CalcPerturbSig(
  object = eccite, 
  assay = "RNA", 
  slot = "data", 
  gd.class ="gene", 
  nt.cell.class = "NT", 
  reduction = "pca", 
  ndims = 40, 
  num.neighbors = 20, 
  split.by = "replicate", 
  new.assay.name = "PRTB")

# Prepare PRTB assay for dimensionality reduction: 
# Normalize data, find variable features and center data.
DefaultAssay(object = eccite) <- 'PRTB'

# Use variable features from RNA assay.
VariableFeatures(object = eccite) <- VariableFeatures(object = eccite[["RNA"]])
eccite <- ScaleData(object = eccite, do.scale = F, do.center = T)

# Run PCA to reduce the dimensionality of the data.
eccite <- RunPCA(object = eccite, reduction.key = 'prtbpca', reduction.name = 'prtbpca')

# Run UMAP to visualize clustering in 2-D.
eccite <- RunUMAP(
  object = eccite, 
  dims = 1:40, 
  reduction = 'prtbpca', 
  reduction.key = 'prtbumap', 
  reduction.name = 'prtbumap')

# Generate plots to check if clustering is driven by biological replicate ID, 
# cell cycle phase or target gene class.
q1 <- DimPlot(
  object = eccite, 
  group.by = 'replicate', 
  reduction = 'prtbumap', 
  pt.size = 0.2, cols = "Dark2", label = F, repel = T) +
  scale_color_brewer(palette = "Dark2") +
  ggtitle("Biological Replicate") +
  ylab("UMAP 2") +
  xlab("UMAP 1") +
  custom_theme

q2 <- DimPlot(
  object = eccite, 
  group.by = 'Phase', 
  reduction = 'prtbumap', 
  pt.size = 0.2, label = F, repel = T) +
  ggtitle("Cell Cycle Phase") +
  ylab("UMAP 2") +
  xlab("UMAP 1") + 
  custom_theme

q3 <- DimPlot(
  object = eccite,
  group.by = 'crispr',
  reduction = 'prtbumap', 
  split.by = "crispr", 
  ncol = 1, 
  pt.size = 0.2, 
  cols = c("grey39","goldenrod3")) +
  ggtitle("Perturbation Status") +
  ylab("UMAP 2") +
  xlab("UMAP 1") +
  custom_theme

# Visualize plots.
(q1 / q2 + plot_layout(guides = 'auto') | q3)
```

Example 15 (unknown):
```unknown
normalmixEM()
```

Example 16 (javascript):
```javascript
# Run mixscape.
eccite <- RunMixscape(
  object = eccite, 
  assay = "PRTB", 
  slot = "scale.data", 
  labels = "gene", 
  nt.class.name = "NT", 
  min.de.genes = 5, 
  iter.num = 10, 
  de.assay = "RNA", 
  verbose = F,
  prtb.type = "KO")

# Calculate percentage of KO cells for all target gene classes.
df <- prop.table(table(eccite$mixscape_class.global, eccite$NT),2)

df2 <- reshape2::melt(df)
df2$Var2 <- as.character(df2$Var2)
test <- df2[which(df2$Var1 == "KO"),]
test <- test[order(test$value, decreasing = T),]
new.levels <- test$Var2
df2$Var2 <- factor(df2$Var2, levels = new.levels )
df2$Var1 <- factor(df2$Var1, levels = c("NT", "NP", "KO"))
df2$gene <- sapply(as.character(df2$Var2), function(x) strsplit(x, split = "g")[[1]][1])
df2$guide_number <- sapply(as.character(df2$Var2), 
                           function(x) strsplit(x, split = "g")[[1]][2])
df3 <- df2[-c(which(df2$gene == "NT")),]

p1 <- ggplot(df3, aes(x = guide_number, y = value*100, fill= Var1)) +
  geom_bar(stat= "identity") +
  theme_classic()+
  scale_fill_manual(values = c("grey49", "grey79","coral1")) + 
  ylab("% of cells") +
  xlab("sgRNA")

p1 + theme(axis.text.x = element_text(size = 18, hjust = 1), 
           axis.text.y = element_text(size = 18), 
           axis.title = element_text(size = 16), 
           strip.text = element_text(size=16, face = "bold")) + 
  facet_wrap(vars(gene),ncol = 5, scales = "free") +
  labs(fill = "mixscape class") +theme(legend.title = element_text(size = 14),
          legend.text = element_text(size = 12))
```

Example 17 (r):
```r
# Run mixscape.
eccite <- RunMixscape(
  object = eccite, 
  assay = "PRTB", 
  slot = "scale.data", 
  labels = "gene", 
  nt.class.name = "NT", 
  min.de.genes = 5, 
  iter.num = 10, 
  de.assay = "RNA", 
  verbose = F,
  prtb.type = "KO")

# Calculate percentage of KO cells for all target gene classes.
df <- prop.table(table(eccite$mixscape_class.global, eccite$NT),2)

df2 <- reshape2::melt(df)
df2$Var2 <- as.character(df2$Var2)
test <- df2[which(df2$Var1 == "KO"),]
test <- test[order(test$value, decreasing = T),]
new.levels <- test$Var2
df2$Var2 <- factor(df2$Var2, levels = new.levels )
df2$Var1 <- factor(df2$Var1, levels = c("NT", "NP", "KO"))
df2$gene <- sapply(as.character(df2$Var2), function(x) strsplit(x, split = "g")[[1]][1])
df2$guide_number <- sapply(as.character(df2$Var2), 
                           function(x) strsplit(x, split = "g")[[1]][2])
df3 <- df2[-c(which(df2$gene == "NT")),]

p1 <- ggplot(df3, aes(x = guide_number, y = value*100, fill= Var1)) +
  geom_bar(stat= "identity") +
  theme_classic()+
  scale_fill_manual(values = c("grey49", "grey79","coral1")) + 
  ylab("% of cells") +
  xlab("sgRNA")

p1 + theme(axis.text.x = element_text(size = 18, hjust = 1), 
           axis.text.y = element_text(size = 18), 
           axis.title = element_text(size = 16), 
           strip.text = element_text(size=16, face = "bold")) + 
  facet_wrap(vars(gene),ncol = 5, scales = "free") +
  labs(fill = "mixscape class") +theme(legend.title = element_text(size = 14),
          legend.text = element_text(size = 12))
```

Example 18 (r):
```r
# Run mixscape.
eccite <- RunMixscape(
  object = eccite, 
  assay = "PRTB", 
  slot = "scale.data", 
  labels = "gene", 
  nt.class.name = "NT", 
  min.de.genes = 5, 
  iter.num = 10, 
  de.assay = "RNA", 
  verbose = F,
  prtb.type = "KO")

# Calculate percentage of KO cells for all target gene classes.
df <- prop.table(table(eccite$mixscape_class.global, eccite$NT),2)

df2 <- reshape2::melt(df)
df2$Var2 <- as.character(df2$Var2)
test <- df2[which(df2$Var1 == "KO"),]
test <- test[order(test$value, decreasing = T),]
new.levels <- test$Var2
df2$Var2 <- factor(df2$Var2, levels = new.levels )
df2$Var1 <- factor(df2$Var1, levels = c("NT", "NP", "KO"))
df2$gene <- sapply(as.character(df2$Var2), function(x) strsplit(x, split = "g")[[1]][1])
df2$guide_number <- sapply(as.character(df2$Var2), 
                           function(x) strsplit(x, split = "g")[[1]][2])
df3 <- df2[-c(which(df2$gene == "NT")),]

p1 <- ggplot(df3, aes(x = guide_number, y = value*100, fill= Var1)) +
  geom_bar(stat= "identity") +
  theme_classic()+
  scale_fill_manual(values = c("grey49", "grey79","coral1")) + 
  ylab("% of cells") +
  xlab("sgRNA")

p1 + theme(axis.text.x = element_text(size = 18, hjust = 1), 
           axis.text.y = element_text(size = 18), 
           axis.title = element_text(size = 16), 
           strip.text = element_text(size=16, face = "bold")) + 
  facet_wrap(vars(gene),ncol = 5, scales = "free") +
  labs(fill = "mixscape class") +theme(legend.title = element_text(size = 14),
          legend.text = element_text(size = 12))
```

Example 19 (python):
```python
# Explore the perturbation scores of cells.
PlotPerturbScore(object = eccite, 
                 target.gene.ident = "IFNGR2", 
                 mixscape.class = "mixscape_class", 
                 col = "coral2") +labs(fill = "mixscape class")
```

Example 20 (r):
```r
# Explore the perturbation scores of cells.
PlotPerturbScore(object = eccite, 
                 target.gene.ident = "IFNGR2", 
                 mixscape.class = "mixscape_class", 
                 col = "coral2") +labs(fill = "mixscape class")
```

Example 21 (r):
```r
# Explore the perturbation scores of cells.
PlotPerturbScore(object = eccite, 
                 target.gene.ident = "IFNGR2", 
                 mixscape.class = "mixscape_class", 
                 col = "coral2") +labs(fill = "mixscape class")
```

Example 22 (unknown):
```unknown
# Inspect the posterior probability values in NP and KO cells.
VlnPlot(eccite, "mixscape_class_p_ko", idents = c("NT", "IFNGR2 KO", "IFNGR2 NP")) +
  theme(axis.text.x = element_text(angle = 0, hjust = 0.5),axis.text = element_text(size = 16) ,plot.title = element_text(size = 20)) + 
  NoLegend() +
  ggtitle("mixscape posterior probabilities")
```

Example 23 (r):
```r
# Inspect the posterior probability values in NP and KO cells.
VlnPlot(eccite, "mixscape_class_p_ko", idents = c("NT", "IFNGR2 KO", "IFNGR2 NP")) +
  theme(axis.text.x = element_text(angle = 0, hjust = 0.5),axis.text = element_text(size = 16) ,plot.title = element_text(size = 20)) + 
  NoLegend() +
  ggtitle("mixscape posterior probabilities")
```

Example 24 (r):
```r
# Inspect the posterior probability values in NP and KO cells.
VlnPlot(eccite, "mixscape_class_p_ko", idents = c("NT", "IFNGR2 KO", "IFNGR2 NP")) +
  theme(axis.text.x = element_text(angle = 0, hjust = 0.5),axis.text = element_text(size = 16) ,plot.title = element_text(size = 20)) + 
  NoLegend() +
  ggtitle("mixscape posterior probabilities")
```

Example 25 (unknown):
```unknown
# Run DE analysis and visualize results on a heatmap ordering cells by their posterior 
# probability values.
Idents(object = eccite) <- "gene"
MixscapeHeatmap(object = eccite, 
                ident.1 = "NT", 
                ident.2 = "IFNGR2", 
                balanced = F, 
                assay = "RNA", 
                max.genes = 20, angle = 0, 
                group.by = "mixscape_class", 
                max.cells.group = 300, 
                size=6.5) + NoLegend() +theme(axis.text.y = element_text(size = 16))
```

Example 26 (r):
```r
# Run DE analysis and visualize results on a heatmap ordering cells by their posterior 
# probability values.
Idents(object = eccite) <- "gene"
MixscapeHeatmap(object = eccite, 
                ident.1 = "NT", 
                ident.2 = "IFNGR2", 
                balanced = F, 
                assay = "RNA", 
                max.genes = 20, angle = 0, 
                group.by = "mixscape_class", 
                max.cells.group = 300, 
                size=6.5) + NoLegend() +theme(axis.text.y = element_text(size = 16))
```

Example 27 (r):
```r
# Run DE analysis and visualize results on a heatmap ordering cells by their posterior 
# probability values.
Idents(object = eccite) <- "gene"
MixscapeHeatmap(object = eccite, 
                ident.1 = "NT", 
                ident.2 = "IFNGR2", 
                balanced = F, 
                assay = "RNA", 
                max.genes = 20, angle = 0, 
                group.by = "mixscape_class", 
                max.cells.group = 300, 
                size=6.5) + NoLegend() +theme(axis.text.y = element_text(size = 16))
```

Example 28 (unknown):
```unknown
# Show that only IFNG pathway KO cells have a reduction in PD-L1 protein expression.
VlnPlot(
  object = eccite, 
  features = "adt_PDL1", 
  idents = c("NT","JAK2","STAT1","IFNGR1","IFNGR2", "IRF1"), 
  group.by = "gene", 
  pt.size = 0.2, 
  sort = T, 
  split.by = "mixscape_class.global", 
  cols = c("coral3","grey79","grey39")) +
  ggtitle("PD-L1 protein") +
  theme(axis.text.x = element_text(angle = 0, hjust = 0.5), plot.title = element_text(size = 20), axis.text = element_text(size = 16))
```

Example 29 (r):
```r
# Show that only IFNG pathway KO cells have a reduction in PD-L1 protein expression.
VlnPlot(
  object = eccite, 
  features = "adt_PDL1", 
  idents = c("NT","JAK2","STAT1","IFNGR1","IFNGR2", "IRF1"), 
  group.by = "gene", 
  pt.size = 0.2, 
  sort = T, 
  split.by = "mixscape_class.global", 
  cols = c("coral3","grey79","grey39")) +
  ggtitle("PD-L1 protein") +
  theme(axis.text.x = element_text(angle = 0, hjust = 0.5), plot.title = element_text(size = 20), axis.text = element_text(size = 16))
```

Example 30 (r):
```r
# Show that only IFNG pathway KO cells have a reduction in PD-L1 protein expression.
VlnPlot(
  object = eccite, 
  features = "adt_PDL1", 
  idents = c("NT","JAK2","STAT1","IFNGR1","IFNGR2", "IRF1"), 
  group.by = "gene", 
  pt.size = 0.2, 
  sort = T, 
  split.by = "mixscape_class.global", 
  cols = c("coral3","grey79","grey39")) +
  ggtitle("PD-L1 protein") +
  theme(axis.text.x = element_text(angle = 0, hjust = 0.5), plot.title = element_text(size = 20), axis.text = element_text(size = 16))
```

Example 31 (unknown):
```unknown
p <- VlnPlot(object = eccite, features = "adt_PDL1", idents = c("NT","JAK2","STAT1","IFNGR1","IFNGR2", "IRF1"), group.by = "gene", pt.size = 0.2, sort = T, split.by = "mixscape_class.global", cols = c("coral3","grey79","grey39")) +ggtitle("PD-L1 protein") +theme(axis.text.x = element_text(angle = 0, hjust = 0.5))
```

Example 32 (r):
```r
p <- VlnPlot(object = eccite, features = "adt_PDL1", idents = c("NT","JAK2","STAT1","IFNGR1","IFNGR2", "IRF1"), group.by = "gene", pt.size = 0.2, sort = T, split.by = "mixscape_class.global", cols = c("coral3","grey79","grey39")) +ggtitle("PD-L1 protein") +theme(axis.text.x = element_text(angle = 0, hjust = 0.5))
```

Example 33 (r):
```r
p <- VlnPlot(object = eccite, features = "adt_PDL1", idents = c("NT","JAK2","STAT1","IFNGR1","IFNGR2", "IRF1"), group.by = "gene", pt.size = 0.2, sort = T, split.by = "mixscape_class.global", cols = c("coral3","grey79","grey39")) +ggtitle("PD-L1 protein") +theme(axis.text.x = element_text(angle = 0, hjust = 0.5))
```

Example 34 (python):
```python
# Remove non-perturbed cells and run LDA to reduce the dimensionality of the data.
Idents(eccite) <- "mixscape_class.global"
sub <- subset(eccite, idents = c("KO", "NT"))

# Run LDA.
sub <- MixscapeLDA(
  object = sub, 
  assay = "RNA", 
  pc.assay = "PRTB", 
  labels = "gene", 
  nt.label = "NT", 
  npcs = 10, 
  logfc.threshold = 0.25, 
  verbose = F)

# Use LDA results to run UMAP and visualize cells on 2-D. 
# Here, we note that the number of the dimensions to be used is equal to the number of 
# labels minus one (to account for NT cells).
sub <- RunUMAP(
  object = sub,
  dims = 1:11,
  reduction = 'lda',
  reduction.key = 'ldaumap',
  reduction.name = 'ldaumap')

# Visualize UMAP clustering results.
Idents(sub) <- "mixscape_class"
sub$mixscape_class <- as.factor(sub$mixscape_class)

# Set colors for each perturbation.
col = setNames(object = hue_pal()(12),nm = levels(sub$mixscape_class))
names(col) <- c(names(col)[1:7], "NT", names(col)[9:12])
col[8] <- "grey39"

p <- DimPlot(object = sub, 
             reduction = "ldaumap", 
             repel = T, 
             label.size = 5, 
             label = T, 
             cols = col) + NoLegend()

p2 <- p+ 
  scale_color_manual(values=col, drop=FALSE) + 
  ylab("UMAP 2") +
  xlab("UMAP 1") +
  custom_theme
p2
```

Example 35 (r):
```r
# Remove non-perturbed cells and run LDA to reduce the dimensionality of the data.
Idents(eccite) <- "mixscape_class.global"
sub <- subset(eccite, idents = c("KO", "NT"))

# Run LDA.
sub <- MixscapeLDA(
  object = sub, 
  assay = "RNA", 
  pc.assay = "PRTB", 
  labels = "gene", 
  nt.label = "NT", 
  npcs = 10, 
  logfc.threshold = 0.25, 
  verbose = F)

# Use LDA results to run UMAP and visualize cells on 2-D. 
# Here, we note that the number of the dimensions to be used is equal to the number of 
# labels minus one (to account for NT cells).
sub <- RunUMAP(
  object = sub,
  dims = 1:11,
  reduction = 'lda',
  reduction.key = 'ldaumap',
  reduction.name = 'ldaumap')

# Visualize UMAP clustering results.
Idents(sub) <- "mixscape_class"
sub$mixscape_class <- as.factor(sub$mixscape_class)

# Set colors for each perturbation.
col = setNames(object = hue_pal()(12),nm = levels(sub$mixscape_class))
names(col) <- c(names(col)[1:7], "NT", names(col)[9:12])
col[8] <- "grey39"

p <- DimPlot(object = sub, 
             reduction = "ldaumap", 
             repel = T, 
             label.size = 5, 
             label = T, 
             cols = col) + NoLegend()

p2 <- p+ 
  scale_color_manual(values=col, drop=FALSE) + 
  ylab("UMAP 2") +
  xlab("UMAP 1") +
  custom_theme
p2
```

Example 36 (r):
```r
# Remove non-perturbed cells and run LDA to reduce the dimensionality of the data.
Idents(eccite) <- "mixscape_class.global"
sub <- subset(eccite, idents = c("KO", "NT"))

# Run LDA.
sub <- MixscapeLDA(
  object = sub, 
  assay = "RNA", 
  pc.assay = "PRTB", 
  labels = "gene", 
  nt.label = "NT", 
  npcs = 10, 
  logfc.threshold = 0.25, 
  verbose = F)

# Use LDA results to run UMAP and visualize cells on 2-D. 
# Here, we note that the number of the dimensions to be used is equal to the number of 
# labels minus one (to account for NT cells).
sub <- RunUMAP(
  object = sub,
  dims = 1:11,
  reduction = 'lda',
  reduction.key = 'ldaumap',
  reduction.name = 'ldaumap')

# Visualize UMAP clustering results.
Idents(sub) <- "mixscape_class"
sub$mixscape_class <- as.factor(sub$mixscape_class)

# Set colors for each perturbation.
col = setNames(object = hue_pal()(12),nm = levels(sub$mixscape_class))
names(col) <- c(names(col)[1:7], "NT", names(col)[9:12])
col[8] <- "grey39"

p <- DimPlot(object = sub, 
             reduction = "ldaumap", 
             repel = T, 
             label.size = 5, 
             label = T, 
             cols = col) + NoLegend()

p2 <- p+ 
  scale_color_manual(values=col, drop=FALSE) + 
  ylab("UMAP 2") +
  xlab("UMAP 1") +
  custom_theme
p2
```

Example 37 (unknown):
```unknown
sessionInfo()
```

Example 38 (r):
```r
sessionInfo()
```

Example 39 (r):
```r
sessionInfo()
```

Example 40 (unknown):
```unknown
## R version 4.2.2 Patched (2022-11-10 r83330)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.6 LTS
## 
## Matrix products: default
## BLAS:   /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.9.0
## LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.9.0
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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       
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
##  [1] reshape2_1.4.4                dplyr_1.1.3                  
##  [3] scales_1.2.1                  patchwork_1.1.3              
##  [5] ggplot2_3.4.4                 thp1.eccite.SeuratData_3.1.5 
##  [7] stxBrain.SeuratData_0.1.1     ssHippo.SeuratData_3.1.4     
##  [9] pbmcsca.SeuratData_3.0.0      pbmcref.SeuratData_1.0.0     
## [11] pbmcMultiome.SeuratData_0.1.4 pbmc3k.SeuratData_3.1.4      
## [13] panc8.SeuratData_3.0.2        ifnb.SeuratData_3.0.0        
## [15] hcabm40k.SeuratData_3.0.0     cbmc.SeuratData_3.1.4        
## [17] bmcite.SeuratData_0.3.0       SeuratData_0.2.2.9001        
## [19] Seurat_5.0.0                  SeuratObject_5.0.0           
## [21] sp_2.1-1                     
## 
## loaded via a namespace (and not attached):
##   [1] spam_2.10-0            systemfonts_1.0.4      plyr_1.8.9            
##   [4] igraph_1.5.1           lazyeval_0.2.2         splines_4.2.2         
##   [7] RcppHNSW_0.5.0         listenv_0.9.0          scattermore_1.2       
##  [10] digest_0.6.33          htmltools_0.5.6.1      fansi_1.0.5           
##  [13] magrittr_2.0.3         memoise_2.0.1          tensor_1.5            
##  [16] cluster_2.1.4          mixtools_2.0.0         ROCR_1.0-11           
##  [19] limma_3.54.1           globals_0.16.2         matrixStats_1.0.0     
##  [22] pkgdown_2.0.7          spatstat.sparse_3.0-3  colorspace_2.1-0      
##  [25] rappdirs_0.3.3         ggrepel_0.9.4          textshaping_0.3.6     
##  [28] xfun_0.40              crayon_1.5.2           jsonlite_1.8.7        
##  [31] progressr_0.14.0       spatstat.data_3.0-3    survival_3.5-7        
##  [34] zoo_1.8-12             glue_1.6.2             polyclip_1.10-6       
##  [37] gtable_0.3.4           leiden_0.4.3           kernlab_0.9-32        
##  [40] future.apply_1.11.0    abind_1.4-5            spatstat.random_3.2-1 
##  [43] miniUI_0.1.1.1         Rcpp_1.0.11            viridisLite_0.4.2     
##  [46] xtable_1.8-4           reticulate_1.34.0      dotCall64_1.1-0       
##  [49] htmlwidgets_1.6.2      httr_1.4.7             RColorBrewer_1.1-3    
##  [52] ellipsis_0.3.2         ica_1.0-3              farver_2.1.1          
##  [55] pkgconfig_2.0.3        sass_0.4.7             uwot_0.1.16           
##  [58] deldir_1.0-9           utf8_1.2.4             labeling_0.4.3        
##  [61] tidyselect_1.2.0       rlang_1.1.1            later_1.3.1           
##  [64] munsell_0.5.0          tools_4.2.2            cachem_1.0.8          
##  [67] cli_3.6.1              generics_0.1.3         ggridges_0.5.4        
##  [70] evaluate_0.22          stringr_1.5.0          fastmap_1.1.1         
##  [73] yaml_2.3.7             ragg_1.2.5             goftest_1.2-3         
##  [76] knitr_1.45             fs_1.6.3               fitdistrplus_1.1-11   
##  [79] purrr_1.0.2            RANN_2.6.1             pbapply_1.7-2         
##  [82] future_1.33.0          nlme_3.1-162           mime_0.12             
##  [85] ggrastr_1.0.1          compiler_4.2.2         beeswarm_0.4.0        
##  [88] plotly_4.10.3          png_0.1-8              spatstat.utils_3.0-4  
##  [91] tibble_3.2.1           bslib_0.5.1            stringi_1.7.12        
##  [94] highr_0.10             desc_1.4.2             RSpectra_0.16-1       
##  [97] lattice_0.21-9         Matrix_1.6-1.1         vctrs_0.6.4           
## [100] pillar_1.9.0           lifecycle_1.0.3        spatstat.geom_3.2-7   
## [103] lmtest_0.9-40          jquerylib_0.1.4        RcppAnnoy_0.0.21      
## [106] data.table_1.14.8      cowplot_1.1.1          irlba_2.3.5.1         
## [109] httpuv_1.6.12          R6_2.5.1               promises_1.2.1        
## [112] KernSmooth_2.23-22     gridExtra_2.3          vipor_0.4.5           
## [115] parallelly_1.36.0      codetools_0.2-19       fastDummies_1.7.3     
## [118] MASS_7.3-58.2          rprojroot_2.0.3        withr_2.5.2           
## [121] presto_1.0.0           sctransform_0.4.1      parallel_4.2.2        
## [124] grid_4.2.2             tidyr_1.3.0            rmarkdown_2.25        
## [127] segmented_1.6-4        Rtsne_0.16             spatstat.explore_3.2-5
## [130] shiny_1.7.5.1          ggbeeswarm_0.7.1
```

Example 41 (unknown):
```unknown
## R version 4.2.2 Patched (2022-11-10 r83330)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.6 LTS
## 
## Matrix products: default
## BLAS:   /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.9.0
## LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.9.0
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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       
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
##  [1] reshape2_1.4.4                dplyr_1.1.3                  
##  [3] scales_1.2.1                  patchwork_1.1.3              
##  [5] ggplot2_3.4.4                 thp1.eccite.SeuratData_3.1.5 
##  [7] stxBrain.SeuratData_0.1.1     ssHippo.SeuratData_3.1.4     
##  [9] pbmcsca.SeuratData_3.0.0      pbmcref.SeuratData_1.0.0     
## [11] pbmcMultiome.SeuratData_0.1.4 pbmc3k.SeuratData_3.1.4      
## [13] panc8.SeuratData_3.0.2        ifnb.SeuratData_3.0.0        
## [15] hcabm40k.SeuratData_3.0.0     cbmc.SeuratData_3.1.4        
## [17] bmcite.SeuratData_0.3.0       SeuratData_0.2.2.9001        
## [19] Seurat_5.0.0                  SeuratObject_5.0.0           
## [21] sp_2.1-1                     
## 
## loaded via a namespace (and not attached):
##   [1] spam_2.10-0            systemfonts_1.0.4      plyr_1.8.9            
##   [4] igraph_1.5.1           lazyeval_0.2.2         splines_4.2.2         
##   [7] RcppHNSW_0.5.0         listenv_0.9.0          scattermore_1.2       
##  [10] digest_0.6.33          htmltools_0.5.6.1      fansi_1.0.5           
##  [13] magrittr_2.0.3         memoise_2.0.1          tensor_1.5            
##  [16] cluster_2.1.4          mixtools_2.0.0         ROCR_1.0-11           
##  [19] limma_3.54.1           globals_0.16.2         matrixStats_1.0.0     
##  [22] pkgdown_2.0.7          spatstat.sparse_3.0-3  colorspace_2.1-0      
##  [25] rappdirs_0.3.3         ggrepel_0.9.4          textshaping_0.3.6     
##  [28] xfun_0.40              crayon_1.5.2           jsonlite_1.8.7        
##  [31] progressr_0.14.0       spatstat.data_3.0-3    survival_3.5-7        
##  [34] zoo_1.8-12             glue_1.6.2             polyclip_1.10-6       
##  [37] gtable_0.3.4           leiden_0.4.3           kernlab_0.9-32        
##  [40] future.apply_1.11.0    abind_1.4-5            spatstat.random_3.2-1 
##  [43] miniUI_0.1.1.1         Rcpp_1.0.11            viridisLite_0.4.2     
##  [46] xtable_1.8-4           reticulate_1.34.0      dotCall64_1.1-0       
##  [49] htmlwidgets_1.6.2      httr_1.4.7             RColorBrewer_1.1-3    
##  [52] ellipsis_0.3.2         ica_1.0-3              farver_2.1.1          
##  [55] pkgconfig_2.0.3        sass_0.4.7             uwot_0.1.16           
##  [58] deldir_1.0-9           utf8_1.2.4             labeling_0.4.3        
##  [61] tidyselect_1.2.0       rlang_1.1.1            later_1.3.1           
##  [64] munsell_0.5.0          tools_4.2.2            cachem_1.0.8          
##  [67] cli_3.6.1              generics_0.1.3         ggridges_0.5.4        
##  [70] evaluate_0.22          stringr_1.5.0          fastmap_1.1.1         
##  [73] yaml_2.3.7             ragg_1.2.5             goftest_1.2-3         
##  [76] knitr_1.45             fs_1.6.3               fitdistrplus_1.1-11   
##  [79] purrr_1.0.2            RANN_2.6.1             pbapply_1.7-2         
##  [82] future_1.33.0          nlme_3.1-162           mime_0.12             
##  [85] ggrastr_1.0.1          compiler_4.2.2         beeswarm_0.4.0        
##  [88] plotly_4.10.3          png_0.1-8              spatstat.utils_3.0-4  
##  [91] tibble_3.2.1           bslib_0.5.1            stringi_1.7.12        
##  [94] highr_0.10             desc_1.4.2             RSpectra_0.16-1       
##  [97] lattice_0.21-9         Matrix_1.6-1.1         vctrs_0.6.4           
## [100] pillar_1.9.0           lifecycle_1.0.3        spatstat.geom_3.2-7   
## [103] lmtest_0.9-40          jquerylib_0.1.4        RcppAnnoy_0.0.21      
## [106] data.table_1.14.8      cowplot_1.1.1          irlba_2.3.5.1         
## [109] httpuv_1.6.12          R6_2.5.1               promises_1.2.1        
## [112] KernSmooth_2.23-22     gridExtra_2.3          vipor_0.4.5           
## [115] parallelly_1.36.0      codetools_0.2-19       fastDummies_1.7.3     
## [118] MASS_7.3-58.2          rprojroot_2.0.3        withr_2.5.2           
## [121] presto_1.0.0           sctransform_0.4.1      parallel_4.2.2        
## [124] grid_4.2.2             tidyr_1.3.0            rmarkdown_2.25        
## [127] segmented_1.6-4        Rtsne_0.16             spatstat.explore_3.2-5
## [130] shiny_1.7.5.1          ggbeeswarm_0.7.1
```

---

## Integrating scRNA-seq and scATAC-seq data • Seurat

**URL:** http://127.0.0.1:9173/seurat/archive/v4.3/atacseq_integration_vignette/index.html

**Contents:**
- Integrating scRNA-seq and scATAC-seq data
    - Compiled: August 30, 2021
- Load in data and process each modality individually
- Identifying anchors between scRNA-seq and scATAC-seq datasets
- Annotate scATAC-seq cells via label transfer
- Co-embedding scRNA-seq and scATAC-seq datasets
- Contents

Single-cell transcriptomics has transformed our ability to characterize cell states, but deep biological understanding requires more than a taxonomic listing of clusters. As new methods arise to measure distinct cellular modalities, a key analytical challenge is to integrate these datasets to better understand cellular identity and function. For example, users may perform scRNA-seq and scATAC-seq experiments on the same biological system and to consistently annotate both datasets with the same set of cell type labels. This analysis is particularly challenging as scATAC-seq datasets are difficult to annotate, due to both the sparsity of genomic data collected at single-cell resolution, and the lack of interpretable gene markers in scRNA-seq data.In Stuart*, Butler* et al, 2019, we introduce methods to integrate scRNA-seq and scATAC-seq datasets collected from the same biological system, and demonstrate these methods in this vignette. In particular, we demonstrate the following analyses:How to use an annotated scRNA-seq dataset to label cells from an scATAC-seq experimentHow to co-visualize (co-embed) cells from scRNA-seq and scATAC-seqHow to project scATAC-seq cells onto a UMAP derived from an scRNA-seq experimentThis vignette makes extensive use of the Signac package, recently developed for the analysis of chromatin datasets collected at single-cell resolution, including scATAC-seq. Please see the Signac website for additional vignettes and documentation for analyzing scATAC-seq data.We demonstrate these methods using a publicly available ~12,000 human PBMC ‘multiome’ dataset from 10x Genomics. In this dataset, scRNA-seq and scATAC-seq profiles were simultaneously collected in the same cells. For the purposes of this vignette, we treat the datasets as originating from two different experiments and integrate them together. Since they were originally measured in the same cells, this provides a ground truth that we can use to assess the accuracy of integration. We emphasize that our use of the multiome dataset here is for demonstration and evaluation purposes, and that users should apply these methods to scRNA-seq and scATAC-seq datasets that are collected separately. We provide a separate weighted nearest neighbors vignette (WNN) that describes analysis strategies for multi-omic single-cell data.Load in data and process each modality individuallyThe PBMC multiome dataset is available from 10x genomics. To facilitate easy loading and exploration, it is also available as part of our SeuratData package. We load the RNA and ATAC data in separately, and pretend that these profiles were measured in separate experiments. We annotated these cells in our WNN vignette, and the annotations are also included in SeuratData. library(SeuratData) # install the dataset and load requirements InstallData("pbmcMultiome") library(Seurat) library(Signac) library(EnsDb.Hsapiens.v86) library(ggplot2) library(cowplot) # load both modalities pbmc.rna <- LoadData("pbmcMultiome", "pbmc.rna") pbmc.atac <- LoadData("pbmcMultiome", "pbmc.atac") # repeat QC steps performed in the WNN vignette pbmc.rna <- subset(pbmc.rna, seurat_annotations != "filtered") pbmc.atac <- subset(pbmc.atac, seurat_annotations != "filtered") # Perform standard analysis of each modality independently RNA analysis pbmc.rna <- NormalizeData(pbmc.rna) pbmc.rna <- FindVariableFeatures(pbmc.rna) pbmc.rna <- ScaleData(pbmc.rna) pbmc.rna <- RunPCA(pbmc.rna) pbmc.rna <- RunUMAP(pbmc.rna, dims = 1:30) # ATAC analysis add gene annotation information annotations <- GetGRangesFromEnsDb(ensdb = EnsDb.Hsapiens.v86) seqlevelsStyle(annotations) <- "UCSC" genome(annotations) <- "hg38" Annotation(pbmc.atac) <- annotations # We exclude the first dimension as this is typically correlated with sequencing depth pbmc.atac <- RunTFIDF(pbmc.atac) pbmc.atac <- FindTopFeatures(pbmc.atac, min.cutoff = "q0") pbmc.atac <- RunSVD(pbmc.atac) pbmc.atac <- RunUMAP(pbmc.atac, reduction = "lsi", dims = 2:30, reduction.name = "umap.atac", reduction.key = "atacUMAP_")Now we plot the results from both modalities. Cells have been previously annotated based on transcriptomic state. We will predict annotations for the scATAC-seq cells. p1 <- DimPlot(pbmc.rna, group.by = "seurat_annotations", label = TRUE) + NoLegend() + ggtitle("RNA") p2 <- DimPlot(pbmc.atac, group.by = "orig.ident", label = FALSE) + NoLegend() + ggtitle("ATAC") p1 + p2Identifying anchors between scRNA-seq and scATAC-seq datasetsIn order to identify ‘anchors’ between scRNA-seq and scATAC-seq experiments, we first generate a rough estimate of the transcriptional activity of each gene by quantifying ATAC-seq counts in the 2 kb-upstream region and gene body, using the GeneActivity() function in the Signac package. The ensuing gene activity scores from the scATAC-seq data are then used as input for canonical correlation analysis, along with the gene expression quantifications from scRNA-seq. We perform this quantification for all genes identified as being highly variable from the scRNA-seq dataset. # quantify gene activity gene.activities <- GeneActivity(pbmc.atac, features = VariableFeatures(pbmc.rna)) # add gene activities as a new assay pbmc.atac[["ACTIVITY"]] <- CreateAssayObject(counts = gene.activities) # normalize gene activities DefaultAssay(pbmc.atac) <- "ACTIVITY" pbmc.atac <- NormalizeData(pbmc.atac) pbmc.atac <- ScaleData(pbmc.atac, features = rownames(pbmc.atac)) # Identify anchors transfer.anchors <- FindTransferAnchors(reference = pbmc.rna, query = pbmc.atac, features = VariableFeatures(object = pbmc.rna), reference.assay = "RNA", query.assay = "ACTIVITY", reduction = "cca")Annotate scATAC-seq cells via label transferAfter identifying anchors, we can transfer annotations from the scRNA-seq dataset onto the scATAC-seq cells. The annotations are stored in the seurat_annotations field, and are provided as input to the refdata parameter. The output will contain a matrix with predictions and confidence scores for each ATAC-seq cell. celltype.predictions <- TransferData(anchorset = transfer.anchors, refdata = pbmc.rna$seurat_annotations, weight.reduction = pbmc.atac[["lsi"]], dims = 2:30) pbmc.atac <- AddMetaData(pbmc.atac, metadata = celltype.predictions)Why do you choose different (non-default) values for reduction and weight.reduction?In FindTransferAnchors(), we typically project the PCA structure from the reference onto the query when transferring between scRNA-seq datasets. However, when transferring across modalities we find that CCA better captures the shared feature correlation structure and therefore set reduction = 'cca' here. Additionally, by default in TransferData() we use the same projected PCA structure to compute the weights of the local neighborhood of anchors that influence each cell’s prediction. In the case of scRNA-seq to scATAC-seq transfer, we use the low dimensional space learned by computing an LSI on the ATAC-seq data to compute these weights as this better captures the internal structure of the ATAC-seq data. After performing transfer, the ATAC-seq cells have predicted annotations (transferred from the scRNA-seq dataset) stored in the predicted.id field. Since these cells were measured with the multiome kit, we also have a ground-truth annotation that can be used for evaluation. You can see that the predicted and actual annotations are extremely similar. pbmc.atac$annotation_correct <- pbmc.atac$predicted.id == pbmc.atac$seurat_annotations p1 <- DimPlot(pbmc.atac, group.by = "predicted.id", label = TRUE) + NoLegend() + ggtitle("Predicted annotation") p2 <- DimPlot(pbmc.atac, group.by = "seurat_annotations", label = TRUE) + NoLegend() + ggtitle("Ground-truth annotation") p1 | p2In this example, the annotation for an scATAC-seq profile is correctly predicted via scRNA-seq integration ~90% of the time. In addition, the prediction.score.max field quantifies the uncertainty associated with our predicted annotations. We can see that cells that are correctly annotated are typically associated with high prediction scores (>90%), while cells that are incorrectly annotated are associated with sharply lower prediction scores (<50%). Incorrect assignments also tend to reflect closely related cell types (i.e. Intermediate vs. Naive B cells). predictions <- table(pbmc.atac$seurat_annotations, pbmc.atac$predicted.id) predictions <- predictions/rowSums(predictions) # normalize for number of cells in each cell type predictions <- as.data.frame(predictions) p1 <- ggplot(predictions, aes(Var1, Var2, fill = Freq)) + geom_tile() + scale_fill_gradient(name = "Fraction of cells", low = "#ffffc8", high = "#7d0025") + xlab("Cell type annotation (RNA)") + ylab("Predicted cell type label (ATAC)") + theme_cowplot() + theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust = 1)) correct <- length(which(pbmc.atac$seurat_annotations == pbmc.atac$predicted.id)) incorrect <- length(which(pbmc.atac$seurat_annotations != pbmc.atac$predicted.id)) data <- FetchData(pbmc.atac, vars = c("prediction.score.max", "annotation_correct")) p2 <- ggplot(data, aes(prediction.score.max, fill = annotation_correct, colour = annotation_correct)) + geom_density(alpha = 0.5) + theme_cowplot() + scale_fill_discrete(name = "Annotation Correct", labels = c(paste0("FALSE (n = ", incorrect, ")"), paste0("TRUE (n = ", correct, ")"))) + scale_color_discrete(name = "Annotation Correct", labels = c(paste0("FALSE (n = ", incorrect, ")"), paste0("TRUE (n = ", correct, ")"))) + xlab("Prediction Score") p1 + p2Co-embedding scRNA-seq and scATAC-seq datasetsIn addition to transferring labels across modalities, it is also possible to visualize scRNA-seq and scATAC-seq cells on the same plot. We emphasize that this step is primarily for visualization, and is an optional step. Typically, when we perform integrative analysis between scRNA-seq and scATAC-seq datasets, we focus primarily on label transfer as described above. We demonstrate our workflows for co-embedding below, and again highlight that this is for demonstration purposes, especially as in this particular case both the scRNA-seq profiles and scATAC-seq profiles were actually measured in the same cells.In order to perform co-embedding, we first ‘impute’ RNA expression into the scATAC-seq cells based on the previously computed anchors, and then merge the datasets. # note that we restrict the imputation to variable genes from scRNA-seq, but could impute the # full transcriptome if we wanted to genes.use <- VariableFeatures(pbmc.rna) refdata <- GetAssayData(pbmc.rna, assay = "RNA", slot = "data")[genes.use, ] # refdata (input) contains a scRNA-seq expression matrix for the scRNA-seq cells. imputation # (output) will contain an imputed scRNA-seq matrix for each of the ATAC cells imputation <- TransferData(anchorset = transfer.anchors, refdata = refdata, weight.reduction = pbmc.atac[["lsi"]], dims = 2:30) pbmc.atac[["RNA"]] <- imputation coembed <- merge(x = pbmc.rna, y = pbmc.atac) # Finally, we run PCA and UMAP on this combined object, to visualize the co-embedding of both # datasets coembed <- ScaleData(coembed, features = genes.use, do.scale = FALSE) coembed <- RunPCA(coembed, features = genes.use, verbose = FALSE) coembed <- RunUMAP(coembed, dims = 1:30) DimPlot(coembed, group.by = c("orig.ident", "seurat_annotations"))Session Info sessionInfo()## R version 4.1.0 (2021-05-18) ## Platform: x86_64-pc-linux-gnu (64-bit) ## Running under: Ubuntu 20.04.2 LTS ## ## Matrix products: default ## BLAS/LAPACK: /usr/lib/x86_64-linux-gnu/openblas-pthread/libopenblasp-r0.3.8.so ## ## locale: ## [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C ## [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8 ## [5] LC_MONETARY=en_US.UTF-8 LC_MESSAGES=C ## [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 ## ## attached base packages: ## [1] stats4 parallel stats graphics grDevices utils datasets ## [8] methods base ## ## other attached packages: ## [1] cowplot_1.1.1 ggplot2_3.3.5 ## [3] EnsDb.Hsapiens.v86_2.99.0 ensembldb_2.16.4 ## [5] AnnotationFilter_1.16.0 GenomicFeatures_1.44.0 ## [7] AnnotationDbi_1.54.1 Biobase_2.52.0 ## [9] GenomicRanges_1.44.0 GenomeInfoDb_1.28.1 ## [11] IRanges_2.26.0 S4Vectors_0.30.0 ## [13] BiocGenerics_0.38.0 Signac_1.3.0 ## [15] SeuratObject_4.0.2 Seurat_4.0.4 ## [17] thp1.eccite.SeuratData_3.1.5 stxBrain.SeuratData_0.1.1 ## [19] ssHippo.SeuratData_3.1.4 pbmcsca.SeuratData_3.0.0 ## [21] pbmcMultiome.SeuratData_0.1.1 pbmc3k.SeuratData_3.1.4 ## [23] panc8.SeuratData_3.0.2 ifnb.SeuratData_3.1.0 ## [25] hcabm40k.SeuratData_3.0.0 bmcite.SeuratData_0.3.0 ## [27] SeuratData_0.2.1 ## ## loaded via a namespace (and not attached): ## [1] rappdirs_0.3.3 SnowballC_0.7.0 ## [3] rtracklayer_1.52.0 scattermore_0.7 ## [5] ragg_1.1.3 tidyr_1.1.3 ## [7] bit64_4.0.5 knitr_1.33 ## [9] irlba_2.3.3 DelayedArray_0.18.0 ## [11] data.table_1.14.0 rpart_4.1-15 ## [13] KEGGREST_1.32.0 RCurl_1.98-1.3 ## [15] generics_0.1.0 RSQLite_2.2.7 ## [17] RANN_2.6.1 future_1.21.0 ## [19] bit_4.0.4 spatstat.data_2.1-0 ## [21] xml2_1.3.2 httpuv_1.6.1 ## [23] SummarizedExperiment_1.22.0 assertthat_0.2.1 ## [25] xfun_0.25 hms_1.1.0 ## [27] jquerylib_0.1.4 evaluate_0.14 ## [29] promises_1.2.0.1 fansi_0.5.0 ## [31] restfulr_0.0.13 progress_1.2.2 ## [33] dbplyr_2.1.1 igraph_1.2.6 ## [35] DBI_1.1.1 htmlwidgets_1.5.3 ## [37] sparsesvd_0.2 spatstat.geom_2.1-0 ## [39] purrr_0.3.4 ellipsis_0.3.2 ## [41] RSpectra_0.16-0 dplyr_1.0.7 ## [43] backports_1.2.1 biomaRt_2.48.2 ## [45] deldir_0.2-10 MatrixGenerics_1.4.2 ## [47] vctrs_0.3.8 ROCR_1.0-11 ## [49] abind_1.4-5 cachem_1.0.5 ## [51] withr_2.4.2 ggforce_0.3.3 ## [53] BSgenome_1.60.0 checkmate_2.0.0 ## [55] sctransform_0.3.2 GenomicAlignments_1.28.0 ## [57] prettyunits_1.1.1 goftest_1.2-2 ## [59] cluster_2.1.2 lazyeval_0.2.2 ## [61] crayon_1.4.1 labeling_0.4.2 ## [63] pkgconfig_2.0.3 slam_0.1-48 ## [65] tweenr_1.0.2 nlme_3.1-152 ## [67] ProtGenerics_1.24.0 nnet_7.3-16 ## [69] rlang_0.4.11 globals_0.14.0 ## [71] lifecycle_1.0.0 miniUI_0.1.1.1 ## [73] filelock_1.0.2 BiocFileCache_2.0.0 ## [75] dichromat_2.0-0 rprojroot_2.0.2 ## [77] polyclip_1.10-0 matrixStats_0.60.0 ## [79] lmtest_0.9-38 Matrix_1.3-3 ## [81] ggseqlogo_0.1 zoo_1.8-9 ## [83] base64enc_0.1-3 ggridges_0.5.3 ## [85] png_0.1-7 viridisLite_0.4.0 ## [87] rjson_0.2.20 bitops_1.0-7 ## [89] KernSmooth_2.23-20 Biostrings_2.60.2 ## [91] blob_1.2.2 stringr_1.4.0 ## [93] parallelly_1.26.0 jpeg_0.1-9 ## [95] scales_1.1.1 memoise_2.0.0 ## [97] magrittr_2.0.1 plyr_1.8.6 ## [99] ica_1.0-2 zlibbioc_1.38.0 ## [101] compiler_4.1.0 BiocIO_1.2.0 ## [103] RColorBrewer_1.1-2 fitdistrplus_1.1-5 ## [105] Rsamtools_2.8.0 cli_3.0.1 ## [107] XVector_0.32.0 listenv_0.8.0 ## [109] patchwork_1.1.1 pbapply_1.4-3 ## [111] htmlTable_2.2.1 formatR_1.11 ## [113] Formula_1.2-4 MASS_7.3-54 ## [115] mgcv_1.8-35 tidyselect_1.1.1 ## [117] stringi_1.7.3 textshaping_0.3.5 ## [119] highr_0.9 yaml_2.2.1 ## [121] latticeExtra_0.6-29 ggrepel_0.9.1 ## [123] grid_4.1.0 VariantAnnotation_1.38.0 ## [125] sass_0.4.0 fastmatch_1.1-3 ## [127] tools_4.1.0 future.apply_1.7.0 ## [129] rstudioapi_0.13 foreign_0.8-81 ## [131] lsa_0.73.2 gridExtra_2.3 ## [133] farver_2.1.0 Rtsne_0.15 ## [135] digest_0.6.27 shiny_1.6.0 ## [137] qlcMatrix_0.9.7 Rcpp_1.0.7 ## [139] later_1.2.0 RcppAnnoy_0.0.18 ## [141] httr_1.4.2 biovizBase_1.40.0 ## [143] colorspace_2.0-2 XML_3.99-0.6 ## [145] fs_1.5.0 tensor_1.5 ## [147] reticulate_1.20 splines_4.1.0 ## [149] uwot_0.1.10 RcppRoll_0.3.0 ## [151] spatstat.utils_2.1-0 pkgdown_1.6.1 ## [153] plotly_4.9.4 systemfonts_1.0.2 ## [155] xtable_1.8-4 jsonlite_1.7.2 ## [157] R6_2.5.0 Hmisc_4.5-0 ## [159] pillar_1.6.2 htmltools_0.5.1.1 ## [161] mime_0.11 glue_1.4.2 ## [163] fastmap_1.1.0 BiocParallel_1.26.1 ## [165] codetools_0.2-18 utf8_1.2.2 ## [167] lattice_0.20-44 bslib_0.2.5.1 ## [169] spatstat.sparse_2.0-0 tibble_3.1.3 ## [171] curl_4.3.2 leiden_0.3.8 ## [173] survival_3.2-11 rmarkdown_2.10 ## [175] docopt_0.7.1 desc_1.3.0 ## [177] munsell_0.5.0 GenomeInfoDbData_1.2.6 ## [179] reshape2_1.4.4 gtable_0.3.0 ## [181] spatstat.core_2.1-2

In Stuart*, Butler* et al, 2019, we introduce methods to integrate scRNA-seq and scATAC-seq datasets collected from the same biological system, and demonstrate these methods in this vignette. In particular, we demonstrate the following analyses:How to use an annotated scRNA-seq dataset to label cells from an scATAC-seq experimentHow to co-visualize (co-embed) cells from scRNA-seq and scATAC-seqHow to project scATAC-seq cells onto a UMAP derived from an scRNA-seq experimentThis vignette makes extensive use of the Signac package, recently developed for the analysis of chromatin datasets collected at single-cell resolution, including scATAC-seq. Please see the Signac website for additional vignettes and documentation for analyzing scATAC-seq data.We demonstrate these methods using a publicly available ~12,000 human PBMC ‘multiome’ dataset from 10x Genomics. In this dataset, scRNA-seq and scATAC-seq profiles were simultaneously collected in the same cells. For the purposes of this vignette, we treat the datasets as originating from two different experiments and integrate them together. Since they were originally measured in the same cells, this provides a ground truth that we can use to assess the accuracy of integration. We emphasize that our use of the multiome dataset here is for demonstration and evaluation purposes, and that users should apply these methods to scRNA-seq and scATAC-seq datasets that are collected separately. We provide a separate weighted nearest neighbors vignette (WNN) that describes analysis strategies for multi-omic single-cell data.Load in data and process each modality individuallyThe PBMC multiome dataset is available from 10x genomics. To facilitate easy loading and exploration, it is also available as part of our SeuratData package. We load the RNA and ATAC data in separately, and pretend that these profiles were measured in separate experiments. We annotated these cells in our WNN vignette, and the annotations are also included in SeuratData. library(SeuratData) # install the dataset and load requirements InstallData("pbmcMultiome") library(Seurat) library(Signac) library(EnsDb.Hsapiens.v86) library(ggplot2) library(cowplot) # load both modalities pbmc.rna <- LoadData("pbmcMultiome", "pbmc.rna") pbmc.atac <- LoadData("pbmcMultiome", "pbmc.atac") # repeat QC steps performed in the WNN vignette pbmc.rna <- subset(pbmc.rna, seurat_annotations != "filtered") pbmc.atac <- subset(pbmc.atac, seurat_annotations != "filtered") # Perform standard analysis of each modality independently RNA analysis pbmc.rna <- NormalizeData(pbmc.rna) pbmc.rna <- FindVariableFeatures(pbmc.rna) pbmc.rna <- ScaleData(pbmc.rna) pbmc.rna <- RunPCA(pbmc.rna) pbmc.rna <- RunUMAP(pbmc.rna, dims = 1:30) # ATAC analysis add gene annotation information annotations <- GetGRangesFromEnsDb(ensdb = EnsDb.Hsapiens.v86) seqlevelsStyle(annotations) <- "UCSC" genome(annotations) <- "hg38" Annotation(pbmc.atac) <- annotations # We exclude the first dimension as this is typically correlated with sequencing depth pbmc.atac <- RunTFIDF(pbmc.atac) pbmc.atac <- FindTopFeatures(pbmc.atac, min.cutoff = "q0") pbmc.atac <- RunSVD(pbmc.atac) pbmc.atac <- RunUMAP(pbmc.atac, reduction = "lsi", dims = 2:30, reduction.name = "umap.atac", reduction.key = "atacUMAP_")Now we plot the results from both modalities. Cells have been previously annotated based on transcriptomic state. We will predict annotations for the scATAC-seq cells. p1 <- DimPlot(pbmc.rna, group.by = "seurat_annotations", label = TRUE) + NoLegend() + ggtitle("RNA") p2 <- DimPlot(pbmc.atac, group.by = "orig.ident", label = FALSE) + NoLegend() + ggtitle("ATAC") p1 + p2Identifying anchors between scRNA-seq and scATAC-seq datasetsIn order to identify ‘anchors’ between scRNA-seq and scATAC-seq experiments, we first generate a rough estimate of the transcriptional activity of each gene by quantifying ATAC-seq counts in the 2 kb-upstream region and gene body, using the GeneActivity() function in the Signac package. The ensuing gene activity scores from the scATAC-seq data are then used as input for canonical correlation analysis, along with the gene expression quantifications from scRNA-seq. We perform this quantification for all genes identified as being highly variable from the scRNA-seq dataset. # quantify gene activity gene.activities <- GeneActivity(pbmc.atac, features = VariableFeatures(pbmc.rna)) # add gene activities as a new assay pbmc.atac[["ACTIVITY"]] <- CreateAssayObject(counts = gene.activities) # normalize gene activities DefaultAssay(pbmc.atac) <- "ACTIVITY" pbmc.atac <- NormalizeData(pbmc.atac) pbmc.atac <- ScaleData(pbmc.atac, features = rownames(pbmc.atac)) # Identify anchors transfer.anchors <- FindTransferAnchors(reference = pbmc.rna, query = pbmc.atac, features = VariableFeatures(object = pbmc.rna), reference.assay = "RNA", query.assay = "ACTIVITY", reduction = "cca")Annotate scATAC-seq cells via label transferAfter identifying anchors, we can transfer annotations from the scRNA-seq dataset onto the scATAC-seq cells. The annotations are stored in the seurat_annotations field, and are provided as input to the refdata parameter. The output will contain a matrix with predictions and confidence scores for each ATAC-seq cell. celltype.predictions <- TransferData(anchorset = transfer.anchors, refdata = pbmc.rna$seurat_annotations, weight.reduction = pbmc.atac[["lsi"]], dims = 2:30) pbmc.atac <- AddMetaData(pbmc.atac, metadata = celltype.predictions)Why do you choose different (non-default) values for reduction and weight.reduction?In FindTransferAnchors(), we typically project the PCA structure from the reference onto the query when transferring between scRNA-seq datasets. However, when transferring across modalities we find that CCA better captures the shared feature correlation structure and therefore set reduction = 'cca' here. Additionally, by default in TransferData() we use the same projected PCA structure to compute the weights of the local neighborhood of anchors that influence each cell’s prediction. In the case of scRNA-seq to scATAC-seq transfer, we use the low dimensional space learned by computing an LSI on the ATAC-seq data to compute these weights as this better captures the internal structure of the ATAC-seq data. After performing transfer, the ATAC-seq cells have predicted annotations (transferred from the scRNA-seq dataset) stored in the predicted.id field. Since these cells were measured with the multiome kit, we also have a ground-truth annotation that can be used for evaluation. You can see that the predicted and actual annotations are extremely similar. pbmc.atac$annotation_correct <- pbmc.atac$predicted.id == pbmc.atac$seurat_annotations p1 <- DimPlot(pbmc.atac, group.by = "predicted.id", label = TRUE) + NoLegend() + ggtitle("Predicted annotation") p2 <- DimPlot(pbmc.atac, group.by = "seurat_annotations", label = TRUE) + NoLegend() + ggtitle("Ground-truth annotation") p1 | p2In this example, the annotation for an scATAC-seq profile is correctly predicted via scRNA-seq integration ~90% of the time. In addition, the prediction.score.max field quantifies the uncertainty associated with our predicted annotations. We can see that cells that are correctly annotated are typically associated with high prediction scores (>90%), while cells that are incorrectly annotated are associated with sharply lower prediction scores (<50%). Incorrect assignments also tend to reflect closely related cell types (i.e. Intermediate vs. Naive B cells). predictions <- table(pbmc.atac$seurat_annotations, pbmc.atac$predicted.id) predictions <- predictions/rowSums(predictions) # normalize for number of cells in each cell type predictions <- as.data.frame(predictions) p1 <- ggplot(predictions, aes(Var1, Var2, fill = Freq)) + geom_tile() + scale_fill_gradient(name = "Fraction of cells", low = "#ffffc8", high = "#7d0025") + xlab("Cell type annotation (RNA)") + ylab("Predicted cell type label (ATAC)") + theme_cowplot() + theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust = 1)) correct <- length(which(pbmc.atac$seurat_annotations == pbmc.atac$predicted.id)) incorrect <- length(which(pbmc.atac$seurat_annotations != pbmc.atac$predicted.id)) data <- FetchData(pbmc.atac, vars = c("prediction.score.max", "annotation_correct")) p2 <- ggplot(data, aes(prediction.score.max, fill = annotation_correct, colour = annotation_correct)) + geom_density(alpha = 0.5) + theme_cowplot() + scale_fill_discrete(name = "Annotation Correct", labels = c(paste0("FALSE (n = ", incorrect, ")"), paste0("TRUE (n = ", correct, ")"))) + scale_color_discrete(name = "Annotation Correct", labels = c(paste0("FALSE (n = ", incorrect, ")"), paste0("TRUE (n = ", correct, ")"))) + xlab("Prediction Score") p1 + p2Co-embedding scRNA-seq and scATAC-seq datasetsIn addition to transferring labels across modalities, it is also possible to visualize scRNA-seq and scATAC-seq cells on the same plot. We emphasize that this step is primarily for visualization, and is an optional step. Typically, when we perform integrative analysis between scRNA-seq and scATAC-seq datasets, we focus primarily on label transfer as described above. We demonstrate our workflows for co-embedding below, and again highlight that this is for demonstration purposes, especially as in this particular case both the scRNA-seq profiles and scATAC-seq profiles were actually measured in the same cells.In order to perform co-embedding, we first ‘impute’ RNA expression into the scATAC-seq cells based on the previously computed anchors, and then merge the datasets. # note that we restrict the imputation to variable genes from scRNA-seq, but could impute the # full transcriptome if we wanted to genes.use <- VariableFeatures(pbmc.rna) refdata <- GetAssayData(pbmc.rna, assay = "RNA", slot = "data")[genes.use, ] # refdata (input) contains a scRNA-seq expression matrix for the scRNA-seq cells. imputation # (output) will contain an imputed scRNA-seq matrix for each of the ATAC cells imputation <- TransferData(anchorset = transfer.anchors, refdata = refdata, weight.reduction = pbmc.atac[["lsi"]], dims = 2:30) pbmc.atac[["RNA"]] <- imputation coembed <- merge(x = pbmc.rna, y = pbmc.atac) # Finally, we run PCA and UMAP on this combined object, to visualize the co-embedding of both # datasets coembed <- ScaleData(coembed, features = genes.use, do.scale = FALSE) coembed <- RunPCA(coembed, features = genes.use, verbose = FALSE) coembed <- RunUMAP(coembed, dims = 1:30) DimPlot(coembed, group.by = c("orig.ident", "seurat_annotations"))Session Info sessionInfo()## R version 4.1.0 (2021-05-18) ## Platform: x86_64-pc-linux-gnu (64-bit) ## Running under: Ubuntu 20.04.2 LTS ## ## Matrix products: default ## BLAS/LAPACK: /usr/lib/x86_64-linux-gnu/openblas-pthread/libopenblasp-r0.3.8.so ## ## locale: ## [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C ## [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8 ## [5] LC_MONETARY=en_US.UTF-8 LC_MESSAGES=C ## [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 ## ## attached base packages: ## [1] stats4 parallel stats graphics grDevices utils datasets ## [8] methods base ## ## other attached packages: ## [1] cowplot_1.1.1 ggplot2_3.3.5 ## [3] EnsDb.Hsapiens.v86_2.99.0 ensembldb_2.16.4 ## [5] AnnotationFilter_1.16.0 GenomicFeatures_1.44.0 ## [7] AnnotationDbi_1.54.1 Biobase_2.52.0 ## [9] GenomicRanges_1.44.0 GenomeInfoDb_1.28.1 ## [11] IRanges_2.26.0 S4Vectors_0.30.0 ## [13] BiocGenerics_0.38.0 Signac_1.3.0 ## [15] SeuratObject_4.0.2 Seurat_4.0.4 ## [17] thp1.eccite.SeuratData_3.1.5 stxBrain.SeuratData_0.1.1 ## [19] ssHippo.SeuratData_3.1.4 pbmcsca.SeuratData_3.0.0 ## [21] pbmcMultiome.SeuratData_0.1.1 pbmc3k.SeuratData_3.1.4 ## [23] panc8.SeuratData_3.0.2 ifnb.SeuratData_3.1.0 ## [25] hcabm40k.SeuratData_3.0.0 bmcite.SeuratData_0.3.0 ## [27] SeuratData_0.2.1 ## ## loaded via a namespace (and not attached): ## [1] rappdirs_0.3.3 SnowballC_0.7.0 ## [3] rtracklayer_1.52.0 scattermore_0.7 ## [5] ragg_1.1.3 tidyr_1.1.3 ## [7] bit64_4.0.5 knitr_1.33 ## [9] irlba_2.3.3 DelayedArray_0.18.0 ## [11] data.table_1.14.0 rpart_4.1-15 ## [13] KEGGREST_1.32.0 RCurl_1.98-1.3 ## [15] generics_0.1.0 RSQLite_2.2.7 ## [17] RANN_2.6.1 future_1.21.0 ## [19] bit_4.0.4 spatstat.data_2.1-0 ## [21] xml2_1.3.2 httpuv_1.6.1 ## [23] SummarizedExperiment_1.22.0 assertthat_0.2.1 ## [25] xfun_0.25 hms_1.1.0 ## [27] jquerylib_0.1.4 evaluate_0.14 ## [29] promises_1.2.0.1 fansi_0.5.0 ## [31] restfulr_0.0.13 progress_1.2.2 ## [33] dbplyr_2.1.1 igraph_1.2.6 ## [35] DBI_1.1.1 htmlwidgets_1.5.3 ## [37] sparsesvd_0.2 spatstat.geom_2.1-0 ## [39] purrr_0.3.4 ellipsis_0.3.2 ## [41] RSpectra_0.16-0 dplyr_1.0.7 ## [43] backports_1.2.1 biomaRt_2.48.2 ## [45] deldir_0.2-10 MatrixGenerics_1.4.2 ## [47] vctrs_0.3.8 ROCR_1.0-11 ## [49] abind_1.4-5 cachem_1.0.5 ## [51] withr_2.4.2 ggforce_0.3.3 ## [53] BSgenome_1.60.0 checkmate_2.0.0 ## [55] sctransform_0.3.2 GenomicAlignments_1.28.0 ## [57] prettyunits_1.1.1 goftest_1.2-2 ## [59] cluster_2.1.2 lazyeval_0.2.2 ## [61] crayon_1.4.1 labeling_0.4.2 ## [63] pkgconfig_2.0.3 slam_0.1-48 ## [65] tweenr_1.0.2 nlme_3.1-152 ## [67] ProtGenerics_1.24.0 nnet_7.3-16 ## [69] rlang_0.4.11 globals_0.14.0 ## [71] lifecycle_1.0.0 miniUI_0.1.1.1 ## [73] filelock_1.0.2 BiocFileCache_2.0.0 ## [75] dichromat_2.0-0 rprojroot_2.0.2 ## [77] polyclip_1.10-0 matrixStats_0.60.0 ## [79] lmtest_0.9-38 Matrix_1.3-3 ## [81] ggseqlogo_0.1 zoo_1.8-9 ## [83] base64enc_0.1-3 ggridges_0.5.3 ## [85] png_0.1-7 viridisLite_0.4.0 ## [87] rjson_0.2.20 bitops_1.0-7 ## [89] KernSmooth_2.23-20 Biostrings_2.60.2 ## [91] blob_1.2.2 stringr_1.4.0 ## [93] parallelly_1.26.0 jpeg_0.1-9 ## [95] scales_1.1.1 memoise_2.0.0 ## [97] magrittr_2.0.1 plyr_1.8.6 ## [99] ica_1.0-2 zlibbioc_1.38.0 ## [101] compiler_4.1.0 BiocIO_1.2.0 ## [103] RColorBrewer_1.1-2 fitdistrplus_1.1-5 ## [105] Rsamtools_2.8.0 cli_3.0.1 ## [107] XVector_0.32.0 listenv_0.8.0 ## [109] patchwork_1.1.1 pbapply_1.4-3 ## [111] htmlTable_2.2.1 formatR_1.11 ## [113] Formula_1.2-4 MASS_7.3-54 ## [115] mgcv_1.8-35 tidyselect_1.1.1 ## [117] stringi_1.7.3 textshaping_0.3.5 ## [119] highr_0.9 yaml_2.2.1 ## [121] latticeExtra_0.6-29 ggrepel_0.9.1 ## [123] grid_4.1.0 VariantAnnotation_1.38.0 ## [125] sass_0.4.0 fastmatch_1.1-3 ## [127] tools_4.1.0 future.apply_1.7.0 ## [129] rstudioapi_0.13 foreign_0.8-81 ## [131] lsa_0.73.2 gridExtra_2.3 ## [133] farver_2.1.0 Rtsne_0.15 ## [135] digest_0.6.27 shiny_1.6.0 ## [137] qlcMatrix_0.9.7 Rcpp_1.0.7 ## [139] later_1.2.0 RcppAnnoy_0.0.18 ## [141] httr_1.4.2 biovizBase_1.40.0 ## [143] colorspace_2.0-2 XML_3.99-0.6 ## [145] fs_1.5.0 tensor_1.5 ## [147] reticulate_1.20 splines_4.1.0 ## [149] uwot_0.1.10 RcppRoll_0.3.0 ## [151] spatstat.utils_2.1-0 pkgdown_1.6.1 ## [153] plotly_4.9.4 systemfonts_1.0.2 ## [155] xtable_1.8-4 jsonlite_1.7.2 ## [157] R6_2.5.0 Hmisc_4.5-0 ## [159] pillar_1.6.2 htmltools_0.5.1.1 ## [161] mime_0.11 glue_1.4.2 ## [163] fastmap_1.1.0 BiocParallel_1.26.1 ## [165] codetools_0.2-18 utf8_1.2.2 ## [167] lattice_0.20-44 bslib_0.2.5.1 ## [169] spatstat.sparse_2.0-0 tibble_3.1.3 ## [171] curl_4.3.2 leiden_0.3.8 ## [173] survival_3.2-11 rmarkdown_2.10 ## [175] docopt_0.7.1 desc_1.3.0 ## [177] munsell_0.5.0 GenomeInfoDbData_1.2.6 ## [179] reshape2_1.4.4 gtable_0.3.0 ## [181] spatstat.core_2.1-2

This vignette makes extensive use of the Signac package, recently developed for the analysis of chromatin datasets collected at single-cell resolution, including scATAC-seq. Please see the Signac website for additional vignettes and documentation for analyzing scATAC-seq data.We demonstrate these methods using a publicly available ~12,000 human PBMC ‘multiome’ dataset from 10x Genomics. In this dataset, scRNA-seq and scATAC-seq profiles were simultaneously collected in the same cells. For the purposes of this vignette, we treat the datasets as originating from two different experiments and integrate them together. Since they were originally measured in the same cells, this provides a ground truth that we can use to assess the accuracy of integration. We emphasize that our use of the multiome dataset here is for demonstration and evaluation purposes, and that users should apply these methods to scRNA-seq and scATAC-seq datasets that are collected separately. We provide a separate weighted nearest neighbors vignette (WNN) that describes analysis strategies for multi-omic single-cell data.Load in data and process each modality individuallyThe PBMC multiome dataset is available from 10x genomics. To facilitate easy loading and exploration, it is also available as part of our SeuratData package. We load the RNA and ATAC data in separately, and pretend that these profiles were measured in separate experiments. We annotated these cells in our WNN vignette, and the annotations are also included in SeuratData. library(SeuratData) # install the dataset and load requirements InstallData("pbmcMultiome") library(Seurat) library(Signac) library(EnsDb.Hsapiens.v86) library(ggplot2) library(cowplot) # load both modalities pbmc.rna <- LoadData("pbmcMultiome", "pbmc.rna") pbmc.atac <- LoadData("pbmcMultiome", "pbmc.atac") # repeat QC steps performed in the WNN vignette pbmc.rna <- subset(pbmc.rna, seurat_annotations != "filtered") pbmc.atac <- subset(pbmc.atac, seurat_annotations != "filtered") # Perform standard analysis of each modality independently RNA analysis pbmc.rna <- NormalizeData(pbmc.rna) pbmc.rna <- FindVariableFeatures(pbmc.rna) pbmc.rna <- ScaleData(pbmc.rna) pbmc.rna <- RunPCA(pbmc.rna) pbmc.rna <- RunUMAP(pbmc.rna, dims = 1:30) # ATAC analysis add gene annotation information annotations <- GetGRangesFromEnsDb(ensdb = EnsDb.Hsapiens.v86) seqlevelsStyle(annotations) <- "UCSC" genome(annotations) <- "hg38" Annotation(pbmc.atac) <- annotations # We exclude the first dimension as this is typically correlated with sequencing depth pbmc.atac <- RunTFIDF(pbmc.atac) pbmc.atac <- FindTopFeatures(pbmc.atac, min.cutoff = "q0") pbmc.atac <- RunSVD(pbmc.atac) pbmc.atac <- RunUMAP(pbmc.atac, reduction = "lsi", dims = 2:30, reduction.name = "umap.atac", reduction.key = "atacUMAP_")Now we plot the results from both modalities. Cells have been previously annotated based on transcriptomic state. We will predict annotations for the scATAC-seq cells. p1 <- DimPlot(pbmc.rna, group.by = "seurat_annotations", label = TRUE) + NoLegend() + ggtitle("RNA") p2 <- DimPlot(pbmc.atac, group.by = "orig.ident", label = FALSE) + NoLegend() + ggtitle("ATAC") p1 + p2Identifying anchors between scRNA-seq and scATAC-seq datasetsIn order to identify ‘anchors’ between scRNA-seq and scATAC-seq experiments, we first generate a rough estimate of the transcriptional activity of each gene by quantifying ATAC-seq counts in the 2 kb-upstream region and gene body, using the GeneActivity() function in the Signac package. The ensuing gene activity scores from the scATAC-seq data are then used as input for canonical correlation analysis, along with the gene expression quantifications from scRNA-seq. We perform this quantification for all genes identified as being highly variable from the scRNA-seq dataset. # quantify gene activity gene.activities <- GeneActivity(pbmc.atac, features = VariableFeatures(pbmc.rna)) # add gene activities as a new assay pbmc.atac[["ACTIVITY"]] <- CreateAssayObject(counts = gene.activities) # normalize gene activities DefaultAssay(pbmc.atac) <- "ACTIVITY" pbmc.atac <- NormalizeData(pbmc.atac) pbmc.atac <- ScaleData(pbmc.atac, features = rownames(pbmc.atac)) # Identify anchors transfer.anchors <- FindTransferAnchors(reference = pbmc.rna, query = pbmc.atac, features = VariableFeatures(object = pbmc.rna), reference.assay = "RNA", query.assay = "ACTIVITY", reduction = "cca")Annotate scATAC-seq cells via label transferAfter identifying anchors, we can transfer annotations from the scRNA-seq dataset onto the scATAC-seq cells. The annotations are stored in the seurat_annotations field, and are provided as input to the refdata parameter. The output will contain a matrix with predictions and confidence scores for each ATAC-seq cell. celltype.predictions <- TransferData(anchorset = transfer.anchors, refdata = pbmc.rna$seurat_annotations, weight.reduction = pbmc.atac[["lsi"]], dims = 2:30) pbmc.atac <- AddMetaData(pbmc.atac, metadata = celltype.predictions)Why do you choose different (non-default) values for reduction and weight.reduction?In FindTransferAnchors(), we typically project the PCA structure from the reference onto the query when transferring between scRNA-seq datasets. However, when transferring across modalities we find that CCA better captures the shared feature correlation structure and therefore set reduction = 'cca' here. Additionally, by default in TransferData() we use the same projected PCA structure to compute the weights of the local neighborhood of anchors that influence each cell’s prediction. In the case of scRNA-seq to scATAC-seq transfer, we use the low dimensional space learned by computing an LSI on the ATAC-seq data to compute these weights as this better captures the internal structure of the ATAC-seq data. After performing transfer, the ATAC-seq cells have predicted annotations (transferred from the scRNA-seq dataset) stored in the predicted.id field. Since these cells were measured with the multiome kit, we also have a ground-truth annotation that can be used for evaluation. You can see that the predicted and actual annotations are extremely similar. pbmc.atac$annotation_correct <- pbmc.atac$predicted.id == pbmc.atac$seurat_annotations p1 <- DimPlot(pbmc.atac, group.by = "predicted.id", label = TRUE) + NoLegend() + ggtitle("Predicted annotation") p2 <- DimPlot(pbmc.atac, group.by = "seurat_annotations", label = TRUE) + NoLegend() + ggtitle("Ground-truth annotation") p1 | p2In this example, the annotation for an scATAC-seq profile is correctly predicted via scRNA-seq integration ~90% of the time. In addition, the prediction.score.max field quantifies the uncertainty associated with our predicted annotations. We can see that cells that are correctly annotated are typically associated with high prediction scores (>90%), while cells that are incorrectly annotated are associated with sharply lower prediction scores (<50%). Incorrect assignments also tend to reflect closely related cell types (i.e. Intermediate vs. Naive B cells). predictions <- table(pbmc.atac$seurat_annotations, pbmc.atac$predicted.id) predictions <- predictions/rowSums(predictions) # normalize for number of cells in each cell type predictions <- as.data.frame(predictions) p1 <- ggplot(predictions, aes(Var1, Var2, fill = Freq)) + geom_tile() + scale_fill_gradient(name = "Fraction of cells", low = "#ffffc8", high = "#7d0025") + xlab("Cell type annotation (RNA)") + ylab("Predicted cell type label (ATAC)") + theme_cowplot() + theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust = 1)) correct <- length(which(pbmc.atac$seurat_annotations == pbmc.atac$predicted.id)) incorrect <- length(which(pbmc.atac$seurat_annotations != pbmc.atac$predicted.id)) data <- FetchData(pbmc.atac, vars = c("prediction.score.max", "annotation_correct")) p2 <- ggplot(data, aes(prediction.score.max, fill = annotation_correct, colour = annotation_correct)) + geom_density(alpha = 0.5) + theme_cowplot() + scale_fill_discrete(name = "Annotation Correct", labels = c(paste0("FALSE (n = ", incorrect, ")"), paste0("TRUE (n = ", correct, ")"))) + scale_color_discrete(name = "Annotation Correct", labels = c(paste0("FALSE (n = ", incorrect, ")"), paste0("TRUE (n = ", correct, ")"))) + xlab("Prediction Score") p1 + p2Co-embedding scRNA-seq and scATAC-seq datasetsIn addition to transferring labels across modalities, it is also possible to visualize scRNA-seq and scATAC-seq cells on the same plot. We emphasize that this step is primarily for visualization, and is an optional step. Typically, when we perform integrative analysis between scRNA-seq and scATAC-seq datasets, we focus primarily on label transfer as described above. We demonstrate our workflows for co-embedding below, and again highlight that this is for demonstration purposes, especially as in this particular case both the scRNA-seq profiles and scATAC-seq profiles were actually measured in the same cells.In order to perform co-embedding, we first ‘impute’ RNA expression into the scATAC-seq cells based on the previously computed anchors, and then merge the datasets. # note that we restrict the imputation to variable genes from scRNA-seq, but could impute the # full transcriptome if we wanted to genes.use <- VariableFeatures(pbmc.rna) refdata <- GetAssayData(pbmc.rna, assay = "RNA", slot = "data")[genes.use, ] # refdata (input) contains a scRNA-seq expression matrix for the scRNA-seq cells. imputation # (output) will contain an imputed scRNA-seq matrix for each of the ATAC cells imputation <- TransferData(anchorset = transfer.anchors, refdata = refdata, weight.reduction = pbmc.atac[["lsi"]], dims = 2:30) pbmc.atac[["RNA"]] <- imputation coembed <- merge(x = pbmc.rna, y = pbmc.atac) # Finally, we run PCA and UMAP on this combined object, to visualize the co-embedding of both # datasets coembed <- ScaleData(coembed, features = genes.use, do.scale = FALSE) coembed <- RunPCA(coembed, features = genes.use, verbose = FALSE) coembed <- RunUMAP(coembed, dims = 1:30) DimPlot(coembed, group.by = c("orig.ident", "seurat_annotations"))Session Info sessionInfo()## R version 4.1.0 (2021-05-18) ## Platform: x86_64-pc-linux-gnu (64-bit) ## Running under: Ubuntu 20.04.2 LTS ## ## Matrix products: default ## BLAS/LAPACK: /usr/lib/x86_64-linux-gnu/openblas-pthread/libopenblasp-r0.3.8.so ## ## locale: ## [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C ## [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8 ## [5] LC_MONETARY=en_US.UTF-8 LC_MESSAGES=C ## [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 ## ## attached base packages: ## [1] stats4 parallel stats graphics grDevices utils datasets ## [8] methods base ## ## other attached packages: ## [1] cowplot_1.1.1 ggplot2_3.3.5 ## [3] EnsDb.Hsapiens.v86_2.99.0 ensembldb_2.16.4 ## [5] AnnotationFilter_1.16.0 GenomicFeatures_1.44.0 ## [7] AnnotationDbi_1.54.1 Biobase_2.52.0 ## [9] GenomicRanges_1.44.0 GenomeInfoDb_1.28.1 ## [11] IRanges_2.26.0 S4Vectors_0.30.0 ## [13] BiocGenerics_0.38.0 Signac_1.3.0 ## [15] SeuratObject_4.0.2 Seurat_4.0.4 ## [17] thp1.eccite.SeuratData_3.1.5 stxBrain.SeuratData_0.1.1 ## [19] ssHippo.SeuratData_3.1.4 pbmcsca.SeuratData_3.0.0 ## [21] pbmcMultiome.SeuratData_0.1.1 pbmc3k.SeuratData_3.1.4 ## [23] panc8.SeuratData_3.0.2 ifnb.SeuratData_3.1.0 ## [25] hcabm40k.SeuratData_3.0.0 bmcite.SeuratData_0.3.0 ## [27] SeuratData_0.2.1 ## ## loaded via a namespace (and not attached): ## [1] rappdirs_0.3.3 SnowballC_0.7.0 ## [3] rtracklayer_1.52.0 scattermore_0.7 ## [5] ragg_1.1.3 tidyr_1.1.3 ## [7] bit64_4.0.5 knitr_1.33 ## [9] irlba_2.3.3 DelayedArray_0.18.0 ## [11] data.table_1.14.0 rpart_4.1-15 ## [13] KEGGREST_1.32.0 RCurl_1.98-1.3 ## [15] generics_0.1.0 RSQLite_2.2.7 ## [17] RANN_2.6.1 future_1.21.0 ## [19] bit_4.0.4 spatstat.data_2.1-0 ## [21] xml2_1.3.2 httpuv_1.6.1 ## [23] SummarizedExperiment_1.22.0 assertthat_0.2.1 ## [25] xfun_0.25 hms_1.1.0 ## [27] jquerylib_0.1.4 evaluate_0.14 ## [29] promises_1.2.0.1 fansi_0.5.0 ## [31] restfulr_0.0.13 progress_1.2.2 ## [33] dbplyr_2.1.1 igraph_1.2.6 ## [35] DBI_1.1.1 htmlwidgets_1.5.3 ## [37] sparsesvd_0.2 spatstat.geom_2.1-0 ## [39] purrr_0.3.4 ellipsis_0.3.2 ## [41] RSpectra_0.16-0 dplyr_1.0.7 ## [43] backports_1.2.1 biomaRt_2.48.2 ## [45] deldir_0.2-10 MatrixGenerics_1.4.2 ## [47] vctrs_0.3.8 ROCR_1.0-11 ## [49] abind_1.4-5 cachem_1.0.5 ## [51] withr_2.4.2 ggforce_0.3.3 ## [53] BSgenome_1.60.0 checkmate_2.0.0 ## [55] sctransform_0.3.2 GenomicAlignments_1.28.0 ## [57] prettyunits_1.1.1 goftest_1.2-2 ## [59] cluster_2.1.2 lazyeval_0.2.2 ## [61] crayon_1.4.1 labeling_0.4.2 ## [63] pkgconfig_2.0.3 slam_0.1-48 ## [65] tweenr_1.0.2 nlme_3.1-152 ## [67] ProtGenerics_1.24.0 nnet_7.3-16 ## [69] rlang_0.4.11 globals_0.14.0 ## [71] lifecycle_1.0.0 miniUI_0.1.1.1 ## [73] filelock_1.0.2 BiocFileCache_2.0.0 ## [75] dichromat_2.0-0 rprojroot_2.0.2 ## [77] polyclip_1.10-0 matrixStats_0.60.0 ## [79] lmtest_0.9-38 Matrix_1.3-3 ## [81] ggseqlogo_0.1 zoo_1.8-9 ## [83] base64enc_0.1-3 ggridges_0.5.3 ## [85] png_0.1-7 viridisLite_0.4.0 ## [87] rjson_0.2.20 bitops_1.0-7 ## [89] KernSmooth_2.23-20 Biostrings_2.60.2 ## [91] blob_1.2.2 stringr_1.4.0 ## [93] parallelly_1.26.0 jpeg_0.1-9 ## [95] scales_1.1.1 memoise_2.0.0 ## [97] magrittr_2.0.1 plyr_1.8.6 ## [99] ica_1.0-2 zlibbioc_1.38.0 ## [101] compiler_4.1.0 BiocIO_1.2.0 ## [103] RColorBrewer_1.1-2 fitdistrplus_1.1-5 ## [105] Rsamtools_2.8.0 cli_3.0.1 ## [107] XVector_0.32.0 listenv_0.8.0 ## [109] patchwork_1.1.1 pbapply_1.4-3 ## [111] htmlTable_2.2.1 formatR_1.11 ## [113] Formula_1.2-4 MASS_7.3-54 ## [115] mgcv_1.8-35 tidyselect_1.1.1 ## [117] stringi_1.7.3 textshaping_0.3.5 ## [119] highr_0.9 yaml_2.2.1 ## [121] latticeExtra_0.6-29 ggrepel_0.9.1 ## [123] grid_4.1.0 VariantAnnotation_1.38.0 ## [125] sass_0.4.0 fastmatch_1.1-3 ## [127] tools_4.1.0 future.apply_1.7.0 ## [129] rstudioapi_0.13 foreign_0.8-81 ## [131] lsa_0.73.2 gridExtra_2.3 ## [133] farver_2.1.0 Rtsne_0.15 ## [135] digest_0.6.27 shiny_1.6.0 ## [137] qlcMatrix_0.9.7 Rcpp_1.0.7 ## [139] later_1.2.0 RcppAnnoy_0.0.18 ## [141] httr_1.4.2 biovizBase_1.40.0 ## [143] colorspace_2.0-2 XML_3.99-0.6 ## [145] fs_1.5.0 tensor_1.5 ## [147] reticulate_1.20 splines_4.1.0 ## [149] uwot_0.1.10 RcppRoll_0.3.0 ## [151] spatstat.utils_2.1-0 pkgdown_1.6.1 ## [153] plotly_4.9.4 systemfonts_1.0.2 ## [155] xtable_1.8-4 jsonlite_1.7.2 ## [157] R6_2.5.0 Hmisc_4.5-0 ## [159] pillar_1.6.2 htmltools_0.5.1.1 ## [161] mime_0.11 glue_1.4.2 ## [163] fastmap_1.1.0 BiocParallel_1.26.1 ## [165] codetools_0.2-18 utf8_1.2.2 ## [167] lattice_0.20-44 bslib_0.2.5.1 ## [169] spatstat.sparse_2.0-0 tibble_3.1.3 ## [171] curl_4.3.2 leiden_0.3.8 ## [173] survival_3.2-11 rmarkdown_2.10 ## [175] docopt_0.7.1 desc_1.3.0 ## [177] munsell_0.5.0 GenomeInfoDbData_1.2.6 ## [179] reshape2_1.4.4 gtable_0.3.0 ## [181] spatstat.core_2.1-2

We demonstrate these methods using a publicly available ~12,000 human PBMC ‘multiome’ dataset from 10x Genomics. In this dataset, scRNA-seq and scATAC-seq profiles were simultaneously collected in the same cells. For the purposes of this vignette, we treat the datasets as originating from two different experiments and integrate them together. Since they were originally measured in the same cells, this provides a ground truth that we can use to assess the accuracy of integration. We emphasize that our use of the multiome dataset here is for demonstration and evaluation purposes, and that users should apply these methods to scRNA-seq and scATAC-seq datasets that are collected separately. We provide a separate weighted nearest neighbors vignette (WNN) that describes analysis strategies for multi-omic single-cell data.Load in data and process each modality individuallyThe PBMC multiome dataset is available from 10x genomics. To facilitate easy loading and exploration, it is also available as part of our SeuratData package. We load the RNA and ATAC data in separately, and pretend that these profiles were measured in separate experiments. We annotated these cells in our WNN vignette, and the annotations are also included in SeuratData. library(SeuratData) # install the dataset and load requirements InstallData("pbmcMultiome") library(Seurat) library(Signac) library(EnsDb.Hsapiens.v86) library(ggplot2) library(cowplot) # load both modalities pbmc.rna <- LoadData("pbmcMultiome", "pbmc.rna") pbmc.atac <- LoadData("pbmcMultiome", "pbmc.atac") # repeat QC steps performed in the WNN vignette pbmc.rna <- subset(pbmc.rna, seurat_annotations != "filtered") pbmc.atac <- subset(pbmc.atac, seurat_annotations != "filtered") # Perform standard analysis of each modality independently RNA analysis pbmc.rna <- NormalizeData(pbmc.rna) pbmc.rna <- FindVariableFeatures(pbmc.rna) pbmc.rna <- ScaleData(pbmc.rna) pbmc.rna <- RunPCA(pbmc.rna) pbmc.rna <- RunUMAP(pbmc.rna, dims = 1:30) # ATAC analysis add gene annotation information annotations <- GetGRangesFromEnsDb(ensdb = EnsDb.Hsapiens.v86) seqlevelsStyle(annotations) <- "UCSC" genome(annotations) <- "hg38" Annotation(pbmc.atac) <- annotations # We exclude the first dimension as this is typically correlated with sequencing depth pbmc.atac <- RunTFIDF(pbmc.atac) pbmc.atac <- FindTopFeatures(pbmc.atac, min.cutoff = "q0") pbmc.atac <- RunSVD(pbmc.atac) pbmc.atac <- RunUMAP(pbmc.atac, reduction = "lsi", dims = 2:30, reduction.name = "umap.atac", reduction.key = "atacUMAP_")Now we plot the results from both modalities. Cells have been previously annotated based on transcriptomic state. We will predict annotations for the scATAC-seq cells. p1 <- DimPlot(pbmc.rna, group.by = "seurat_annotations", label = TRUE) + NoLegend() + ggtitle("RNA") p2 <- DimPlot(pbmc.atac, group.by = "orig.ident", label = FALSE) + NoLegend() + ggtitle("ATAC") p1 + p2Identifying anchors between scRNA-seq and scATAC-seq datasetsIn order to identify ‘anchors’ between scRNA-seq and scATAC-seq experiments, we first generate a rough estimate of the transcriptional activity of each gene by quantifying ATAC-seq counts in the 2 kb-upstream region and gene body, using the GeneActivity() function in the Signac package. The ensuing gene activity scores from the scATAC-seq data are then used as input for canonical correlation analysis, along with the gene expression quantifications from scRNA-seq. We perform this quantification for all genes identified as being highly variable from the scRNA-seq dataset. # quantify gene activity gene.activities <- GeneActivity(pbmc.atac, features = VariableFeatures(pbmc.rna)) # add gene activities as a new assay pbmc.atac[["ACTIVITY"]] <- CreateAssayObject(counts = gene.activities) # normalize gene activities DefaultAssay(pbmc.atac) <- "ACTIVITY" pbmc.atac <- NormalizeData(pbmc.atac) pbmc.atac <- ScaleData(pbmc.atac, features = rownames(pbmc.atac)) # Identify anchors transfer.anchors <- FindTransferAnchors(reference = pbmc.rna, query = pbmc.atac, features = VariableFeatures(object = pbmc.rna), reference.assay = "RNA", query.assay = "ACTIVITY", reduction = "cca")Annotate scATAC-seq cells via label transferAfter identifying anchors, we can transfer annotations from the scRNA-seq dataset onto the scATAC-seq cells. The annotations are stored in the seurat_annotations field, and are provided as input to the refdata parameter. The output will contain a matrix with predictions and confidence scores for each ATAC-seq cell. celltype.predictions <- TransferData(anchorset = transfer.anchors, refdata = pbmc.rna$seurat_annotations, weight.reduction = pbmc.atac[["lsi"]], dims = 2:30) pbmc.atac <- AddMetaData(pbmc.atac, metadata = celltype.predictions)Why do you choose different (non-default) values for reduction and weight.reduction?In FindTransferAnchors(), we typically project the PCA structure from the reference onto the query when transferring between scRNA-seq datasets. However, when transferring across modalities we find that CCA better captures the shared feature correlation structure and therefore set reduction = 'cca' here. Additionally, by default in TransferData() we use the same projected PCA structure to compute the weights of the local neighborhood of anchors that influence each cell’s prediction. In the case of scRNA-seq to scATAC-seq transfer, we use the low dimensional space learned by computing an LSI on the ATAC-seq data to compute these weights as this better captures the internal structure of the ATAC-seq data. After performing transfer, the ATAC-seq cells have predicted annotations (transferred from the scRNA-seq dataset) stored in the predicted.id field. Since these cells were measured with the multiome kit, we also have a ground-truth annotation that can be used for evaluation. You can see that the predicted and actual annotations are extremely similar. pbmc.atac$annotation_correct <- pbmc.atac$predicted.id == pbmc.atac$seurat_annotations p1 <- DimPlot(pbmc.atac, group.by = "predicted.id", label = TRUE) + NoLegend() + ggtitle("Predicted annotation") p2 <- DimPlot(pbmc.atac, group.by = "seurat_annotations", label = TRUE) + NoLegend() + ggtitle("Ground-truth annotation") p1 | p2In this example, the annotation for an scATAC-seq profile is correctly predicted via scRNA-seq integration ~90% of the time. In addition, the prediction.score.max field quantifies the uncertainty associated with our predicted annotations. We can see that cells that are correctly annotated are typically associated with high prediction scores (>90%), while cells that are incorrectly annotated are associated with sharply lower prediction scores (<50%). Incorrect assignments also tend to reflect closely related cell types (i.e. Intermediate vs. Naive B cells). predictions <- table(pbmc.atac$seurat_annotations, pbmc.atac$predicted.id) predictions <- predictions/rowSums(predictions) # normalize for number of cells in each cell type predictions <- as.data.frame(predictions) p1 <- ggplot(predictions, aes(Var1, Var2, fill = Freq)) + geom_tile() + scale_fill_gradient(name = "Fraction of cells", low = "#ffffc8", high = "#7d0025") + xlab("Cell type annotation (RNA)") + ylab("Predicted cell type label (ATAC)") + theme_cowplot() + theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust = 1)) correct <- length(which(pbmc.atac$seurat_annotations == pbmc.atac$predicted.id)) incorrect <- length(which(pbmc.atac$seurat_annotations != pbmc.atac$predicted.id)) data <- FetchData(pbmc.atac, vars = c("prediction.score.max", "annotation_correct")) p2 <- ggplot(data, aes(prediction.score.max, fill = annotation_correct, colour = annotation_correct)) + geom_density(alpha = 0.5) + theme_cowplot() + scale_fill_discrete(name = "Annotation Correct", labels = c(paste0("FALSE (n = ", incorrect, ")"), paste0("TRUE (n = ", correct, ")"))) + scale_color_discrete(name = "Annotation Correct", labels = c(paste0("FALSE (n = ", incorrect, ")"), paste0("TRUE (n = ", correct, ")"))) + xlab("Prediction Score") p1 + p2Co-embedding scRNA-seq and scATAC-seq datasetsIn addition to transferring labels across modalities, it is also possible to visualize scRNA-seq and scATAC-seq cells on the same plot. We emphasize that this step is primarily for visualization, and is an optional step. Typically, when we perform integrative analysis between scRNA-seq and scATAC-seq datasets, we focus primarily on label transfer as described above. We demonstrate our workflows for co-embedding below, and again highlight that this is for demonstration purposes, especially as in this particular case both the scRNA-seq profiles and scATAC-seq profiles were actually measured in the same cells.In order to perform co-embedding, we first ‘impute’ RNA expression into the scATAC-seq cells based on the previously computed anchors, and then merge the datasets. # note that we restrict the imputation to variable genes from scRNA-seq, but could impute the # full transcriptome if we wanted to genes.use <- VariableFeatures(pbmc.rna) refdata <- GetAssayData(pbmc.rna, assay = "RNA", slot = "data")[genes.use, ] # refdata (input) contains a scRNA-seq expression matrix for the scRNA-seq cells. imputation # (output) will contain an imputed scRNA-seq matrix for each of the ATAC cells imputation <- TransferData(anchorset = transfer.anchors, refdata = refdata, weight.reduction = pbmc.atac[["lsi"]], dims = 2:30) pbmc.atac[["RNA"]] <- imputation coembed <- merge(x = pbmc.rna, y = pbmc.atac) # Finally, we run PCA and UMAP on this combined object, to visualize the co-embedding of both # datasets coembed <- ScaleData(coembed, features = genes.use, do.scale = FALSE) coembed <- RunPCA(coembed, features = genes.use, verbose = FALSE) coembed <- RunUMAP(coembed, dims = 1:30) DimPlot(coembed, group.by = c("orig.ident", "seurat_annotations"))Session Info sessionInfo()## R version 4.1.0 (2021-05-18) ## Platform: x86_64-pc-linux-gnu (64-bit) ## Running under: Ubuntu 20.04.2 LTS ## ## Matrix products: default ## BLAS/LAPACK: /usr/lib/x86_64-linux-gnu/openblas-pthread/libopenblasp-r0.3.8.so ## ## locale: ## [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C ## [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8 ## [5] LC_MONETARY=en_US.UTF-8 LC_MESSAGES=C ## [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 ## ## attached base packages: ## [1] stats4 parallel stats graphics grDevices utils datasets ## [8] methods base ## ## other attached packages: ## [1] cowplot_1.1.1 ggplot2_3.3.5 ## [3] EnsDb.Hsapiens.v86_2.99.0 ensembldb_2.16.4 ## [5] AnnotationFilter_1.16.0 GenomicFeatures_1.44.0 ## [7] AnnotationDbi_1.54.1 Biobase_2.52.0 ## [9] GenomicRanges_1.44.0 GenomeInfoDb_1.28.1 ## [11] IRanges_2.26.0 S4Vectors_0.30.0 ## [13] BiocGenerics_0.38.0 Signac_1.3.0 ## [15] SeuratObject_4.0.2 Seurat_4.0.4 ## [17] thp1.eccite.SeuratData_3.1.5 stxBrain.SeuratData_0.1.1 ## [19] ssHippo.SeuratData_3.1.4 pbmcsca.SeuratData_3.0.0 ## [21] pbmcMultiome.SeuratData_0.1.1 pbmc3k.SeuratData_3.1.4 ## [23] panc8.SeuratData_3.0.2 ifnb.SeuratData_3.1.0 ## [25] hcabm40k.SeuratData_3.0.0 bmcite.SeuratData_0.3.0 ## [27] SeuratData_0.2.1 ## ## loaded via a namespace (and not attached): ## [1] rappdirs_0.3.3 SnowballC_0.7.0 ## [3] rtracklayer_1.52.0 scattermore_0.7 ## [5] ragg_1.1.3 tidyr_1.1.3 ## [7] bit64_4.0.5 knitr_1.33 ## [9] irlba_2.3.3 DelayedArray_0.18.0 ## [11] data.table_1.14.0 rpart_4.1-15 ## [13] KEGGREST_1.32.0 RCurl_1.98-1.3 ## [15] generics_0.1.0 RSQLite_2.2.7 ## [17] RANN_2.6.1 future_1.21.0 ## [19] bit_4.0.4 spatstat.data_2.1-0 ## [21] xml2_1.3.2 httpuv_1.6.1 ## [23] SummarizedExperiment_1.22.0 assertthat_0.2.1 ## [25] xfun_0.25 hms_1.1.0 ## [27] jquerylib_0.1.4 evaluate_0.14 ## [29] promises_1.2.0.1 fansi_0.5.0 ## [31] restfulr_0.0.13 progress_1.2.2 ## [33] dbplyr_2.1.1 igraph_1.2.6 ## [35] DBI_1.1.1 htmlwidgets_1.5.3 ## [37] sparsesvd_0.2 spatstat.geom_2.1-0 ## [39] purrr_0.3.4 ellipsis_0.3.2 ## [41] RSpectra_0.16-0 dplyr_1.0.7 ## [43] backports_1.2.1 biomaRt_2.48.2 ## [45] deldir_0.2-10 MatrixGenerics_1.4.2 ## [47] vctrs_0.3.8 ROCR_1.0-11 ## [49] abind_1.4-5 cachem_1.0.5 ## [51] withr_2.4.2 ggforce_0.3.3 ## [53] BSgenome_1.60.0 checkmate_2.0.0 ## [55] sctransform_0.3.2 GenomicAlignments_1.28.0 ## [57] prettyunits_1.1.1 goftest_1.2-2 ## [59] cluster_2.1.2 lazyeval_0.2.2 ## [61] crayon_1.4.1 labeling_0.4.2 ## [63] pkgconfig_2.0.3 slam_0.1-48 ## [65] tweenr_1.0.2 nlme_3.1-152 ## [67] ProtGenerics_1.24.0 nnet_7.3-16 ## [69] rlang_0.4.11 globals_0.14.0 ## [71] lifecycle_1.0.0 miniUI_0.1.1.1 ## [73] filelock_1.0.2 BiocFileCache_2.0.0 ## [75] dichromat_2.0-0 rprojroot_2.0.2 ## [77] polyclip_1.10-0 matrixStats_0.60.0 ## [79] lmtest_0.9-38 Matrix_1.3-3 ## [81] ggseqlogo_0.1 zoo_1.8-9 ## [83] base64enc_0.1-3 ggridges_0.5.3 ## [85] png_0.1-7 viridisLite_0.4.0 ## [87] rjson_0.2.20 bitops_1.0-7 ## [89] KernSmooth_2.23-20 Biostrings_2.60.2 ## [91] blob_1.2.2 stringr_1.4.0 ## [93] parallelly_1.26.0 jpeg_0.1-9 ## [95] scales_1.1.1 memoise_2.0.0 ## [97] magrittr_2.0.1 plyr_1.8.6 ## [99] ica_1.0-2 zlibbioc_1.38.0 ## [101] compiler_4.1.0 BiocIO_1.2.0 ## [103] RColorBrewer_1.1-2 fitdistrplus_1.1-5 ## [105] Rsamtools_2.8.0 cli_3.0.1 ## [107] XVector_0.32.0 listenv_0.8.0 ## [109] patchwork_1.1.1 pbapply_1.4-3 ## [111] htmlTable_2.2.1 formatR_1.11 ## [113] Formula_1.2-4 MASS_7.3-54 ## [115] mgcv_1.8-35 tidyselect_1.1.1 ## [117] stringi_1.7.3 textshaping_0.3.5 ## [119] highr_0.9 yaml_2.2.1 ## [121] latticeExtra_0.6-29 ggrepel_0.9.1 ## [123] grid_4.1.0 VariantAnnotation_1.38.0 ## [125] sass_0.4.0 fastmatch_1.1-3 ## [127] tools_4.1.0 future.apply_1.7.0 ## [129] rstudioapi_0.13 foreign_0.8-81 ## [131] lsa_0.73.2 gridExtra_2.3 ## [133] farver_2.1.0 Rtsne_0.15 ## [135] digest_0.6.27 shiny_1.6.0 ## [137] qlcMatrix_0.9.7 Rcpp_1.0.7 ## [139] later_1.2.0 RcppAnnoy_0.0.18 ## [141] httr_1.4.2 biovizBase_1.40.0 ## [143] colorspace_2.0-2 XML_3.99-0.6 ## [145] fs_1.5.0 tensor_1.5 ## [147] reticulate_1.20 splines_4.1.0 ## [149] uwot_0.1.10 RcppRoll_0.3.0 ## [151] spatstat.utils_2.1-0 pkgdown_1.6.1 ## [153] plotly_4.9.4 systemfonts_1.0.2 ## [155] xtable_1.8-4 jsonlite_1.7.2 ## [157] R6_2.5.0 Hmisc_4.5-0 ## [159] pillar_1.6.2 htmltools_0.5.1.1 ## [161] mime_0.11 glue_1.4.2 ## [163] fastmap_1.1.0 BiocParallel_1.26.1 ## [165] codetools_0.2-18 utf8_1.2.2 ## [167] lattice_0.20-44 bslib_0.2.5.1 ## [169] spatstat.sparse_2.0-0 tibble_3.1.3 ## [171] curl_4.3.2 leiden_0.3.8 ## [173] survival_3.2-11 rmarkdown_2.10 ## [175] docopt_0.7.1 desc_1.3.0 ## [177] munsell_0.5.0 GenomeInfoDbData_1.2.6 ## [179] reshape2_1.4.4 gtable_0.3.0 ## [181] spatstat.core_2.1-2

The PBMC multiome dataset is available from 10x genomics. To facilitate easy loading and exploration, it is also available as part of our SeuratData package. We load the RNA and ATAC data in separately, and pretend that these profiles were measured in separate experiments. We annotated these cells in our WNN vignette, and the annotations are also included in SeuratData. library(SeuratData) # install the dataset and load requirements InstallData("pbmcMultiome") library(Seurat) library(Signac) library(EnsDb.Hsapiens.v86) library(ggplot2) library(cowplot) # load both modalities pbmc.rna <- LoadData("pbmcMultiome", "pbmc.rna") pbmc.atac <- LoadData("pbmcMultiome", "pbmc.atac") # repeat QC steps performed in the WNN vignette pbmc.rna <- subset(pbmc.rna, seurat_annotations != "filtered") pbmc.atac <- subset(pbmc.atac, seurat_annotations != "filtered") # Perform standard analysis of each modality independently RNA analysis pbmc.rna <- NormalizeData(pbmc.rna) pbmc.rna <- FindVariableFeatures(pbmc.rna) pbmc.rna <- ScaleData(pbmc.rna) pbmc.rna <- RunPCA(pbmc.rna) pbmc.rna <- RunUMAP(pbmc.rna, dims = 1:30) # ATAC analysis add gene annotation information annotations <- GetGRangesFromEnsDb(ensdb = EnsDb.Hsapiens.v86) seqlevelsStyle(annotations) <- "UCSC" genome(annotations) <- "hg38" Annotation(pbmc.atac) <- annotations # We exclude the first dimension as this is typically correlated with sequencing depth pbmc.atac <- RunTFIDF(pbmc.atac) pbmc.atac <- FindTopFeatures(pbmc.atac, min.cutoff = "q0") pbmc.atac <- RunSVD(pbmc.atac) pbmc.atac <- RunUMAP(pbmc.atac, reduction = "lsi", dims = 2:30, reduction.name = "umap.atac", reduction.key = "atacUMAP_")Now we plot the results from both modalities. Cells have been previously annotated based on transcriptomic state. We will predict annotations for the scATAC-seq cells. p1 <- DimPlot(pbmc.rna, group.by = "seurat_annotations", label = TRUE) + NoLegend() + ggtitle("RNA") p2 <- DimPlot(pbmc.atac, group.by = "orig.ident", label = FALSE) + NoLegend() + ggtitle("ATAC") p1 + p2

Now we plot the results from both modalities. Cells have been previously annotated based on transcriptomic state. We will predict annotations for the scATAC-seq cells. p1 <- DimPlot(pbmc.rna, group.by = "seurat_annotations", label = TRUE) + NoLegend() + ggtitle("RNA") p2 <- DimPlot(pbmc.atac, group.by = "orig.ident", label = FALSE) + NoLegend() + ggtitle("ATAC") p1 + p2

In order to identify ‘anchors’ between scRNA-seq and scATAC-seq experiments, we first generate a rough estimate of the transcriptional activity of each gene by quantifying ATAC-seq counts in the 2 kb-upstream region and gene body, using the GeneActivity() function in the Signac package. The ensuing gene activity scores from the scATAC-seq data are then used as input for canonical correlation analysis, along with the gene expression quantifications from scRNA-seq. We perform this quantification for all genes identified as being highly variable from the scRNA-seq dataset. # quantify gene activity gene.activities <- GeneActivity(pbmc.atac, features = VariableFeatures(pbmc.rna)) # add gene activities as a new assay pbmc.atac[["ACTIVITY"]] <- CreateAssayObject(counts = gene.activities) # normalize gene activities DefaultAssay(pbmc.atac) <- "ACTIVITY" pbmc.atac <- NormalizeData(pbmc.atac) pbmc.atac <- ScaleData(pbmc.atac, features = rownames(pbmc.atac)) # Identify anchors transfer.anchors <- FindTransferAnchors(reference = pbmc.rna, query = pbmc.atac, features = VariableFeatures(object = pbmc.rna), reference.assay = "RNA", query.assay = "ACTIVITY", reduction = "cca")

After identifying anchors, we can transfer annotations from the scRNA-seq dataset onto the scATAC-seq cells. The annotations are stored in the seurat_annotations field, and are provided as input to the refdata parameter. The output will contain a matrix with predictions and confidence scores for each ATAC-seq cell. celltype.predictions <- TransferData(anchorset = transfer.anchors, refdata = pbmc.rna$seurat_annotations, weight.reduction = pbmc.atac[["lsi"]], dims = 2:30) pbmc.atac <- AddMetaData(pbmc.atac, metadata = celltype.predictions)Why do you choose different (non-default) values for reduction and weight.reduction?In FindTransferAnchors(), we typically project the PCA structure from the reference onto the query when transferring between scRNA-seq datasets. However, when transferring across modalities we find that CCA better captures the shared feature correlation structure and therefore set reduction = 'cca' here. Additionally, by default in TransferData() we use the same projected PCA structure to compute the weights of the local neighborhood of anchors that influence each cell’s prediction. In the case of scRNA-seq to scATAC-seq transfer, we use the low dimensional space learned by computing an LSI on the ATAC-seq data to compute these weights as this better captures the internal structure of the ATAC-seq data. After performing transfer, the ATAC-seq cells have predicted annotations (transferred from the scRNA-seq dataset) stored in the predicted.id field. Since these cells were measured with the multiome kit, we also have a ground-truth annotation that can be used for evaluation. You can see that the predicted and actual annotations are extremely similar. pbmc.atac$annotation_correct <- pbmc.atac$predicted.id == pbmc.atac$seurat_annotations p1 <- DimPlot(pbmc.atac, group.by = "predicted.id", label = TRUE) + NoLegend() + ggtitle("Predicted annotation") p2 <- DimPlot(pbmc.atac, group.by = "seurat_annotations", label = TRUE) + NoLegend() + ggtitle("Ground-truth annotation") p1 | p2In this example, the annotation for an scATAC-seq profile is correctly predicted via scRNA-seq integration ~90% of the time. In addition, the prediction.score.max field quantifies the uncertainty associated with our predicted annotations. We can see that cells that are correctly annotated are typically associated with high prediction scores (>90%), while cells that are incorrectly annotated are associated with sharply lower prediction scores (<50%). Incorrect assignments also tend to reflect closely related cell types (i.e. Intermediate vs. Naive B cells). predictions <- table(pbmc.atac$seurat_annotations, pbmc.atac$predicted.id) predictions <- predictions/rowSums(predictions) # normalize for number of cells in each cell type predictions <- as.data.frame(predictions) p1 <- ggplot(predictions, aes(Var1, Var2, fill = Freq)) + geom_tile() + scale_fill_gradient(name = "Fraction of cells", low = "#ffffc8", high = "#7d0025") + xlab("Cell type annotation (RNA)") + ylab("Predicted cell type label (ATAC)") + theme_cowplot() + theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust = 1)) correct <- length(which(pbmc.atac$seurat_annotations == pbmc.atac$predicted.id)) incorrect <- length(which(pbmc.atac$seurat_annotations != pbmc.atac$predicted.id)) data <- FetchData(pbmc.atac, vars = c("prediction.score.max", "annotation_correct")) p2 <- ggplot(data, aes(prediction.score.max, fill = annotation_correct, colour = annotation_correct)) + geom_density(alpha = 0.5) + theme_cowplot() + scale_fill_discrete(name = "Annotation Correct", labels = c(paste0("FALSE (n = ", incorrect, ")"), paste0("TRUE (n = ", correct, ")"))) + scale_color_discrete(name = "Annotation Correct", labels = c(paste0("FALSE (n = ", incorrect, ")"), paste0("TRUE (n = ", correct, ")"))) + xlab("Prediction Score") p1 + p2

In FindTransferAnchors(), we typically project the PCA structure from the reference onto the query when transferring between scRNA-seq datasets. However, when transferring across modalities we find that CCA better captures the shared feature correlation structure and therefore set reduction = 'cca' here. Additionally, by default in TransferData() we use the same projected PCA structure to compute the weights of the local neighborhood of anchors that influence each cell’s prediction. In the case of scRNA-seq to scATAC-seq transfer, we use the low dimensional space learned by computing an LSI on the ATAC-seq data to compute these weights as this better captures the internal structure of the ATAC-seq data.

In FindTransferAnchors(), we typically project the PCA structure from the reference onto the query when transferring between scRNA-seq datasets. However, when transferring across modalities we find that CCA better captures the shared feature correlation structure and therefore set reduction = 'cca' here. Additionally, by default in TransferData() we use the same projected PCA structure to compute the weights of the local neighborhood of anchors that influence each cell’s prediction. In the case of scRNA-seq to scATAC-seq transfer, we use the low dimensional space learned by computing an LSI on the ATAC-seq data to compute these weights as this better captures the internal structure of the ATAC-seq data.

After performing transfer, the ATAC-seq cells have predicted annotations (transferred from the scRNA-seq dataset) stored in the predicted.id field. Since these cells were measured with the multiome kit, we also have a ground-truth annotation that can be used for evaluation. You can see that the predicted and actual annotations are extremely similar. pbmc.atac$annotation_correct <- pbmc.atac$predicted.id == pbmc.atac$seurat_annotations p1 <- DimPlot(pbmc.atac, group.by = "predicted.id", label = TRUE) + NoLegend() + ggtitle("Predicted annotation") p2 <- DimPlot(pbmc.atac, group.by = "seurat_annotations", label = TRUE) + NoLegend() + ggtitle("Ground-truth annotation") p1 | p2In this example, the annotation for an scATAC-seq profile is correctly predicted via scRNA-seq integration ~90% of the time. In addition, the prediction.score.max field quantifies the uncertainty associated with our predicted annotations. We can see that cells that are correctly annotated are typically associated with high prediction scores (>90%), while cells that are incorrectly annotated are associated with sharply lower prediction scores (<50%). Incorrect assignments also tend to reflect closely related cell types (i.e. Intermediate vs. Naive B cells). predictions <- table(pbmc.atac$seurat_annotations, pbmc.atac$predicted.id) predictions <- predictions/rowSums(predictions) # normalize for number of cells in each cell type predictions <- as.data.frame(predictions) p1 <- ggplot(predictions, aes(Var1, Var2, fill = Freq)) + geom_tile() + scale_fill_gradient(name = "Fraction of cells", low = "#ffffc8", high = "#7d0025") + xlab("Cell type annotation (RNA)") + ylab("Predicted cell type label (ATAC)") + theme_cowplot() + theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust = 1)) correct <- length(which(pbmc.atac$seurat_annotations == pbmc.atac$predicted.id)) incorrect <- length(which(pbmc.atac$seurat_annotations != pbmc.atac$predicted.id)) data <- FetchData(pbmc.atac, vars = c("prediction.score.max", "annotation_correct")) p2 <- ggplot(data, aes(prediction.score.max, fill = annotation_correct, colour = annotation_correct)) + geom_density(alpha = 0.5) + theme_cowplot() + scale_fill_discrete(name = "Annotation Correct", labels = c(paste0("FALSE (n = ", incorrect, ")"), paste0("TRUE (n = ", correct, ")"))) + scale_color_discrete(name = "Annotation Correct", labels = c(paste0("FALSE (n = ", incorrect, ")"), paste0("TRUE (n = ", correct, ")"))) + xlab("Prediction Score") p1 + p2

After performing transfer, the ATAC-seq cells have predicted annotations (transferred from the scRNA-seq dataset) stored in the predicted.id field. Since these cells were measured with the multiome kit, we also have a ground-truth annotation that can be used for evaluation. You can see that the predicted and actual annotations are extremely similar. pbmc.atac$annotation_correct <- pbmc.atac$predicted.id == pbmc.atac$seurat_annotations p1 <- DimPlot(pbmc.atac, group.by = "predicted.id", label = TRUE) + NoLegend() + ggtitle("Predicted annotation") p2 <- DimPlot(pbmc.atac, group.by = "seurat_annotations", label = TRUE) + NoLegend() + ggtitle("Ground-truth annotation") p1 | p2In this example, the annotation for an scATAC-seq profile is correctly predicted via scRNA-seq integration ~90% of the time. In addition, the prediction.score.max field quantifies the uncertainty associated with our predicted annotations. We can see that cells that are correctly annotated are typically associated with high prediction scores (>90%), while cells that are incorrectly annotated are associated with sharply lower prediction scores (<50%). Incorrect assignments also tend to reflect closely related cell types (i.e. Intermediate vs. Naive B cells). predictions <- table(pbmc.atac$seurat_annotations, pbmc.atac$predicted.id) predictions <- predictions/rowSums(predictions) # normalize for number of cells in each cell type predictions <- as.data.frame(predictions) p1 <- ggplot(predictions, aes(Var1, Var2, fill = Freq)) + geom_tile() + scale_fill_gradient(name = "Fraction of cells", low = "#ffffc8", high = "#7d0025") + xlab("Cell type annotation (RNA)") + ylab("Predicted cell type label (ATAC)") + theme_cowplot() + theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust = 1)) correct <- length(which(pbmc.atac$seurat_annotations == pbmc.atac$predicted.id)) incorrect <- length(which(pbmc.atac$seurat_annotations != pbmc.atac$predicted.id)) data <- FetchData(pbmc.atac, vars = c("prediction.score.max", "annotation_correct")) p2 <- ggplot(data, aes(prediction.score.max, fill = annotation_correct, colour = annotation_correct)) + geom_density(alpha = 0.5) + theme_cowplot() + scale_fill_discrete(name = "Annotation Correct", labels = c(paste0("FALSE (n = ", incorrect, ")"), paste0("TRUE (n = ", correct, ")"))) + scale_color_discrete(name = "Annotation Correct", labels = c(paste0("FALSE (n = ", incorrect, ")"), paste0("TRUE (n = ", correct, ")"))) + xlab("Prediction Score") p1 + p2

In this example, the annotation for an scATAC-seq profile is correctly predicted via scRNA-seq integration ~90% of the time. In addition, the prediction.score.max field quantifies the uncertainty associated with our predicted annotations. We can see that cells that are correctly annotated are typically associated with high prediction scores (>90%), while cells that are incorrectly annotated are associated with sharply lower prediction scores (<50%). Incorrect assignments also tend to reflect closely related cell types (i.e. Intermediate vs. Naive B cells). predictions <- table(pbmc.atac$seurat_annotations, pbmc.atac$predicted.id) predictions <- predictions/rowSums(predictions) # normalize for number of cells in each cell type predictions <- as.data.frame(predictions) p1 <- ggplot(predictions, aes(Var1, Var2, fill = Freq)) + geom_tile() + scale_fill_gradient(name = "Fraction of cells", low = "#ffffc8", high = "#7d0025") + xlab("Cell type annotation (RNA)") + ylab("Predicted cell type label (ATAC)") + theme_cowplot() + theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust = 1)) correct <- length(which(pbmc.atac$seurat_annotations == pbmc.atac$predicted.id)) incorrect <- length(which(pbmc.atac$seurat_annotations != pbmc.atac$predicted.id)) data <- FetchData(pbmc.atac, vars = c("prediction.score.max", "annotation_correct")) p2 <- ggplot(data, aes(prediction.score.max, fill = annotation_correct, colour = annotation_correct)) + geom_density(alpha = 0.5) + theme_cowplot() + scale_fill_discrete(name = "Annotation Correct", labels = c(paste0("FALSE (n = ", incorrect, ")"), paste0("TRUE (n = ", correct, ")"))) + scale_color_discrete(name = "Annotation Correct", labels = c(paste0("FALSE (n = ", incorrect, ")"), paste0("TRUE (n = ", correct, ")"))) + xlab("Prediction Score") p1 + p2

In this example, the annotation for an scATAC-seq profile is correctly predicted via scRNA-seq integration ~90% of the time. In addition, the prediction.score.max field quantifies the uncertainty associated with our predicted annotations. We can see that cells that are correctly annotated are typically associated with high prediction scores (>90%), while cells that are incorrectly annotated are associated with sharply lower prediction scores (<50%). Incorrect assignments also tend to reflect closely related cell types (i.e. Intermediate vs. Naive B cells). predictions <- table(pbmc.atac$seurat_annotations, pbmc.atac$predicted.id) predictions <- predictions/rowSums(predictions) # normalize for number of cells in each cell type predictions <- as.data.frame(predictions) p1 <- ggplot(predictions, aes(Var1, Var2, fill = Freq)) + geom_tile() + scale_fill_gradient(name = "Fraction of cells", low = "#ffffc8", high = "#7d0025") + xlab("Cell type annotation (RNA)") + ylab("Predicted cell type label (ATAC)") + theme_cowplot() + theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust = 1)) correct <- length(which(pbmc.atac$seurat_annotations == pbmc.atac$predicted.id)) incorrect <- length(which(pbmc.atac$seurat_annotations != pbmc.atac$predicted.id)) data <- FetchData(pbmc.atac, vars = c("prediction.score.max", "annotation_correct")) p2 <- ggplot(data, aes(prediction.score.max, fill = annotation_correct, colour = annotation_correct)) + geom_density(alpha = 0.5) + theme_cowplot() + scale_fill_discrete(name = "Annotation Correct", labels = c(paste0("FALSE (n = ", incorrect, ")"), paste0("TRUE (n = ", correct, ")"))) + scale_color_discrete(name = "Annotation Correct", labels = c(paste0("FALSE (n = ", incorrect, ")"), paste0("TRUE (n = ", correct, ")"))) + xlab("Prediction Score") p1 + p2

In addition to transferring labels across modalities, it is also possible to visualize scRNA-seq and scATAC-seq cells on the same plot. We emphasize that this step is primarily for visualization, and is an optional step. Typically, when we perform integrative analysis between scRNA-seq and scATAC-seq datasets, we focus primarily on label transfer as described above. We demonstrate our workflows for co-embedding below, and again highlight that this is for demonstration purposes, especially as in this particular case both the scRNA-seq profiles and scATAC-seq profiles were actually measured in the same cells.In order to perform co-embedding, we first ‘impute’ RNA expression into the scATAC-seq cells based on the previously computed anchors, and then merge the datasets. # note that we restrict the imputation to variable genes from scRNA-seq, but could impute the # full transcriptome if we wanted to genes.use <- VariableFeatures(pbmc.rna) refdata <- GetAssayData(pbmc.rna, assay = "RNA", slot = "data")[genes.use, ] # refdata (input) contains a scRNA-seq expression matrix for the scRNA-seq cells. imputation # (output) will contain an imputed scRNA-seq matrix for each of the ATAC cells imputation <- TransferData(anchorset = transfer.anchors, refdata = refdata, weight.reduction = pbmc.atac[["lsi"]], dims = 2:30) pbmc.atac[["RNA"]] <- imputation coembed <- merge(x = pbmc.rna, y = pbmc.atac) # Finally, we run PCA and UMAP on this combined object, to visualize the co-embedding of both # datasets coembed <- ScaleData(coembed, features = genes.use, do.scale = FALSE) coembed <- RunPCA(coembed, features = genes.use, verbose = FALSE) coembed <- RunUMAP(coembed, dims = 1:30) DimPlot(coembed, group.by = c("orig.ident", "seurat_annotations"))Session Info sessionInfo()## R version 4.1.0 (2021-05-18) ## Platform: x86_64-pc-linux-gnu (64-bit) ## Running under: Ubuntu 20.04.2 LTS ## ## Matrix products: default ## BLAS/LAPACK: /usr/lib/x86_64-linux-gnu/openblas-pthread/libopenblasp-r0.3.8.so ## ## locale: ## [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C ## [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8 ## [5] LC_MONETARY=en_US.UTF-8 LC_MESSAGES=C ## [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 ## ## attached base packages: ## [1] stats4 parallel stats graphics grDevices utils datasets ## [8] methods base ## ## other attached packages: ## [1] cowplot_1.1.1 ggplot2_3.3.5 ## [3] EnsDb.Hsapiens.v86_2.99.0 ensembldb_2.16.4 ## [5] AnnotationFilter_1.16.0 GenomicFeatures_1.44.0 ## [7] AnnotationDbi_1.54.1 Biobase_2.52.0 ## [9] GenomicRanges_1.44.0 GenomeInfoDb_1.28.1 ## [11] IRanges_2.26.0 S4Vectors_0.30.0 ## [13] BiocGenerics_0.38.0 Signac_1.3.0 ## [15] SeuratObject_4.0.2 Seurat_4.0.4 ## [17] thp1.eccite.SeuratData_3.1.5 stxBrain.SeuratData_0.1.1 ## [19] ssHippo.SeuratData_3.1.4 pbmcsca.SeuratData_3.0.0 ## [21] pbmcMultiome.SeuratData_0.1.1 pbmc3k.SeuratData_3.1.4 ## [23] panc8.SeuratData_3.0.2 ifnb.SeuratData_3.1.0 ## [25] hcabm40k.SeuratData_3.0.0 bmcite.SeuratData_0.3.0 ## [27] SeuratData_0.2.1 ## ## loaded via a namespace (and not attached): ## [1] rappdirs_0.3.3 SnowballC_0.7.0 ## [3] rtracklayer_1.52.0 scattermore_0.7 ## [5] ragg_1.1.3 tidyr_1.1.3 ## [7] bit64_4.0.5 knitr_1.33 ## [9] irlba_2.3.3 DelayedArray_0.18.0 ## [11] data.table_1.14.0 rpart_4.1-15 ## [13] KEGGREST_1.32.0 RCurl_1.98-1.3 ## [15] generics_0.1.0 RSQLite_2.2.7 ## [17] RANN_2.6.1 future_1.21.0 ## [19] bit_4.0.4 spatstat.data_2.1-0 ## [21] xml2_1.3.2 httpuv_1.6.1 ## [23] SummarizedExperiment_1.22.0 assertthat_0.2.1 ## [25] xfun_0.25 hms_1.1.0 ## [27] jquerylib_0.1.4 evaluate_0.14 ## [29] promises_1.2.0.1 fansi_0.5.0 ## [31] restfulr_0.0.13 progress_1.2.2 ## [33] dbplyr_2.1.1 igraph_1.2.6 ## [35] DBI_1.1.1 htmlwidgets_1.5.3 ## [37] sparsesvd_0.2 spatstat.geom_2.1-0 ## [39] purrr_0.3.4 ellipsis_0.3.2 ## [41] RSpectra_0.16-0 dplyr_1.0.7 ## [43] backports_1.2.1 biomaRt_2.48.2 ## [45] deldir_0.2-10 MatrixGenerics_1.4.2 ## [47] vctrs_0.3.8 ROCR_1.0-11 ## [49] abind_1.4-5 cachem_1.0.5 ## [51] withr_2.4.2 ggforce_0.3.3 ## [53] BSgenome_1.60.0 checkmate_2.0.0 ## [55] sctransform_0.3.2 GenomicAlignments_1.28.0 ## [57] prettyunits_1.1.1 goftest_1.2-2 ## [59] cluster_2.1.2 lazyeval_0.2.2 ## [61] crayon_1.4.1 labeling_0.4.2 ## [63] pkgconfig_2.0.3 slam_0.1-48 ## [65] tweenr_1.0.2 nlme_3.1-152 ## [67] ProtGenerics_1.24.0 nnet_7.3-16 ## [69] rlang_0.4.11 globals_0.14.0 ## [71] lifecycle_1.0.0 miniUI_0.1.1.1 ## [73] filelock_1.0.2 BiocFileCache_2.0.0 ## [75] dichromat_2.0-0 rprojroot_2.0.2 ## [77] polyclip_1.10-0 matrixStats_0.60.0 ## [79] lmtest_0.9-38 Matrix_1.3-3 ## [81] ggseqlogo_0.1 zoo_1.8-9 ## [83] base64enc_0.1-3 ggridges_0.5.3 ## [85] png_0.1-7 viridisLite_0.4.0 ## [87] rjson_0.2.20 bitops_1.0-7 ## [89] KernSmooth_2.23-20 Biostrings_2.60.2 ## [91] blob_1.2.2 stringr_1.4.0 ## [93] parallelly_1.26.0 jpeg_0.1-9 ## [95] scales_1.1.1 memoise_2.0.0 ## [97] magrittr_2.0.1 plyr_1.8.6 ## [99] ica_1.0-2 zlibbioc_1.38.0 ## [101] compiler_4.1.0 BiocIO_1.2.0 ## [103] RColorBrewer_1.1-2 fitdistrplus_1.1-5 ## [105] Rsamtools_2.8.0 cli_3.0.1 ## [107] XVector_0.32.0 listenv_0.8.0 ## [109] patchwork_1.1.1 pbapply_1.4-3 ## [111] htmlTable_2.2.1 formatR_1.11 ## [113] Formula_1.2-4 MASS_7.3-54 ## [115] mgcv_1.8-35 tidyselect_1.1.1 ## [117] stringi_1.7.3 textshaping_0.3.5 ## [119] highr_0.9 yaml_2.2.1 ## [121] latticeExtra_0.6-29 ggrepel_0.9.1 ## [123] grid_4.1.0 VariantAnnotation_1.38.0 ## [125] sass_0.4.0 fastmatch_1.1-3 ## [127] tools_4.1.0 future.apply_1.7.0 ## [129] rstudioapi_0.13 foreign_0.8-81 ## [131] lsa_0.73.2 gridExtra_2.3 ## [133] farver_2.1.0 Rtsne_0.15 ## [135] digest_0.6.27 shiny_1.6.0 ## [137] qlcMatrix_0.9.7 Rcpp_1.0.7 ## [139] later_1.2.0 RcppAnnoy_0.0.18 ## [141] httr_1.4.2 biovizBase_1.40.0 ## [143] colorspace_2.0-2 XML_3.99-0.6 ## [145] fs_1.5.0 tensor_1.5 ## [147] reticulate_1.20 splines_4.1.0 ## [149] uwot_0.1.10 RcppRoll_0.3.0 ## [151] spatstat.utils_2.1-0 pkgdown_1.6.1 ## [153] plotly_4.9.4 systemfonts_1.0.2 ## [155] xtable_1.8-4 jsonlite_1.7.2 ## [157] R6_2.5.0 Hmisc_4.5-0 ## [159] pillar_1.6.2 htmltools_0.5.1.1 ## [161] mime_0.11 glue_1.4.2 ## [163] fastmap_1.1.0 BiocParallel_1.26.1 ## [165] codetools_0.2-18 utf8_1.2.2 ## [167] lattice_0.20-44 bslib_0.2.5.1 ## [169] spatstat.sparse_2.0-0 tibble_3.1.3 ## [171] curl_4.3.2 leiden_0.3.8 ## [173] survival_3.2-11 rmarkdown_2.10 ## [175] docopt_0.7.1 desc_1.3.0 ## [177] munsell_0.5.0 GenomeInfoDbData_1.2.6 ## [179] reshape2_1.4.4 gtable_0.3.0 ## [181] spatstat.core_2.1-2

In order to perform co-embedding, we first ‘impute’ RNA expression into the scATAC-seq cells based on the previously computed anchors, and then merge the datasets. # note that we restrict the imputation to variable genes from scRNA-seq, but could impute the # full transcriptome if we wanted to genes.use <- VariableFeatures(pbmc.rna) refdata <- GetAssayData(pbmc.rna, assay = "RNA", slot = "data")[genes.use, ] # refdata (input) contains a scRNA-seq expression matrix for the scRNA-seq cells. imputation # (output) will contain an imputed scRNA-seq matrix for each of the ATAC cells imputation <- TransferData(anchorset = transfer.anchors, refdata = refdata, weight.reduction = pbmc.atac[["lsi"]], dims = 2:30) pbmc.atac[["RNA"]] <- imputation coembed <- merge(x = pbmc.rna, y = pbmc.atac) # Finally, we run PCA and UMAP on this combined object, to visualize the co-embedding of both # datasets coembed <- ScaleData(coembed, features = genes.use, do.scale = FALSE) coembed <- RunPCA(coembed, features = genes.use, verbose = FALSE) coembed <- RunUMAP(coembed, dims = 1:30) DimPlot(coembed, group.by = c("orig.ident", "seurat_annotations"))Session Info sessionInfo()## R version 4.1.0 (2021-05-18) ## Platform: x86_64-pc-linux-gnu (64-bit) ## Running under: Ubuntu 20.04.2 LTS ## ## Matrix products: default ## BLAS/LAPACK: /usr/lib/x86_64-linux-gnu/openblas-pthread/libopenblasp-r0.3.8.so ## ## locale: ## [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C ## [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8 ## [5] LC_MONETARY=en_US.UTF-8 LC_MESSAGES=C ## [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 ## ## attached base packages: ## [1] stats4 parallel stats graphics grDevices utils datasets ## [8] methods base ## ## other attached packages: ## [1] cowplot_1.1.1 ggplot2_3.3.5 ## [3] EnsDb.Hsapiens.v86_2.99.0 ensembldb_2.16.4 ## [5] AnnotationFilter_1.16.0 GenomicFeatures_1.44.0 ## [7] AnnotationDbi_1.54.1 Biobase_2.52.0 ## [9] GenomicRanges_1.44.0 GenomeInfoDb_1.28.1 ## [11] IRanges_2.26.0 S4Vectors_0.30.0 ## [13] BiocGenerics_0.38.0 Signac_1.3.0 ## [15] SeuratObject_4.0.2 Seurat_4.0.4 ## [17] thp1.eccite.SeuratData_3.1.5 stxBrain.SeuratData_0.1.1 ## [19] ssHippo.SeuratData_3.1.4 pbmcsca.SeuratData_3.0.0 ## [21] pbmcMultiome.SeuratData_0.1.1 pbmc3k.SeuratData_3.1.4 ## [23] panc8.SeuratData_3.0.2 ifnb.SeuratData_3.1.0 ## [25] hcabm40k.SeuratData_3.0.0 bmcite.SeuratData_0.3.0 ## [27] SeuratData_0.2.1 ## ## loaded via a namespace (and not attached): ## [1] rappdirs_0.3.3 SnowballC_0.7.0 ## [3] rtracklayer_1.52.0 scattermore_0.7 ## [5] ragg_1.1.3 tidyr_1.1.3 ## [7] bit64_4.0.5 knitr_1.33 ## [9] irlba_2.3.3 DelayedArray_0.18.0 ## [11] data.table_1.14.0 rpart_4.1-15 ## [13] KEGGREST_1.32.0 RCurl_1.98-1.3 ## [15] generics_0.1.0 RSQLite_2.2.7 ## [17] RANN_2.6.1 future_1.21.0 ## [19] bit_4.0.4 spatstat.data_2.1-0 ## [21] xml2_1.3.2 httpuv_1.6.1 ## [23] SummarizedExperiment_1.22.0 assertthat_0.2.1 ## [25] xfun_0.25 hms_1.1.0 ## [27] jquerylib_0.1.4 evaluate_0.14 ## [29] promises_1.2.0.1 fansi_0.5.0 ## [31] restfulr_0.0.13 progress_1.2.2 ## [33] dbplyr_2.1.1 igraph_1.2.6 ## [35] DBI_1.1.1 htmlwidgets_1.5.3 ## [37] sparsesvd_0.2 spatstat.geom_2.1-0 ## [39] purrr_0.3.4 ellipsis_0.3.2 ## [41] RSpectra_0.16-0 dplyr_1.0.7 ## [43] backports_1.2.1 biomaRt_2.48.2 ## [45] deldir_0.2-10 MatrixGenerics_1.4.2 ## [47] vctrs_0.3.8 ROCR_1.0-11 ## [49] abind_1.4-5 cachem_1.0.5 ## [51] withr_2.4.2 ggforce_0.3.3 ## [53] BSgenome_1.60.0 checkmate_2.0.0 ## [55] sctransform_0.3.2 GenomicAlignments_1.28.0 ## [57] prettyunits_1.1.1 goftest_1.2-2 ## [59] cluster_2.1.2 lazyeval_0.2.2 ## [61] crayon_1.4.1 labeling_0.4.2 ## [63] pkgconfig_2.0.3 slam_0.1-48 ## [65] tweenr_1.0.2 nlme_3.1-152 ## [67] ProtGenerics_1.24.0 nnet_7.3-16 ## [69] rlang_0.4.11 globals_0.14.0 ## [71] lifecycle_1.0.0 miniUI_0.1.1.1 ## [73] filelock_1.0.2 BiocFileCache_2.0.0 ## [75] dichromat_2.0-0 rprojroot_2.0.2 ## [77] polyclip_1.10-0 matrixStats_0.60.0 ## [79] lmtest_0.9-38 Matrix_1.3-3 ## [81] ggseqlogo_0.1 zoo_1.8-9 ## [83] base64enc_0.1-3 ggridges_0.5.3 ## [85] png_0.1-7 viridisLite_0.4.0 ## [87] rjson_0.2.20 bitops_1.0-7 ## [89] KernSmooth_2.23-20 Biostrings_2.60.2 ## [91] blob_1.2.2 stringr_1.4.0 ## [93] parallelly_1.26.0 jpeg_0.1-9 ## [95] scales_1.1.1 memoise_2.0.0 ## [97] magrittr_2.0.1 plyr_1.8.6 ## [99] ica_1.0-2 zlibbioc_1.38.0 ## [101] compiler_4.1.0 BiocIO_1.2.0 ## [103] RColorBrewer_1.1-2 fitdistrplus_1.1-5 ## [105] Rsamtools_2.8.0 cli_3.0.1 ## [107] XVector_0.32.0 listenv_0.8.0 ## [109] patchwork_1.1.1 pbapply_1.4-3 ## [111] htmlTable_2.2.1 formatR_1.11 ## [113] Formula_1.2-4 MASS_7.3-54 ## [115] mgcv_1.8-35 tidyselect_1.1.1 ## [117] stringi_1.7.3 textshaping_0.3.5 ## [119] highr_0.9 yaml_2.2.1 ## [121] latticeExtra_0.6-29 ggrepel_0.9.1 ## [123] grid_4.1.0 VariantAnnotation_1.38.0 ## [125] sass_0.4.0 fastmatch_1.1-3 ## [127] tools_4.1.0 future.apply_1.7.0 ## [129] rstudioapi_0.13 foreign_0.8-81 ## [131] lsa_0.73.2 gridExtra_2.3 ## [133] farver_2.1.0 Rtsne_0.15 ## [135] digest_0.6.27 shiny_1.6.0 ## [137] qlcMatrix_0.9.7 Rcpp_1.0.7 ## [139] later_1.2.0 RcppAnnoy_0.0.18 ## [141] httr_1.4.2 biovizBase_1.40.0 ## [143] colorspace_2.0-2 XML_3.99-0.6 ## [145] fs_1.5.0 tensor_1.5 ## [147] reticulate_1.20 splines_4.1.0 ## [149] uwot_0.1.10 RcppRoll_0.3.0 ## [151] spatstat.utils_2.1-0 pkgdown_1.6.1 ## [153] plotly_4.9.4 systemfonts_1.0.2 ## [155] xtable_1.8-4 jsonlite_1.7.2 ## [157] R6_2.5.0 Hmisc_4.5-0 ## [159] pillar_1.6.2 htmltools_0.5.1.1 ## [161] mime_0.11 glue_1.4.2 ## [163] fastmap_1.1.0 BiocParallel_1.26.1 ## [165] codetools_0.2-18 utf8_1.2.2 ## [167] lattice_0.20-44 bslib_0.2.5.1 ## [169] spatstat.sparse_2.0-0 tibble_3.1.3 ## [171] curl_4.3.2 leiden_0.3.8 ## [173] survival_3.2-11 rmarkdown_2.10 ## [175] docopt_0.7.1 desc_1.3.0 ## [177] munsell_0.5.0 GenomeInfoDbData_1.2.6 ## [179] reshape2_1.4.4 gtable_0.3.0 ## [181] spatstat.core_2.1-2

Session Info sessionInfo()## R version 4.1.0 (2021-05-18) ## Platform: x86_64-pc-linux-gnu (64-bit) ## Running under: Ubuntu 20.04.2 LTS ## ## Matrix products: default ## BLAS/LAPACK: /usr/lib/x86_64-linux-gnu/openblas-pthread/libopenblasp-r0.3.8.so ## ## locale: ## [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C ## [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8 ## [5] LC_MONETARY=en_US.UTF-8 LC_MESSAGES=C ## [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 ## ## attached base packages: ## [1] stats4 parallel stats graphics grDevices utils datasets ## [8] methods base ## ## other attached packages: ## [1] cowplot_1.1.1 ggplot2_3.3.5 ## [3] EnsDb.Hsapiens.v86_2.99.0 ensembldb_2.16.4 ## [5] AnnotationFilter_1.16.0 GenomicFeatures_1.44.0 ## [7] AnnotationDbi_1.54.1 Biobase_2.52.0 ## [9] GenomicRanges_1.44.0 GenomeInfoDb_1.28.1 ## [11] IRanges_2.26.0 S4Vectors_0.30.0 ## [13] BiocGenerics_0.38.0 Signac_1.3.0 ## [15] SeuratObject_4.0.2 Seurat_4.0.4 ## [17] thp1.eccite.SeuratData_3.1.5 stxBrain.SeuratData_0.1.1 ## [19] ssHippo.SeuratData_3.1.4 pbmcsca.SeuratData_3.0.0 ## [21] pbmcMultiome.SeuratData_0.1.1 pbmc3k.SeuratData_3.1.4 ## [23] panc8.SeuratData_3.0.2 ifnb.SeuratData_3.1.0 ## [25] hcabm40k.SeuratData_3.0.0 bmcite.SeuratData_0.3.0 ## [27] SeuratData_0.2.1 ## ## loaded via a namespace (and not attached): ## [1] rappdirs_0.3.3 SnowballC_0.7.0 ## [3] rtracklayer_1.52.0 scattermore_0.7 ## [5] ragg_1.1.3 tidyr_1.1.3 ## [7] bit64_4.0.5 knitr_1.33 ## [9] irlba_2.3.3 DelayedArray_0.18.0 ## [11] data.table_1.14.0 rpart_4.1-15 ## [13] KEGGREST_1.32.0 RCurl_1.98-1.3 ## [15] generics_0.1.0 RSQLite_2.2.7 ## [17] RANN_2.6.1 future_1.21.0 ## [19] bit_4.0.4 spatstat.data_2.1-0 ## [21] xml2_1.3.2 httpuv_1.6.1 ## [23] SummarizedExperiment_1.22.0 assertthat_0.2.1 ## [25] xfun_0.25 hms_1.1.0 ## [27] jquerylib_0.1.4 evaluate_0.14 ## [29] promises_1.2.0.1 fansi_0.5.0 ## [31] restfulr_0.0.13 progress_1.2.2 ## [33] dbplyr_2.1.1 igraph_1.2.6 ## [35] DBI_1.1.1 htmlwidgets_1.5.3 ## [37] sparsesvd_0.2 spatstat.geom_2.1-0 ## [39] purrr_0.3.4 ellipsis_0.3.2 ## [41] RSpectra_0.16-0 dplyr_1.0.7 ## [43] backports_1.2.1 biomaRt_2.48.2 ## [45] deldir_0.2-10 MatrixGenerics_1.4.2 ## [47] vctrs_0.3.8 ROCR_1.0-11 ## [49] abind_1.4-5 cachem_1.0.5 ## [51] withr_2.4.2 ggforce_0.3.3 ## [53] BSgenome_1.60.0 checkmate_2.0.0 ## [55] sctransform_0.3.2 GenomicAlignments_1.28.0 ## [57] prettyunits_1.1.1 goftest_1.2-2 ## [59] cluster_2.1.2 lazyeval_0.2.2 ## [61] crayon_1.4.1 labeling_0.4.2 ## [63] pkgconfig_2.0.3 slam_0.1-48 ## [65] tweenr_1.0.2 nlme_3.1-152 ## [67] ProtGenerics_1.24.0 nnet_7.3-16 ## [69] rlang_0.4.11 globals_0.14.0 ## [71] lifecycle_1.0.0 miniUI_0.1.1.1 ## [73] filelock_1.0.2 BiocFileCache_2.0.0 ## [75] dichromat_2.0-0 rprojroot_2.0.2 ## [77] polyclip_1.10-0 matrixStats_0.60.0 ## [79] lmtest_0.9-38 Matrix_1.3-3 ## [81] ggseqlogo_0.1 zoo_1.8-9 ## [83] base64enc_0.1-3 ggridges_0.5.3 ## [85] png_0.1-7 viridisLite_0.4.0 ## [87] rjson_0.2.20 bitops_1.0-7 ## [89] KernSmooth_2.23-20 Biostrings_2.60.2 ## [91] blob_1.2.2 stringr_1.4.0 ## [93] parallelly_1.26.0 jpeg_0.1-9 ## [95] scales_1.1.1 memoise_2.0.0 ## [97] magrittr_2.0.1 plyr_1.8.6 ## [99] ica_1.0-2 zlibbioc_1.38.0 ## [101] compiler_4.1.0 BiocIO_1.2.0 ## [103] RColorBrewer_1.1-2 fitdistrplus_1.1-5 ## [105] Rsamtools_2.8.0 cli_3.0.1 ## [107] XVector_0.32.0 listenv_0.8.0 ## [109] patchwork_1.1.1 pbapply_1.4-3 ## [111] htmlTable_2.2.1 formatR_1.11 ## [113] Formula_1.2-4 MASS_7.3-54 ## [115] mgcv_1.8-35 tidyselect_1.1.1 ## [117] stringi_1.7.3 textshaping_0.3.5 ## [119] highr_0.9 yaml_2.2.1 ## [121] latticeExtra_0.6-29 ggrepel_0.9.1 ## [123] grid_4.1.0 VariantAnnotation_1.38.0 ## [125] sass_0.4.0 fastmatch_1.1-3 ## [127] tools_4.1.0 future.apply_1.7.0 ## [129] rstudioapi_0.13 foreign_0.8-81 ## [131] lsa_0.73.2 gridExtra_2.3 ## [133] farver_2.1.0 Rtsne_0.15 ## [135] digest_0.6.27 shiny_1.6.0 ## [137] qlcMatrix_0.9.7 Rcpp_1.0.7 ## [139] later_1.2.0 RcppAnnoy_0.0.18 ## [141] httr_1.4.2 biovizBase_1.40.0 ## [143] colorspace_2.0-2 XML_3.99-0.6 ## [145] fs_1.5.0 tensor_1.5 ## [147] reticulate_1.20 splines_4.1.0 ## [149] uwot_0.1.10 RcppRoll_0.3.0 ## [151] spatstat.utils_2.1-0 pkgdown_1.6.1 ## [153] plotly_4.9.4 systemfonts_1.0.2 ## [155] xtable_1.8-4 jsonlite_1.7.2 ## [157] R6_2.5.0 Hmisc_4.5-0 ## [159] pillar_1.6.2 htmltools_0.5.1.1 ## [161] mime_0.11 glue_1.4.2 ## [163] fastmap_1.1.0 BiocParallel_1.26.1 ## [165] codetools_0.2-18 utf8_1.2.2 ## [167] lattice_0.20-44 bslib_0.2.5.1 ## [169] spatstat.sparse_2.0-0 tibble_3.1.3 ## [171] curl_4.3.2 leiden_0.3.8 ## [173] survival_3.2-11 rmarkdown_2.10 ## [175] docopt_0.7.1 desc_1.3.0 ## [177] munsell_0.5.0 GenomeInfoDbData_1.2.6 ## [179] reshape2_1.4.4 gtable_0.3.0 ## [181] spatstat.core_2.1-2

sessionInfo()## R version 4.1.0 (2021-05-18) ## Platform: x86_64-pc-linux-gnu (64-bit) ## Running under: Ubuntu 20.04.2 LTS ## ## Matrix products: default ## BLAS/LAPACK: /usr/lib/x86_64-linux-gnu/openblas-pthread/libopenblasp-r0.3.8.so ## ## locale: ## [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C ## [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8 ## [5] LC_MONETARY=en_US.UTF-8 LC_MESSAGES=C ## [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 ## ## attached base packages: ## [1] stats4 parallel stats graphics grDevices utils datasets ## [8] methods base ## ## other attached packages: ## [1] cowplot_1.1.1 ggplot2_3.3.5 ## [3] EnsDb.Hsapiens.v86_2.99.0 ensembldb_2.16.4 ## [5] AnnotationFilter_1.16.0 GenomicFeatures_1.44.0 ## [7] AnnotationDbi_1.54.1 Biobase_2.52.0 ## [9] GenomicRanges_1.44.0 GenomeInfoDb_1.28.1 ## [11] IRanges_2.26.0 S4Vectors_0.30.0 ## [13] BiocGenerics_0.38.0 Signac_1.3.0 ## [15] SeuratObject_4.0.2 Seurat_4.0.4 ## [17] thp1.eccite.SeuratData_3.1.5 stxBrain.SeuratData_0.1.1 ## [19] ssHippo.SeuratData_3.1.4 pbmcsca.SeuratData_3.0.0 ## [21] pbmcMultiome.SeuratData_0.1.1 pbmc3k.SeuratData_3.1.4 ## [23] panc8.SeuratData_3.0.2 ifnb.SeuratData_3.1.0 ## [25] hcabm40k.SeuratData_3.0.0 bmcite.SeuratData_0.3.0 ## [27] SeuratData_0.2.1 ## ## loaded via a namespace (and not attached): ## [1] rappdirs_0.3.3 SnowballC_0.7.0 ## [3] rtracklayer_1.52.0 scattermore_0.7 ## [5] ragg_1.1.3 tidyr_1.1.3 ## [7] bit64_4.0.5 knitr_1.33 ## [9] irlba_2.3.3 DelayedArray_0.18.0 ## [11] data.table_1.14.0 rpart_4.1-15 ## [13] KEGGREST_1.32.0 RCurl_1.98-1.3 ## [15] generics_0.1.0 RSQLite_2.2.7 ## [17] RANN_2.6.1 future_1.21.0 ## [19] bit_4.0.4 spatstat.data_2.1-0 ## [21] xml2_1.3.2 httpuv_1.6.1 ## [23] SummarizedExperiment_1.22.0 assertthat_0.2.1 ## [25] xfun_0.25 hms_1.1.0 ## [27] jquerylib_0.1.4 evaluate_0.14 ## [29] promises_1.2.0.1 fansi_0.5.0 ## [31] restfulr_0.0.13 progress_1.2.2 ## [33] dbplyr_2.1.1 igraph_1.2.6 ## [35] DBI_1.1.1 htmlwidgets_1.5.3 ## [37] sparsesvd_0.2 spatstat.geom_2.1-0 ## [39] purrr_0.3.4 ellipsis_0.3.2 ## [41] RSpectra_0.16-0 dplyr_1.0.7 ## [43] backports_1.2.1 biomaRt_2.48.2 ## [45] deldir_0.2-10 MatrixGenerics_1.4.2 ## [47] vctrs_0.3.8 ROCR_1.0-11 ## [49] abind_1.4-5 cachem_1.0.5 ## [51] withr_2.4.2 ggforce_0.3.3 ## [53] BSgenome_1.60.0 checkmate_2.0.0 ## [55] sctransform_0.3.2 GenomicAlignments_1.28.0 ## [57] prettyunits_1.1.1 goftest_1.2-2 ## [59] cluster_2.1.2 lazyeval_0.2.2 ## [61] crayon_1.4.1 labeling_0.4.2 ## [63] pkgconfig_2.0.3 slam_0.1-48 ## [65] tweenr_1.0.2 nlme_3.1-152 ## [67] ProtGenerics_1.24.0 nnet_7.3-16 ## [69] rlang_0.4.11 globals_0.14.0 ## [71] lifecycle_1.0.0 miniUI_0.1.1.1 ## [73] filelock_1.0.2 BiocFileCache_2.0.0 ## [75] dichromat_2.0-0 rprojroot_2.0.2 ## [77] polyclip_1.10-0 matrixStats_0.60.0 ## [79] lmtest_0.9-38 Matrix_1.3-3 ## [81] ggseqlogo_0.1 zoo_1.8-9 ## [83] base64enc_0.1-3 ggridges_0.5.3 ## [85] png_0.1-7 viridisLite_0.4.0 ## [87] rjson_0.2.20 bitops_1.0-7 ## [89] KernSmooth_2.23-20 Biostrings_2.60.2 ## [91] blob_1.2.2 stringr_1.4.0 ## [93] parallelly_1.26.0 jpeg_0.1-9 ## [95] scales_1.1.1 memoise_2.0.0 ## [97] magrittr_2.0.1 plyr_1.8.6 ## [99] ica_1.0-2 zlibbioc_1.38.0 ## [101] compiler_4.1.0 BiocIO_1.2.0 ## [103] RColorBrewer_1.1-2 fitdistrplus_1.1-5 ## [105] Rsamtools_2.8.0 cli_3.0.1 ## [107] XVector_0.32.0 listenv_0.8.0 ## [109] patchwork_1.1.1 pbapply_1.4-3 ## [111] htmlTable_2.2.1 formatR_1.11 ## [113] Formula_1.2-4 MASS_7.3-54 ## [115] mgcv_1.8-35 tidyselect_1.1.1 ## [117] stringi_1.7.3 textshaping_0.3.5 ## [119] highr_0.9 yaml_2.2.1 ## [121] latticeExtra_0.6-29 ggrepel_0.9.1 ## [123] grid_4.1.0 VariantAnnotation_1.38.0 ## [125] sass_0.4.0 fastmatch_1.1-3 ## [127] tools_4.1.0 future.apply_1.7.0 ## [129] rstudioapi_0.13 foreign_0.8-81 ## [131] lsa_0.73.2 gridExtra_2.3 ## [133] farver_2.1.0 Rtsne_0.15 ## [135] digest_0.6.27 shiny_1.6.0 ## [137] qlcMatrix_0.9.7 Rcpp_1.0.7 ## [139] later_1.2.0 RcppAnnoy_0.0.18 ## [141] httr_1.4.2 biovizBase_1.40.0 ## [143] colorspace_2.0-2 XML_3.99-0.6 ## [145] fs_1.5.0 tensor_1.5 ## [147] reticulate_1.20 splines_4.1.0 ## [149] uwot_0.1.10 RcppRoll_0.3.0 ## [151] spatstat.utils_2.1-0 pkgdown_1.6.1 ## [153] plotly_4.9.4 systemfonts_1.0.2 ## [155] xtable_1.8-4 jsonlite_1.7.2 ## [157] R6_2.5.0 Hmisc_4.5-0 ## [159] pillar_1.6.2 htmltools_0.5.1.1 ## [161] mime_0.11 glue_1.4.2 ## [163] fastmap_1.1.0 BiocParallel_1.26.1 ## [165] codetools_0.2-18 utf8_1.2.2 ## [167] lattice_0.20-44 bslib_0.2.5.1 ## [169] spatstat.sparse_2.0-0 tibble_3.1.3 ## [171] curl_4.3.2 leiden_0.3.8 ## [173] survival_3.2-11 rmarkdown_2.10 ## [175] docopt_0.7.1 desc_1.3.0 ## [177] munsell_0.5.0 GenomeInfoDbData_1.2.6 ## [179] reshape2_1.4.4 gtable_0.3.0 ## [181] spatstat.core_2.1-2

Developed by Paul Hoffman, Satija Lab and Collaborators.

Site built with pkgdown 1.6.1.

**Examples:**

Example 1 (unknown):
```unknown
vignettes/atacseq_integration_vignette.Rmd
```

Example 2 (unknown):
```unknown
atacseq_integration_vignette.Rmd
```

Example 3 (unknown):
```unknown
library(SeuratData)
# install the dataset and load requirements
InstallData("pbmcMultiome")
```

Example 4 (r):
```r
library(SeuratData)
# install the dataset and load requirements
InstallData("pbmcMultiome")
```

Example 5 (r):
```r
library(SeuratData)
# install the dataset and load requirements
InstallData("pbmcMultiome")
```

Example 6 (unknown):
```unknown
library(Seurat)
library(Signac)
library(EnsDb.Hsapiens.v86)
library(ggplot2)
library(cowplot)
```

Example 7 (r):
```r
library(Seurat)
library(Signac)
library(EnsDb.Hsapiens.v86)
library(ggplot2)
library(cowplot)
```

Example 8 (r):
```r
library(Seurat)
library(Signac)
library(EnsDb.Hsapiens.v86)
library(ggplot2)
library(cowplot)
```

Example 9 (unknown):
```unknown
# load both modalities
pbmc.rna <- LoadData("pbmcMultiome", "pbmc.rna")
pbmc.atac <- LoadData("pbmcMultiome", "pbmc.atac")

# repeat QC steps performed in the WNN vignette
pbmc.rna <- subset(pbmc.rna, seurat_annotations != "filtered")
pbmc.atac <- subset(pbmc.atac, seurat_annotations != "filtered")

# Perform standard analysis of each modality independently RNA analysis
pbmc.rna <- NormalizeData(pbmc.rna)
pbmc.rna <- FindVariableFeatures(pbmc.rna)
pbmc.rna <- ScaleData(pbmc.rna)
pbmc.rna <- RunPCA(pbmc.rna)
pbmc.rna <- RunUMAP(pbmc.rna, dims = 1:30)

# ATAC analysis add gene annotation information
annotations <- GetGRangesFromEnsDb(ensdb = EnsDb.Hsapiens.v86)
seqlevelsStyle(annotations) <- "UCSC"
genome(annotations) <- "hg38"
Annotation(pbmc.atac) <- annotations

# We exclude the first dimension as this is typically correlated with sequencing depth
pbmc.atac <- RunTFIDF(pbmc.atac)
pbmc.atac <- FindTopFeatures(pbmc.atac, min.cutoff = "q0")
pbmc.atac <- RunSVD(pbmc.atac)
pbmc.atac <- RunUMAP(pbmc.atac, reduction = "lsi", dims = 2:30, reduction.name = "umap.atac", reduction.key = "atacUMAP_")
```

Example 10 (r):
```r
# load both modalities
pbmc.rna <- LoadData("pbmcMultiome", "pbmc.rna")
pbmc.atac <- LoadData("pbmcMultiome", "pbmc.atac")

# repeat QC steps performed in the WNN vignette
pbmc.rna <- subset(pbmc.rna, seurat_annotations != "filtered")
pbmc.atac <- subset(pbmc.atac, seurat_annotations != "filtered")

# Perform standard analysis of each modality independently RNA analysis
pbmc.rna <- NormalizeData(pbmc.rna)
pbmc.rna <- FindVariableFeatures(pbmc.rna)
pbmc.rna <- ScaleData(pbmc.rna)
pbmc.rna <- RunPCA(pbmc.rna)
pbmc.rna <- RunUMAP(pbmc.rna, dims = 1:30)

# ATAC analysis add gene annotation information
annotations <- GetGRangesFromEnsDb(ensdb = EnsDb.Hsapiens.v86)
seqlevelsStyle(annotations) <- "UCSC"
genome(annotations) <- "hg38"
Annotation(pbmc.atac) <- annotations

# We exclude the first dimension as this is typically correlated with sequencing depth
pbmc.atac <- RunTFIDF(pbmc.atac)
pbmc.atac <- FindTopFeatures(pbmc.atac, min.cutoff = "q0")
pbmc.atac <- RunSVD(pbmc.atac)
pbmc.atac <- RunUMAP(pbmc.atac, reduction = "lsi", dims = 2:30, reduction.name = "umap.atac", reduction.key = "atacUMAP_")
```

Example 11 (r):
```r
# load both modalities
pbmc.rna <- LoadData("pbmcMultiome", "pbmc.rna")
pbmc.atac <- LoadData("pbmcMultiome", "pbmc.atac")

# repeat QC steps performed in the WNN vignette
pbmc.rna <- subset(pbmc.rna, seurat_annotations != "filtered")
pbmc.atac <- subset(pbmc.atac, seurat_annotations != "filtered")

# Perform standard analysis of each modality independently RNA analysis
pbmc.rna <- NormalizeData(pbmc.rna)
pbmc.rna <- FindVariableFeatures(pbmc.rna)
pbmc.rna <- ScaleData(pbmc.rna)
pbmc.rna <- RunPCA(pbmc.rna)
pbmc.rna <- RunUMAP(pbmc.rna, dims = 1:30)

# ATAC analysis add gene annotation information
annotations <- GetGRangesFromEnsDb(ensdb = EnsDb.Hsapiens.v86)
seqlevelsStyle(annotations) <- "UCSC"
genome(annotations) <- "hg38"
Annotation(pbmc.atac) <- annotations

# We exclude the first dimension as this is typically correlated with sequencing depth
pbmc.atac <- RunTFIDF(pbmc.atac)
pbmc.atac <- FindTopFeatures(pbmc.atac, min.cutoff = "q0")
pbmc.atac <- RunSVD(pbmc.atac)
pbmc.atac <- RunUMAP(pbmc.atac, reduction = "lsi", dims = 2:30, reduction.name = "umap.atac", reduction.key = "atacUMAP_")
```

Example 12 (unknown):
```unknown
p1 <- DimPlot(pbmc.rna, group.by = "seurat_annotations", label = TRUE) + NoLegend() + ggtitle("RNA")
p2 <- DimPlot(pbmc.atac, group.by = "orig.ident", label = FALSE) + NoLegend() + ggtitle("ATAC")
p1 + p2
```

Example 13 (r):
```r
p1 <- DimPlot(pbmc.rna, group.by = "seurat_annotations", label = TRUE) + NoLegend() + ggtitle("RNA")
p2 <- DimPlot(pbmc.atac, group.by = "orig.ident", label = FALSE) + NoLegend() + ggtitle("ATAC")
p1 + p2
```

Example 14 (r):
```r
p1 <- DimPlot(pbmc.rna, group.by = "seurat_annotations", label = TRUE) + NoLegend() + ggtitle("RNA")
p2 <- DimPlot(pbmc.atac, group.by = "orig.ident", label = FALSE) + NoLegend() + ggtitle("ATAC")
p1 + p2
```

Example 15 (unknown):
```unknown
GeneActivity()
```

Example 16 (unknown):
```unknown
# quantify gene activity
gene.activities <- GeneActivity(pbmc.atac, features = VariableFeatures(pbmc.rna))

# add gene activities as a new assay
pbmc.atac[["ACTIVITY"]] <- CreateAssayObject(counts = gene.activities)

# normalize gene activities
DefaultAssay(pbmc.atac) <- "ACTIVITY"
pbmc.atac <- NormalizeData(pbmc.atac)
pbmc.atac <- ScaleData(pbmc.atac, features = rownames(pbmc.atac))
```

Example 17 (r):
```r
# quantify gene activity
gene.activities <- GeneActivity(pbmc.atac, features = VariableFeatures(pbmc.rna))

# add gene activities as a new assay
pbmc.atac[["ACTIVITY"]] <- CreateAssayObject(counts = gene.activities)

# normalize gene activities
DefaultAssay(pbmc.atac) <- "ACTIVITY"
pbmc.atac <- NormalizeData(pbmc.atac)
pbmc.atac <- ScaleData(pbmc.atac, features = rownames(pbmc.atac))
```

Example 18 (r):
```r
# quantify gene activity
gene.activities <- GeneActivity(pbmc.atac, features = VariableFeatures(pbmc.rna))

# add gene activities as a new assay
pbmc.atac[["ACTIVITY"]] <- CreateAssayObject(counts = gene.activities)

# normalize gene activities
DefaultAssay(pbmc.atac) <- "ACTIVITY"
pbmc.atac <- NormalizeData(pbmc.atac)
pbmc.atac <- ScaleData(pbmc.atac, features = rownames(pbmc.atac))
```

Example 19 (unknown):
```unknown
# Identify anchors
transfer.anchors <- FindTransferAnchors(reference = pbmc.rna, query = pbmc.atac, features = VariableFeatures(object = pbmc.rna),
    reference.assay = "RNA", query.assay = "ACTIVITY", reduction = "cca")
```

Example 20 (r):
```r
# Identify anchors
transfer.anchors <- FindTransferAnchors(reference = pbmc.rna, query = pbmc.atac, features = VariableFeatures(object = pbmc.rna),
    reference.assay = "RNA", query.assay = "ACTIVITY", reduction = "cca")
```

Example 21 (r):
```r
# Identify anchors
transfer.anchors <- FindTransferAnchors(reference = pbmc.rna, query = pbmc.atac, features = VariableFeatures(object = pbmc.rna),
    reference.assay = "RNA", query.assay = "ACTIVITY", reduction = "cca")
```

Example 22 (unknown):
```unknown
seurat_annotations
```

Example 23 (python):
```python
celltype.predictions <- TransferData(anchorset = transfer.anchors, refdata = pbmc.rna$seurat_annotations,
    weight.reduction = pbmc.atac[["lsi"]], dims = 2:30)

pbmc.atac <- AddMetaData(pbmc.atac, metadata = celltype.predictions)
```

Example 24 (r):
```r
celltype.predictions <- TransferData(anchorset = transfer.anchors, refdata = pbmc.rna$seurat_annotations,
    weight.reduction = pbmc.atac[["lsi"]], dims = 2:30)

pbmc.atac <- AddMetaData(pbmc.atac, metadata = celltype.predictions)
```

Example 25 (r):
```r
celltype.predictions <- TransferData(anchorset = transfer.anchors, refdata = pbmc.rna$seurat_annotations,
    weight.reduction = pbmc.atac[["lsi"]], dims = 2:30)

pbmc.atac <- AddMetaData(pbmc.atac, metadata = celltype.predictions)
```

Example 26 (unknown):
```unknown
FindTransferAnchors()
```

Example 27 (unknown):
```unknown
reduction = 'cca'
```

Example 28 (unknown):
```unknown
TransferData()
```

Example 29 (unknown):
```unknown
predicted.id
```

Example 30 (unknown):
```unknown
pbmc.atac$annotation_correct <- pbmc.atac$predicted.id == pbmc.atac$seurat_annotations
p1 <- DimPlot(pbmc.atac, group.by = "predicted.id", label = TRUE) + NoLegend() + ggtitle("Predicted annotation")
p2 <- DimPlot(pbmc.atac, group.by = "seurat_annotations", label = TRUE) + NoLegend() + ggtitle("Ground-truth annotation")
p1 | p2
```

Example 31 (r):
```r
pbmc.atac$annotation_correct <- pbmc.atac$predicted.id == pbmc.atac$seurat_annotations
p1 <- DimPlot(pbmc.atac, group.by = "predicted.id", label = TRUE) + NoLegend() + ggtitle("Predicted annotation")
p2 <- DimPlot(pbmc.atac, group.by = "seurat_annotations", label = TRUE) + NoLegend() + ggtitle("Ground-truth annotation")
p1 | p2
```

Example 32 (r):
```r
pbmc.atac$annotation_correct <- pbmc.atac$predicted.id == pbmc.atac$seurat_annotations
p1 <- DimPlot(pbmc.atac, group.by = "predicted.id", label = TRUE) + NoLegend() + ggtitle("Predicted annotation")
p2 <- DimPlot(pbmc.atac, group.by = "seurat_annotations", label = TRUE) + NoLegend() + ggtitle("Ground-truth annotation")
p1 | p2
```

Example 33 (unknown):
```unknown
prediction.score.max
```

Example 34 (unknown):
```unknown
predictions <- table(pbmc.atac$seurat_annotations, pbmc.atac$predicted.id)
predictions <- predictions/rowSums(predictions)  # normalize for number of cells in each cell type
predictions <- as.data.frame(predictions)
p1 <- ggplot(predictions, aes(Var1, Var2, fill = Freq)) + geom_tile() + scale_fill_gradient(name = "Fraction of cells",
    low = "#ffffc8", high = "#7d0025") + xlab("Cell type annotation (RNA)") + ylab("Predicted cell type label (ATAC)") +
    theme_cowplot() + theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust = 1))

correct <- length(which(pbmc.atac$seurat_annotations == pbmc.atac$predicted.id))
incorrect <- length(which(pbmc.atac$seurat_annotations != pbmc.atac$predicted.id))
data <- FetchData(pbmc.atac, vars = c("prediction.score.max", "annotation_correct"))
p2 <- ggplot(data, aes(prediction.score.max, fill = annotation_correct, colour = annotation_correct)) +
    geom_density(alpha = 0.5) + theme_cowplot() + scale_fill_discrete(name = "Annotation Correct",
    labels = c(paste0("FALSE (n = ", incorrect, ")"), paste0("TRUE (n = ", correct, ")"))) + scale_color_discrete(name = "Annotation Correct",
    labels = c(paste0("FALSE (n = ", incorrect, ")"), paste0("TRUE (n = ", correct, ")"))) + xlab("Prediction Score")
p1 + p2
```

Example 35 (r):
```r
predictions <- table(pbmc.atac$seurat_annotations, pbmc.atac$predicted.id)
predictions <- predictions/rowSums(predictions)  # normalize for number of cells in each cell type
predictions <- as.data.frame(predictions)
p1 <- ggplot(predictions, aes(Var1, Var2, fill = Freq)) + geom_tile() + scale_fill_gradient(name = "Fraction of cells",
    low = "#ffffc8", high = "#7d0025") + xlab("Cell type annotation (RNA)") + ylab("Predicted cell type label (ATAC)") +
    theme_cowplot() + theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust = 1))

correct <- length(which(pbmc.atac$seurat_annotations == pbmc.atac$predicted.id))
incorrect <- length(which(pbmc.atac$seurat_annotations != pbmc.atac$predicted.id))
data <- FetchData(pbmc.atac, vars = c("prediction.score.max", "annotation_correct"))
p2 <- ggplot(data, aes(prediction.score.max, fill = annotation_correct, colour = annotation_correct)) +
    geom_density(alpha = 0.5) + theme_cowplot() + scale_fill_discrete(name = "Annotation Correct",
    labels = c(paste0("FALSE (n = ", incorrect, ")"), paste0("TRUE (n = ", correct, ")"))) + scale_color_discrete(name = "Annotation Correct",
    labels = c(paste0("FALSE (n = ", incorrect, ")"), paste0("TRUE (n = ", correct, ")"))) + xlab("Prediction Score")
p1 + p2
```

Example 36 (r):
```r
predictions <- table(pbmc.atac$seurat_annotations, pbmc.atac$predicted.id)
predictions <- predictions/rowSums(predictions)  # normalize for number of cells in each cell type
predictions <- as.data.frame(predictions)
p1 <- ggplot(predictions, aes(Var1, Var2, fill = Freq)) + geom_tile() + scale_fill_gradient(name = "Fraction of cells",
    low = "#ffffc8", high = "#7d0025") + xlab("Cell type annotation (RNA)") + ylab("Predicted cell type label (ATAC)") +
    theme_cowplot() + theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust = 1))

correct <- length(which(pbmc.atac$seurat_annotations == pbmc.atac$predicted.id))
incorrect <- length(which(pbmc.atac$seurat_annotations != pbmc.atac$predicted.id))
data <- FetchData(pbmc.atac, vars = c("prediction.score.max", "annotation_correct"))
p2 <- ggplot(data, aes(prediction.score.max, fill = annotation_correct, colour = annotation_correct)) +
    geom_density(alpha = 0.5) + theme_cowplot() + scale_fill_discrete(name = "Annotation Correct",
    labels = c(paste0("FALSE (n = ", incorrect, ")"), paste0("TRUE (n = ", correct, ")"))) + scale_color_discrete(name = "Annotation Correct",
    labels = c(paste0("FALSE (n = ", incorrect, ")"), paste0("TRUE (n = ", correct, ")"))) + xlab("Prediction Score")
p1 + p2
```

Example 37 (python):
```python
# note that we restrict the imputation to variable genes from scRNA-seq, but could impute the
# full transcriptome if we wanted to
genes.use <- VariableFeatures(pbmc.rna)
refdata <- GetAssayData(pbmc.rna, assay = "RNA", slot = "data")[genes.use, ]

# refdata (input) contains a scRNA-seq expression matrix for the scRNA-seq cells.  imputation
# (output) will contain an imputed scRNA-seq matrix for each of the ATAC cells
imputation <- TransferData(anchorset = transfer.anchors, refdata = refdata, weight.reduction = pbmc.atac[["lsi"]],
    dims = 2:30)
pbmc.atac[["RNA"]] <- imputation

coembed <- merge(x = pbmc.rna, y = pbmc.atac)

# Finally, we run PCA and UMAP on this combined object, to visualize the co-embedding of both
# datasets
coembed <- ScaleData(coembed, features = genes.use, do.scale = FALSE)
coembed <- RunPCA(coembed, features = genes.use, verbose = FALSE)
coembed <- RunUMAP(coembed, dims = 1:30)

DimPlot(coembed, group.by = c("orig.ident", "seurat_annotations"))
```

Example 38 (r):
```r
# note that we restrict the imputation to variable genes from scRNA-seq, but could impute the
# full transcriptome if we wanted to
genes.use <- VariableFeatures(pbmc.rna)
refdata <- GetAssayData(pbmc.rna, assay = "RNA", slot = "data")[genes.use, ]

# refdata (input) contains a scRNA-seq expression matrix for the scRNA-seq cells.  imputation
# (output) will contain an imputed scRNA-seq matrix for each of the ATAC cells
imputation <- TransferData(anchorset = transfer.anchors, refdata = refdata, weight.reduction = pbmc.atac[["lsi"]],
    dims = 2:30)
pbmc.atac[["RNA"]] <- imputation

coembed <- merge(x = pbmc.rna, y = pbmc.atac)

# Finally, we run PCA and UMAP on this combined object, to visualize the co-embedding of both
# datasets
coembed <- ScaleData(coembed, features = genes.use, do.scale = FALSE)
coembed <- RunPCA(coembed, features = genes.use, verbose = FALSE)
coembed <- RunUMAP(coembed, dims = 1:30)

DimPlot(coembed, group.by = c("orig.ident", "seurat_annotations"))
```

Example 39 (r):
```r
# note that we restrict the imputation to variable genes from scRNA-seq, but could impute the
# full transcriptome if we wanted to
genes.use <- VariableFeatures(pbmc.rna)
refdata <- GetAssayData(pbmc.rna, assay = "RNA", slot = "data")[genes.use, ]

# refdata (input) contains a scRNA-seq expression matrix for the scRNA-seq cells.  imputation
# (output) will contain an imputed scRNA-seq matrix for each of the ATAC cells
imputation <- TransferData(anchorset = transfer.anchors, refdata = refdata, weight.reduction = pbmc.atac[["lsi"]],
    dims = 2:30)
pbmc.atac[["RNA"]] <- imputation

coembed <- merge(x = pbmc.rna, y = pbmc.atac)

# Finally, we run PCA and UMAP on this combined object, to visualize the co-embedding of both
# datasets
coembed <- ScaleData(coembed, features = genes.use, do.scale = FALSE)
coembed <- RunPCA(coembed, features = genes.use, verbose = FALSE)
coembed <- RunUMAP(coembed, dims = 1:30)

DimPlot(coembed, group.by = c("orig.ident", "seurat_annotations"))
```

Example 40 (unknown):
```unknown
sessionInfo()
```

Example 41 (r):
```r
sessionInfo()
```

Example 42 (r):
```r
sessionInfo()
```

Example 43 (unknown):
```unknown
## R version 4.1.0 (2021-05-18)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.2 LTS
## 
## Matrix products: default
## BLAS/LAPACK: /usr/lib/x86_64-linux-gnu/openblas-pthread/libopenblasp-r0.3.8.so
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [5] LC_MONETARY=en_US.UTF-8    LC_MESSAGES=C             
##  [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       
## 
## attached base packages:
## [1] stats4    parallel  stats     graphics  grDevices utils     datasets 
## [8] methods   base     
## 
## other attached packages:
##  [1] cowplot_1.1.1                 ggplot2_3.3.5                
##  [3] EnsDb.Hsapiens.v86_2.99.0     ensembldb_2.16.4             
##  [5] AnnotationFilter_1.16.0       GenomicFeatures_1.44.0       
##  [7] AnnotationDbi_1.54.1          Biobase_2.52.0               
##  [9] GenomicRanges_1.44.0          GenomeInfoDb_1.28.1          
## [11] IRanges_2.26.0                S4Vectors_0.30.0             
## [13] BiocGenerics_0.38.0           Signac_1.3.0                 
## [15] SeuratObject_4.0.2            Seurat_4.0.4                 
## [17] thp1.eccite.SeuratData_3.1.5  stxBrain.SeuratData_0.1.1    
## [19] ssHippo.SeuratData_3.1.4      pbmcsca.SeuratData_3.0.0     
## [21] pbmcMultiome.SeuratData_0.1.1 pbmc3k.SeuratData_3.1.4      
## [23] panc8.SeuratData_3.0.2        ifnb.SeuratData_3.1.0        
## [25] hcabm40k.SeuratData_3.0.0     bmcite.SeuratData_0.3.0      
## [27] SeuratData_0.2.1             
## 
## loaded via a namespace (and not attached):
##   [1] rappdirs_0.3.3              SnowballC_0.7.0            
##   [3] rtracklayer_1.52.0          scattermore_0.7            
##   [5] ragg_1.1.3                  tidyr_1.1.3                
##   [7] bit64_4.0.5                 knitr_1.33                 
##   [9] irlba_2.3.3                 DelayedArray_0.18.0        
##  [11] data.table_1.14.0           rpart_4.1-15               
##  [13] KEGGREST_1.32.0             RCurl_1.98-1.3             
##  [15] generics_0.1.0              RSQLite_2.2.7              
##  [17] RANN_2.6.1                  future_1.21.0              
##  [19] bit_4.0.4                   spatstat.data_2.1-0        
##  [21] xml2_1.3.2                  httpuv_1.6.1               
##  [23] SummarizedExperiment_1.22.0 assertthat_0.2.1           
##  [25] xfun_0.25                   hms_1.1.0                  
##  [27] jquerylib_0.1.4             evaluate_0.14              
##  [29] promises_1.2.0.1            fansi_0.5.0                
##  [31] restfulr_0.0.13             progress_1.2.2             
##  [33] dbplyr_2.1.1                igraph_1.2.6               
##  [35] DBI_1.1.1                   htmlwidgets_1.5.3          
##  [37] sparsesvd_0.2               spatstat.geom_2.1-0        
##  [39] purrr_0.3.4                 ellipsis_0.3.2             
##  [41] RSpectra_0.16-0             dplyr_1.0.7                
##  [43] backports_1.2.1             biomaRt_2.48.2             
##  [45] deldir_0.2-10               MatrixGenerics_1.4.2       
##  [47] vctrs_0.3.8                 ROCR_1.0-11                
##  [49] abind_1.4-5                 cachem_1.0.5               
##  [51] withr_2.4.2                 ggforce_0.3.3              
##  [53] BSgenome_1.60.0             checkmate_2.0.0            
##  [55] sctransform_0.3.2           GenomicAlignments_1.28.0   
##  [57] prettyunits_1.1.1           goftest_1.2-2              
##  [59] cluster_2.1.2               lazyeval_0.2.2             
##  [61] crayon_1.4.1                labeling_0.4.2             
##  [63] pkgconfig_2.0.3             slam_0.1-48                
##  [65] tweenr_1.0.2                nlme_3.1-152               
##  [67] ProtGenerics_1.24.0         nnet_7.3-16                
##  [69] rlang_0.4.11                globals_0.14.0             
##  [71] lifecycle_1.0.0             miniUI_0.1.1.1             
##  [73] filelock_1.0.2              BiocFileCache_2.0.0        
##  [75] dichromat_2.0-0             rprojroot_2.0.2            
##  [77] polyclip_1.10-0             matrixStats_0.60.0         
##  [79] lmtest_0.9-38               Matrix_1.3-3               
##  [81] ggseqlogo_0.1               zoo_1.8-9                  
##  [83] base64enc_0.1-3             ggridges_0.5.3             
##  [85] png_0.1-7                   viridisLite_0.4.0          
##  [87] rjson_0.2.20                bitops_1.0-7               
##  [89] KernSmooth_2.23-20          Biostrings_2.60.2          
##  [91] blob_1.2.2                  stringr_1.4.0              
##  [93] parallelly_1.26.0           jpeg_0.1-9                 
##  [95] scales_1.1.1                memoise_2.0.0              
##  [97] magrittr_2.0.1              plyr_1.8.6                 
##  [99] ica_1.0-2                   zlibbioc_1.38.0            
## [101] compiler_4.1.0              BiocIO_1.2.0               
## [103] RColorBrewer_1.1-2          fitdistrplus_1.1-5         
## [105] Rsamtools_2.8.0             cli_3.0.1                  
## [107] XVector_0.32.0              listenv_0.8.0              
## [109] patchwork_1.1.1             pbapply_1.4-3              
## [111] htmlTable_2.2.1             formatR_1.11               
## [113] Formula_1.2-4               MASS_7.3-54                
## [115] mgcv_1.8-35                 tidyselect_1.1.1           
## [117] stringi_1.7.3               textshaping_0.3.5          
## [119] highr_0.9                   yaml_2.2.1                 
## [121] latticeExtra_0.6-29         ggrepel_0.9.1              
## [123] grid_4.1.0                  VariantAnnotation_1.38.0   
## [125] sass_0.4.0                  fastmatch_1.1-3            
## [127] tools_4.1.0                 future.apply_1.7.0         
## [129] rstudioapi_0.13             foreign_0.8-81             
## [131] lsa_0.73.2                  gridExtra_2.3              
## [133] farver_2.1.0                Rtsne_0.15                 
## [135] digest_0.6.27               shiny_1.6.0                
## [137] qlcMatrix_0.9.7             Rcpp_1.0.7                 
## [139] later_1.2.0                 RcppAnnoy_0.0.18           
## [141] httr_1.4.2                  biovizBase_1.40.0          
## [143] colorspace_2.0-2            XML_3.99-0.6               
## [145] fs_1.5.0                    tensor_1.5                 
## [147] reticulate_1.20             splines_4.1.0              
## [149] uwot_0.1.10                 RcppRoll_0.3.0             
## [151] spatstat.utils_2.1-0        pkgdown_1.6.1              
## [153] plotly_4.9.4                systemfonts_1.0.2          
## [155] xtable_1.8-4                jsonlite_1.7.2             
## [157] R6_2.5.0                    Hmisc_4.5-0                
## [159] pillar_1.6.2                htmltools_0.5.1.1          
## [161] mime_0.11                   glue_1.4.2                 
## [163] fastmap_1.1.0               BiocParallel_1.26.1        
## [165] codetools_0.2-18            utf8_1.2.2                 
## [167] lattice_0.20-44             bslib_0.2.5.1              
## [169] spatstat.sparse_2.0-0       tibble_3.1.3               
## [171] curl_4.3.2                  leiden_0.3.8               
## [173] survival_3.2-11             rmarkdown_2.10             
## [175] docopt_0.7.1                desc_1.3.0                 
## [177] munsell_0.5.0               GenomeInfoDbData_1.2.6     
## [179] reshape2_1.4.4              gtable_0.3.0               
## [181] spatstat.core_2.1-2
```

Example 44 (unknown):
```unknown
## R version 4.1.0 (2021-05-18)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.2 LTS
## 
## Matrix products: default
## BLAS/LAPACK: /usr/lib/x86_64-linux-gnu/openblas-pthread/libopenblasp-r0.3.8.so
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [5] LC_MONETARY=en_US.UTF-8    LC_MESSAGES=C             
##  [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       
## 
## attached base packages:
## [1] stats4    parallel  stats     graphics  grDevices utils     datasets 
## [8] methods   base     
## 
## other attached packages:
##  [1] cowplot_1.1.1                 ggplot2_3.3.5                
##  [3] EnsDb.Hsapiens.v86_2.99.0     ensembldb_2.16.4             
##  [5] AnnotationFilter_1.16.0       GenomicFeatures_1.44.0       
##  [7] AnnotationDbi_1.54.1          Biobase_2.52.0               
##  [9] GenomicRanges_1.44.0          GenomeInfoDb_1.28.1          
## [11] IRanges_2.26.0                S4Vectors_0.30.0             
## [13] BiocGenerics_0.38.0           Signac_1.3.0                 
## [15] SeuratObject_4.0.2            Seurat_4.0.4                 
## [17] thp1.eccite.SeuratData_3.1.5  stxBrain.SeuratData_0.1.1    
## [19] ssHippo.SeuratData_3.1.4      pbmcsca.SeuratData_3.0.0     
## [21] pbmcMultiome.SeuratData_0.1.1 pbmc3k.SeuratData_3.1.4      
## [23] panc8.SeuratData_3.0.2        ifnb.SeuratData_3.1.0        
## [25] hcabm40k.SeuratData_3.0.0     bmcite.SeuratData_0.3.0      
## [27] SeuratData_0.2.1             
## 
## loaded via a namespace (and not attached):
##   [1] rappdirs_0.3.3              SnowballC_0.7.0            
##   [3] rtracklayer_1.52.0          scattermore_0.7            
##   [5] ragg_1.1.3                  tidyr_1.1.3                
##   [7] bit64_4.0.5                 knitr_1.33                 
##   [9] irlba_2.3.3                 DelayedArray_0.18.0        
##  [11] data.table_1.14.0           rpart_4.1-15               
##  [13] KEGGREST_1.32.0             RCurl_1.98-1.3             
##  [15] generics_0.1.0              RSQLite_2.2.7              
##  [17] RANN_2.6.1                  future_1.21.0              
##  [19] bit_4.0.4                   spatstat.data_2.1-0        
##  [21] xml2_1.3.2                  httpuv_1.6.1               
##  [23] SummarizedExperiment_1.22.0 assertthat_0.2.1           
##  [25] xfun_0.25                   hms_1.1.0                  
##  [27] jquerylib_0.1.4             evaluate_0.14              
##  [29] promises_1.2.0.1            fansi_0.5.0                
##  [31] restfulr_0.0.13             progress_1.2.2             
##  [33] dbplyr_2.1.1                igraph_1.2.6               
##  [35] DBI_1.1.1                   htmlwidgets_1.5.3          
##  [37] sparsesvd_0.2               spatstat.geom_2.1-0        
##  [39] purrr_0.3.4                 ellipsis_0.3.2             
##  [41] RSpectra_0.16-0             dplyr_1.0.7                
##  [43] backports_1.2.1             biomaRt_2.48.2             
##  [45] deldir_0.2-10               MatrixGenerics_1.4.2       
##  [47] vctrs_0.3.8                 ROCR_1.0-11                
##  [49] abind_1.4-5                 cachem_1.0.5               
##  [51] withr_2.4.2                 ggforce_0.3.3              
##  [53] BSgenome_1.60.0             checkmate_2.0.0            
##  [55] sctransform_0.3.2           GenomicAlignments_1.28.0   
##  [57] prettyunits_1.1.1           goftest_1.2-2              
##  [59] cluster_2.1.2               lazyeval_0.2.2             
##  [61] crayon_1.4.1                labeling_0.4.2             
##  [63] pkgconfig_2.0.3             slam_0.1-48                
##  [65] tweenr_1.0.2                nlme_3.1-152               
##  [67] ProtGenerics_1.24.0         nnet_7.3-16                
##  [69] rlang_0.4.11                globals_0.14.0             
##  [71] lifecycle_1.0.0             miniUI_0.1.1.1             
##  [73] filelock_1.0.2              BiocFileCache_2.0.0        
##  [75] dichromat_2.0-0             rprojroot_2.0.2            
##  [77] polyclip_1.10-0             matrixStats_0.60.0         
##  [79] lmtest_0.9-38               Matrix_1.3-3               
##  [81] ggseqlogo_0.1               zoo_1.8-9                  
##  [83] base64enc_0.1-3             ggridges_0.5.3             
##  [85] png_0.1-7                   viridisLite_0.4.0          
##  [87] rjson_0.2.20                bitops_1.0-7               
##  [89] KernSmooth_2.23-20          Biostrings_2.60.2          
##  [91] blob_1.2.2                  stringr_1.4.0              
##  [93] parallelly_1.26.0           jpeg_0.1-9                 
##  [95] scales_1.1.1                memoise_2.0.0              
##  [97] magrittr_2.0.1              plyr_1.8.6                 
##  [99] ica_1.0-2                   zlibbioc_1.38.0            
## [101] compiler_4.1.0              BiocIO_1.2.0               
## [103] RColorBrewer_1.1-2          fitdistrplus_1.1-5         
## [105] Rsamtools_2.8.0             cli_3.0.1                  
## [107] XVector_0.32.0              listenv_0.8.0              
## [109] patchwork_1.1.1             pbapply_1.4-3              
## [111] htmlTable_2.2.1             formatR_1.11               
## [113] Formula_1.2-4               MASS_7.3-54                
## [115] mgcv_1.8-35                 tidyselect_1.1.1           
## [117] stringi_1.7.3               textshaping_0.3.5          
## [119] highr_0.9                   yaml_2.2.1                 
## [121] latticeExtra_0.6-29         ggrepel_0.9.1              
## [123] grid_4.1.0                  VariantAnnotation_1.38.0   
## [125] sass_0.4.0                  fastmatch_1.1-3            
## [127] tools_4.1.0                 future.apply_1.7.0         
## [129] rstudioapi_0.13             foreign_0.8-81             
## [131] lsa_0.73.2                  gridExtra_2.3              
## [133] farver_2.1.0                Rtsne_0.15                 
## [135] digest_0.6.27               shiny_1.6.0                
## [137] qlcMatrix_0.9.7             Rcpp_1.0.7                 
## [139] later_1.2.0                 RcppAnnoy_0.0.18           
## [141] httr_1.4.2                  biovizBase_1.40.0          
## [143] colorspace_2.0-2            XML_3.99-0.6               
## [145] fs_1.5.0                    tensor_1.5                 
## [147] reticulate_1.20             splines_4.1.0              
## [149] uwot_0.1.10                 RcppRoll_0.3.0             
## [151] spatstat.utils_2.1-0        pkgdown_1.6.1              
## [153] plotly_4.9.4                systemfonts_1.0.2          
## [155] xtable_1.8-4                jsonlite_1.7.2             
## [157] R6_2.5.0                    Hmisc_4.5-0                
## [159] pillar_1.6.2                htmltools_0.5.1.1          
## [161] mime_0.11                   glue_1.4.2                 
## [163] fastmap_1.1.0               BiocParallel_1.26.1        
## [165] codetools_0.2-18            utf8_1.2.2                 
## [167] lattice_0.20-44             bslib_0.2.5.1              
## [169] spatstat.sparse_2.0-0       tibble_3.1.3               
## [171] curl_4.3.2                  leiden_0.3.8               
## [173] survival_3.2-11             rmarkdown_2.10             
## [175] docopt_0.7.1                desc_1.3.0                 
## [177] munsell_0.5.0               GenomeInfoDbData_1.2.6     
## [179] reshape2_1.4.4              gtable_0.3.0               
## [181] spatstat.core_2.1-2
```

---

## Parallelization in Seurat with future

**URL:** http://127.0.0.1:9173/seurat/archive/v3.2/future_vignette/index.html

**Contents:**
- Parallelization in Seurat with future
    - Compiled: October 02, 2020
  - How to use parallelization in Seurat
  - 'Futurized' functions in Seurat
  - Comparison of sequential vs. parallel
  - Frequently asked questions

In Seurat, we have chosen to use the future framework for parallelization. In this vignette, we will demonstrate how you can take advantage of the future implementation of certain Seurat functions from a user's perspective. If you are interested in learning more about the future framework beyond what is described here, please see the package vignettes here for a comprehensive and detailed description.

To access the parallel version of functions in Seurat, you need to load the future package and set the plan. The plan will specify how the function is executed. The default behavior is to evaluate in a non-parallelized fashion (sequentially). To achieve parallel (asynchronous) behavior, we typically recommend the "multiprocess" strategy. By default, this uses all available cores but you can set the workers parameter to limit the number of concurrently active futures.

The following functions have been written to take advantage of the future framework and will be parallelized if the current plan is set appropriately. Importantly, the way you call the function shouldn't change.

For example, to run the parallel version of FindMarkers, you simply need to set the plan and call the function as usual.

Here we'll perform a brief comparison the runtimes for the same function calls with and without parallelization. Note that while we expect that using a parallelized strategy will decrease the runtimes of the functions listed above, the magnitude of that decrease will depend on many factors (e.g. the size of the dataset, the number of workers, specs of the system, the future strategy, etc). The following benchmarks were performed on a desktop computer running Ubuntu 16.04.5 LTS with an Intel(R) Core(TM) i7-6800K CPU @ 3.40GHz and 96 GB of RAM.

Click to see bencharking code

Where did my progress bar go? Unfortantely, the when running these functions in any of the parallel plan modes you will lose the progress bar. This is due to some technical limitations in the future framework and R generally. If you want to monitor function progress, you'll need to forgo parallelization and use plan("sequential").

What should I do if I keep seeing the following error?

For certain functions, each worker needs access to certain global variables. If these are larger than the default limit, you will see this error. To get around this, you can set options(future.globals.maxSize = X), where X is the maximum allowed size in bytes. So to set it to 1GB, you would run options(future.globals.maxSize = 1000 * 1024^2). Note that this will increase your RAM usage so set this number mindfully.

**Examples:**

Example 1 (r):
```r
library(future)
# check the current active plan
plan()
```

Example 2 (r):
```r
library(future)
# check the current active plan
plan()
```

Example 3 (unknown):
```unknown
## sequential:
## - args: function (expr, envir = parent.frame(), substitute = TRUE, lazy = FALSE, seed = NULL, globals = TRUE, local = TRUE, earlySignal = FALSE, label = NULL, ...)
## - tweaked: FALSE
## - call: NULL
```

Example 4 (unknown):
```unknown
## sequential:
## - args: function (expr, envir = parent.frame(), substitute = TRUE, lazy = FALSE, seed = NULL, globals = TRUE, local = TRUE, earlySignal = FALSE, label = NULL, ...)
## - tweaked: FALSE
## - call: NULL
```

Example 5 (r):
```r
# change the current plan to access parallelization
plan("multiprocess", workers = 4)
plan()
```

Example 6 (r):
```r
# change the current plan to access parallelization
plan("multiprocess", workers = 4)
plan()
```

Example 7 (unknown):
```unknown
## multiprocess:
## - args: function (expr, envir = parent.frame(), substitute = TRUE, lazy = FALSE, seed = NULL, globals = TRUE, workers = 4, gc = FALSE, earlySignal = FALSE, label = NULL, ...)
## - tweaked: TRUE
## - call: plan("multiprocess", workers = 4)
```

Example 8 (unknown):
```unknown
## multiprocess:
## - args: function (expr, envir = parent.frame(), substitute = TRUE, lazy = FALSE, seed = NULL, globals = TRUE, workers = 4, gc = FALSE, earlySignal = FALSE, label = NULL, ...)
## - tweaked: TRUE
## - call: plan("multiprocess", workers = 4)
```

Example 9 (unknown):
```unknown
NormalizeData
```

Example 10 (unknown):
```unknown
FindMarkers
```

Example 11 (unknown):
```unknown
FindIntegrationAnchors
```

Example 12 (unknown):
```unknown
FindClusters
```

Example 13 (unknown):
```unknown
FindMarkers
```

Example 14 (r):
```r
library(Seurat)
pbmc <- readRDS("../data/pbmc3k_final.rds")

# Enable parallelization
plan("multiprocess", workers = 4)
markers <- FindMarkers(pbmc, ident.1 = "NK", verbose = FALSE)
```

Example 15 (r):
```r
library(Seurat)
pbmc <- readRDS("../data/pbmc3k_final.rds")

# Enable parallelization
plan("multiprocess", workers = 4)
markers <- FindMarkers(pbmc, ident.1 = "NK", verbose = FALSE)
```

Example 16 (r):
```r
timing.comparisons <- data.frame(fxn = character(), time = numeric(), strategy = character())
plan("sequential")
start <- Sys.time()
pbmc <- ScaleData(pbmc, vars.to.regress = "percent.mt", verbose = FALSE)
end <- Sys.time()
timing.comparisons <- rbind(timing.comparisons, data.frame(fxn = "ScaleData", time = as.numeric(end - 
    start, units = "secs"), strategy = "sequential"))

start <- Sys.time()
markers <- FindMarkers(pbmc, ident.1 = "NK", verbose = FALSE)
end <- Sys.time()
timing.comparisons <- rbind(timing.comparisons, data.frame(fxn = "FindMarkers", time = as.numeric(end - 
    start, units = "secs"), strategy = "sequential"))

plan("multiprocess", workers = 4)
start <- Sys.time()
pbmc <- ScaleData(pbmc, vars.to.regress = "percent.mt", verbose = FALSE)
end <- Sys.time()
timing.comparisons <- rbind(timing.comparisons, data.frame(fxn = "ScaleData", time = as.numeric(end - 
    start, units = "secs"), strategy = "multiprocess"))

start <- Sys.time()
markers <- FindMarkers(pbmc, ident.1 = "NK", verbose = FALSE)
end <- Sys.time()
timing.comparisons <- rbind(timing.comparisons, data.frame(fxn = "FindMarkers", time = as.numeric(end - 
    start, units = "secs"), strategy = "multiprocess"))
```

Example 17 (r):
```r
timing.comparisons <- data.frame(fxn = character(), time = numeric(), strategy = character())
plan("sequential")
start <- Sys.time()
pbmc <- ScaleData(pbmc, vars.to.regress = "percent.mt", verbose = FALSE)
end <- Sys.time()
timing.comparisons <- rbind(timing.comparisons, data.frame(fxn = "ScaleData", time = as.numeric(end - 
    start, units = "secs"), strategy = "sequential"))

start <- Sys.time()
markers <- FindMarkers(pbmc, ident.1 = "NK", verbose = FALSE)
end <- Sys.time()
timing.comparisons <- rbind(timing.comparisons, data.frame(fxn = "FindMarkers", time = as.numeric(end - 
    start, units = "secs"), strategy = "sequential"))

plan("multiprocess", workers = 4)
start <- Sys.time()
pbmc <- ScaleData(pbmc, vars.to.regress = "percent.mt", verbose = FALSE)
end <- Sys.time()
timing.comparisons <- rbind(timing.comparisons, data.frame(fxn = "ScaleData", time = as.numeric(end - 
    start, units = "secs"), strategy = "multiprocess"))

start <- Sys.time()
markers <- FindMarkers(pbmc, ident.1 = "NK", verbose = FALSE)
end <- Sys.time()
timing.comparisons <- rbind(timing.comparisons, data.frame(fxn = "FindMarkers", time = as.numeric(end - 
    start, units = "secs"), strategy = "multiprocess"))
```

Example 18 (r):
```r
library(ggplot2)
library(cowplot)
ggplot(timing.comparisons, aes(fxn, time)) + geom_bar(aes(fill = strategy), stat = "identity", position = "dodge") + 
    ylab("Time(s)") + xlab("Function") + theme_cowplot()
```

Example 19 (r):
```r
library(ggplot2)
library(cowplot)
ggplot(timing.comparisons, aes(fxn, time)) + geom_bar(aes(fill = strategy), stat = "identity", position = "dodge") + 
    ylab("Time(s)") + xlab("Function") + theme_cowplot()
```

Example 20 (unknown):
```unknown
plan("sequential")
```

Example 21 (unknown):
```unknown
Error in getGlobalsAndPackages(expr, envir = envir, globals = TRUE) : 
  The total size of the X globals that need to be exported for the future expression ('FUN()') is X GiB. This exceeds the maximum allowed size of 500.00 MiB (option 'future.globals.maxSize'). The X largest globals are ...
```

Example 22 (unknown):
```unknown
Error in getGlobalsAndPackages(expr, envir = envir, globals = TRUE) : 
  The total size of the X globals that need to be exported for the future expression ('FUN()') is X GiB. This exceeds the maximum allowed size of 500.00 MiB (option 'future.globals.maxSize'). The X largest globals are ...
```

Example 23 (unknown):
```unknown
options(future.globals.maxSize = X)
```

Example 24 (unknown):
```unknown
options(future.globals.maxSize = 1000 * 1024^2)
```

---

## Analysis of Image-based Spatial Data in Seurat • Seurat

**URL:** http://127.0.0.1:9173/seurat/articles/seurat5_spatial_vignette_2/index.html

**Contents:**
- Analysis of Image-based Spatial Data in Seurat
    - Compiled: August 20, 2025
- Overview
- Mouse Brain: Vizgen MERSCOPE
  - Preprocessing and unsupervised analysis
- Mouse Brain: 10x Genomics Xenium In Situ
- Human Lung: Nanostring CosMx Spatial Molecular Imager
  - Visualization of cell type and expression localization patterns
- Human Lymph Node: Akoya CODEX system

In this vignette, we introduce a Seurat extension to analyze new types of spatially-resolved data. We have previously introduced a spatial framework which is compatible with sequencing-based technologies, like the 10x Genomics Visium system, or SLIDE-seq. Here, we extend this framework to analyze new data types that are captured via highly multiplexed imaging. In contrast to sequencing-based technologies, these datasets are often targeted (i.e. they profile a pre-selected set of genes). However they can resolve individual molecules - retaining single-cell (and subcellular) resolution. These approaches also often capture cellular boundaries (segmentations).

We update the Seurat infrastructure to enable the analysis, visualization, and exploration of these exciting datasets. In this vignette, we focus on three datasets produced by different multiplexed imaging technologies, each of which is publicly available. We will be adding support for additional imaging-based technologies in the coming months.

First, we load the packages necessary for this vignette.

This dataset was produced using the Vizgen MERSCOPE system, which utilizes the MERFISH technology. The total dataset is available for public download, and contains nine samples (three full coronal slices of the mouse brain, with three biological replicates per slice). The gene panel consists of 483 gene targets, representing known anonical cell type markers, nonsensory G-Protein coupled receptors (GPCRs), and Receptor Tyrosine Kinases (RTKs). In this vignette, we analyze one of the samples - slice 2, replicate 1. The median number of transcripts detected in each cell is 206.

First, we read in the dataset and create a Seurat object.

We use the LoadVizgen() function, which we have written to read in the output of the Vizgen analysis pipeline. The resulting Seurat object contains the following information:

The next pieces of information are specific to imaging assays, and is stored in the images slot of the resulting Seurat object:

We start by performing a standard unsupervised clustering analysis, essentially first treating the dataset as an scRNA-seq experiment. We use SCTransform-based normalization, though we slightly modify the default clipping parameters to mitigate the effect of outliers that we occasionally observe in smFISH experiments. After normalization, we can run dimensional reduction and clustering.

We can then visualize the results of the clustering either in UMAP space (with DimPlot()) or overlaid on the image with ImageDimPlot().

You can also customize multiple aspect of the plot, including the color scheme, cell border widths, and size (see below).

The ImageDimPlot() and ImageFeaturePlot() functions have a few parameters which you can customize individual visualizations. These include:

Since it can be difficult to visualize the spatial localization patterns of an individual cluster when viewing them all together, we can highlight all cells that belong to a particular cluster:

We can find markers of individual clusters and visualize their spatial expression pattern. We can color cells based on their quantified expression of an individual gene, using ImageFeaturePlot(), which is analagous to the FeaturePlot() function for visualizing expression on a 2D embedding. Since MERFISH images individual molecules, we can also visualize the location of individual molecules.

Note that the nmols parameter can be used to reduce the total number of molecules shown to reduce overplotting. You can also use the mols.size, mols.cols, and mols.alpha parameter to further optimize.

Plotting molecules is especially useful for visualizing co-expression of multiple genes on the same plot.

The updated Seurat spatial framework has the option to treat cells as individual points, or also to visualize cell boundaries (segmentations). By default, Seurat ignores cell segmentations and treats each cell as a point (‘centroids’). This speeds up plotting, especially when looking at large areas, where cell boundaries are too small to visualize.

We can zoom into a region of tissue, creating a new field of view. For example, we can zoom into a region that contains the hippocampus. Once zoomed-in, we can set DefaultBoundary() to show cell segmentations. You can also ‘simplify’ the cell segmentations, reducing the number of edges in each polygon to speed up plotting.

The tol parameter determines how simplified the resulting segmentations are. A higher value of tol will reduce the number of vertices more drastically which will speed up plotting, but some segmentation detail will be lost. See https://rgeos.r-forge.r-project.org/reference/topo-unary-gSimplify.html for examples using different values for tol.

We can visualize individual molecules plotted at higher resolution after zooming-in

In this section we’ll analyze data produced by the Xenium platform. The vignette demonstrates how to load the per-transcript location data, cell x gene matrix, cell segmentation, and cell centroid information available in the Xenium outputs. The resulting Seurat object will contain the gene expression profile of each cell, the centroid and boundary of each cell, and the location of each individual detected transcript. The per-cell gene expression profiles are similar to standard single-cell RNA-seq and can be analyzed using the same tools.

This uses the Tiny subset dataset from 10x Genomics provided in the Fresh Frozen Mouse Brain for Xenium Explorer Demo which can be downloaded as described below. These analysis steps are also compatible with the larger Full coronal section, but will take longer to execute.

First we read in the dataset and create a Seurat object. Provide the path to the data folder for a Xenium run as the input path. The RNA data is stored in the Xenium assay of the Seurat object. This step should take about a minute (you can improve this by installing arrow and hdf5r).

Spatial information is loaded into slots of the Seurat object, labelled by the name of “field of view” (FOV) being loaded. Initially all the data is loaded into the FOV named fov. Later, we will make a cropped FOV that zooms into a region of interest.

Standard QC plots provided by Seurat are available via the Xenium assay. Here are violin plots of genes per cell (nFeature_Xenium) and transcript counts per cell (nCount_Xenium)

Next, we plot the positions of the pan-inhibitory neuron marker Gad1, inhibitory neuron sub-type markers Pvalb, and Sst, and astrocyte marker Gfap on the tissue using ImageDimPlot().

Here we visualize the expression level of some key layer marker genes at the per-cell level using ImageFeaturePlot() which is analogous to the FeaturePlot() function for visualizing expression on a 2D embedding. We manually adjust the max.cutoff for each gene to roughly the 90th percentile (which can be specified with max.cutoff='q90') of it’s count distribution to improve contrast.

We can zoom in on a chosen area with the Crop() function. Once zoomed-in, we can visualize cell segmentation boundaries along with individual molecules.

Next, we use SCTransform for normalization followed by standard dimensionality reduction and clustering. This step takes about 5 minutes from start to finish.

We can then visualize the results of the clustering by coloring each cell according to its cluster either in UMAP space with DimPlot() or overlaid on the image with ImageDimPlot().

We can visualize the expression level of the markers we looked at earlier on the UMAP coordinates.

We can now use ImageDimPlot() to color the cell positions colored by the cluster labels determined in the previous step.

Using the positional information of each cell, we compute spatial niches. We use a cortex reference from the the Allen Brain Institute to annotate cells, so we first crop the dataset to the cortex. The Allen Brain reference can be installed here.

Below, we use Slc17a7 expression to help determine the cortical region.

While FindTransferAnchors can be used to integrate spot-level data from spatial transcriptomic datasets, Seurat v5 also includes support for the Robust Cell Type Decomposition, a computational approach to deconvolve spot-level data from spatial datasets, when provided with an scRNA-seq reference. RCTD has been shown to accurately annotate spatial data from a variety of technologies, including SLIDE-seq, Visium, and the 10x Xenium in-situ spatial platform.

To run RCTD, we first install the spacexr package from GitHub which implements RCTD.

Counts, cluster, and spot information is extracted from the Seurat query and reference objects to construct Reference and SpatialRNA objects used by RCTD for annotation. The output of the annotation is then added to the Seurat object.

While the previous analyses consider each cell independently, spatial data enables cells to be defined not just by their neighborhood, but also by their broader spatial context. In Seurat v5, we introduce support for ‘niche’ analysis of spatial data, which demarcates regions of tissue (‘niches’), each of which is defined by a different composition of spatially adjacent cell types. Inspired by methods in Goltsev et al, Cell 2018 and He et al, NBT 2022, we consider the ‘local neighborhood’ for each cell - consisting of its k.neighbor spatially closest neighbors, and count the occurrences of each cell type present in this neighborhood. We then use k-means clustering to group cells that have similar neighborhoods together, into spatial niches.

We call the BuildNicheAssay function from within Seurat to construct a new assay called niche containing the cell type composition spatially neighboring each cell. A metadata column called niches is also returned, which contains cluster assignments based on the niche assay.

We can then group cells either by their cell type identity, or their niche identity. The niches identified clearly demarcate the neuronal layers in the cortex.

Further, we observe that the composition of each niche is enriched for distinct cell types.

This dataset was produced using Nanostring CosMx Spatial Molecular Imager (SMI). The CosMX SMI performs multiplexed single molecule profiling, can profile both RNA and protein targets, and can be applied directly to FFPE tissues. The dataset represents 8 FFPE samples taken from 5 non-small-cell lung cancer (NSCLC) tissues, and is available for public download. The gene panel consists of 960 transcripts.

In this vignette, we load one of 8 samples (lung 5, replicate 1). We use the LoadNanostring() function, which parses the outputs available on the public download site. Note that the coordinates for the cell boundaries were provided by Nanostring by request, and are available for download here.

For this dataset, instead of performing unsupervised analysis, we map the Nanostring profiles to our Azimuth Healthy Human Lung reference, which was defined by scRNA-seq. We used Azimuth version 0.4.3 with the human lung reference version 1.0.0. You can download the precomputed results here, which include annotations, prediction scores, and a UMAP visualization. The median number of detected transcripts/cell is 249, which does create uncertainty for the annotation process.

We can visualize the Nanostring cells and annotations, projected onto the reference-defined UMAP. Note that for this NSCLC sample, tumor samples are annotated as ‘basal’, which is the closest cell type match in the healthy reference.

As in the previous example, ImageDimPlot() plots c ells based on their spatial locations, and colors them based on their assigned cell type. Notice that the basal cell population (tumor cells) is tightly spatially organized, as expected.

Since there are many cell types present, we can highlight the localization of a few select groups.

We can also visualize gene expression markers a few different ways:

We can plot molecules in order to co-visualize the expression of multiple markers, including KRT17 (basal cells), C1QA (macrophages), IL7R (T cells), and TAGLN (Smooth muscle cells).

We zoom in on one basal-rich region using the Crop() function. Once zoomed-in, we can visualize individual cell boundaries as well in all visualizations.

This dataset was produced using Akoya CODEX system. The CODEX system performs multiplexed spatially-resolved protein profiling, iteratively visualizing antibody-binding events. The dataset here represents a tissue section from a human lymph node, and was generated by the University of Florida as part of the Human Biomolecular Atlas Program (HuBMAP). More information about the sample and experiment is available here. The protein panel in this dataset consists of 28 markers, and protein intensities were quantified as part of the Akoya processor pipeline, which outputs a CSV file providing the intensity of each marker in each cell, as well as the cell coordinates. The file is available for public download via Globus here.

First, we load in the data of a HuBMAP dataset using the LoadAkoya() function in Seurat:

We can now run unsupervised analysis to identify cell clusters. To normalize the protein data, we use centered log-ratio based normalization, as we typically apply to the protein modality of CITE-seq data. We then run dimensional reduction and graph-based clustering.

We can visualize the cell clusters based on a protein intensity-based UMAP embedding, or also based on their spatial location.

The expression patters of individual markers clearly denote different cell types and spatial structures, including Lyve1 (lymphatic endothelial cells), CD34 (blood endothelial cells), and CD21 (B cells). As expected, endothelial cells group together into vessels, and B cells are key components of specialized microstructures known as germinal zones. You can read more about protein markers in this dataset, as well as cellular networks in human lynmphatic tissues, in this preprint.

Each of these datasets represents an opportunity to learn organizing principles that govern the spatial localization of different cell types. Stay tuned for future updates to Seurat enabling further exploration and characterization of the relationship between spatial position and molecular state.

Developed by Rahul Satija, Satija Lab and Collaborators.

Site built with pkgdown 2.1.3.

**Examples:**

Example 1 (unknown):
```unknown
vignettes/seurat5_spatial_vignette_2.Rmd
```

Example 2 (unknown):
```unknown
seurat5_spatial_vignette_2.Rmd
```

Example 3 (unknown):
```unknown
library(Seurat)
library(future)
plan("multisession", workers = 10)
library(ggplot2)

options(future.globals.maxSize = 10 * 1024^3)
```

Example 4 (r):
```r
library(Seurat)
library(future)
plan("multisession", workers = 10)
library(ggplot2)

options(future.globals.maxSize = 10 * 1024^3)
```

Example 5 (r):
```r
library(Seurat)
library(future)
plan("multisession", workers = 10)
library(ggplot2)

options(future.globals.maxSize = 10 * 1024^3)
```

Example 6 (unknown):
```unknown
LoadVizgen()
```

Example 7 (unknown):
```unknown
# Loading segmentations is a slow process and multi processing with the future pacakge is
# recommended
vizgen.obj <- LoadVizgen(data.dir = "/brahms/hartmana/vignette_data/vizgen/s2r1/", fov = "s2r1")
```

Example 8 (r):
```r
# Loading segmentations is a slow process and multi processing with the future pacakge is
# recommended
vizgen.obj <- LoadVizgen(data.dir = "/brahms/hartmana/vignette_data/vizgen/s2r1/", fov = "s2r1")
```

Example 9 (r):
```r
# Loading segmentations is a slow process and multi processing with the future pacakge is
# recommended
vizgen.obj <- LoadVizgen(data.dir = "/brahms/hartmana/vignette_data/vizgen/s2r1/", fov = "s2r1")
```

Example 10 (unknown):
```unknown
# Get the center position of each centroid. There is one row per cell in this dataframe.
head(GetTissueCoordinates(vizgen.obj[["s2r1"]][["centroids"]]))
```

Example 11 (r):
```r
# Get the center position of each centroid. There is one row per cell in this dataframe.
head(GetTissueCoordinates(vizgen.obj[["s2r1"]][["centroids"]]))
```

Example 12 (r):
```r
# Get the center position of each centroid. There is one row per cell in this dataframe.
head(GetTissueCoordinates(vizgen.obj[["s2r1"]][["centroids"]]))
```

Example 13 (unknown):
```unknown
##          x        y                                    cell
## 1 638.5640 4594.216 149164679103246548309819743981609972453
## 2 593.8034 4516.240 215843146921706462965382248182021894607
## 3 597.3134 4566.676 230248905804673613678286091156141465134
## 4 613.2434 4609.498 237155298815097057940587033798543926454
## 5 609.1934 4603.180 256099454901769634241742157204636917386
## 6 623.8814 4642.708  52442222147121971758529793775250916001
```

Example 14 (unknown):
```unknown
##          x        y                                    cell
## 1 638.5640 4594.216 149164679103246548309819743981609972453
## 2 593.8034 4516.240 215843146921706462965382248182021894607
## 3 597.3134 4566.676 230248905804673613678286091156141465134
## 4 613.2434 4609.498 237155298815097057940587033798543926454
## 5 609.1934 4603.180 256099454901769634241742157204636917386
## 6 623.8814 4642.708  52442222147121971758529793775250916001
```

Example 15 (unknown):
```unknown
# Get the coordinates for each segmentation vertice. Each cell will have a variable number of
# vertices describing its shape.
head(GetTissueCoordinates(vizgen.obj[["s2r1"]][["segmentation"]]))
```

Example 16 (r):
```r
# Get the coordinates for each segmentation vertice. Each cell will have a variable number of
# vertices describing its shape.
head(GetTissueCoordinates(vizgen.obj[["s2r1"]][["segmentation"]]))
```

Example 17 (r):
```r
# Get the coordinates for each segmentation vertice. Each cell will have a variable number of
# vertices describing its shape.
head(GetTissueCoordinates(vizgen.obj[["s2r1"]][["segmentation"]]))
```

Example 18 (unknown):
```unknown
##          x        y                                    cell
## 1 644.0774 4589.022 149164679103246548309819743981609972453
## 2 643.9694 4589.022 149164679103246548309819743981609972453
## 3 643.8614 4589.022 149164679103246548309819743981609972453
## 4 643.7642 4588.924 149164679103246548309819743981609972453
## 5 643.7534 4588.914 149164679103246548309819743981609972453
## 6 643.6454 4588.914 149164679103246548309819743981609972453
```

Example 19 (unknown):
```unknown
##          x        y                                    cell
## 1 644.0774 4589.022 149164679103246548309819743981609972453
## 2 643.9694 4589.022 149164679103246548309819743981609972453
## 3 643.8614 4589.022 149164679103246548309819743981609972453
## 4 643.7642 4588.924 149164679103246548309819743981609972453
## 5 643.7534 4588.914 149164679103246548309819743981609972453
## 6 643.6454 4588.914 149164679103246548309819743981609972453
```

Example 20 (unknown):
```unknown
# Fetch molecules positions for Chrm1
head(FetchData(vizgen.obj[["s2r1"]][["molecules"]], vars = "Chrm1"))
```

Example 21 (r):
```r
# Fetch molecules positions for Chrm1
head(FetchData(vizgen.obj[["s2r1"]][["molecules"]], vars = "Chrm1"))
```

Example 22 (r):
```r
# Fetch molecules positions for Chrm1
head(FetchData(vizgen.obj[["s2r1"]][["molecules"]], vars = "Chrm1"))
```

Example 23 (unknown):
```unknown
##          x        y molecule
## 1 577.3373 4205.977    Chrm1
## 2 600.0218 3917.781    Chrm1
## 3 508.2736 3934.063    Chrm1
## 4 630.7590 3948.586    Chrm1
## 5 635.1143 3969.567    Chrm1
## 6 582.7043 4021.577    Chrm1
```

Example 24 (unknown):
```unknown
##          x        y molecule
## 1 577.3373 4205.977    Chrm1
## 2 600.0218 3917.781    Chrm1
## 3 508.2736 3934.063    Chrm1
## 4 630.7590 3948.586    Chrm1
## 5 635.1143 3969.567    Chrm1
## 6 582.7043 4021.577    Chrm1
```

Example 25 (unknown):
```unknown
vizgen.obj <- SCTransform(vizgen.obj, assay = "Vizgen", clip.range = c(-10, 10))
vizgen.obj <- RunPCA(vizgen.obj, npcs = 30, features = rownames(vizgen.obj))
vizgen.obj <- RunUMAP(vizgen.obj, dims = 1:30)
vizgen.obj <- FindNeighbors(vizgen.obj, reduction = "pca", dims = 1:30)
vizgen.obj <- FindClusters(vizgen.obj, resolution = 0.3)
```

Example 26 (r):
```r
vizgen.obj <- SCTransform(vizgen.obj, assay = "Vizgen", clip.range = c(-10, 10))
vizgen.obj <- RunPCA(vizgen.obj, npcs = 30, features = rownames(vizgen.obj))
vizgen.obj <- RunUMAP(vizgen.obj, dims = 1:30)
vizgen.obj <- FindNeighbors(vizgen.obj, reduction = "pca", dims = 1:30)
vizgen.obj <- FindClusters(vizgen.obj, resolution = 0.3)
```

Example 27 (r):
```r
vizgen.obj <- SCTransform(vizgen.obj, assay = "Vizgen", clip.range = c(-10, 10))
vizgen.obj <- RunPCA(vizgen.obj, npcs = 30, features = rownames(vizgen.obj))
vizgen.obj <- RunUMAP(vizgen.obj, dims = 1:30)
vizgen.obj <- FindNeighbors(vizgen.obj, reduction = "pca", dims = 1:30)
vizgen.obj <- FindClusters(vizgen.obj, resolution = 0.3)
```

Example 28 (unknown):
```unknown
ImageDimPlot()
```

Example 29 (unknown):
```unknown
DimPlot(vizgen.obj, reduction = "umap")
```

Example 30 (r):
```r
DimPlot(vizgen.obj, reduction = "umap")
```

Example 31 (r):
```r
DimPlot(vizgen.obj, reduction = "umap")
```

Example 32 (unknown):
```unknown
ImageDimPlot(vizgen.obj, fov = "s2r1", cols = "polychrome", axes = TRUE)
```

Example 33 (r):
```r
ImageDimPlot(vizgen.obj, fov = "s2r1", cols = "polychrome", axes = TRUE)
```

Example 34 (r):
```r
ImageDimPlot(vizgen.obj, fov = "s2r1", cols = "polychrome", axes = TRUE)
```

Example 35 (unknown):
```unknown
ImageDimPlot()
```

Example 36 (unknown):
```unknown
ImageFeaturePlot()
```

Example 37 (unknown):
```unknown
shuffle.cols = TRUE
```

Example 38 (unknown):
```unknown
p1 <- ImageDimPlot(vizgen.obj, fov = "s2r1", cols = "red", cells = WhichCells(vizgen.obj, idents = 1))
p2 <- ImageDimPlot(vizgen.obj, fov = "s2r1", cols = "red", cells = WhichCells(vizgen.obj, idents = 15))
p1 + p2
```

Example 39 (r):
```r
p1 <- ImageDimPlot(vizgen.obj, fov = "s2r1", cols = "red", cells = WhichCells(vizgen.obj, idents = 1))
p2 <- ImageDimPlot(vizgen.obj, fov = "s2r1", cols = "red", cells = WhichCells(vizgen.obj, idents = 15))
p1 + p2
```

Example 40 (r):
```r
p1 <- ImageDimPlot(vizgen.obj, fov = "s2r1", cols = "red", cells = WhichCells(vizgen.obj, idents = 1))
p2 <- ImageDimPlot(vizgen.obj, fov = "s2r1", cols = "red", cells = WhichCells(vizgen.obj, idents = 15))
p1 + p2
```

Example 41 (unknown):
```unknown
ImageFeaturePlot()
```

Example 42 (unknown):
```unknown
FeaturePlot()
```

Example 43 (unknown):
```unknown
p1 <- ImageFeaturePlot(vizgen.obj, features = "Slc17a7")
p2 <- ImageDimPlot(vizgen.obj, molecules = "Slc17a7", nmols = 10000, alpha = 0.3, mols.cols = "red")
p1 + p2
```

Example 44 (r):
```r
p1 <- ImageFeaturePlot(vizgen.obj, features = "Slc17a7")
p2 <- ImageDimPlot(vizgen.obj, molecules = "Slc17a7", nmols = 10000, alpha = 0.3, mols.cols = "red")
p1 + p2
```

Example 45 (r):
```r
p1 <- ImageFeaturePlot(vizgen.obj, features = "Slc17a7")
p2 <- ImageDimPlot(vizgen.obj, molecules = "Slc17a7", nmols = 10000, alpha = 0.3, mols.cols = "red")
p1 + p2
```

Example 46 (unknown):
```unknown
p1 <- ImageDimPlot(vizgen.obj, fov = "s2r1", alpha = 0.3, molecules = c("Slc17a7", "Olig1"), nmols = 10000)
markers.14 <- FindMarkers(vizgen.obj, ident.1 = "14")
p2 <- ImageDimPlot(vizgen.obj, fov = "s2r1", alpha = 0.3, molecules = rownames(markers.14)[1:4],
    nmols = 10000)
p1 + p2
```

Example 47 (r):
```r
p1 <- ImageDimPlot(vizgen.obj, fov = "s2r1", alpha = 0.3, molecules = c("Slc17a7", "Olig1"), nmols = 10000)
markers.14 <- FindMarkers(vizgen.obj, ident.1 = "14")
p2 <- ImageDimPlot(vizgen.obj, fov = "s2r1", alpha = 0.3, molecules = rownames(markers.14)[1:4],
    nmols = 10000)
p1 + p2
```

Example 48 (r):
```r
p1 <- ImageDimPlot(vizgen.obj, fov = "s2r1", alpha = 0.3, molecules = c("Slc17a7", "Olig1"), nmols = 10000)
markers.14 <- FindMarkers(vizgen.obj, ident.1 = "14")
p2 <- ImageDimPlot(vizgen.obj, fov = "s2r1", alpha = 0.3, molecules = rownames(markers.14)[1:4],
    nmols = 10000)
p1 + p2
```

Example 49 (unknown):
```unknown
DefaultBoundary()
```

Example 50 (unknown):
```unknown
# create a Crop
cropped.coords <- Crop(vizgen.obj[["s2r1"]], x = c(1750, 3000), y = c(3750, 5250), coords = "plot")
# set a new field of view (fov)
vizgen.obj[["hippo"]] <- cropped.coords

# visualize FOV using default settings (no cell boundaries)
p1 <- ImageDimPlot(vizgen.obj, fov = "hippo", axes = TRUE, size = 0.7, border.color = "white", cols = "polychrome",
    coord.fixed = FALSE)

# visualize FOV with full cell segmentations
DefaultBoundary(vizgen.obj[["hippo"]]) <- "segmentation"
p2 <- ImageDimPlot(vizgen.obj, fov = "hippo", axes = TRUE, border.color = "white", border.size = 0.1,
    cols = "polychrome", coord.fixed = FALSE)

# simplify cell segmentations
vizgen.obj[["hippo"]][["simplified.segmentations"]] <- Simplify(coords = vizgen.obj[["hippo"]][["segmentation"]],
    tol = 3)
DefaultBoundary(vizgen.obj[["hippo"]]) <- "simplified.segmentations"

# visualize FOV with simplified cell segmentations
DefaultBoundary(vizgen.obj[["hippo"]]) <- "simplified.segmentations"
p3 <- ImageDimPlot(vizgen.obj, fov = "hippo", axes = TRUE, border.color = "white", border.size = 0.1,
    cols = "polychrome", coord.fixed = FALSE)

p1 + p2 + p3
```

Example 51 (r):
```r
# create a Crop
cropped.coords <- Crop(vizgen.obj[["s2r1"]], x = c(1750, 3000), y = c(3750, 5250), coords = "plot")
# set a new field of view (fov)
vizgen.obj[["hippo"]] <- cropped.coords

# visualize FOV using default settings (no cell boundaries)
p1 <- ImageDimPlot(vizgen.obj, fov = "hippo", axes = TRUE, size = 0.7, border.color = "white", cols = "polychrome",
    coord.fixed = FALSE)

# visualize FOV with full cell segmentations
DefaultBoundary(vizgen.obj[["hippo"]]) <- "segmentation"
p2 <- ImageDimPlot(vizgen.obj, fov = "hippo", axes = TRUE, border.color = "white", border.size = 0.1,
    cols = "polychrome", coord.fixed = FALSE)

# simplify cell segmentations
vizgen.obj[["hippo"]][["simplified.segmentations"]] <- Simplify(coords = vizgen.obj[["hippo"]][["segmentation"]],
    tol = 3)
DefaultBoundary(vizgen.obj[["hippo"]]) <- "simplified.segmentations"

# visualize FOV with simplified cell segmentations
DefaultBoundary(vizgen.obj[["hippo"]]) <- "simplified.segmentations"
p3 <- ImageDimPlot(vizgen.obj, fov = "hippo", axes = TRUE, border.color = "white", border.size = 0.1,
    cols = "polychrome", coord.fixed = FALSE)

p1 + p2 + p3
```

Example 52 (r):
```r
# create a Crop
cropped.coords <- Crop(vizgen.obj[["s2r1"]], x = c(1750, 3000), y = c(3750, 5250), coords = "plot")
# set a new field of view (fov)
vizgen.obj[["hippo"]] <- cropped.coords

# visualize FOV using default settings (no cell boundaries)
p1 <- ImageDimPlot(vizgen.obj, fov = "hippo", axes = TRUE, size = 0.7, border.color = "white", cols = "polychrome",
    coord.fixed = FALSE)

# visualize FOV with full cell segmentations
DefaultBoundary(vizgen.obj[["hippo"]]) <- "segmentation"
p2 <- ImageDimPlot(vizgen.obj, fov = "hippo", axes = TRUE, border.color = "white", border.size = 0.1,
    cols = "polychrome", coord.fixed = FALSE)

# simplify cell segmentations
vizgen.obj[["hippo"]][["simplified.segmentations"]] <- Simplify(coords = vizgen.obj[["hippo"]][["segmentation"]],
    tol = 3)
DefaultBoundary(vizgen.obj[["hippo"]]) <- "simplified.segmentations"

# visualize FOV with simplified cell segmentations
DefaultBoundary(vizgen.obj[["hippo"]]) <- "simplified.segmentations"
p3 <- ImageDimPlot(vizgen.obj, fov = "hippo", axes = TRUE, border.color = "white", border.size = 0.1,
    cols = "polychrome", coord.fixed = FALSE)

p1 + p2 + p3
```

Example 53 (unknown):
```unknown
# Since there is nothing behind the segmentations, alpha will slightly mute colors
ImageDimPlot(vizgen.obj, fov = "hippo", molecules = rownames(markers.14)[1:4], cols = "polychrome",
    mols.size = 1, alpha = 0.5, mols.cols = c("red", "blue", "yellow", "green"))
```

Example 54 (r):
```r
# Since there is nothing behind the segmentations, alpha will slightly mute colors
ImageDimPlot(vizgen.obj, fov = "hippo", molecules = rownames(markers.14)[1:4], cols = "polychrome",
    mols.size = 1, alpha = 0.5, mols.cols = c("red", "blue", "yellow", "green"))
```

Example 55 (r):
```r
# Since there is nothing behind the segmentations, alpha will slightly mute colors
ImageDimPlot(vizgen.obj, fov = "hippo", molecules = rownames(markers.14)[1:4], cols = "polychrome",
    mols.size = 1, alpha = 0.5, mols.cols = c("red", "blue", "yellow", "green"))
```

Example 56 (unknown):
```unknown
Tiny subset
```

Example 57 (unknown):
```unknown
Full coronal section
```

Example 58 (unknown):
```unknown
wget https://cf.10xgenomics.com/samples/xenium/1.0.2/Xenium_V1_FF_Mouse_Brain_Coronal_Subset_CTX_HP/Xenium_V1_FF_Mouse_Brain_Coronal_Subset_CTX_HP_outs.zip
unzip Xenium_V1_FF_Mouse_Brain_Coronal_Subset_CTX_HP_outs.zip
```

Example 59 (bash):
```bash
wget https://cf.10xgenomics.com/samples/xenium/1.0.2/Xenium_V1_FF_Mouse_Brain_Coronal_Subset_CTX_HP/Xenium_V1_FF_Mouse_Brain_Coronal_Subset_CTX_HP_outs.zip
unzip Xenium_V1_FF_Mouse_Brain_Coronal_Subset_CTX_HP_outs.zip
```

Example 60 (bash):
```bash
wget https://cf.10xgenomics.com/samples/xenium/1.0.2/Xenium_V1_FF_Mouse_Brain_Coronal_Subset_CTX_HP/Xenium_V1_FF_Mouse_Brain_Coronal_Subset_CTX_HP_outs.zip
unzip Xenium_V1_FF_Mouse_Brain_Coronal_Subset_CTX_HP_outs.zip
```

Example 61 (unknown):
```unknown
path <- "/brahms/hartmana/vignette_data/xenium_tiny_subset"
# Load the Xenium data
xenium.obj <- LoadXenium(path, fov = "fov", segmentations = "cell")
# remove cells with 0 counts
xenium.obj <- subset(xenium.obj, subset = nCount_Xenium > 0)
```

Example 62 (r):
```r
path <- "/brahms/hartmana/vignette_data/xenium_tiny_subset"
# Load the Xenium data
xenium.obj <- LoadXenium(path, fov = "fov", segmentations = "cell")
# remove cells with 0 counts
xenium.obj <- subset(xenium.obj, subset = nCount_Xenium > 0)
```

Example 63 (r):
```r
path <- "/brahms/hartmana/vignette_data/xenium_tiny_subset"
# Load the Xenium data
xenium.obj <- LoadXenium(path, fov = "fov", segmentations = "cell")
# remove cells with 0 counts
xenium.obj <- subset(xenium.obj, subset = nCount_Xenium > 0)
```

Example 64 (unknown):
```unknown
nFeature_Xenium
```

Example 65 (unknown):
```unknown
nCount_Xenium
```

Example 66 (unknown):
```unknown
VlnPlot(xenium.obj, features = c("nFeature_Xenium", "nCount_Xenium"), ncol = 2, pt.size = 0)
```

Example 67 (r):
```r
VlnPlot(xenium.obj, features = c("nFeature_Xenium", "nCount_Xenium"), ncol = 2, pt.size = 0)
```

Example 68 (r):
```r
VlnPlot(xenium.obj, features = c("nFeature_Xenium", "nCount_Xenium"), ncol = 2, pt.size = 0)
```

Example 69 (unknown):
```unknown
ImageDimPlot()
```

Example 70 (unknown):
```unknown
ImageDimPlot(xenium.obj, fov = "fov", molecules = c("Gad1", "Sst", "Pvalb", "Gfap"), nmols = 20000)
```

Example 71 (r):
```r
ImageDimPlot(xenium.obj, fov = "fov", molecules = c("Gad1", "Sst", "Pvalb", "Gfap"), nmols = 20000)
```

Example 72 (r):
```r
ImageDimPlot(xenium.obj, fov = "fov", molecules = c("Gad1", "Sst", "Pvalb", "Gfap"), nmols = 20000)
```

Example 73 (unknown):
```unknown
ImageFeaturePlot()
```

Example 74 (unknown):
```unknown
FeaturePlot()
```

Example 75 (unknown):
```unknown
max.cutoff='q90'
```

Example 76 (unknown):
```unknown
ImageFeaturePlot(xenium.obj, features = c("Cux2", "Rorb", "Bcl11b", "Foxp2"), max.cutoff = c(25,
    35, 12, 10), size = 0.75, cols = c("white", "red"))
```

Example 77 (r):
```r
ImageFeaturePlot(xenium.obj, features = c("Cux2", "Rorb", "Bcl11b", "Foxp2"), max.cutoff = c(25,
    35, 12, 10), size = 0.75, cols = c("white", "red"))
```

Example 78 (r):
```r
ImageFeaturePlot(xenium.obj, features = c("Cux2", "Rorb", "Bcl11b", "Foxp2"), max.cutoff = c(25,
    35, 12, 10), size = 0.75, cols = c("white", "red"))
```

Example 79 (unknown):
```unknown
cropped.coords <- Crop(xenium.obj[["fov"]], x = c(1200, 2900), y = c(3750, 4550), coords = "plot")
xenium.obj[["zoom"]] <- cropped.coords
# visualize cropped area with cell segmentations & selected molecules
DefaultBoundary(xenium.obj[["zoom"]]) <- "segmentation"
ImageDimPlot(xenium.obj, fov = "zoom", axes = TRUE, border.color = "white", border.size = 0.1, cols = "polychrome",
    coord.fixed = FALSE, molecules = c("Gad1", "Sst", "Npy2r", "Pvalb", "Nrn1"), nmols = 10000)
```

Example 80 (r):
```r
cropped.coords <- Crop(xenium.obj[["fov"]], x = c(1200, 2900), y = c(3750, 4550), coords = "plot")
xenium.obj[["zoom"]] <- cropped.coords
# visualize cropped area with cell segmentations & selected molecules
DefaultBoundary(xenium.obj[["zoom"]]) <- "segmentation"
ImageDimPlot(xenium.obj, fov = "zoom", axes = TRUE, border.color = "white", border.size = 0.1, cols = "polychrome",
    coord.fixed = FALSE, molecules = c("Gad1", "Sst", "Npy2r", "Pvalb", "Nrn1"), nmols = 10000)
```

Example 81 (r):
```r
cropped.coords <- Crop(xenium.obj[["fov"]], x = c(1200, 2900), y = c(3750, 4550), coords = "plot")
xenium.obj[["zoom"]] <- cropped.coords
# visualize cropped area with cell segmentations & selected molecules
DefaultBoundary(xenium.obj[["zoom"]]) <- "segmentation"
ImageDimPlot(xenium.obj, fov = "zoom", axes = TRUE, border.color = "white", border.size = 0.1, cols = "polychrome",
    coord.fixed = FALSE, molecules = c("Gad1", "Sst", "Npy2r", "Pvalb", "Nrn1"), nmols = 10000)
```

Example 82 (unknown):
```unknown
xenium.obj <- SCTransform(xenium.obj, assay = "Xenium")
xenium.obj <- RunPCA(xenium.obj, npcs = 30, features = rownames(xenium.obj))
xenium.obj <- RunUMAP(xenium.obj, dims = 1:30)
xenium.obj <- FindNeighbors(xenium.obj, reduction = "pca", dims = 1:30)
xenium.obj <- FindClusters(xenium.obj, resolution = 0.3)
```

Example 83 (r):
```r
xenium.obj <- SCTransform(xenium.obj, assay = "Xenium")
xenium.obj <- RunPCA(xenium.obj, npcs = 30, features = rownames(xenium.obj))
xenium.obj <- RunUMAP(xenium.obj, dims = 1:30)
xenium.obj <- FindNeighbors(xenium.obj, reduction = "pca", dims = 1:30)
xenium.obj <- FindClusters(xenium.obj, resolution = 0.3)
```

Example 84 (r):
```r
xenium.obj <- SCTransform(xenium.obj, assay = "Xenium")
xenium.obj <- RunPCA(xenium.obj, npcs = 30, features = rownames(xenium.obj))
xenium.obj <- RunUMAP(xenium.obj, dims = 1:30)
xenium.obj <- FindNeighbors(xenium.obj, reduction = "pca", dims = 1:30)
xenium.obj <- FindClusters(xenium.obj, resolution = 0.3)
```

Example 85 (unknown):
```unknown
ImageDimPlot()
```

Example 86 (unknown):
```unknown
DimPlot(xenium.obj)
```

Example 87 (r):
```r
DimPlot(xenium.obj)
```

Example 88 (r):
```r
DimPlot(xenium.obj)
```

Example 89 (unknown):
```unknown
FeaturePlot(xenium.obj, features = c("Cux2", "Bcl11b", "Foxp2", "Gad1", "Sst", "Gfap"))
```

Example 90 (r):
```r
FeaturePlot(xenium.obj, features = c("Cux2", "Bcl11b", "Foxp2", "Gad1", "Sst", "Gfap"))
```

Example 91 (r):
```r
FeaturePlot(xenium.obj, features = c("Cux2", "Bcl11b", "Foxp2", "Gad1", "Sst", "Gfap"))
```

Example 92 (unknown):
```unknown
ImageDimPlot()
```

Example 93 (unknown):
```unknown
ImageDimPlot(xenium.obj, cols = "polychrome", size = 0.75)
```

Example 94 (r):
```r
ImageDimPlot(xenium.obj, cols = "polychrome", size = 0.75)
```

Example 95 (r):
```r
ImageDimPlot(xenium.obj, cols = "polychrome", size = 0.75)
```

Example 96 (unknown):
```unknown
xenium.obj <- LoadXenium("/brahms/hartmana/vignette_data/xenium_tiny_subset")
p1 <- ImageFeaturePlot(xenium.obj, features = "Slc17a7", axes = TRUE, max.cutoff = "q90")
p1
```

Example 97 (r):
```r
xenium.obj <- LoadXenium("/brahms/hartmana/vignette_data/xenium_tiny_subset")
p1 <- ImageFeaturePlot(xenium.obj, features = "Slc17a7", axes = TRUE, max.cutoff = "q90")
p1
```

Example 98 (r):
```r
xenium.obj <- LoadXenium("/brahms/hartmana/vignette_data/xenium_tiny_subset")
p1 <- ImageFeaturePlot(xenium.obj, features = "Slc17a7", axes = TRUE, max.cutoff = "q90")
p1
```

Example 99 (unknown):
```unknown
crop <- Crop(xenium.obj[["fov"]], x = c(600, 2100), y = c(900, 4700))
xenium.obj[["crop"]] <- crop
p2 <- ImageFeaturePlot(xenium.obj, fov = "crop", features = "Slc17a7", size = 1, axes = TRUE, max.cutoff = "q90")
p2
```

Example 100 (r):
```r
crop <- Crop(xenium.obj[["fov"]], x = c(600, 2100), y = c(900, 4700))
xenium.obj[["crop"]] <- crop
p2 <- ImageFeaturePlot(xenium.obj, fov = "crop", features = "Slc17a7", size = 1, axes = TRUE, max.cutoff = "q90")
p2
```

Example 101 (r):
```r
crop <- Crop(xenium.obj[["fov"]], x = c(600, 2100), y = c(900, 4700))
xenium.obj[["crop"]] <- crop
p2 <- ImageFeaturePlot(xenium.obj, fov = "crop", features = "Slc17a7", size = 1, axes = TRUE, max.cutoff = "q90")
p2
```

Example 102 (unknown):
```unknown
FindTransferAnchors
```

Example 103 (unknown):
```unknown
devtools::install_github("dmcable/spacexr", build_vignettes = FALSE)
```

Example 104 (r):
```r
devtools::install_github("dmcable/spacexr", build_vignettes = FALSE)
```

Example 105 (r):
```r
devtools::install_github("dmcable/spacexr", build_vignettes = FALSE)
```

Example 106 (unknown):
```unknown
library(spacexr)

query.counts <- GetAssayData(xenium.obj, assay = "Xenium", slot = "counts")[, Cells(xenium.obj[["crop"]])]
coords <- GetTissueCoordinates(xenium.obj[["crop"]], which = "centroids")
rownames(coords) <- coords$cell
coords$cell <- NULL
query <- SpatialRNA(coords, query.counts, colSums(query.counts))
```

Example 107 (r):
```r
library(spacexr)

query.counts <- GetAssayData(xenium.obj, assay = "Xenium", slot = "counts")[, Cells(xenium.obj[["crop"]])]
coords <- GetTissueCoordinates(xenium.obj[["crop"]], which = "centroids")
rownames(coords) <- coords$cell
coords$cell <- NULL
query <- SpatialRNA(coords, query.counts, colSums(query.counts))
```

Example 108 (r):
```r
library(spacexr)

query.counts <- GetAssayData(xenium.obj, assay = "Xenium", slot = "counts")[, Cells(xenium.obj[["crop"]])]
coords <- GetTissueCoordinates(xenium.obj[["crop"]], which = "centroids")
rownames(coords) <- coords$cell
coords$cell <- NULL
query <- SpatialRNA(coords, query.counts, colSums(query.counts))
```

Example 109 (python):
```python
# allen.corted.ref can be downloaded here:
# https://www.dropbox.com/s/cuowvm4vrf65pvq/allen_cortex.rds?dl=1
allen.cortex.ref <- readRDS("/brahms/shared/vignette-data/allen_cortex.rds")
allen.cortex.ref <- UpdateSeuratObject(allen.cortex.ref)

Idents(allen.cortex.ref) <- "subclass"
# remove CR cells because there aren't enough of them for annotation
allen.cortex.ref <- subset(allen.cortex.ref, subset = subclass != "CR")
counts <- GetAssayData(allen.cortex.ref, assay = "RNA", slot = "counts")
cluster <- as.factor(allen.cortex.ref$subclass)
names(cluster) <- colnames(allen.cortex.ref)
nUMI <- allen.cortex.ref$nCount_RNA
names(nUMI) <- colnames(allen.cortex.ref)
nUMI <- colSums(counts)
levels(cluster) <- gsub("/", "-", levels(cluster))
reference <- Reference(counts, cluster, nUMI)
```

Example 110 (r):
```r
# allen.corted.ref can be downloaded here:
# https://www.dropbox.com/s/cuowvm4vrf65pvq/allen_cortex.rds?dl=1
allen.cortex.ref <- readRDS("/brahms/shared/vignette-data/allen_cortex.rds")
allen.cortex.ref <- UpdateSeuratObject(allen.cortex.ref)

Idents(allen.cortex.ref) <- "subclass"
# remove CR cells because there aren't enough of them for annotation
allen.cortex.ref <- subset(allen.cortex.ref, subset = subclass != "CR")
counts <- GetAssayData(allen.cortex.ref, assay = "RNA", slot = "counts")
cluster <- as.factor(allen.cortex.ref$subclass)
names(cluster) <- colnames(allen.cortex.ref)
nUMI <- allen.cortex.ref$nCount_RNA
names(nUMI) <- colnames(allen.cortex.ref)
nUMI <- colSums(counts)
levels(cluster) <- gsub("/", "-", levels(cluster))
reference <- Reference(counts, cluster, nUMI)
```

Example 111 (r):
```r
# allen.corted.ref can be downloaded here:
# https://www.dropbox.com/s/cuowvm4vrf65pvq/allen_cortex.rds?dl=1
allen.cortex.ref <- readRDS("/brahms/shared/vignette-data/allen_cortex.rds")
allen.cortex.ref <- UpdateSeuratObject(allen.cortex.ref)

Idents(allen.cortex.ref) <- "subclass"
# remove CR cells because there aren't enough of them for annotation
allen.cortex.ref <- subset(allen.cortex.ref, subset = subclass != "CR")
counts <- GetAssayData(allen.cortex.ref, assay = "RNA", slot = "counts")
cluster <- as.factor(allen.cortex.ref$subclass)
names(cluster) <- colnames(allen.cortex.ref)
nUMI <- allen.cortex.ref$nCount_RNA
names(nUMI) <- colnames(allen.cortex.ref)
nUMI <- colSums(counts)
levels(cluster) <- gsub("/", "-", levels(cluster))
reference <- Reference(counts, cluster, nUMI)
```

Example 112 (unknown):
```unknown
# run RCTD with many cores
RCTD <- create.RCTD(query, reference, max_cores = 8)
RCTD <- run.RCTD(RCTD, doublet_mode = "doublet")
```

Example 113 (r):
```r
# run RCTD with many cores
RCTD <- create.RCTD(query, reference, max_cores = 8)
RCTD <- run.RCTD(RCTD, doublet_mode = "doublet")
```

Example 114 (r):
```r
# run RCTD with many cores
RCTD <- create.RCTD(query, reference, max_cores = 8)
RCTD <- run.RCTD(RCTD, doublet_mode = "doublet")
```

Example 115 (unknown):
```unknown
annotations.df <- RCTD@results$results_df
annotations <- annotations.df$first_type
names(annotations) <- rownames(annotations.df)
xenium.obj$predicted.celltype <- annotations
keep.cells <- Cells(xenium.obj)[!is.na(xenium.obj$predicted.celltype)]
xenium.obj <- subset(xenium.obj, cells = keep.cells)
```

Example 116 (r):
```r
annotations.df <- RCTD@results$results_df
annotations <- annotations.df$first_type
names(annotations) <- rownames(annotations.df)
xenium.obj$predicted.celltype <- annotations
keep.cells <- Cells(xenium.obj)[!is.na(xenium.obj$predicted.celltype)]
xenium.obj <- subset(xenium.obj, cells = keep.cells)
```

Example 117 (r):
```r
annotations.df <- RCTD@results$results_df
annotations <- annotations.df$first_type
names(annotations) <- rownames(annotations.df)
xenium.obj$predicted.celltype <- annotations
keep.cells <- Cells(xenium.obj)[!is.na(xenium.obj$predicted.celltype)]
xenium.obj <- subset(xenium.obj, cells = keep.cells)
```

Example 118 (unknown):
```unknown
BuildNicheAssay
```

Example 119 (unknown):
```unknown
xenium.obj <- BuildNicheAssay(object = xenium.obj, fov = "crop", group.by = "predicted.celltype",
    niches.k = 5, neighbors.k = 30)
```

Example 120 (r):
```r
xenium.obj <- BuildNicheAssay(object = xenium.obj, fov = "crop", group.by = "predicted.celltype",
    niches.k = 5, neighbors.k = 30)
```

Example 121 (r):
```r
xenium.obj <- BuildNicheAssay(object = xenium.obj, fov = "crop", group.by = "predicted.celltype",
    niches.k = 5, neighbors.k = 30)
```

Example 122 (unknown):
```unknown
celltype.plot <- ImageDimPlot(xenium.obj, group.by = "predicted.celltype", size = 1.5, cols = "polychrome",
    dark.background = F) + ggtitle("Cell type")
niche.plot <- ImageDimPlot(xenium.obj, group.by = "niches", size = 1.5, dark.background = F) + ggtitle("Niches") +
    scale_fill_manual(values = c("#442288", "#6CA2EA", "#B5D33D", "#FED23F", "#EB7D5B"))
celltype.plot | niche.plot
```

Example 123 (r):
```r
celltype.plot <- ImageDimPlot(xenium.obj, group.by = "predicted.celltype", size = 1.5, cols = "polychrome",
    dark.background = F) + ggtitle("Cell type")
niche.plot <- ImageDimPlot(xenium.obj, group.by = "niches", size = 1.5, dark.background = F) + ggtitle("Niches") +
    scale_fill_manual(values = c("#442288", "#6CA2EA", "#B5D33D", "#FED23F", "#EB7D5B"))
celltype.plot | niche.plot
```

Example 124 (r):
```r
celltype.plot <- ImageDimPlot(xenium.obj, group.by = "predicted.celltype", size = 1.5, cols = "polychrome",
    dark.background = F) + ggtitle("Cell type")
niche.plot <- ImageDimPlot(xenium.obj, group.by = "niches", size = 1.5, dark.background = F) + ggtitle("Niches") +
    scale_fill_manual(values = c("#442288", "#6CA2EA", "#B5D33D", "#FED23F", "#EB7D5B"))
celltype.plot | niche.plot
```

Example 125 (unknown):
```unknown
table(xenium.obj$predicted.celltype, xenium.obj$niches)
```

Example 126 (r):
```r
table(xenium.obj$predicted.celltype, xenium.obj$niches)
```

Example 127 (r):
```r
table(xenium.obj$predicted.celltype, xenium.obj$niches)
```

Example 128 (unknown):
```unknown
##             
##                 1    2    3    4    5
##   Astro       115  484  241  146   89
##   Endo         27  250   66   62   45
##   L2-3 IT       0 1749   14    5    6
##   L4            2 2163    3   94   14
##   L5 IT         2   66    2  627   84
##   L5 PT         2   92    4  711   21
##   L6 CT        82    2    0   34  857
##   L6 IT         4   22    1   56  275
##   L6b          95    0    0    2    2
##   Lamp5         4   77   61    8    7
##   Macrophage    7   48   15   16   10
##   Meis2         0    0    0    0    0
##   NP            0    1    0   78    9
##   Oligo       305  130   42   76   70
##   Peri          6   40    4   10   12
##   Pvalb         5  155    0   75   54
##   Serpinf1      0    5    0    1    1
##   SMC           2   34    2   12    2
##   Sncg          3   15    1    0    5
##   Sst           0   53    0   55   26
##   Vip           3   85    5   14    4
##   VLMC          2   31  257    7    2
```

Example 129 (unknown):
```unknown
##             
##                 1    2    3    4    5
##   Astro       115  484  241  146   89
##   Endo         27  250   66   62   45
##   L2-3 IT       0 1749   14    5    6
##   L4            2 2163    3   94   14
##   L5 IT         2   66    2  627   84
##   L5 PT         2   92    4  711   21
##   L6 CT        82    2    0   34  857
##   L6 IT         4   22    1   56  275
##   L6b          95    0    0    2    2
##   Lamp5         4   77   61    8    7
##   Macrophage    7   48   15   16   10
##   Meis2         0    0    0    0    0
##   NP            0    1    0   78    9
##   Oligo       305  130   42   76   70
##   Peri          6   40    4   10   12
##   Pvalb         5  155    0   75   54
##   Serpinf1      0    5    0    1    1
##   SMC           2   34    2   12    2
##   Sncg          3   15    1    0    5
##   Sst           0   53    0   55   26
##   Vip           3   85    5   14    4
##   VLMC          2   31  257    7    2
```

Example 130 (unknown):
```unknown
LoadNanostring()
```

Example 131 (unknown):
```unknown
nano.obj <- LoadNanostring(data.dir = "/brahms/hartmana/vignette_data/nanostring/lung5_rep1", fov = "lung5.rep1")
```

Example 132 (r):
```r
nano.obj <- LoadNanostring(data.dir = "/brahms/hartmana/vignette_data/nanostring/lung5_rep1", fov = "lung5.rep1")
```

Example 133 (r):
```r
nano.obj <- LoadNanostring(data.dir = "/brahms/hartmana/vignette_data/nanostring/lung5_rep1", fov = "lung5.rep1")
```

Example 134 (python):
```python
# add in precomputed Azimuth annotations
azimuth.data <- readRDS("/brahms/hartmana/vignette_data/nanostring_data.Rds")
nano.obj <- AddMetaData(nano.obj, metadata = azimuth.data$annotations)
nano.obj[["proj.umap"]] <- azimuth.data$umap
Idents(nano.obj) <- nano.obj$predicted.annotation.l1

nano.obj <- SCTransform(nano.obj, assay = "Nanostring", clip.range = c(-10, 10), verbose = FALSE)

# text display of annotations and prediction scores
head(slot(object = nano.obj, name = "meta.data")[2:5])
```

Example 135 (r):
```r
# add in precomputed Azimuth annotations
azimuth.data <- readRDS("/brahms/hartmana/vignette_data/nanostring_data.Rds")
nano.obj <- AddMetaData(nano.obj, metadata = azimuth.data$annotations)
nano.obj[["proj.umap"]] <- azimuth.data$umap
Idents(nano.obj) <- nano.obj$predicted.annotation.l1

nano.obj <- SCTransform(nano.obj, assay = "Nanostring", clip.range = c(-10, 10), verbose = FALSE)

# text display of annotations and prediction scores
head(slot(object = nano.obj, name = "meta.data")[2:5])
```

Example 136 (r):
```r
# add in precomputed Azimuth annotations
azimuth.data <- readRDS("/brahms/hartmana/vignette_data/nanostring_data.Rds")
nano.obj <- AddMetaData(nano.obj, metadata = azimuth.data$annotations)
nano.obj[["proj.umap"]] <- azimuth.data$umap
Idents(nano.obj) <- nano.obj$predicted.annotation.l1

nano.obj <- SCTransform(nano.obj, assay = "Nanostring", clip.range = c(-10, 10), verbose = FALSE)

# text display of annotations and prediction scores
head(slot(object = nano.obj, name = "meta.data")[2:5])
```

Example 137 (unknown):
```unknown
##     nCount_Nanostring nFeature_Nanostring predicted.annotation.l1
## 1_1                23                  19               Dendritic
## 2_1                26                  23              Macrophage
## 3_1                74                  51          Neuroendocrine
## 4_1                60                  48              Macrophage
## 5_1                52                  39              Macrophage
## 6_1                 5                   5                   CD4 T
##     predicted.annotation.l1.score
## 1_1                     0.5884506
## 2_1                     0.5707920
## 3_1                     0.5449661
## 4_1                     0.6951970
## 5_1                     0.8155319
## 6_1                     0.5677324
```

Example 138 (unknown):
```unknown
##     nCount_Nanostring nFeature_Nanostring predicted.annotation.l1
## 1_1                23                  19               Dendritic
## 2_1                26                  23              Macrophage
## 3_1                74                  51          Neuroendocrine
## 4_1                60                  48              Macrophage
## 5_1                52                  39              Macrophage
## 6_1                 5                   5                   CD4 T
##     predicted.annotation.l1.score
## 1_1                     0.5884506
## 2_1                     0.5707920
## 3_1                     0.5449661
## 4_1                     0.6951970
## 5_1                     0.8155319
## 6_1                     0.5677324
```

Example 139 (unknown):
```unknown
DimPlot(nano.obj)
```

Example 140 (r):
```r
DimPlot(nano.obj)
```

Example 141 (r):
```r
DimPlot(nano.obj)
```

Example 142 (unknown):
```unknown
ImageDimPlot()
```

Example 143 (unknown):
```unknown
ImageDimPlot(nano.obj, fov = "lung5.rep1", axes = TRUE, cols = "glasbey")
```

Example 144 (r):
```r
ImageDimPlot(nano.obj, fov = "lung5.rep1", axes = TRUE, cols = "glasbey")
```

Example 145 (r):
```r
ImageDimPlot(nano.obj, fov = "lung5.rep1", axes = TRUE, cols = "glasbey")
```

Example 146 (unknown):
```unknown
ImageDimPlot(nano.obj, fov = "lung5.rep1", cells = WhichCells(nano.obj, idents = c("Basal", "Macrophage",
    "Smooth Muscle", "CD4 T")), cols = c("red", "green", "blue", "orange"), size = 0.6)
```

Example 147 (r):
```r
ImageDimPlot(nano.obj, fov = "lung5.rep1", cells = WhichCells(nano.obj, idents = c("Basal", "Macrophage",
    "Smooth Muscle", "CD4 T")), cols = c("red", "green", "blue", "orange"), size = 0.6)
```

Example 148 (r):
```r
ImageDimPlot(nano.obj, fov = "lung5.rep1", cells = WhichCells(nano.obj, idents = c("Basal", "Macrophage",
    "Smooth Muscle", "CD4 T")), cols = c("red", "green", "blue", "orange"), size = 0.6)
```

Example 149 (unknown):
```unknown
VlnPlot(nano.obj, features = "KRT17", assay = "Nanostring", layer = "counts", pt.size = 0.1, y.max = 30) +
    NoLegend()
```

Example 150 (r):
```r
VlnPlot(nano.obj, features = "KRT17", assay = "Nanostring", layer = "counts", pt.size = 0.1, y.max = 30) +
    NoLegend()
```

Example 151 (r):
```r
VlnPlot(nano.obj, features = "KRT17", assay = "Nanostring", layer = "counts", pt.size = 0.1, y.max = 30) +
    NoLegend()
```

Example 152 (unknown):
```unknown
FeaturePlot(nano.obj, features = "KRT17", max.cutoff = "q95")
```

Example 153 (r):
```r
FeaturePlot(nano.obj, features = "KRT17", max.cutoff = "q95")
```

Example 154 (r):
```r
FeaturePlot(nano.obj, features = "KRT17", max.cutoff = "q95")
```

Example 155 (unknown):
```unknown
p1 <- ImageFeaturePlot(nano.obj, fov = "lung5.rep1", features = "KRT17", max.cutoff = "q95")
p2 <- ImageDimPlot(nano.obj, fov = "lung5.rep1", alpha = 0.3, molecules = "KRT17", nmols = 10000) +
    NoLegend()
p1 + p2
```

Example 156 (r):
```r
p1 <- ImageFeaturePlot(nano.obj, fov = "lung5.rep1", features = "KRT17", max.cutoff = "q95")
p2 <- ImageDimPlot(nano.obj, fov = "lung5.rep1", alpha = 0.3, molecules = "KRT17", nmols = 10000) +
    NoLegend()
p1 + p2
```

Example 157 (r):
```r
p1 <- ImageFeaturePlot(nano.obj, fov = "lung5.rep1", features = "KRT17", max.cutoff = "q95")
p2 <- ImageDimPlot(nano.obj, fov = "lung5.rep1", alpha = 0.3, molecules = "KRT17", nmols = 10000) +
    NoLegend()
p1 + p2
```

Example 158 (unknown):
```unknown
# Plot some of the molecules which seem to display spatial correlation with each other
ImageDimPlot(nano.obj, fov = "lung5.rep1", group.by = NA, alpha = 0.3, molecules = c("KRT17", "C1QA",
    "IL7R", "TAGLN"), nmols = 20000)
```

Example 159 (r):
```r
# Plot some of the molecules which seem to display spatial correlation with each other
ImageDimPlot(nano.obj, fov = "lung5.rep1", group.by = NA, alpha = 0.3, molecules = c("KRT17", "C1QA",
    "IL7R", "TAGLN"), nmols = 20000)
```

Example 160 (r):
```r
# Plot some of the molecules which seem to display spatial correlation with each other
ImageDimPlot(nano.obj, fov = "lung5.rep1", group.by = NA, alpha = 0.3, molecules = c("KRT17", "C1QA",
    "IL7R", "TAGLN"), nmols = 20000)
```

Example 161 (unknown):
```unknown
basal.crop <- Crop(nano.obj[["lung5.rep1"]], x = c(159500, 164000), y = c(8700, 10500))
nano.obj[["zoom1"]] <- basal.crop
DefaultBoundary(nano.obj[["zoom1"]]) <- "segmentation"
```

Example 162 (r):
```r
basal.crop <- Crop(nano.obj[["lung5.rep1"]], x = c(159500, 164000), y = c(8700, 10500))
nano.obj[["zoom1"]] <- basal.crop
DefaultBoundary(nano.obj[["zoom1"]]) <- "segmentation"
```

Example 163 (r):
```r
basal.crop <- Crop(nano.obj[["lung5.rep1"]], x = c(159500, 164000), y = c(8700, 10500))
nano.obj[["zoom1"]] <- basal.crop
DefaultBoundary(nano.obj[["zoom1"]]) <- "segmentation"
```

Example 164 (unknown):
```unknown
ImageDimPlot(nano.obj, fov = "zoom1", cols = "polychrome", coord.fixed = FALSE)
```

Example 165 (r):
```r
ImageDimPlot(nano.obj, fov = "zoom1", cols = "polychrome", coord.fixed = FALSE)
```

Example 166 (r):
```r
ImageDimPlot(nano.obj, fov = "zoom1", cols = "polychrome", coord.fixed = FALSE)
```

Example 167 (unknown):
```unknown
# note the clouds of TPSAB1 molecules denoting mast cells
ImageDimPlot(nano.obj, fov = "zoom1", cols = "polychrome", alpha = 0.3, molecules = c("KRT17", "IL7R",
    "TPSAB1"), mols.size = 0.3, nmols = 20000, border.color = "black", coord.fixed = FALSE)
```

Example 168 (r):
```r
# note the clouds of TPSAB1 molecules denoting mast cells
ImageDimPlot(nano.obj, fov = "zoom1", cols = "polychrome", alpha = 0.3, molecules = c("KRT17", "IL7R",
    "TPSAB1"), mols.size = 0.3, nmols = 20000, border.color = "black", coord.fixed = FALSE)
```

Example 169 (r):
```r
# note the clouds of TPSAB1 molecules denoting mast cells
ImageDimPlot(nano.obj, fov = "zoom1", cols = "polychrome", alpha = 0.3, molecules = c("KRT17", "IL7R",
    "TPSAB1"), mols.size = 0.3, nmols = 20000, border.color = "black", coord.fixed = FALSE)
```

Example 170 (unknown):
```unknown
LoadAkoya()
```

Example 171 (unknown):
```unknown
codex.obj <- LoadAkoya(filename = "/brahms/hartmana/vignette_data/LN7910_20_008_11022020_reg001_compensated.csv",
    type = "processor", fov = "HBM754.WKLP.262")
```

Example 172 (r):
```r
codex.obj <- LoadAkoya(filename = "/brahms/hartmana/vignette_data/LN7910_20_008_11022020_reg001_compensated.csv",
    type = "processor", fov = "HBM754.WKLP.262")
```

Example 173 (r):
```r
codex.obj <- LoadAkoya(filename = "/brahms/hartmana/vignette_data/LN7910_20_008_11022020_reg001_compensated.csv",
    type = "processor", fov = "HBM754.WKLP.262")
```

Example 174 (unknown):
```unknown
codex.obj <- NormalizeData(object = codex.obj, normalization.method = "CLR", margin = 2)
codex.obj <- ScaleData(codex.obj)
VariableFeatures(codex.obj) <- rownames(codex.obj)  # since the panel is small, treat all features as variable.
codex.obj <- RunPCA(object = codex.obj, npcs = 20, verbose = FALSE)
codex.obj <- RunUMAP(object = codex.obj, dims = 1:20, verbose = FALSE)
codex.obj <- FindNeighbors(object = codex.obj, dims = 1:20, verbose = FALSE)
codex.obj <- FindClusters(object = codex.obj, verbose = FALSE, resolution = 0.4, n.start = 1)
```

Example 175 (r):
```r
codex.obj <- NormalizeData(object = codex.obj, normalization.method = "CLR", margin = 2)
codex.obj <- ScaleData(codex.obj)
VariableFeatures(codex.obj) <- rownames(codex.obj)  # since the panel is small, treat all features as variable.
codex.obj <- RunPCA(object = codex.obj, npcs = 20, verbose = FALSE)
codex.obj <- RunUMAP(object = codex.obj, dims = 1:20, verbose = FALSE)
codex.obj <- FindNeighbors(object = codex.obj, dims = 1:20, verbose = FALSE)
codex.obj <- FindClusters(object = codex.obj, verbose = FALSE, resolution = 0.4, n.start = 1)
```

Example 176 (r):
```r
codex.obj <- NormalizeData(object = codex.obj, normalization.method = "CLR", margin = 2)
codex.obj <- ScaleData(codex.obj)
VariableFeatures(codex.obj) <- rownames(codex.obj)  # since the panel is small, treat all features as variable.
codex.obj <- RunPCA(object = codex.obj, npcs = 20, verbose = FALSE)
codex.obj <- RunUMAP(object = codex.obj, dims = 1:20, verbose = FALSE)
codex.obj <- FindNeighbors(object = codex.obj, dims = 1:20, verbose = FALSE)
codex.obj <- FindClusters(object = codex.obj, verbose = FALSE, resolution = 0.4, n.start = 1)
```

Example 177 (unknown):
```unknown
DimPlot(codex.obj, label = TRUE, label.box = TRUE) + NoLegend()
```

Example 178 (r):
```r
DimPlot(codex.obj, label = TRUE, label.box = TRUE) + NoLegend()
```

Example 179 (r):
```r
DimPlot(codex.obj, label = TRUE, label.box = TRUE) + NoLegend()
```

Example 180 (unknown):
```unknown
ImageDimPlot(codex.obj, cols = "parade")
```

Example 181 (r):
```r
ImageDimPlot(codex.obj, cols = "parade")
```

Example 182 (r):
```r
ImageDimPlot(codex.obj, cols = "parade")
```

Example 183 (unknown):
```unknown
p1 <- ImageFeaturePlot(codex.obj, fov = "HBM754.WKLP.262", features = c("CD34", "CD21", "Lyve1"),
    min.cutoff = "q10", max.cutoff = "q90")
p2 <- ImageDimPlot(codex.obj, fov = "HBM754.WKLP.262", cols = "parade")
p1 + p2
```

Example 184 (r):
```r
p1 <- ImageFeaturePlot(codex.obj, fov = "HBM754.WKLP.262", features = c("CD34", "CD21", "Lyve1"),
    min.cutoff = "q10", max.cutoff = "q90")
p2 <- ImageDimPlot(codex.obj, fov = "HBM754.WKLP.262", cols = "parade")
p1 + p2
```

Example 185 (r):
```r
p1 <- ImageFeaturePlot(codex.obj, fov = "HBM754.WKLP.262", features = c("CD34", "CD21", "Lyve1"),
    min.cutoff = "q10", max.cutoff = "q90")
p2 <- ImageDimPlot(codex.obj, fov = "HBM754.WKLP.262", cols = "parade")
p1 + p2
```

Example 186 (unknown):
```unknown
sessionInfo()
```

Example 187 (r):
```r
sessionInfo()
```

Example 188 (r):
```r
sessionInfo()
```

Example 189 (unknown):
```unknown
## R version 4.4.2 (2024-10-31)
## Platform: x86_64-pc-linux-gnu
## Running under: Ubuntu 20.04.6 LTS
## 
## Matrix products: default
## BLAS:   /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.9.0 
## LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.9.0
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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: America/New_York
## tzcode source: system (glibc)
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
## [1] spacexr_2.2.1      ggplot2_3.5.2      future_1.67.0      Seurat_5.3.1 
## [5] SeuratObject_5.1.0 sp_2.2-0          
## 
## loaded via a namespace (and not attached):
##   [1] RcppAnnoy_0.0.22            splines_4.4.2              
##   [3] later_1.4.2                 tibble_3.2.1               
##   [5] R.oo_1.27.1                 polyclip_1.10-7            
##   [7] fastDummies_1.7.5           lifecycle_1.0.4            
##   [9] sf_1.0-21                   doParallel_1.0.17          
##  [11] globals_0.18.0              lattice_0.22-7             
##  [13] hdf5r_1.3.12                MASS_7.3-65                
##  [15] magrittr_2.0.3              plotly_4.10.4              
##  [17] sass_0.4.10                 rmarkdown_2.29             
##  [19] jquerylib_0.1.4             yaml_2.3.10                
##  [21] httpuv_1.6.16               glmGamPoi_1.18.0           
##  [23] sctransform_0.4.2           spam_2.11-1                
##  [25] spatstat.sparse_3.1-0       reticulate_1.42.0          
##  [27] cowplot_1.1.3               pbapply_1.7-2              
##  [29] DBI_1.2.3                   RColorBrewer_1.1-3         
##  [31] abind_1.4-8                 zlibbioc_1.52.0            
##  [33] Rtsne_0.17                  GenomicRanges_1.58.0       
##  [35] purrr_1.0.4                 presto_1.0.0               
##  [37] R.utils_2.13.0              BiocGenerics_0.52.0        
##  [39] GenomeInfoDbData_1.2.13     IRanges_2.40.1             
##  [41] S4Vectors_0.44.0            ggrepel_0.9.6              
##  [43] irlba_2.3.5.1               listenv_0.9.1              
##  [45] spatstat.utils_3.1-4        units_0.8-7                
##  [47] goftest_1.2-3               RSpectra_0.16-2            
##  [49] spatstat.random_3.4-1       fitdistrplus_1.2-2         
##  [51] parallelly_1.45.1           pkgdown_2.1.3              
##  [53] codetools_0.2-20            DelayedArray_0.32.0        
##  [55] tidyselect_1.2.1            UCSC.utils_1.2.0           
##  [57] farver_2.1.2                matrixStats_1.5.0          
##  [59] stats4_4.4.2                spatstat.explore_3.4-3     
##  [61] jsonlite_2.0.0              e1071_1.7-16               
##  [63] progressr_0.15.1            iterators_1.0.14           
##  [65] ggridges_0.5.6              survival_3.8-3             
##  [67] systemfonts_1.2.3           foreach_1.5.2              
##  [69] tools_4.4.2                 ragg_1.4.0                 
##  [71] ica_1.0-3                   Rcpp_1.1.0                 
##  [73] glue_1.8.0                  gridExtra_2.3              
##  [75] SparseArray_1.6.2           xfun_0.52                  
##  [77] MatrixGenerics_1.18.1       GenomeInfoDb_1.42.3        
##  [79] dplyr_1.1.4                 withr_3.0.2                
##  [81] formatR_1.14                fastmap_1.2.0              
##  [83] digest_0.6.37               R6_2.6.1                   
##  [85] mime_0.13                   textshaping_1.0.1          
##  [87] Cairo_1.6-2                 scattermore_1.2            
##  [89] tensor_1.5                  dichromat_2.0-0.1          
##  [91] spatstat.data_3.1-6         R.methodsS3_1.8.2          
##  [93] tidyr_1.3.1                 generics_0.1.4             
##  [95] data.table_1.17.4           class_7.3-23               
##  [97] httr_1.4.7                  htmlwidgets_1.6.4          
##  [99] S4Arrays_1.6.0              uwot_0.2.3                 
## [101] pkgconfig_2.0.3             gtable_0.3.6               
## [103] lmtest_0.9-40               XVector_0.46.0             
## [105] htmltools_0.5.8.1           dotCall64_1.2              
## [107] scales_1.4.0                Biobase_2.66.0             
## [109] png_0.1-8                   spatstat.univar_3.1-3      
## [111] knitr_1.50                  rstudioapi_0.17.1          
## [113] reshape2_1.4.4              nlme_3.1-168               
## [115] proxy_0.4-27                cachem_1.1.0               
## [117] zoo_1.8-14                  stringr_1.5.1              
## [119] KernSmooth_2.23-26          vipor_0.4.7                
## [121] parallel_4.4.2              miniUI_0.1.2               
## [123] arrow_21.0.0                ggrastr_1.0.2              
## [125] desc_1.4.3                  pillar_1.10.2              
## [127] grid_4.4.2                  vctrs_0.6.5                
## [129] RANN_2.6.2                  promises_1.3.3             
## [131] xtable_1.8-4                cluster_2.1.8.1            
## [133] beeswarm_0.4.0              evaluate_1.0.3             
## [135] cli_3.6.5                   compiler_4.4.2             
## [137] rlang_1.1.6                 crayon_1.5.3               
## [139] future.apply_1.20.0         labeling_0.4.3             
## [141] classInt_0.4-11             ggbeeswarm_0.7.2           
## [143] plyr_1.8.9                  fs_1.6.6                   
## [145] stringi_1.8.7               viridisLite_0.4.2          
## [147] deldir_2.0-4                assertthat_0.2.1           
## [149] lazyeval_0.2.2              spatstat.geom_3.4-1        
## [151] Matrix_1.7-3                RcppHNSW_0.6.0             
## [153] patchwork_1.3.0             bit64_4.6.0-1              
## [155] shiny_1.10.0                SummarizedExperiment_1.36.0
## [157] ROCR_1.0-11                 igraph_2.1.4               
## [159] bslib_0.9.0                 bit_4.6.0
```

Example 190 (unknown):
```unknown
## R version 4.4.2 (2024-10-31)
## Platform: x86_64-pc-linux-gnu
## Running under: Ubuntu 20.04.6 LTS
## 
## Matrix products: default
## BLAS:   /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.9.0 
## LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.9.0
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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: America/New_York
## tzcode source: system (glibc)
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
## [1] spacexr_2.2.1      ggplot2_3.5.2      future_1.67.0      Seurat_5.3.1 
## [5] SeuratObject_5.1.0 sp_2.2-0          
## 
## loaded via a namespace (and not attached):
##   [1] RcppAnnoy_0.0.22            splines_4.4.2              
##   [3] later_1.4.2                 tibble_3.2.1               
##   [5] R.oo_1.27.1                 polyclip_1.10-7            
##   [7] fastDummies_1.7.5           lifecycle_1.0.4            
##   [9] sf_1.0-21                   doParallel_1.0.17          
##  [11] globals_0.18.0              lattice_0.22-7             
##  [13] hdf5r_1.3.12                MASS_7.3-65                
##  [15] magrittr_2.0.3              plotly_4.10.4              
##  [17] sass_0.4.10                 rmarkdown_2.29             
##  [19] jquerylib_0.1.4             yaml_2.3.10                
##  [21] httpuv_1.6.16               glmGamPoi_1.18.0           
##  [23] sctransform_0.4.2           spam_2.11-1                
##  [25] spatstat.sparse_3.1-0       reticulate_1.42.0          
##  [27] cowplot_1.1.3               pbapply_1.7-2              
##  [29] DBI_1.2.3                   RColorBrewer_1.1-3         
##  [31] abind_1.4-8                 zlibbioc_1.52.0            
##  [33] Rtsne_0.17                  GenomicRanges_1.58.0       
##  [35] purrr_1.0.4                 presto_1.0.0               
##  [37] R.utils_2.13.0              BiocGenerics_0.52.0        
##  [39] GenomeInfoDbData_1.2.13     IRanges_2.40.1             
##  [41] S4Vectors_0.44.0            ggrepel_0.9.6              
##  [43] irlba_2.3.5.1               listenv_0.9.1              
##  [45] spatstat.utils_3.1-4        units_0.8-7                
##  [47] goftest_1.2-3               RSpectra_0.16-2            
##  [49] spatstat.random_3.4-1       fitdistrplus_1.2-2         
##  [51] parallelly_1.45.1           pkgdown_2.1.3              
##  [53] codetools_0.2-20            DelayedArray_0.32.0        
##  [55] tidyselect_1.2.1            UCSC.utils_1.2.0           
##  [57] farver_2.1.2                matrixStats_1.5.0          
##  [59] stats4_4.4.2                spatstat.explore_3.4-3     
##  [61] jsonlite_2.0.0              e1071_1.7-16               
##  [63] progressr_0.15.1            iterators_1.0.14           
##  [65] ggridges_0.5.6              survival_3.8-3             
##  [67] systemfonts_1.2.3           foreach_1.5.2              
##  [69] tools_4.4.2                 ragg_1.4.0                 
##  [71] ica_1.0-3                   Rcpp_1.1.0                 
##  [73] glue_1.8.0                  gridExtra_2.3              
##  [75] SparseArray_1.6.2           xfun_0.52                  
##  [77] MatrixGenerics_1.18.1       GenomeInfoDb_1.42.3        
##  [79] dplyr_1.1.4                 withr_3.0.2                
##  [81] formatR_1.14                fastmap_1.2.0              
##  [83] digest_0.6.37               R6_2.6.1                   
##  [85] mime_0.13                   textshaping_1.0.1          
##  [87] Cairo_1.6-2                 scattermore_1.2            
##  [89] tensor_1.5                  dichromat_2.0-0.1          
##  [91] spatstat.data_3.1-6         R.methodsS3_1.8.2          
##  [93] tidyr_1.3.1                 generics_0.1.4             
##  [95] data.table_1.17.4           class_7.3-23               
##  [97] httr_1.4.7                  htmlwidgets_1.6.4          
##  [99] S4Arrays_1.6.0              uwot_0.2.3                 
## [101] pkgconfig_2.0.3             gtable_0.3.6               
## [103] lmtest_0.9-40               XVector_0.46.0             
## [105] htmltools_0.5.8.1           dotCall64_1.2              
## [107] scales_1.4.0                Biobase_2.66.0             
## [109] png_0.1-8                   spatstat.univar_3.1-3      
## [111] knitr_1.50                  rstudioapi_0.17.1          
## [113] reshape2_1.4.4              nlme_3.1-168               
## [115] proxy_0.4-27                cachem_1.1.0               
## [117] zoo_1.8-14                  stringr_1.5.1              
## [119] KernSmooth_2.23-26          vipor_0.4.7                
## [121] parallel_4.4.2              miniUI_0.1.2               
## [123] arrow_21.0.0                ggrastr_1.0.2              
## [125] desc_1.4.3                  pillar_1.10.2              
## [127] grid_4.4.2                  vctrs_0.6.5                
## [129] RANN_2.6.2                  promises_1.3.3             
## [131] xtable_1.8-4                cluster_2.1.8.1            
## [133] beeswarm_0.4.0              evaluate_1.0.3             
## [135] cli_3.6.5                   compiler_4.4.2             
## [137] rlang_1.1.6                 crayon_1.5.3               
## [139] future.apply_1.20.0         labeling_0.4.3             
## [141] classInt_0.4-11             ggbeeswarm_0.7.2           
## [143] plyr_1.8.9                  fs_1.6.6                   
## [145] stringi_1.8.7               viridisLite_0.4.2          
## [147] deldir_2.0-4                assertthat_0.2.1           
## [149] lazyeval_0.2.2              spatstat.geom_3.4-1        
## [151] Matrix_1.7-3                RcppHNSW_0.6.0             
## [153] patchwork_1.3.0             bit64_4.6.0-1              
## [155] shiny_1.10.0                SummarizedExperiment_1.36.0
## [157] ROCR_1.0-11                 igraph_2.1.4               
## [159] bslib_0.9.0                 bit_4.6.0
```

---

## Fast integration using reciprocal PCA (RPCA) • Seurat

**URL:** http://127.0.0.1:9173/seurat/archive/v4.3/integration_rpca/index.html

**Contents:**
- Fast integration using reciprocal PCA (RPCA)
    - Compiled: January 11, 2022
- Perform integration
- Modifying the strength of integration
- Performing integration on datasets normalized with SCTransform
- Contents

In this vignette, we present a slightly modified workflow for the integration of scRNA-seq datasets. Instead of utilizing canonical correlation analysis (‘CCA’) to identify anchors, we instead utilize reciprocal PCA (‘RPCA’). When determining anchors between any two datasets using RPCA, we project each dataset into the others PCA space and constrain the anchors by the same mutual neighborhood requirement. The commands for both workflows are largely identical, but the two methods may be applied in different context.

By identifying shared sources of variation between datasets, CCA is well-suited for identifying anchors when cell types are conserved, but there are very substantial differences in gene expression across experiments. CCA-based integration therefore enables integrative analysis when experimental conditions or disease states introduce very strong expression shifts, or when integrating datasets across modalities and species. However, CCA-based integration may also lead to overcorrection, especially when a large proportion of cells are non-overlapping across datasets.

RPCA-based integration runs significantly faster, and also represents a more conservative approach where cells in different biological states are less likely to ‘align’ after integration. We therefore,recommend RPCA during integrative analysis where: * A substantial fraction of cells in one dataset have no matching type in the other * Datasets originate from the same platform (i.e. multiple lanes of 10x genomics) * There are a large number of datasets or cells to integrate (see INSERT LINK for more tips on integrating large datasets)

Below, we demonstrate the use of reciprocal PCA to align the same stimulated and resting datasets first analyzed in our introduction to scRNA-seq integration vignette. While the list of commands is nearly identical, this workflow requires users to run principal components analysis (PCA) individually on each dataset prior to integration. Users should also set the ‘reduction’ argument to ‘rpca’, when running FindIntegrationAnchors().

We then identify anchors using the FindIntegrationAnchors() function, which takes a list of Seurat objects as input, and use these anchors to integrate the two datasets together with IntegrateData().

Now we can run a single integrated analysis on all cells!

The results show that rpca-based integration is more conservative, and in this case, do not perfectly align a subset of cells (which are naive and memory T cells) across experiments. You can increase the strength of alignment by increasing the k.anchor parameter, which is set to 5 by default. Increasing this parameter to 20 will assist in aligning these populations.

Now that the datasets have been integrated, you can follow the previous steps in the introduction to scRNA-seq integration vignette to identify cell types and cell type-specific responses.

As an additional example, we repeat the analyses performed above, but normalize the datasets using SCTransform. We may choose to set the method parameter to glmGamPoi (install here) in order to enable faster estimation of regression parameters in SCTransform().

Developed by Paul Hoffman, Satija Lab and Collaborators.

Site built with pkgdown 1.6.1.

**Examples:**

Example 1 (unknown):
```unknown
vignettes/integration_rpca.Rmd
```

Example 2 (unknown):
```unknown
integration_rpca.Rmd
```

Example 3 (unknown):
```unknown
FindIntegrationAnchors()
```

Example 4 (unknown):
```unknown
library(SeuratData)
# install dataset
InstallData("ifnb")
```

Example 5 (r):
```r
library(SeuratData)
# install dataset
InstallData("ifnb")
```

Example 6 (r):
```r
library(SeuratData)
# install dataset
InstallData("ifnb")
```

Example 7 (javascript):
```javascript
# load dataset
LoadData("ifnb")

# split the dataset into a list of two seurat objects (stim and CTRL)
ifnb.list <- SplitObject(ifnb, split.by = "stim")

# normalize and identify variable features for each dataset independently
ifnb.list <- lapply(X = ifnb.list, FUN = function(x) {
    x <- NormalizeData(x)
    x <- FindVariableFeatures(x, selection.method = "vst", nfeatures = 2000)
})

# select features that are repeatedly variable across datasets for integration run PCA on each
# dataset using these features
features <- SelectIntegrationFeatures(object.list = ifnb.list)
ifnb.list <- lapply(X = ifnb.list, FUN = function(x) {
    x <- ScaleData(x, features = features, verbose = FALSE)
    x <- RunPCA(x, features = features, verbose = FALSE)
})
```

Example 8 (r):
```r
# load dataset
LoadData("ifnb")

# split the dataset into a list of two seurat objects (stim and CTRL)
ifnb.list <- SplitObject(ifnb, split.by = "stim")

# normalize and identify variable features for each dataset independently
ifnb.list <- lapply(X = ifnb.list, FUN = function(x) {
    x <- NormalizeData(x)
    x <- FindVariableFeatures(x, selection.method = "vst", nfeatures = 2000)
})

# select features that are repeatedly variable across datasets for integration run PCA on each
# dataset using these features
features <- SelectIntegrationFeatures(object.list = ifnb.list)
ifnb.list <- lapply(X = ifnb.list, FUN = function(x) {
    x <- ScaleData(x, features = features, verbose = FALSE)
    x <- RunPCA(x, features = features, verbose = FALSE)
})
```

Example 9 (r):
```r
# load dataset
LoadData("ifnb")

# split the dataset into a list of two seurat objects (stim and CTRL)
ifnb.list <- SplitObject(ifnb, split.by = "stim")

# normalize and identify variable features for each dataset independently
ifnb.list <- lapply(X = ifnb.list, FUN = function(x) {
    x <- NormalizeData(x)
    x <- FindVariableFeatures(x, selection.method = "vst", nfeatures = 2000)
})

# select features that are repeatedly variable across datasets for integration run PCA on each
# dataset using these features
features <- SelectIntegrationFeatures(object.list = ifnb.list)
ifnb.list <- lapply(X = ifnb.list, FUN = function(x) {
    x <- ScaleData(x, features = features, verbose = FALSE)
    x <- RunPCA(x, features = features, verbose = FALSE)
})
```

Example 10 (unknown):
```unknown
FindIntegrationAnchors()
```

Example 11 (unknown):
```unknown
IntegrateData()
```

Example 12 (unknown):
```unknown
immune.anchors <- FindIntegrationAnchors(object.list = ifnb.list, anchor.features = features, reduction = "rpca")
```

Example 13 (r):
```r
immune.anchors <- FindIntegrationAnchors(object.list = ifnb.list, anchor.features = features, reduction = "rpca")
```

Example 14 (r):
```r
immune.anchors <- FindIntegrationAnchors(object.list = ifnb.list, anchor.features = features, reduction = "rpca")
```

Example 15 (unknown):
```unknown
# this command creates an 'integrated' data assay
immune.combined <- IntegrateData(anchorset = immune.anchors)
```

Example 16 (r):
```r
# this command creates an 'integrated' data assay
immune.combined <- IntegrateData(anchorset = immune.anchors)
```

Example 17 (r):
```r
# this command creates an 'integrated' data assay
immune.combined <- IntegrateData(anchorset = immune.anchors)
```

Example 18 (unknown):
```unknown
# specify that we will perform downstream analysis on the corrected data note that the
# original unmodified data still resides in the 'RNA' assay
DefaultAssay(immune.combined) <- "integrated"

# Run the standard workflow for visualization and clustering
immune.combined <- ScaleData(immune.combined, verbose = FALSE)
immune.combined <- RunPCA(immune.combined, npcs = 30, verbose = FALSE)
immune.combined <- RunUMAP(immune.combined, reduction = "pca", dims = 1:30)
immune.combined <- FindNeighbors(immune.combined, reduction = "pca", dims = 1:30)
immune.combined <- FindClusters(immune.combined, resolution = 0.5)
```

Example 19 (r):
```r
# specify that we will perform downstream analysis on the corrected data note that the
# original unmodified data still resides in the 'RNA' assay
DefaultAssay(immune.combined) <- "integrated"

# Run the standard workflow for visualization and clustering
immune.combined <- ScaleData(immune.combined, verbose = FALSE)
immune.combined <- RunPCA(immune.combined, npcs = 30, verbose = FALSE)
immune.combined <- RunUMAP(immune.combined, reduction = "pca", dims = 1:30)
immune.combined <- FindNeighbors(immune.combined, reduction = "pca", dims = 1:30)
immune.combined <- FindClusters(immune.combined, resolution = 0.5)
```

Example 20 (r):
```r
# specify that we will perform downstream analysis on the corrected data note that the
# original unmodified data still resides in the 'RNA' assay
DefaultAssay(immune.combined) <- "integrated"

# Run the standard workflow for visualization and clustering
immune.combined <- ScaleData(immune.combined, verbose = FALSE)
immune.combined <- RunPCA(immune.combined, npcs = 30, verbose = FALSE)
immune.combined <- RunUMAP(immune.combined, reduction = "pca", dims = 1:30)
immune.combined <- FindNeighbors(immune.combined, reduction = "pca", dims = 1:30)
immune.combined <- FindClusters(immune.combined, resolution = 0.5)
```

Example 21 (unknown):
```unknown
# Visualization
p1 <- DimPlot(immune.combined, reduction = "umap", group.by = "stim")
p2 <- DimPlot(immune.combined, reduction = "umap", group.by = "seurat_annotations", label = TRUE,
    repel = TRUE)
p1 + p2
```

Example 22 (r):
```r
# Visualization
p1 <- DimPlot(immune.combined, reduction = "umap", group.by = "stim")
p2 <- DimPlot(immune.combined, reduction = "umap", group.by = "seurat_annotations", label = TRUE,
    repel = TRUE)
p1 + p2
```

Example 23 (r):
```r
# Visualization
p1 <- DimPlot(immune.combined, reduction = "umap", group.by = "stim")
p2 <- DimPlot(immune.combined, reduction = "umap", group.by = "seurat_annotations", label = TRUE,
    repel = TRUE)
p1 + p2
```

Example 24 (unknown):
```unknown
immune.anchors <- FindIntegrationAnchors(object.list = ifnb.list, anchor.features = features, reduction = "rpca",
    k.anchor = 20)
immune.combined <- IntegrateData(anchorset = immune.anchors)

immune.combined <- ScaleData(immune.combined, verbose = FALSE)
immune.combined <- RunPCA(immune.combined, npcs = 30, verbose = FALSE)
immune.combined <- RunUMAP(immune.combined, reduction = "pca", dims = 1:30)
immune.combined <- FindNeighbors(immune.combined, reduction = "pca", dims = 1:30)
immune.combined <- FindClusters(immune.combined, resolution = 0.5)
```

Example 25 (r):
```r
immune.anchors <- FindIntegrationAnchors(object.list = ifnb.list, anchor.features = features, reduction = "rpca",
    k.anchor = 20)
immune.combined <- IntegrateData(anchorset = immune.anchors)

immune.combined <- ScaleData(immune.combined, verbose = FALSE)
immune.combined <- RunPCA(immune.combined, npcs = 30, verbose = FALSE)
immune.combined <- RunUMAP(immune.combined, reduction = "pca", dims = 1:30)
immune.combined <- FindNeighbors(immune.combined, reduction = "pca", dims = 1:30)
immune.combined <- FindClusters(immune.combined, resolution = 0.5)
```

Example 26 (r):
```r
immune.anchors <- FindIntegrationAnchors(object.list = ifnb.list, anchor.features = features, reduction = "rpca",
    k.anchor = 20)
immune.combined <- IntegrateData(anchorset = immune.anchors)

immune.combined <- ScaleData(immune.combined, verbose = FALSE)
immune.combined <- RunPCA(immune.combined, npcs = 30, verbose = FALSE)
immune.combined <- RunUMAP(immune.combined, reduction = "pca", dims = 1:30)
immune.combined <- FindNeighbors(immune.combined, reduction = "pca", dims = 1:30)
immune.combined <- FindClusters(immune.combined, resolution = 0.5)
```

Example 27 (unknown):
```unknown
## Modularity Optimizer version 1.3.0 by Ludo Waltman and Nees Jan van Eck
## 
## Number of nodes: 13999
## Number of edges: 589767
## 
## Running Louvain algorithm...
## Maximum modularity in 10 random starts: 0.9094
## Number of communities: 15
## Elapsed time: 4 seconds
```

Example 28 (unknown):
```unknown
## Modularity Optimizer version 1.3.0 by Ludo Waltman and Nees Jan van Eck
## 
## Number of nodes: 13999
## Number of edges: 589767
## 
## Running Louvain algorithm...
## Maximum modularity in 10 random starts: 0.9094
## Number of communities: 15
## Elapsed time: 4 seconds
```

Example 29 (unknown):
```unknown
# Visualization
p1 <- DimPlot(immune.combined, reduction = "umap", group.by = "stim")
p2 <- DimPlot(immune.combined, reduction = "umap", label = TRUE, repel = TRUE)
p1 + p2
```

Example 30 (r):
```r
# Visualization
p1 <- DimPlot(immune.combined, reduction = "umap", group.by = "stim")
p2 <- DimPlot(immune.combined, reduction = "umap", label = TRUE, repel = TRUE)
p1 + p2
```

Example 31 (r):
```r
# Visualization
p1 <- DimPlot(immune.combined, reduction = "umap", group.by = "stim")
p2 <- DimPlot(immune.combined, reduction = "umap", label = TRUE, repel = TRUE)
p1 + p2
```

Example 32 (unknown):
```unknown
SCTransform()
```

Example 33 (unknown):
```unknown
LoadData("ifnb")
ifnb.list <- SplitObject(ifnb, split.by = "stim")
ifnb.list <- lapply(X = ifnb.list, FUN = SCTransform, method = "glmGamPoi")
features <- SelectIntegrationFeatures(object.list = ifnb.list, nfeatures = 3000)
ifnb.list <- PrepSCTIntegration(object.list = ifnb.list, anchor.features = features)
ifnb.list <- lapply(X = ifnb.list, FUN = RunPCA, features = features)
```

Example 34 (r):
```r
LoadData("ifnb")
ifnb.list <- SplitObject(ifnb, split.by = "stim")
ifnb.list <- lapply(X = ifnb.list, FUN = SCTransform, method = "glmGamPoi")
features <- SelectIntegrationFeatures(object.list = ifnb.list, nfeatures = 3000)
ifnb.list <- PrepSCTIntegration(object.list = ifnb.list, anchor.features = features)
ifnb.list <- lapply(X = ifnb.list, FUN = RunPCA, features = features)
```

Example 35 (r):
```r
LoadData("ifnb")
ifnb.list <- SplitObject(ifnb, split.by = "stim")
ifnb.list <- lapply(X = ifnb.list, FUN = SCTransform, method = "glmGamPoi")
features <- SelectIntegrationFeatures(object.list = ifnb.list, nfeatures = 3000)
ifnb.list <- PrepSCTIntegration(object.list = ifnb.list, anchor.features = features)
ifnb.list <- lapply(X = ifnb.list, FUN = RunPCA, features = features)
```

Example 36 (unknown):
```unknown
immune.anchors <- FindIntegrationAnchors(object.list = ifnb.list, normalization.method = "SCT",
    anchor.features = features, dims = 1:30, reduction = "rpca", k.anchor = 20)
immune.combined.sct <- IntegrateData(anchorset = immune.anchors, normalization.method = "SCT", dims = 1:30)
```

Example 37 (r):
```r
immune.anchors <- FindIntegrationAnchors(object.list = ifnb.list, normalization.method = "SCT",
    anchor.features = features, dims = 1:30, reduction = "rpca", k.anchor = 20)
immune.combined.sct <- IntegrateData(anchorset = immune.anchors, normalization.method = "SCT", dims = 1:30)
```

Example 38 (r):
```r
immune.anchors <- FindIntegrationAnchors(object.list = ifnb.list, normalization.method = "SCT",
    anchor.features = features, dims = 1:30, reduction = "rpca", k.anchor = 20)
immune.combined.sct <- IntegrateData(anchorset = immune.anchors, normalization.method = "SCT", dims = 1:30)
```

Example 39 (unknown):
```unknown
immune.combined.sct <- RunPCA(immune.combined.sct, verbose = FALSE)
immune.combined.sct <- RunUMAP(immune.combined.sct, reduction = "pca", dims = 1:30)
```

Example 40 (r):
```r
immune.combined.sct <- RunPCA(immune.combined.sct, verbose = FALSE)
immune.combined.sct <- RunUMAP(immune.combined.sct, reduction = "pca", dims = 1:30)
```

Example 41 (r):
```r
immune.combined.sct <- RunPCA(immune.combined.sct, verbose = FALSE)
immune.combined.sct <- RunUMAP(immune.combined.sct, reduction = "pca", dims = 1:30)
```

Example 42 (unknown):
```unknown
# Visualization
p1 <- DimPlot(immune.combined.sct, reduction = "umap", group.by = "stim")
p2 <- DimPlot(immune.combined.sct, reduction = "umap", group.by = "seurat_annotations", label = TRUE,
    repel = TRUE)
p1 + p2
```

Example 43 (r):
```r
# Visualization
p1 <- DimPlot(immune.combined.sct, reduction = "umap", group.by = "stim")
p2 <- DimPlot(immune.combined.sct, reduction = "umap", group.by = "seurat_annotations", label = TRUE,
    repel = TRUE)
p1 + p2
```

Example 44 (r):
```r
# Visualization
p1 <- DimPlot(immune.combined.sct, reduction = "umap", group.by = "stim")
p2 <- DimPlot(immune.combined.sct, reduction = "umap", group.by = "seurat_annotations", label = TRUE,
    repel = TRUE)
p1 + p2
```

Example 45 (unknown):
```unknown
sessionInfo()
```

Example 46 (r):
```r
sessionInfo()
```

Example 47 (r):
```r
sessionInfo()
```

Example 48 (unknown):
```unknown
## R version 4.1.0 (2021-05-18)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.2 LTS
## 
## Matrix products: default
## BLAS/LAPACK: /usr/lib/x86_64-linux-gnu/openblas-pthread/libopenblasp-r0.3.8.so
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [5] LC_MONETARY=en_US.UTF-8    LC_MESSAGES=C             
##  [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       
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
##  [1] ggplot2_3.3.5                 SeuratObject_4.0.4           
##  [3] Seurat_4.0.6                  thp1.eccite.SeuratData_3.1.5 
##  [5] stxBrain.SeuratData_0.1.1     ssHippo.SeuratData_3.1.4     
##  [7] pbmcsca.SeuratData_3.0.0      pbmcMultiome.SeuratData_0.1.1
##  [9] pbmc3k.SeuratData_3.1.4       panc8.SeuratData_3.0.2       
## [11] ifnb.SeuratData_3.1.0         hcabm40k.SeuratData_3.0.0    
## [13] bmcite.SeuratData_0.3.0       SeuratData_0.2.1             
## 
## loaded via a namespace (and not attached):
##   [1] systemfonts_1.0.2           plyr_1.8.6                 
##   [3] igraph_1.2.11               lazyeval_0.2.2             
##   [5] splines_4.1.0               listenv_0.8.0              
##   [7] scattermore_0.7             GenomeInfoDb_1.28.1        
##   [9] digest_0.6.29               htmltools_0.5.2            
##  [11] fansi_1.0.0                 magrittr_2.0.1             
##  [13] memoise_2.0.0               tensor_1.5                 
##  [15] cluster_2.1.2               ROCR_1.0-11                
##  [17] globals_0.14.0              matrixStats_0.61.0         
##  [19] pkgdown_1.6.1               spatstat.sparse_2.1-0      
##  [21] colorspace_2.0-2            rappdirs_0.3.3             
##  [23] ggrepel_0.9.1               textshaping_0.3.5          
##  [25] xfun_0.25                   dplyr_1.0.7                
##  [27] RCurl_1.98-1.3              crayon_1.4.2               
##  [29] jsonlite_1.7.2              spatstat.data_2.1-2        
##  [31] survival_3.2-11             zoo_1.8-9                  
##  [33] glue_1.6.0                  polyclip_1.10-0            
##  [35] gtable_0.3.0                zlibbioc_1.38.0            
##  [37] XVector_0.32.0              leiden_0.3.9               
##  [39] DelayedArray_0.18.0         future.apply_1.8.1         
##  [41] BiocGenerics_0.38.0         abind_1.4-5                
##  [43] scales_1.1.1                DBI_1.1.1                  
##  [45] miniUI_0.1.1.1              Rcpp_1.0.7                 
##  [47] viridisLite_0.4.0           xtable_1.8-4               
##  [49] reticulate_1.22             spatstat.core_2.3-2        
##  [51] stats4_4.1.0                htmlwidgets_1.5.4          
##  [53] httr_1.4.2                  RColorBrewer_1.1-2         
##  [55] ellipsis_0.3.2              ica_1.0-2                  
##  [57] pkgconfig_2.0.3             farver_2.1.0               
##  [59] sass_0.4.0                  uwot_0.1.11                
##  [61] deldir_1.0-6                utf8_1.2.2                 
##  [63] tidyselect_1.1.1            labeling_0.4.2             
##  [65] rlang_0.4.12                reshape2_1.4.4             
##  [67] later_1.3.0                 munsell_0.5.0              
##  [69] tools_4.1.0                 cachem_1.0.6               
##  [71] cli_3.1.0                   generics_0.1.1             
##  [73] ggridges_0.5.3              evaluate_0.14              
##  [75] stringr_1.4.0               fastmap_1.1.0              
##  [77] yaml_2.2.1                  ragg_1.1.3                 
##  [79] goftest_1.2-3               knitr_1.33                 
##  [81] fs_1.5.2                    fitdistrplus_1.1-6         
##  [83] purrr_0.3.4                 RANN_2.6.1                 
##  [85] sparseMatrixStats_1.4.2     pbapply_1.5-0              
##  [87] future_1.23.0               nlme_3.1-152               
##  [89] mime_0.12                   formatR_1.11               
##  [91] compiler_4.1.0              plotly_4.10.0              
##  [93] png_0.1-7                   spatstat.utils_2.3-0       
##  [95] tibble_3.1.6                bslib_0.3.1                
##  [97] glmGamPoi_1.4.0             stringi_1.7.6              
##  [99] highr_0.9                   desc_1.4.0                 
## [101] RSpectra_0.16-0             lattice_0.20-44            
## [103] Matrix_1.3-3                vctrs_0.3.8                
## [105] pillar_1.6.4                lifecycle_1.0.1            
## [107] spatstat.geom_2.3-1         lmtest_0.9-39              
## [109] jquerylib_0.1.4             RcppAnnoy_0.0.19           
## [111] bitops_1.0-7                data.table_1.14.2          
## [113] cowplot_1.1.1               irlba_2.3.5                
## [115] GenomicRanges_1.44.0        httpuv_1.6.5               
## [117] patchwork_1.1.1             R6_2.5.1                   
## [119] promises_1.2.0.1            KernSmooth_2.23-20         
## [121] gridExtra_2.3               IRanges_2.26.0             
## [123] parallelly_1.30.0           codetools_0.2-18           
## [125] MASS_7.3-54                 assertthat_0.2.1           
## [127] SummarizedExperiment_1.22.0 rprojroot_2.0.2            
## [129] withr_2.4.3                 sctransform_0.3.2          
## [131] GenomeInfoDbData_1.2.6      S4Vectors_0.30.0           
## [133] mgcv_1.8-35                 parallel_4.1.0             
## [135] grid_4.1.0                  rpart_4.1-15               
## [137] tidyr_1.1.4                 DelayedMatrixStats_1.14.2  
## [139] rmarkdown_2.10              MatrixGenerics_1.4.2       
## [141] Rtsne_0.15                  Biobase_2.52.0             
## [143] shiny_1.7.1
```

Example 49 (unknown):
```unknown
## R version 4.1.0 (2021-05-18)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.2 LTS
## 
## Matrix products: default
## BLAS/LAPACK: /usr/lib/x86_64-linux-gnu/openblas-pthread/libopenblasp-r0.3.8.so
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [5] LC_MONETARY=en_US.UTF-8    LC_MESSAGES=C             
##  [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       
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
##  [1] ggplot2_3.3.5                 SeuratObject_4.0.4           
##  [3] Seurat_4.0.6                  thp1.eccite.SeuratData_3.1.5 
##  [5] stxBrain.SeuratData_0.1.1     ssHippo.SeuratData_3.1.4     
##  [7] pbmcsca.SeuratData_3.0.0      pbmcMultiome.SeuratData_0.1.1
##  [9] pbmc3k.SeuratData_3.1.4       panc8.SeuratData_3.0.2       
## [11] ifnb.SeuratData_3.1.0         hcabm40k.SeuratData_3.0.0    
## [13] bmcite.SeuratData_0.3.0       SeuratData_0.2.1             
## 
## loaded via a namespace (and not attached):
##   [1] systemfonts_1.0.2           plyr_1.8.6                 
##   [3] igraph_1.2.11               lazyeval_0.2.2             
##   [5] splines_4.1.0               listenv_0.8.0              
##   [7] scattermore_0.7             GenomeInfoDb_1.28.1        
##   [9] digest_0.6.29               htmltools_0.5.2            
##  [11] fansi_1.0.0                 magrittr_2.0.1             
##  [13] memoise_2.0.0               tensor_1.5                 
##  [15] cluster_2.1.2               ROCR_1.0-11                
##  [17] globals_0.14.0              matrixStats_0.61.0         
##  [19] pkgdown_1.6.1               spatstat.sparse_2.1-0      
##  [21] colorspace_2.0-2            rappdirs_0.3.3             
##  [23] ggrepel_0.9.1               textshaping_0.3.5          
##  [25] xfun_0.25                   dplyr_1.0.7                
##  [27] RCurl_1.98-1.3              crayon_1.4.2               
##  [29] jsonlite_1.7.2              spatstat.data_2.1-2        
##  [31] survival_3.2-11             zoo_1.8-9                  
##  [33] glue_1.6.0                  polyclip_1.10-0            
##  [35] gtable_0.3.0                zlibbioc_1.38.0            
##  [37] XVector_0.32.0              leiden_0.3.9               
##  [39] DelayedArray_0.18.0         future.apply_1.8.1         
##  [41] BiocGenerics_0.38.0         abind_1.4-5                
##  [43] scales_1.1.1                DBI_1.1.1                  
##  [45] miniUI_0.1.1.1              Rcpp_1.0.7                 
##  [47] viridisLite_0.4.0           xtable_1.8-4               
##  [49] reticulate_1.22             spatstat.core_2.3-2        
##  [51] stats4_4.1.0                htmlwidgets_1.5.4          
##  [53] httr_1.4.2                  RColorBrewer_1.1-2         
##  [55] ellipsis_0.3.2              ica_1.0-2                  
##  [57] pkgconfig_2.0.3             farver_2.1.0               
##  [59] sass_0.4.0                  uwot_0.1.11                
##  [61] deldir_1.0-6                utf8_1.2.2                 
##  [63] tidyselect_1.1.1            labeling_0.4.2             
##  [65] rlang_0.4.12                reshape2_1.4.4             
##  [67] later_1.3.0                 munsell_0.5.0              
##  [69] tools_4.1.0                 cachem_1.0.6               
##  [71] cli_3.1.0                   generics_0.1.1             
##  [73] ggridges_0.5.3              evaluate_0.14              
##  [75] stringr_1.4.0               fastmap_1.1.0              
##  [77] yaml_2.2.1                  ragg_1.1.3                 
##  [79] goftest_1.2-3               knitr_1.33                 
##  [81] fs_1.5.2                    fitdistrplus_1.1-6         
##  [83] purrr_0.3.4                 RANN_2.6.1                 
##  [85] sparseMatrixStats_1.4.2     pbapply_1.5-0              
##  [87] future_1.23.0               nlme_3.1-152               
##  [89] mime_0.12                   formatR_1.11               
##  [91] compiler_4.1.0              plotly_4.10.0              
##  [93] png_0.1-7                   spatstat.utils_2.3-0       
##  [95] tibble_3.1.6                bslib_0.3.1                
##  [97] glmGamPoi_1.4.0             stringi_1.7.6              
##  [99] highr_0.9                   desc_1.4.0                 
## [101] RSpectra_0.16-0             lattice_0.20-44            
## [103] Matrix_1.3-3                vctrs_0.3.8                
## [105] pillar_1.6.4                lifecycle_1.0.1            
## [107] spatstat.geom_2.3-1         lmtest_0.9-39              
## [109] jquerylib_0.1.4             RcppAnnoy_0.0.19           
## [111] bitops_1.0-7                data.table_1.14.2          
## [113] cowplot_1.1.1               irlba_2.3.5                
## [115] GenomicRanges_1.44.0        httpuv_1.6.5               
## [117] patchwork_1.1.1             R6_2.5.1                   
## [119] promises_1.2.0.1            KernSmooth_2.23-20         
## [121] gridExtra_2.3               IRanges_2.26.0             
## [123] parallelly_1.30.0           codetools_0.2-18           
## [125] MASS_7.3-54                 assertthat_0.2.1           
## [127] SummarizedExperiment_1.22.0 rprojroot_2.0.2            
## [129] withr_2.4.3                 sctransform_0.3.2          
## [131] GenomeInfoDbData_1.2.6      S4Vectors_0.30.0           
## [133] mgcv_1.8-35                 parallel_4.1.0             
## [135] grid_4.1.0                  rpart_4.1-15               
## [137] tidyr_1.1.4                 DelayedMatrixStats_1.14.2  
## [139] rmarkdown_2.10              MatrixGenerics_1.4.2       
## [141] Rtsne_0.15                  Biobase_2.52.0             
## [143] shiny_1.7.1
```

---

## Analysis, visualization, and integration of Visium HD spatial datasets with Seurat • Seurat

**URL:** http://127.0.0.1:9173/seurat/articles/integration_mapping/index.html

**Contents:**
- Mapping and annotating query datasets
    - Compiled: 2023-10-31
- Introduction to single-cell reference mapping
- Dataset preprocessing
- Cell type classification using an integrated reference
- Unimodal UMAP Projection
- Contents

In this vignette, we first build an integrated reference and then demonstrate how to leverage this reference to annotate new query datasets. Generating an integrated reference follows the same workflow described in more detail in the integration introduction vignette. Once generated, this reference can be used to analyze additional query datasets through tasks like cell type label transfer and projecting query cells onto reference UMAPs. Notably, this does not require correction of the underlying raw query data and can therefore be an efficient strategy if a high quality reference is available.

For the purposes of this example, we’ve chosen human pancreatic islet cell datasets produced across four technologies, CelSeq (GSE81076) CelSeq2 (GSE85241), Fluidigm C1 (GSE86469), and SMART-Seq2 (E-MTAB-5061). For convenience, we distribute this dataset through our SeuratData package. The metadata contains the technology (tech column) and cell type annotations (celltype column) for each cell in the four datasets.

As a demonstration, we will use a subset of technologies to construct a reference. We will then map the remaining datasets onto this reference. We start by selecting cells from four technologies, and performing an analysis without integration.

Next, we integrate the datasets into a shared reference. Please see our introduction to integration vignette

Seurat also supports the projection of reference data (or meta data) onto a query object. While many of the methods are conserved (both procedures begin by identifying anchors), there are two important distinctions between data transfer and integration:

After finding anchors, we use the TransferData() function to classify the query cells based on reference data (a vector of reference cell type labels). TransferData() returns a matrix with predicted IDs and prediction scores, which we can add to the query metadata.

Because we have the original label annotations from our full integrated analysis, we can evaluate how well our predicted cell type annotations match the full reference. In this example, we find that there is a high agreement in cell type classification, with over 96% of cells being labeled correctly.

To verify this further, we can examine some canonical cell type markers for specific pancreatic islet cell populations. Note that even though some of these cell types are only represented by one or two cells (e.g. epsilon cells), we are still able to classify them correctly.

We also enable projection of a query onto the reference UMAP structure. This can be achieved by computing the reference UMAP model and then calling MapQuery() instead of TransferData().

What is MapQuery doing?

MapQuery() is a wrapper around three functions: TransferData(), IntegrateEmbeddings(), and ProjectUMAP(). TransferData() is used to transfer cell type labels and impute the ADT values; IntegrateEmbeddings() is used to integrate reference with query by correcting the query’s projected low-dimensional embeddings; and finally ProjectUMAP() is used to project the query data onto the UMAP structure of the reference. The equivalent code for doing this with the intermediate functions is below:

We can now visualize the query cells alongside our reference.

Developed by Rahul Satija, Satija Lab and Collaborators.

Site built with pkgdown 2.0.7.

**Examples:**

Example 1 (unknown):
```unknown
vignettes/integration_mapping.Rmd
```

Example 2 (unknown):
```unknown
integration_mapping.Rmd
```

Example 3 (unknown):
```unknown
library(Seurat)
library(SeuratData)
library(ggplot2)
```

Example 4 (r):
```r
library(Seurat)
library(SeuratData)
library(ggplot2)
```

Example 5 (r):
```r
library(Seurat)
library(SeuratData)
library(ggplot2)
```

Example 6 (unknown):
```unknown
InstallData("panc8")
```

Example 7 (r):
```r
InstallData("panc8")
```

Example 8 (r):
```r
InstallData("panc8")
```

Example 9 (unknown):
```unknown
panc8 <- LoadData("panc8")
table(panc8$tech)
```

Example 10 (r):
```r
panc8 <- LoadData("panc8")
table(panc8$tech)
```

Example 11 (r):
```r
panc8 <- LoadData("panc8")
table(panc8$tech)
```

Example 12 (unknown):
```unknown
## 
##     celseq    celseq2 fluidigmc1     indrop  smartseq2 
##       1004       2285        638       8569       2394
```

Example 13 (unknown):
```unknown
## 
##     celseq    celseq2 fluidigmc1     indrop  smartseq2 
##       1004       2285        638       8569       2394
```

Example 14 (python):
```python
# we will use data from 2 technologies for the reference
pancreas.ref <- subset(panc8, tech %in% c("celseq2", "smartseq2"))
pancreas.ref[["RNA"]] <- split(pancreas.ref[["RNA"]], f = pancreas.ref$tech)

# pre-process dataset (without integration)
pancreas.ref <- NormalizeData(pancreas.ref)
pancreas.ref <- FindVariableFeatures(pancreas.ref)
pancreas.ref <- ScaleData(pancreas.ref)
pancreas.ref <- RunPCA(pancreas.ref)
pancreas.ref <- FindNeighbors(pancreas.ref, dims = 1:30)
pancreas.ref <- FindClusters(pancreas.ref)
```

Example 15 (r):
```r
# we will use data from 2 technologies for the reference
pancreas.ref <- subset(panc8, tech %in% c("celseq2", "smartseq2"))
pancreas.ref[["RNA"]] <- split(pancreas.ref[["RNA"]], f = pancreas.ref$tech)

# pre-process dataset (without integration)
pancreas.ref <- NormalizeData(pancreas.ref)
pancreas.ref <- FindVariableFeatures(pancreas.ref)
pancreas.ref <- ScaleData(pancreas.ref)
pancreas.ref <- RunPCA(pancreas.ref)
pancreas.ref <- FindNeighbors(pancreas.ref, dims = 1:30)
pancreas.ref <- FindClusters(pancreas.ref)
```

Example 16 (r):
```r
# we will use data from 2 technologies for the reference
pancreas.ref <- subset(panc8, tech %in% c("celseq2", "smartseq2"))
pancreas.ref[["RNA"]] <- split(pancreas.ref[["RNA"]], f = pancreas.ref$tech)

# pre-process dataset (without integration)
pancreas.ref <- NormalizeData(pancreas.ref)
pancreas.ref <- FindVariableFeatures(pancreas.ref)
pancreas.ref <- ScaleData(pancreas.ref)
pancreas.ref <- RunPCA(pancreas.ref)
pancreas.ref <- FindNeighbors(pancreas.ref, dims = 1:30)
pancreas.ref <- FindClusters(pancreas.ref)
```

Example 17 (unknown):
```unknown
## Modularity Optimizer version 1.3.0 by Ludo Waltman and Nees Jan van Eck
## 
## Number of nodes: 4679
## Number of edges: 174953
## 
## Running Louvain algorithm...
## Maximum modularity in 10 random starts: 0.9180
## Number of communities: 19
## Elapsed time: 0 seconds
```

Example 18 (unknown):
```unknown
## Modularity Optimizer version 1.3.0 by Ludo Waltman and Nees Jan van Eck
## 
## Number of nodes: 4679
## Number of edges: 174953
## 
## Running Louvain algorithm...
## Maximum modularity in 10 random starts: 0.9180
## Number of communities: 19
## Elapsed time: 0 seconds
```

Example 19 (unknown):
```unknown
pancreas.ref <- RunUMAP(pancreas.ref, dims = 1:30)
DimPlot(pancreas.ref, group.by = c("celltytpe", "tech"))
```

Example 20 (r):
```r
pancreas.ref <- RunUMAP(pancreas.ref, dims = 1:30)
DimPlot(pancreas.ref, group.by = c("celltytpe", "tech"))
```

Example 21 (r):
```r
pancreas.ref <- RunUMAP(pancreas.ref, dims = 1:30)
DimPlot(pancreas.ref, group.by = c("celltytpe", "tech"))
```

Example 22 (unknown):
```unknown
pancreas.ref <- IntegrateLayers(object = pancreas.ref, method = CCAIntegration, orig.reduction = "pca",
    new.reduction = "integrated.cca", verbose = FALSE)
pancreas.ref <- FindNeighbors(pancreas.ref, reduction = "integrated.cca", dims = 1:30)
pancreas.ref <- FindClusters(pancreas.ref)
```

Example 23 (r):
```r
pancreas.ref <- IntegrateLayers(object = pancreas.ref, method = CCAIntegration, orig.reduction = "pca",
    new.reduction = "integrated.cca", verbose = FALSE)
pancreas.ref <- FindNeighbors(pancreas.ref, reduction = "integrated.cca", dims = 1:30)
pancreas.ref <- FindClusters(pancreas.ref)
```

Example 24 (r):
```r
pancreas.ref <- IntegrateLayers(object = pancreas.ref, method = CCAIntegration, orig.reduction = "pca",
    new.reduction = "integrated.cca", verbose = FALSE)
pancreas.ref <- FindNeighbors(pancreas.ref, reduction = "integrated.cca", dims = 1:30)
pancreas.ref <- FindClusters(pancreas.ref)
```

Example 25 (unknown):
```unknown
## Modularity Optimizer version 1.3.0 by Ludo Waltman and Nees Jan van Eck
## 
## Number of nodes: 4679
## Number of edges: 190152
## 
## Running Louvain algorithm...
## Maximum modularity in 10 random starts: 0.8680
## Number of communities: 15
## Elapsed time: 0 seconds
```

Example 26 (unknown):
```unknown
## Modularity Optimizer version 1.3.0 by Ludo Waltman and Nees Jan van Eck
## 
## Number of nodes: 4679
## Number of edges: 190152
## 
## Running Louvain algorithm...
## Maximum modularity in 10 random starts: 0.8680
## Number of communities: 15
## Elapsed time: 0 seconds
```

Example 27 (unknown):
```unknown
pancreas.ref <- RunUMAP(pancreas.ref, reduction = "integrated.cca", dims = 1:30)
DimPlot(pancreas.ref, group.by = c("tech", "celltype"))
```

Example 28 (r):
```r
pancreas.ref <- RunUMAP(pancreas.ref, reduction = "integrated.cca", dims = 1:30)
DimPlot(pancreas.ref, group.by = c("tech", "celltype"))
```

Example 29 (r):
```r
pancreas.ref <- RunUMAP(pancreas.ref, reduction = "integrated.cca", dims = 1:30)
DimPlot(pancreas.ref, group.by = c("tech", "celltype"))
```

Example 30 (unknown):
```unknown
TransferData()
```

Example 31 (unknown):
```unknown
TransferData()
```

Example 32 (python):
```python
# select two technologies for the query datasets
pancreas.query <- subset(panc8, tech %in% c("fluidigmc1", "celseq"))
pancreas.query <- NormalizeData(pancreas.query)
pancreas.anchors <- FindTransferAnchors(reference = pancreas.ref, query = pancreas.query, dims = 1:30,
    reference.reduction = "pca")
predictions <- TransferData(anchorset = pancreas.anchors, refdata = pancreas.ref$celltype, dims = 1:30)
pancreas.query <- AddMetaData(pancreas.query, metadata = predictions)
```

Example 33 (r):
```r
# select two technologies for the query datasets
pancreas.query <- subset(panc8, tech %in% c("fluidigmc1", "celseq"))
pancreas.query <- NormalizeData(pancreas.query)
pancreas.anchors <- FindTransferAnchors(reference = pancreas.ref, query = pancreas.query, dims = 1:30,
    reference.reduction = "pca")
predictions <- TransferData(anchorset = pancreas.anchors, refdata = pancreas.ref$celltype, dims = 1:30)
pancreas.query <- AddMetaData(pancreas.query, metadata = predictions)
```

Example 34 (r):
```r
# select two technologies for the query datasets
pancreas.query <- subset(panc8, tech %in% c("fluidigmc1", "celseq"))
pancreas.query <- NormalizeData(pancreas.query)
pancreas.anchors <- FindTransferAnchors(reference = pancreas.ref, query = pancreas.query, dims = 1:30,
    reference.reduction = "pca")
predictions <- TransferData(anchorset = pancreas.anchors, refdata = pancreas.ref$celltype, dims = 1:30)
pancreas.query <- AddMetaData(pancreas.query, metadata = predictions)
```

Example 35 (unknown):
```unknown
pancreas.query$prediction.match <- pancreas.query$predicted.id == pancreas.query$celltype
table(pancreas.query$prediction.match)
```

Example 36 (r):
```r
pancreas.query$prediction.match <- pancreas.query$predicted.id == pancreas.query$celltype
table(pancreas.query$prediction.match)
```

Example 37 (r):
```r
pancreas.query$prediction.match <- pancreas.query$predicted.id == pancreas.query$celltype
table(pancreas.query$prediction.match)
```

Example 38 (unknown):
```unknown
## 
## FALSE  TRUE 
##    63  1579
```

Example 39 (unknown):
```unknown
## 
## FALSE  TRUE 
##    63  1579
```

Example 40 (unknown):
```unknown
table(pancreas.query$predicted.id)
```

Example 41 (r):
```r
table(pancreas.query$predicted.id)
```

Example 42 (r):
```r
table(pancreas.query$predicted.id)
```

Example 43 (unknown):
```unknown
## 
##             acinar activated_stellate              alpha               beta 
##                262                 39                436                419 
##              delta             ductal        endothelial              gamma 
##                 73                330                 19                 41 
##         macrophage               mast            schwann 
##                 15                  2                  6
```

Example 44 (unknown):
```unknown
## 
##             acinar activated_stellate              alpha               beta 
##                262                 39                436                419 
##              delta             ductal        endothelial              gamma 
##                 73                330                 19                 41 
##         macrophage               mast            schwann 
##                 15                  2                  6
```

Example 45 (unknown):
```unknown
VlnPlot(pancreas.query, c("REG1A", "PPY", "SST", "GHRL", "VWF", "SOX10"), group.by = "predicted.id")
```

Example 46 (r):
```r
VlnPlot(pancreas.query, c("REG1A", "PPY", "SST", "GHRL", "VWF", "SOX10"), group.by = "predicted.id")
```

Example 47 (r):
```r
VlnPlot(pancreas.query, c("REG1A", "PPY", "SST", "GHRL", "VWF", "SOX10"), group.by = "predicted.id")
```

Example 48 (unknown):
```unknown
TransferData()
```

Example 49 (unknown):
```unknown
pancreas.ref <- RunUMAP(pancreas.ref, dims = 1:30, reduction = "integrated.cca", return.model = TRUE)
pancreas.query <- MapQuery(anchorset = pancreas.anchors, reference = pancreas.ref, query = pancreas.query,
    refdata = list(celltype = "celltype"), reference.reduction = "pca", reduction.model = "umap")
```

Example 50 (r):
```r
pancreas.ref <- RunUMAP(pancreas.ref, dims = 1:30, reduction = "integrated.cca", return.model = TRUE)
pancreas.query <- MapQuery(anchorset = pancreas.anchors, reference = pancreas.ref, query = pancreas.query,
    refdata = list(celltype = "celltype"), reference.reduction = "pca", reduction.model = "umap")
```

Example 51 (r):
```r
pancreas.ref <- RunUMAP(pancreas.ref, dims = 1:30, reduction = "integrated.cca", return.model = TRUE)
pancreas.query <- MapQuery(anchorset = pancreas.anchors, reference = pancreas.ref, query = pancreas.query,
    refdata = list(celltype = "celltype"), reference.reduction = "pca", reduction.model = "umap")
```

Example 52 (unknown):
```unknown
TransferData()
```

Example 53 (unknown):
```unknown
IntegrateEmbeddings()
```

Example 54 (unknown):
```unknown
ProjectUMAP()
```

Example 55 (unknown):
```unknown
TransferData()
```

Example 56 (unknown):
```unknown
IntegrateEmbeddings()
```

Example 57 (unknown):
```unknown
ProjectUMAP()
```

Example 58 (unknown):
```unknown
pancreas.query <- TransferData(anchorset = pancreas.anchors, reference = pancreas.ref, query = pancreas.query,
    refdata = list(celltype = "celltype"))
pancreas.query <- IntegrateEmbeddings(anchorset = pancreas.anchors, reference = pancreas.ref, query = pancreas.query,
    new.reduction.name = "ref.pca")
pancreas.query <- ProjectUMAP(query = pancreas.query, query.reduction = "ref.pca", reference = pancreas.ref,
    reference.reduction = "pca", reduction.model = "umap")
```

Example 59 (r):
```r
pancreas.query <- TransferData(anchorset = pancreas.anchors, reference = pancreas.ref, query = pancreas.query,
    refdata = list(celltype = "celltype"))
pancreas.query <- IntegrateEmbeddings(anchorset = pancreas.anchors, reference = pancreas.ref, query = pancreas.query,
    new.reduction.name = "ref.pca")
pancreas.query <- ProjectUMAP(query = pancreas.query, query.reduction = "ref.pca", reference = pancreas.ref,
    reference.reduction = "pca", reduction.model = "umap")
```

Example 60 (r):
```r
pancreas.query <- TransferData(anchorset = pancreas.anchors, reference = pancreas.ref, query = pancreas.query,
    refdata = list(celltype = "celltype"))
pancreas.query <- IntegrateEmbeddings(anchorset = pancreas.anchors, reference = pancreas.ref, query = pancreas.query,
    new.reduction.name = "ref.pca")
pancreas.query <- ProjectUMAP(query = pancreas.query, query.reduction = "ref.pca", reference = pancreas.ref,
    reference.reduction = "pca", reduction.model = "umap")
```

Example 61 (unknown):
```unknown
p1 <- DimPlot(pancreas.ref, reduction = "umap", group.by = "celltype", label = TRUE, label.size = 3,
    repel = TRUE) + NoLegend() + ggtitle("Reference annotations")
p2 <- DimPlot(pancreas.query, reduction = "ref.umap", group.by = "predicted.celltype", label = TRUE,
    label.size = 3, repel = TRUE) + NoLegend() + ggtitle("Query transferred labels")
p1 + p2
```

Example 62 (r):
```r
p1 <- DimPlot(pancreas.ref, reduction = "umap", group.by = "celltype", label = TRUE, label.size = 3,
    repel = TRUE) + NoLegend() + ggtitle("Reference annotations")
p2 <- DimPlot(pancreas.query, reduction = "ref.umap", group.by = "predicted.celltype", label = TRUE,
    label.size = 3, repel = TRUE) + NoLegend() + ggtitle("Query transferred labels")
p1 + p2
```

Example 63 (r):
```r
p1 <- DimPlot(pancreas.ref, reduction = "umap", group.by = "celltype", label = TRUE, label.size = 3,
    repel = TRUE) + NoLegend() + ggtitle("Reference annotations")
p2 <- DimPlot(pancreas.query, reduction = "ref.umap", group.by = "predicted.celltype", label = TRUE,
    label.size = 3, repel = TRUE) + NoLegend() + ggtitle("Query transferred labels")
p1 + p2
```

Example 64 (unknown):
```unknown
sessionInfo()
```

Example 65 (r):
```r
sessionInfo()
```

Example 66 (r):
```r
sessionInfo()
```

Example 67 (unknown):
```unknown
## R version 4.2.2 Patched (2022-11-10 r83330)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.6 LTS
## 
## Matrix products: default
## BLAS:   /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.9.0
## LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.9.0
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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       
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
##  [1] ggplot2_3.4.4                 thp1.eccite.SeuratData_3.1.5 
##  [3] stxBrain.SeuratData_0.1.1     ssHippo.SeuratData_3.1.4     
##  [5] pbmcsca.SeuratData_3.0.0      pbmcref.SeuratData_1.0.0     
##  [7] pbmcMultiome.SeuratData_0.1.4 pbmc3k.SeuratData_3.1.4      
##  [9] panc8.SeuratData_3.0.2        ifnb.SeuratData_3.0.0        
## [11] hcabm40k.SeuratData_3.0.0     cbmc.SeuratData_3.1.4        
## [13] bmcite.SeuratData_0.3.0       SeuratData_0.2.2.9001        
## [15] Seurat_5.0.0                  SeuratObject_5.0.0           
## [17] sp_2.1-1                     
## 
## loaded via a namespace (and not attached):
##   [1] spam_2.10-0            systemfonts_1.0.4      plyr_1.8.9            
##   [4] igraph_1.5.1           lazyeval_0.2.2         splines_4.2.2         
##   [7] RcppHNSW_0.5.0         listenv_0.9.0          scattermore_1.2       
##  [10] digest_0.6.33          htmltools_0.5.6.1      fansi_1.0.5           
##  [13] magrittr_2.0.3         memoise_2.0.1          tensor_1.5            
##  [16] cluster_2.1.4          ROCR_1.0-11            globals_0.16.2        
##  [19] matrixStats_1.0.0      pkgdown_2.0.7          spatstat.sparse_3.0-3 
##  [22] colorspace_2.1-0       rappdirs_0.3.3         ggrepel_0.9.4         
##  [25] textshaping_0.3.6      xfun_0.40              dplyr_1.1.3           
##  [28] crayon_1.5.2           jsonlite_1.8.7         progressr_0.14.0      
##  [31] spatstat.data_3.0-3    survival_3.5-7         zoo_1.8-12            
##  [34] glue_1.6.2             polyclip_1.10-6        gtable_0.3.4          
##  [37] leiden_0.4.3           future.apply_1.11.0    abind_1.4-5           
##  [40] scales_1.2.1           spatstat.random_3.2-1  miniUI_0.1.1.1        
##  [43] Rcpp_1.0.11            viridisLite_0.4.2      xtable_1.8-4          
##  [46] reticulate_1.34.0      dotCall64_1.1-0        htmlwidgets_1.6.2     
##  [49] httr_1.4.7             RColorBrewer_1.1-3     ellipsis_0.3.2        
##  [52] ica_1.0-3              farver_2.1.1           pkgconfig_2.0.3       
##  [55] sass_0.4.7             uwot_0.1.16            deldir_1.0-9          
##  [58] utf8_1.2.4             labeling_0.4.3         tidyselect_1.2.0      
##  [61] rlang_1.1.1            reshape2_1.4.4         later_1.3.1           
##  [64] munsell_0.5.0          tools_4.2.2            cachem_1.0.8          
##  [67] cli_3.6.1              generics_0.1.3         ggridges_0.5.4        
##  [70] evaluate_0.22          stringr_1.5.0          fastmap_1.1.1         
##  [73] yaml_2.3.7             ragg_1.2.5             goftest_1.2-3         
##  [76] knitr_1.45             fs_1.6.3               fitdistrplus_1.1-11   
##  [79] purrr_1.0.2            RANN_2.6.1             pbapply_1.7-2         
##  [82] future_1.33.0          nlme_3.1-162           mime_0.12             
##  [85] formatR_1.14           ggrastr_1.0.1          compiler_4.2.2        
##  [88] beeswarm_0.4.0         plotly_4.10.3          png_0.1-8             
##  [91] spatstat.utils_3.0-4   tibble_3.2.1           bslib_0.5.1           
##  [94] stringi_1.7.12         highr_0.10             desc_1.4.2            
##  [97] RSpectra_0.16-1        lattice_0.21-9         Matrix_1.6-1.1        
## [100] vctrs_0.6.4            pillar_1.9.0           lifecycle_1.0.3       
## [103] spatstat.geom_3.2-7    lmtest_0.9-40          jquerylib_0.1.4       
## [106] RcppAnnoy_0.0.21       data.table_1.14.8      cowplot_1.1.1         
## [109] irlba_2.3.5.1          httpuv_1.6.12          patchwork_1.1.3       
## [112] R6_2.5.1               promises_1.2.1         KernSmooth_2.23-22    
## [115] gridExtra_2.3          vipor_0.4.5            parallelly_1.36.0     
## [118] codetools_0.2-19       fastDummies_1.7.3      MASS_7.3-58.2         
## [121] rprojroot_2.0.3        withr_2.5.2            sctransform_0.4.1     
## [124] parallel_4.2.2         grid_4.2.2             tidyr_1.3.0           
## [127] rmarkdown_2.25         Rtsne_0.16             spatstat.explore_3.2-5
## [130] shiny_1.7.5.1          ggbeeswarm_0.7.1
```

Example 68 (unknown):
```unknown
## R version 4.2.2 Patched (2022-11-10 r83330)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.6 LTS
## 
## Matrix products: default
## BLAS:   /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.9.0
## LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.9.0
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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       
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
##  [1] ggplot2_3.4.4                 thp1.eccite.SeuratData_3.1.5 
##  [3] stxBrain.SeuratData_0.1.1     ssHippo.SeuratData_3.1.4     
##  [5] pbmcsca.SeuratData_3.0.0      pbmcref.SeuratData_1.0.0     
##  [7] pbmcMultiome.SeuratData_0.1.4 pbmc3k.SeuratData_3.1.4      
##  [9] panc8.SeuratData_3.0.2        ifnb.SeuratData_3.0.0        
## [11] hcabm40k.SeuratData_3.0.0     cbmc.SeuratData_3.1.4        
## [13] bmcite.SeuratData_0.3.0       SeuratData_0.2.2.9001        
## [15] Seurat_5.0.0                  SeuratObject_5.0.0           
## [17] sp_2.1-1                     
## 
## loaded via a namespace (and not attached):
##   [1] spam_2.10-0            systemfonts_1.0.4      plyr_1.8.9            
##   [4] igraph_1.5.1           lazyeval_0.2.2         splines_4.2.2         
##   [7] RcppHNSW_0.5.0         listenv_0.9.0          scattermore_1.2       
##  [10] digest_0.6.33          htmltools_0.5.6.1      fansi_1.0.5           
##  [13] magrittr_2.0.3         memoise_2.0.1          tensor_1.5            
##  [16] cluster_2.1.4          ROCR_1.0-11            globals_0.16.2        
##  [19] matrixStats_1.0.0      pkgdown_2.0.7          spatstat.sparse_3.0-3 
##  [22] colorspace_2.1-0       rappdirs_0.3.3         ggrepel_0.9.4         
##  [25] textshaping_0.3.6      xfun_0.40              dplyr_1.1.3           
##  [28] crayon_1.5.2           jsonlite_1.8.7         progressr_0.14.0      
##  [31] spatstat.data_3.0-3    survival_3.5-7         zoo_1.8-12            
##  [34] glue_1.6.2             polyclip_1.10-6        gtable_0.3.4          
##  [37] leiden_0.4.3           future.apply_1.11.0    abind_1.4-5           
##  [40] scales_1.2.1           spatstat.random_3.2-1  miniUI_0.1.1.1        
##  [43] Rcpp_1.0.11            viridisLite_0.4.2      xtable_1.8-4          
##  [46] reticulate_1.34.0      dotCall64_1.1-0        htmlwidgets_1.6.2     
##  [49] httr_1.4.7             RColorBrewer_1.1-3     ellipsis_0.3.2        
##  [52] ica_1.0-3              farver_2.1.1           pkgconfig_2.0.3       
##  [55] sass_0.4.7             uwot_0.1.16            deldir_1.0-9          
##  [58] utf8_1.2.4             labeling_0.4.3         tidyselect_1.2.0      
##  [61] rlang_1.1.1            reshape2_1.4.4         later_1.3.1           
##  [64] munsell_0.5.0          tools_4.2.2            cachem_1.0.8          
##  [67] cli_3.6.1              generics_0.1.3         ggridges_0.5.4        
##  [70] evaluate_0.22          stringr_1.5.0          fastmap_1.1.1         
##  [73] yaml_2.3.7             ragg_1.2.5             goftest_1.2-3         
##  [76] knitr_1.45             fs_1.6.3               fitdistrplus_1.1-11   
##  [79] purrr_1.0.2            RANN_2.6.1             pbapply_1.7-2         
##  [82] future_1.33.0          nlme_3.1-162           mime_0.12             
##  [85] formatR_1.14           ggrastr_1.0.1          compiler_4.2.2        
##  [88] beeswarm_0.4.0         plotly_4.10.3          png_0.1-8             
##  [91] spatstat.utils_3.0-4   tibble_3.2.1           bslib_0.5.1           
##  [94] stringi_1.7.12         highr_0.10             desc_1.4.2            
##  [97] RSpectra_0.16-1        lattice_0.21-9         Matrix_1.6-1.1        
## [100] vctrs_0.6.4            pillar_1.9.0           lifecycle_1.0.3       
## [103] spatstat.geom_3.2-7    lmtest_0.9-40          jquerylib_0.1.4       
## [106] RcppAnnoy_0.0.21       data.table_1.14.8      cowplot_1.1.1         
## [109] irlba_2.3.5.1          httpuv_1.6.12          patchwork_1.1.3       
## [112] R6_2.5.1               promises_1.2.1         KernSmooth_2.23-22    
## [115] gridExtra_2.3          vipor_0.4.5            parallelly_1.36.0     
## [118] codetools_0.2-19       fastDummies_1.7.3      MASS_7.3-58.2         
## [121] rprojroot_2.0.3        withr_2.5.2            sctransform_0.4.1     
## [124] parallel_4.2.2         grid_4.2.2             tidyr_1.3.0           
## [127] rmarkdown_2.25         Rtsne_0.16             spatstat.explore_3.2-5
## [130] shiny_1.7.5.1          ggbeeswarm_0.7.1
```

---

## Integration and Label Transfer

**URL:** http://127.0.0.1:9173/seurat/archive/v3.0/integration/index.html

**Contents:**
- Integration and Label Transfer
    - Compiled: 2019-07-16
  - Intro: Seurat v3 Integration
  - Standard Workflow
    - Dataset preprocessing
    - Integration of 3 pancreatic islet cell datasets
    - Cell type classification using an integrated reference
  - SCTransform
  - Reference-based
  - Reciprocal PCA

As described in Stuart*, Butler*, et al. Cell 2019, Seurat v3 introduces new methods for the integration of multiple single-cell datasets. These methods aim to identify shared cell states that are present across different datasets, even if they were collected from different individuals, experimental conditions, technologies, or even species.

Our method aims to first identify ‘anchors’ between pairs of datasets. These represent pairwise correspondences between individual cells (one in each dataset), that we hypothesize originate from the same biological state. These ‘anchors’ are then used to harmonize the datasets, or transfer information from one dataset to another. Below, we demonstrate multiple applications of integrative analysis, and also introduce new functionality beyond what was described in the 2019 manuscript. To help guide users, we briefly introduce these vignettes below:

In this example workflow, we demonstrate two new methods we recently introduced in our paper, Comprehensive Integration of Single Cell Data:

For the purposes of this example, we’ve chosen human pancreatic islet cell datasets produced across four technologies, CelSeq (GSE81076) CelSeq2 (GSE85241), Fluidigm C1 (GSE86469), and SMART-Seq2 (E-MTAB-5061). We provide a combined raw data matrix and associated metadata file here to get started.

The code for the new methodology is implemented in Seurat v3. You can download and install from CRAN with install.packages.

In addition to new methods, Seurat v3 includes a number of improvements aiming to improve the Seurat object and user interaction. To help users familiarize themselves with these changes, we put together a command cheat sheet for common tasks.

Load in expression matrix and metadata. The metadata file contains the technology (tech column) and cell type annotations (cell type column) for each cell in the four datasets.

To construct a reference, we will identify ‘anchors’ between the individual datasets. First, we split the combined object into a list, with each dataset as an element.

Prior to finding anchors, we perform standard preprocessing (log-normalization), and identify variable features individually for each. Note that Seurat v3 implements an improved method for variable feature selection based on a variance stabilizing transformation ("vst")

Next, we identify anchors using the FindIntegrationAnchors function, which takes a list of Seurat objects as input. Here, we integrate three of the objects into a reference (we will use the fourth later in this vignette)

We then pass these anchors to the IntegrateData function, which returns a Seurat object.

After running IntegrateData, the Seurat object will contain a new Assay with the integrated expression matrix. Note that the original (uncorrected values) are still stored in the object in the “RNA” assay, so you can switch back and forth.

We can then use this new integrated matrix for downstream analysis and visualization. Here we scale the integrated data, run PCA, and visualize the results with UMAP. The integrated datasets cluster by cell type, instead of by technology.

Seurat v3 also supports the projection of reference data (or meta data) onto a query object. While many of the methods are conserved (both procedures begin by identifying anchors), there are two important distinctions between data transfer and integration:

After finding anchors, we use the TransferData function to classify the query cells based on reference data (a vector of reference cell type labels). TransferData returns a matrix with predicted IDs and prediction scores, which we can add to the query metadata.

Because we have the original label annotations from our full integrated analysis, we can evaluate how well our predicted cell type annotations match the full reference. In this example, we find that there is a high agreement in cell type classification, with over 97% of cells being labeled correctly.

To verify this further, we can examine some canonical cell type markers for specific pancreatic islet cell populations. Note that even though some of these cell types are only represented by one or two cells (e.g. epsilon cells), we are still able to classify them correctly.

On the previous tab, we demonstrate how to integrate datasets after each has been pre-processed using standard log-normalization. Here, we modify the workflow to take advantage of our improved pre-processing and normalization workflow: SCTransform. You can read more about SCTransform in our recent preprint, and see how to apply it to a single dataset in a separate vignette. We suggest exploring these resources before proceeding.

Conceptually, this workflow is very similar to what we have previously introduced, where we ‘correct’ (or harmonize) log-normalized expression values across datasets. Here, instead, we will harmonize the Pearson residuals that are output from SCTransform. As demonstrated below, the workflow consists of the following steps:

First, you will need to have the development version of Seurat installed. Then, setup the Seurat object list, and run SCTransform on each object separately:

Next, select features for downstream integration, and run PrepSCTIntegration, which ensures that all necessary Pearson residuals have been calculated.

Next, identify anchors and integrate the datasets. Commands are identical to the standard workflow, but make sure to set normalization.method = 'SCT':

Now proceed with downstream analysis (i.e. visualization, clustering) on the integrated dataset. Commands are identical to the standard workflow, but do not run the ScaleData function after integration. You can see that after integration, cells group by their biological cell type (which has been pre-annotated), instead of by their underlying technology.

To further demonstrate this workflow, we next apply it to a series of human PBMC datasets from eight different technologies, produced as a systematic technology benchmark by the Human Cell Atlas. Data was downloaded from the Broad Single Cell Portal. We provide the count matrix and metadata file for convenience in getting started.

Note that again, cells are grouped together by shared biological subtype, instead of by technology. In this case, the authors labeled “CellType” in each dataset independently, and you can see that this is consistent with our integrated analysis:

However, our integrated analysis reveals finer subdivisions amongst these broad cell types, since the combined dataset has substantially greater statistical power. We don’t do a full clustering here on the integrated dataset, but note that we can observe subpopulations of CD4+ (Memory/Naive), CD8 (multiple cytotoxic populations), and B cells (multiple developmental stages). Below, we visualize the expression of the original measurements on our integrated visualization (note that you can add split.by = 'Method to make these plots for each technology independently)"

Here, we present an additional modification to the Seurat integration workflow, which we refer to as ‘Reference-based’ integration. In the previous workflows, we identify anchors between all pairs of datasets. While this gives datasets equal weight in downstream integration, it can also become computationally intensive. For example, when integrating 10 different datasets, we perform 45 different pairwise comparisons.

As an alternative, we introduce here the possibility of specifying one or more of the datasets as the ‘reference’ for integrated analysis, with the remainder designated as ‘query’ datasets. In this workflow, we do not identify anchors between pairs of query datasets, reducing the number of comparisons. For example, when integrating 10 datasets with one specified as a reference, we perform only 9 comparisons. Reference-based integration can be applied to either log-normalized or SCTransform-normalized datasets.

In practice, we often observe very similar results between the approaches, but with substantially reduced computational time. We demonstrate this using the same PBMC analysis as in the previous tab with highly concordant outputs. We therefore recommend this workflow for users who are integrating a large number of datasets, and desire increased computational efficiency.

This approach does require users to pre-select datasets to serve as a reference. In this example, we use the 10X v3 dataset, as the dataset contains both high cell number and high sensitivity. Users can apply similar criteria when selecting a reference. Furthermore, you can change this setting in the workflow below (for example, try selecting the 10X v2, or Drop-seq datasets as a reference), with only very minor differences in the final result.

The workflow is demonstrated below. Commands are identical to the previous tab, except that we specify a reference argument in the FindIntegrationAnchors function. You will also need to have the development version of Seurat installed. Data was originally downloaded from the Broad Single Cell Portal but we provide the count matrix and metadata file for convenience in getting started.

For very large datasets, Canonical Correlation Analysis can sometimes become a prohibitively computationally expensive step. In this workflow, we introduce an alternate form of dimension reduction, reciprocal PCA, to identify an effective space in which to find anchors. When determining anchors between any two datasets using reciprocal PCA, we project each dataset into the other’s PCA space and constrain the anchors by the same mutual neighborhood requirement. All downstream integration steps remain the same and we are able to ‘correct’ (or harmonize) the datasets.

As demonstrated below, the workflow consists of the following steps:

In general, we observe strikingly similar results between the two workflows, but with substantial reduction in compute time and memory when using reciprocal PCA. However, if the datasets are highly divergent (for example, cross-modality mapping or cross-species mapping), where only a small subset of features can be used to facilitate integration, and you may observe superior results using CCA.

For large studies with many datasets, we recommend also combining reciprocal PCA with reference-based integration, or SCTransform normalization (see details on previous tab).

First, you will need to have the development version of Seurat installed.

For these examples, we will be using the “Immune Cell Atlas” data from the Human Cell Atlas which can be found here. First, we will integrate a randomly downsampled version of this dataset and then the full dataset. The randomly downsampled version contains 40K cells (5K from each donor) and is available through our new SeuratData package.

After acquiring the data, we first perform standard normalization and variable feature selection.

Next, select features for downstream integration, and run PCA on each object in the list, which is required for running the reciprocal PCA workflow.

Since this dataset contains both men and women, we will chose one male and one female (BM1 and BM2) to use in the reference-based workflow. We determined donor sex by examining the expression of the XIST gene. Next, identify anchors and integrate the datasets. Commands are identical to the standard workflow, but make sure to set reduction = 'rpca':

Now proceed with downstream analysis (i.e. visualization, clustering) on the integrated dataset. Commands are identical to the standard workflow.

To further demonstrate this workflow, we next apply it to the full dataset. While we do not provide this through SeuratData, you can find the counts matrix on the HCA Data Portal site. The commands below are identical to the 40k integration except we’ve increased the dimensionality to 50 to reflect the increased cell number and diversity.

**Examples:**

Example 1 (unknown):
```unknown
install.packages
```

Example 2 (r):
```r
install.packages("Seurat")
```

Example 3 (r):
```r
install.packages("Seurat")
```

Example 4 (r):
```r
library(Seurat)
pancreas.data <- readRDS(file = "../data/pancreas_expression_matrix.rds")
metadata <- readRDS(file = "../data/pancreas_metadata.rds")
```

Example 5 (r):
```r
library(Seurat)
pancreas.data <- readRDS(file = "../data/pancreas_expression_matrix.rds")
metadata <- readRDS(file = "../data/pancreas_metadata.rds")
```

Example 6 (r):
```r
pancreas <- CreateSeuratObject(pancreas.data, meta.data = metadata)
pancreas.list <- SplitObject(pancreas, split.by = "tech")
```

Example 7 (r):
```r
pancreas <- CreateSeuratObject(pancreas.data, meta.data = metadata)
pancreas.list <- SplitObject(pancreas, split.by = "tech")
```

Example 8 (r):
```r
for (i in 1:length(pancreas.list)) {
    pancreas.list[[i]] <- NormalizeData(pancreas.list[[i]], verbose = FALSE)
    pancreas.list[[i]] <- FindVariableFeatures(pancreas.list[[i]], selection.method = "vst", 
        nfeatures = 2000, verbose = FALSE)
}
```

Example 9 (r):
```r
for (i in 1:length(pancreas.list)) {
    pancreas.list[[i]] <- NormalizeData(pancreas.list[[i]], verbose = FALSE)
    pancreas.list[[i]] <- FindVariableFeatures(pancreas.list[[i]], selection.method = "vst", 
        nfeatures = 2000, verbose = FALSE)
}
```

Example 10 (unknown):
```unknown
FindIntegrationAnchors
```

Example 11 (r):
```r
reference.list <- pancreas.list[c("celseq", "celseq2", "smartseq2")]
pancreas.anchors <- FindIntegrationAnchors(object.list = reference.list, dims = 1:30)
```

Example 12 (r):
```r
reference.list <- pancreas.list[c("celseq", "celseq2", "smartseq2")]
pancreas.anchors <- FindIntegrationAnchors(object.list = reference.list, dims = 1:30)
```

Example 13 (unknown):
```unknown
IntegrateData
```

Example 14 (r):
```r
pancreas.integrated <- IntegrateData(anchorset = pancreas.anchors, dims = 1:30)
```

Example 15 (r):
```r
pancreas.integrated <- IntegrateData(anchorset = pancreas.anchors, dims = 1:30)
```

Example 16 (unknown):
```unknown
IntegrateData
```

Example 17 (r):
```r
library(ggplot2)
library(cowplot)
# switch to integrated assay. The variable features of this assay are automatically
# set during IntegrateData
DefaultAssay(pancreas.integrated) <- "integrated"

# Run the standard workflow for visualization and clustering
pancreas.integrated <- ScaleData(pancreas.integrated, verbose = FALSE)
pancreas.integrated <- RunPCA(pancreas.integrated, npcs = 30, verbose = FALSE)
pancreas.integrated <- RunUMAP(pancreas.integrated, reduction = "pca", dims = 1:30)
p1 <- DimPlot(pancreas.integrated, reduction = "umap", group.by = "tech")
p2 <- DimPlot(pancreas.integrated, reduction = "umap", group.by = "celltype", label = TRUE, 
    repel = TRUE) + NoLegend()
plot_grid(p1, p2)
```

Example 18 (r):
```r
library(ggplot2)
library(cowplot)
# switch to integrated assay. The variable features of this assay are automatically
# set during IntegrateData
DefaultAssay(pancreas.integrated) <- "integrated"

# Run the standard workflow for visualization and clustering
pancreas.integrated <- ScaleData(pancreas.integrated, verbose = FALSE)
pancreas.integrated <- RunPCA(pancreas.integrated, npcs = 30, verbose = FALSE)
pancreas.integrated <- RunUMAP(pancreas.integrated, reduction = "pca", dims = 1:30)
p1 <- DimPlot(pancreas.integrated, reduction = "umap", group.by = "tech")
p2 <- DimPlot(pancreas.integrated, reduction = "umap", group.by = "celltype", label = TRUE, 
    repel = TRUE) + NoLegend()
plot_grid(p1, p2)
```

Example 19 (unknown):
```unknown
TransferData
```

Example 20 (unknown):
```unknown
TransferData
```

Example 21 (r):
```r
pancreas.query <- pancreas.list[["fluidigmc1"]]
pancreas.anchors <- FindTransferAnchors(reference = pancreas.integrated, query = pancreas.query, 
    dims = 1:30)
predictions <- TransferData(anchorset = pancreas.anchors, refdata = pancreas.integrated$celltype, 
    dims = 1:30)
pancreas.query <- AddMetaData(pancreas.query, metadata = predictions)
```

Example 22 (r):
```r
pancreas.query <- pancreas.list[["fluidigmc1"]]
pancreas.anchors <- FindTransferAnchors(reference = pancreas.integrated, query = pancreas.query, 
    dims = 1:30)
predictions <- TransferData(anchorset = pancreas.anchors, refdata = pancreas.integrated$celltype, 
    dims = 1:30)
pancreas.query <- AddMetaData(pancreas.query, metadata = predictions)
```

Example 23 (r):
```r
pancreas.query$prediction.match <- pancreas.query$predicted.id == pancreas.query$celltype
table(pancreas.query$prediction.match)
```

Example 24 (r):
```r
pancreas.query$prediction.match <- pancreas.query$predicted.id == pancreas.query$celltype
table(pancreas.query$prediction.match)
```

Example 25 (unknown):
```unknown
## 
## FALSE  TRUE 
##    16   622
```

Example 26 (unknown):
```unknown
## 
## FALSE  TRUE 
##    16   622
```

Example 27 (r):
```r
table(pancreas.query$predicted.id)
```

Example 28 (r):
```r
table(pancreas.query$predicted.id)
```

Example 29 (unknown):
```unknown
## 
##             acinar activated_stellate              alpha 
##                 21                 17                248 
##               beta              delta             ductal 
##                258                 22                 33 
##        endothelial            epsilon              gamma 
##                 13                  1                 17 
##         macrophage               mast            schwann 
##                  1                  2                  5
```

Example 30 (unknown):
```unknown
## 
##             acinar activated_stellate              alpha 
##                 21                 17                248 
##               beta              delta             ductal 
##                258                 22                 33 
##        endothelial            epsilon              gamma 
##                 13                  1                 17 
##         macrophage               mast            schwann 
##                  1                  2                  5
```

Example 31 (r):
```r
VlnPlot(pancreas.query, c("REG1A", "PPY", "SST", "GHRL", "VWF", "SOX10"), group.by = "predicted.id")
```

Example 32 (r):
```r
VlnPlot(pancreas.query, c("REG1A", "PPY", "SST", "GHRL", "VWF", "SOX10"), group.by = "predicted.id")
```

Example 33 (r):
```r
devtools::install_github(repo = "satijalab/seurat", ref = "develop")
```

Example 34 (r):
```r
devtools::install_github(repo = "satijalab/seurat", ref = "develop")
```

Example 35 (r):
```r
library(Seurat)
library(ggplot2)
options(future.globals.maxSize = 4000 * 1024^2)
pancreas.data <- readRDS(file = "../data/pancreas_expression_matrix.rds")
metadata <- readRDS(file = "../data/pancreas_metadata.rds")
pancreas <- CreateSeuratObject(pancreas.data, meta.data = metadata)
pancreas.list <- SplitObject(pancreas, split.by = "tech")

for (i in 1:length(pancreas.list)) {
    pancreas.list[[i]] <- SCTransform(pancreas.list[[i]], verbose = FALSE)
}
```

Example 36 (r):
```r
library(Seurat)
library(ggplot2)
options(future.globals.maxSize = 4000 * 1024^2)
pancreas.data <- readRDS(file = "../data/pancreas_expression_matrix.rds")
metadata <- readRDS(file = "../data/pancreas_metadata.rds")
pancreas <- CreateSeuratObject(pancreas.data, meta.data = metadata)
pancreas.list <- SplitObject(pancreas, split.by = "tech")

for (i in 1:length(pancreas.list)) {
    pancreas.list[[i]] <- SCTransform(pancreas.list[[i]], verbose = FALSE)
}
```

Example 37 (unknown):
```unknown
PrepSCTIntegration
```

Example 38 (r):
```r
pancreas.features <- SelectIntegrationFeatures(object.list = pancreas.list, nfeatures = 3000)
pancreas.list <- PrepSCTIntegration(object.list = pancreas.list, anchor.features = pancreas.features, 
    verbose = FALSE)
```

Example 39 (r):
```r
pancreas.features <- SelectIntegrationFeatures(object.list = pancreas.list, nfeatures = 3000)
pancreas.list <- PrepSCTIntegration(object.list = pancreas.list, anchor.features = pancreas.features, 
    verbose = FALSE)
```

Example 40 (unknown):
```unknown
normalization.method = 'SCT'
```

Example 41 (r):
```r
pancreas.anchors <- FindIntegrationAnchors(object.list = pancreas.list, normalization.method = "SCT", 
    anchor.features = pancreas.features, verbose = FALSE)
pancreas.integrated <- IntegrateData(anchorset = pancreas.anchors, normalization.method = "SCT", 
    verbose = FALSE)
```

Example 42 (r):
```r
pancreas.anchors <- FindIntegrationAnchors(object.list = pancreas.list, normalization.method = "SCT", 
    anchor.features = pancreas.features, verbose = FALSE)
pancreas.integrated <- IntegrateData(anchorset = pancreas.anchors, normalization.method = "SCT", 
    verbose = FALSE)
```

Example 43 (r):
```r
pancreas.integrated <- RunPCA(pancreas.integrated, verbose = FALSE)
pancreas.integrated <- RunUMAP(pancreas.integrated, dims = 1:30)
plots <- DimPlot(pancreas.integrated, group.by = c("tech", "celltype"), combine = FALSE)
plots <- lapply(X = plots, FUN = function(x) x + theme(legend.position = "top") + guides(color = guide_legend(nrow = 3, 
    byrow = TRUE, override.aes = list(size = 3))))
CombinePlots(plots)
```

Example 44 (r):
```r
pancreas.integrated <- RunPCA(pancreas.integrated, verbose = FALSE)
pancreas.integrated <- RunUMAP(pancreas.integrated, dims = 1:30)
plots <- DimPlot(pancreas.integrated, group.by = c("tech", "celltype"), combine = FALSE)
plots <- lapply(X = plots, FUN = function(x) x + theme(legend.position = "top") + guides(color = guide_legend(nrow = 3, 
    byrow = TRUE, override.aes = list(size = 3))))
CombinePlots(plots)
```

Example 45 (r):
```r
pbmc.data <- readRDS("../data/pbmc_ssc_mat.rds")
pbmc.metadata <- readRDS("../data/pbmc_ssc_metadata.rds")
pbmc <- CreateSeuratObject(counts = pbmc.data, meta.data = pbmc.metadata)

pbmc <- subset(pbmc, subset = nFeature_RNA > 200)
pbmc.list <- SplitObject(pbmc, split.by = "Method")
for (i in names(pbmc.list)) {
    pbmc.list[[i]] <- SCTransform(pbmc.list[[i]], verbose = FALSE)
}
pbmc.features <- SelectIntegrationFeatures(object.list = pbmc.list, nfeatures = 3000)
pbmc.list <- PrepSCTIntegration(object.list = pbmc.list, anchor.features = pbmc.features)
pbmc.anchors <- FindIntegrationAnchors(object.list = pbmc.list, normalization.method = "SCT", 
    anchor.features = pbmc.features)
pbmc.integrated <- IntegrateData(anchorset = pbmc.anchors, normalization.method = "SCT")

pbmc.integrated <- RunPCA(object = pbmc.integrated, verbose = FALSE)
pbmc.integrated <- RunUMAP(object = pbmc.integrated, dims = 1:30)
```

Example 46 (r):
```r
pbmc.data <- readRDS("../data/pbmc_ssc_mat.rds")
pbmc.metadata <- readRDS("../data/pbmc_ssc_metadata.rds")
pbmc <- CreateSeuratObject(counts = pbmc.data, meta.data = pbmc.metadata)

pbmc <- subset(pbmc, subset = nFeature_RNA > 200)
pbmc.list <- SplitObject(pbmc, split.by = "Method")
for (i in names(pbmc.list)) {
    pbmc.list[[i]] <- SCTransform(pbmc.list[[i]], verbose = FALSE)
}
pbmc.features <- SelectIntegrationFeatures(object.list = pbmc.list, nfeatures = 3000)
pbmc.list <- PrepSCTIntegration(object.list = pbmc.list, anchor.features = pbmc.features)
pbmc.anchors <- FindIntegrationAnchors(object.list = pbmc.list, normalization.method = "SCT", 
    anchor.features = pbmc.features)
pbmc.integrated <- IntegrateData(anchorset = pbmc.anchors, normalization.method = "SCT")

pbmc.integrated <- RunPCA(object = pbmc.integrated, verbose = FALSE)
pbmc.integrated <- RunUMAP(object = pbmc.integrated, dims = 1:30)
```

Example 47 (r):
```r
plots <- DimPlot(pbmc.integrated, group.by = c("Method", "CellType"), combine = FALSE)
plots <- lapply(X = plots, FUN = function(x) x + theme(legend.position = "top") + guides(color = guide_legend(nrow = 3, 
    byrow = TRUE, override.aes = list(size = 3))))
CombinePlots(plots)
```

Example 48 (r):
```r
plots <- DimPlot(pbmc.integrated, group.by = c("Method", "CellType"), combine = FALSE)
plots <- lapply(X = plots, FUN = function(x) x + theme(legend.position = "top") + guides(color = guide_legend(nrow = 3, 
    byrow = TRUE, override.aes = list(size = 3))))
CombinePlots(plots)
```

Example 49 (r):
```r
DimPlot(pbmc.integrated, group.by = "CellType", split.by = "Method", ncol = 3)
```

Example 50 (r):
```r
DimPlot(pbmc.integrated, group.by = "CellType", split.by = "Method", ncol = 3)
```

Example 51 (unknown):
```unknown
split.by = 'Method
```

Example 52 (r):
```r
DefaultAssay(pbmc.integrated) <- "RNA"
# Normalize RNA data for visualization purposes
pbmc.integrated <- NormalizeData(pbmc.integrated, verbose = FALSE)
FeaturePlot(pbmc.integrated, c("CCR7", "S100A4", "GZMB", "GZMK", "GZMH", "TCL1A"))
```

Example 53 (r):
```r
DefaultAssay(pbmc.integrated) <- "RNA"
# Normalize RNA data for visualization purposes
pbmc.integrated <- NormalizeData(pbmc.integrated, verbose = FALSE)
FeaturePlot(pbmc.integrated, c("CCR7", "S100A4", "GZMB", "GZMK", "GZMH", "TCL1A"))
```

Example 54 (unknown):
```unknown
FindIntegrationAnchors
```

Example 55 (r):
```r
devtools::install_github(repo = "satijalab/seurat", ref = "develop")
```

Example 56 (r):
```r
devtools::install_github(repo = "satijalab/seurat", ref = "develop")
```

Example 57 (r):
```r
library(Seurat)
library(ggplot2)
pbmc.data <- readRDS("../data/pbmc_ssc_mat.rds")
pbmc.metadata <- readRDS("../data/pbmc_ssc_metadata.rds")
pbmc <- CreateSeuratObject(counts = pbmc.data, meta.data = pbmc.metadata)

pbmc <- subset(pbmc, subset = nFeature_RNA > 200)
pbmc.list <- SplitObject(pbmc, split.by = "Method")
for (i in names(pbmc.list)) {
    pbmc.list[[i]] <- SCTransform(pbmc.list[[i]], verbose = FALSE)
}
pbmc.features <- SelectIntegrationFeatures(object.list = pbmc.list, nfeatures = 3000)
pbmc.list <- PrepSCTIntegration(object.list = pbmc.list, anchor.features = pbmc.features)

# This command returns dataset 5.  We can also specify multiple refs. (i.e. c(5,6))
reference_dataset <- which(names(pbmc.list) == "10x Chromium (v3)")

pbmc.anchors <- FindIntegrationAnchors(object.list = pbmc.list, normalization.method = "SCT", 
    anchor.features = pbmc.features, reference = reference_dataset)
pbmc.integrated <- IntegrateData(anchorset = pbmc.anchors, normalization.method = "SCT")

pbmc.integrated <- RunPCA(object = pbmc.integrated, verbose = FALSE)
pbmc.integrated <- RunUMAP(object = pbmc.integrated, dims = 1:30)
```

Example 58 (r):
```r
library(Seurat)
library(ggplot2)
pbmc.data <- readRDS("../data/pbmc_ssc_mat.rds")
pbmc.metadata <- readRDS("../data/pbmc_ssc_metadata.rds")
pbmc <- CreateSeuratObject(counts = pbmc.data, meta.data = pbmc.metadata)

pbmc <- subset(pbmc, subset = nFeature_RNA > 200)
pbmc.list <- SplitObject(pbmc, split.by = "Method")
for (i in names(pbmc.list)) {
    pbmc.list[[i]] <- SCTransform(pbmc.list[[i]], verbose = FALSE)
}
pbmc.features <- SelectIntegrationFeatures(object.list = pbmc.list, nfeatures = 3000)
pbmc.list <- PrepSCTIntegration(object.list = pbmc.list, anchor.features = pbmc.features)

# This command returns dataset 5.  We can also specify multiple refs. (i.e. c(5,6))
reference_dataset <- which(names(pbmc.list) == "10x Chromium (v3)")

pbmc.anchors <- FindIntegrationAnchors(object.list = pbmc.list, normalization.method = "SCT", 
    anchor.features = pbmc.features, reference = reference_dataset)
pbmc.integrated <- IntegrateData(anchorset = pbmc.anchors, normalization.method = "SCT")

pbmc.integrated <- RunPCA(object = pbmc.integrated, verbose = FALSE)
pbmc.integrated <- RunUMAP(object = pbmc.integrated, dims = 1:30)
```

Example 59 (r):
```r
plots <- DimPlot(pbmc.integrated, group.by = c("Method", "CellType"), combine = FALSE)
plots <- lapply(X = plots, FUN = function(x) x + theme(legend.position = "top") + guides(color = guide_legend(nrow = 3, 
    byrow = TRUE, override.aes = list(size = 3))))
CombinePlots(plots)
```

Example 60 (r):
```r
plots <- DimPlot(pbmc.integrated, group.by = c("Method", "CellType"), combine = FALSE)
plots <- lapply(X = plots, FUN = function(x) x + theme(legend.position = "top") + guides(color = guide_legend(nrow = 3, 
    byrow = TRUE, override.aes = list(size = 3))))
CombinePlots(plots)
```

Example 61 (r):
```r
DefaultAssay(pbmc.integrated) <- "RNA"
# Normalize RNA data for visualization purposes
pbmc.integrated <- NormalizeData(pbmc.integrated, verbose = FALSE)
FeaturePlot(pbmc.integrated, c("CCR7", "S100A4", "GZMB", "GZMK", "GZMH", "TCL1A"))
```

Example 62 (r):
```r
DefaultAssay(pbmc.integrated) <- "RNA"
# Normalize RNA data for visualization purposes
pbmc.integrated <- NormalizeData(pbmc.integrated, verbose = FALSE)
FeaturePlot(pbmc.integrated, c("CCR7", "S100A4", "GZMB", "GZMK", "GZMH", "TCL1A"))
```

Example 63 (r):
```r
devtools::install_github(repo = "satijalab/seurat", ref = "develop")
```

Example 64 (r):
```r
devtools::install_github(repo = "satijalab/seurat", ref = "develop")
```

Example 65 (r):
```r
library(SeuratData)
library(Seurat)
```

Example 66 (r):
```r
library(SeuratData)
library(Seurat)
```

Example 67 (r):
```r
# Get data from seurat-data
InstallData(pkgs = "bm40k.SeuratData")
```

Example 68 (r):
```r
# Get data from seurat-data
InstallData(pkgs = "bm40k.SeuratData")
```

Example 69 (r):
```r
library(ggplot2)
# set up future for parallelization
library(future)
library(future.apply)
plan("multiprocess", workers = 4)
options(future.globals.maxSize = 20000 * 1024^2)
# load in the data
data(hcabm40k)
bm40k.list <- SplitObject(hcabm40k, split.by = "orig.ident")
bm40k.list <- lapply(X = bm40k.list, FUN = function(x) {
    x <- NormalizeData(x, verbose = FALSE)
    x <- FindVariableFeatures(x, verbose = FALSE)
})
```

Example 70 (r):
```r
library(ggplot2)
# set up future for parallelization
library(future)
library(future.apply)
plan("multiprocess", workers = 4)
options(future.globals.maxSize = 20000 * 1024^2)
# load in the data
data(hcabm40k)
bm40k.list <- SplitObject(hcabm40k, split.by = "orig.ident")
bm40k.list <- lapply(X = bm40k.list, FUN = function(x) {
    x <- NormalizeData(x, verbose = FALSE)
    x <- FindVariableFeatures(x, verbose = FALSE)
})
```

Example 71 (r):
```r
features <- SelectIntegrationFeatures(object.list = bm40k.list)
bm40k.list <- lapply(X = bm40k.list, FUN = function(x) {
    x <- ScaleData(x, features = features, verbose = FALSE)
    x <- RunPCA(x, features = features, verbose = FALSE)
})
```

Example 72 (r):
```r
features <- SelectIntegrationFeatures(object.list = bm40k.list)
bm40k.list <- lapply(X = bm40k.list, FUN = function(x) {
    x <- ScaleData(x, features = features, verbose = FALSE)
    x <- RunPCA(x, features = features, verbose = FALSE)
})
```

Example 73 (unknown):
```unknown
reduction = 'rpca'
```

Example 74 (r):
```r
anchors <- FindIntegrationAnchors(object.list = bm40k.list, reference = c(1, 2), reduction = "rpca", 
    dims = 1:30)
bm40k.integrated <- IntegrateData(anchorset = anchors, dims = 1:30)
```

Example 75 (r):
```r
anchors <- FindIntegrationAnchors(object.list = bm40k.list, reference = c(1, 2), reduction = "rpca", 
    dims = 1:30)
bm40k.integrated <- IntegrateData(anchorset = anchors, dims = 1:30)
```

Example 76 (r):
```r
bm40k.integrated <- ScaleData(bm40k.integrated, verbose = FALSE)
bm40k.integrated <- RunPCA(bm40k.integrated, verbose = FALSE)
bm40k.integrated <- RunUMAP(bm40k.integrated, dims = 1:30)
```

Example 77 (r):
```r
bm40k.integrated <- ScaleData(bm40k.integrated, verbose = FALSE)
bm40k.integrated <- RunPCA(bm40k.integrated, verbose = FALSE)
bm40k.integrated <- RunUMAP(bm40k.integrated, dims = 1:30)
```

Example 78 (r):
```r
DimPlot(bm40k.integrated, group.by = "orig.ident")
```

Example 79 (r):
```r
DimPlot(bm40k.integrated, group.by = "orig.ident")
```

Example 80 (r):
```r
bm280k.data <- Read10X_h5("../data/ica_bone_marrow_h5.h5")
bm280k <- CreateSeuratObject(counts = bm280k.data, min.cells = 100, min.features = 500)
bm280k.list <- SplitObject(bm280k, split.by = "orig.ident")
bm280k.list <- future_lapply(X = bm280k.list, FUN = function(x) {
    x <- NormalizeData(x, verbose = FALSE)
    x <- FindVariableFeatures(x, verbose = FALSE)
})
```

Example 81 (r):
```r
bm280k.data <- Read10X_h5("../data/ica_bone_marrow_h5.h5")
bm280k <- CreateSeuratObject(counts = bm280k.data, min.cells = 100, min.features = 500)
bm280k.list <- SplitObject(bm280k, split.by = "orig.ident")
bm280k.list <- future_lapply(X = bm280k.list, FUN = function(x) {
    x <- NormalizeData(x, verbose = FALSE)
    x <- FindVariableFeatures(x, verbose = FALSE)
})
```

Example 82 (r):
```r
features <- SelectIntegrationFeatures(object.list = bm280k.list)
bm280k.list <- future_lapply(X = bm280k.list, FUN = function(x) {
    x <- ScaleData(x, features = features, verbose = FALSE)
    x <- RunPCA(x, features = features, verbose = FALSE)
})
```

Example 83 (r):
```r
features <- SelectIntegrationFeatures(object.list = bm280k.list)
bm280k.list <- future_lapply(X = bm280k.list, FUN = function(x) {
    x <- ScaleData(x, features = features, verbose = FALSE)
    x <- RunPCA(x, features = features, verbose = FALSE)
})
```

Example 84 (r):
```r
anchors <- FindIntegrationAnchors(object.list = bm280k.list, reference = c(1, 2), reduction = "rpca", 
    dims = 1:50)
bm280k.integrated <- IntegrateData(anchorset = anchors, dims = 1:50)
```

Example 85 (r):
```r
anchors <- FindIntegrationAnchors(object.list = bm280k.list, reference = c(1, 2), reduction = "rpca", 
    dims = 1:50)
bm280k.integrated <- IntegrateData(anchorset = anchors, dims = 1:50)
```

Example 86 (r):
```r
bm280k.integrated <- ScaleData(bm280k.integrated, verbose = FALSE)
bm280k.integrated <- RunPCA(bm280k.integrated, verbose = FALSE)
bm280k.integrated <- RunUMAP(bm280k.integrated, dims = 1:50)
```

Example 87 (r):
```r
bm280k.integrated <- ScaleData(bm280k.integrated, verbose = FALSE)
bm280k.integrated <- RunPCA(bm280k.integrated, verbose = FALSE)
bm280k.integrated <- RunUMAP(bm280k.integrated, dims = 1:50)
```

Example 88 (r):
```r
DimPlot(bm280k.integrated, group.by = "orig.ident")
```

Example 89 (r):
```r
DimPlot(bm280k.integrated, group.by = "orig.ident")
```

---

## Interoperability between single-cell object formats

**URL:** http://127.0.0.1:9173/seurat/archive/v3.2/conversion_vignette/index.html

**Contents:**
- Interoperability between single-cell object formats
    - Compiled: 2020-10-02
  - Converting to/from SingleCellExperiment
  - Converting to/from loom
  - Converting to/from AnnData
- Acknowledgments

In this vignette, we demonstrate the ability to convert between Seurat objects, SingleCellExperiment objects, and anndata objects.

SingleCellExperiment is a class for storing single-cell experiment data, created by Davide Risso, Aaron Lun, and Keegan Korthauer, and is used by many Bioconductor analysis packages. Here we demonstrate converting the Seurat object produced in our 3k PBMC tutorial to SingleCellExperiment for use with Davis McCarthy's scater package.

Seurat also allows conversion from SingleCellExperiment objects to Seurat objects; we demonstrate this on some publicly available data downloaded from a repository maintained by Martin Hemberg's group.

The loom format is a file structure imposed on HDF5 files designed by Sten Linnarson's group. It is designed to efficiently hold large single-cell genomics datasets. For more details about the loom format, please see the loom file format specification.

Seurat can also read in loom files connected via loomR into a Seurat object; we demonstrate this on a subset of the Mouse Brain Atlas created by the Linnarson lab.

For more details about interacting with loom files in R and Seurat, please see loomR on GitHub.

AnnData provides a Python class, created by Alex Wolf and Philipp Angerer, that can be used to store single-cell data. This data format is also use for storage in their Scanpy package for which we now support interoperability. Seurat has a new function ReadH5AD to read the data from the H5AD files that AnnData uses.

We currently do not support writing to an H5AD file at this time; however, transferring data from Seurat to Scanpy can be done via loom files

Many thanks to Davis McCarthy and Alex Wolf for their help in drafting the conversion functions.

**Examples:**

Example 1 (r):
```r
# install scater https://bioconductor.org/packages/release/bioc/html/scater.html
library(scater)
# install loomR from GitHub using the remotes package remotes::install_github(repo =
# 'mojaveazure/loomR', ref = 'develop')
library(loomR)
library(Seurat)
library(patchwork)
```

Example 2 (r):
```r
# install scater https://bioconductor.org/packages/release/bioc/html/scater.html
library(scater)
# install loomR from GitHub using the remotes package remotes::install_github(repo =
# 'mojaveazure/loomR', ref = 'develop')
library(loomR)
library(Seurat)
library(patchwork)
```

Example 3 (unknown):
```unknown
SingleCellExperiment
```

Example 4 (unknown):
```unknown
SingleCellExperiment
```

Example 5 (r):
```r
# download from satija lab https://www.dropbox.com/s/kwd3kcxkmpzqg6w/pbmc3k_final.rds?dl=0
pbmc <- readRDS(file = "../data/pbmc3k_final.rds")
pbmc.sce <- as.SingleCellExperiment(pbmc)
p1 <- plotExpression(pbmc.sce, features = "MS4A1", x = "ident") + theme(axis.text.x = element_text(angle = 45, 
    hjust = 1))
p2 <- plotPCA(pbmc.sce, colour_by = "ident")
p1 + p2
```

Example 6 (r):
```r
# download from satija lab https://www.dropbox.com/s/kwd3kcxkmpzqg6w/pbmc3k_final.rds?dl=0
pbmc <- readRDS(file = "../data/pbmc3k_final.rds")
pbmc.sce <- as.SingleCellExperiment(pbmc)
p1 <- plotExpression(pbmc.sce, features = "MS4A1", x = "ident") + theme(axis.text.x = element_text(angle = 45, 
    hjust = 1))
p2 <- plotPCA(pbmc.sce, colour_by = "ident")
p1 + p2
```

Example 7 (unknown):
```unknown
SingleCellExperiment
```

Example 8 (r):
```r
# download from hemberg lab
# https://scrnaseq-public-datasets.s3.amazonaws.com/scater-objects/manno_human.rds
manno <- readRDS(file = "../data/manno_human.rds")
manno <- runPCA(manno)
manno.seurat <- as.Seurat(manno, counts = "counts", data = "logcounts")
# gives the same results; but omits defaults provided in the last line
manno.seurat <- as.Seurat(manno)
Idents(manno.seurat) <- "cell_type1"
p1 <- DimPlot(manno.seurat, reduction = "PCA", group.by = "Source") + NoLegend()
p2 <- RidgePlot(manno.seurat, features = "ACTB", group.by = "Source")
p1 + p2
```

Example 9 (r):
```r
# download from hemberg lab
# https://scrnaseq-public-datasets.s3.amazonaws.com/scater-objects/manno_human.rds
manno <- readRDS(file = "../data/manno_human.rds")
manno <- runPCA(manno)
manno.seurat <- as.Seurat(manno, counts = "counts", data = "logcounts")
# gives the same results; but omits defaults provided in the last line
manno.seurat <- as.Seurat(manno)
Idents(manno.seurat) <- "cell_type1"
p1 <- DimPlot(manno.seurat, reduction = "PCA", group.by = "Source") + NoLegend()
p2 <- RidgePlot(manno.seurat, features = "ACTB", group.by = "Source")
p1 + p2
```

Example 10 (r):
```r
pbmc.loom <- as.loom(pbmc, filename = "../output/pbmc3k.loom", verbose = FALSE)
pbmc.loom
```

Example 11 (r):
```r
pbmc.loom <- as.loom(pbmc, filename = "../output/pbmc3k.loom", verbose = FALSE)
pbmc.loom
```

Example 12 (unknown):
```unknown
## Class: loom
## Filename: /__w/1/s/output/pbmc3k.loom
## Access type: H5F_ACC_RDWR
## Attributes: version, chunks, LOOM_SPEC_VERSION, assay, last_modified
## Listing:
##        name    obj_type dataset.dims dataset.type_class
##   col_attrs   H5I_GROUP         <NA>               <NA>
##  col_graphs   H5I_GROUP         <NA>               <NA>
##      layers   H5I_GROUP         <NA>               <NA>
##      matrix H5I_DATASET 2638 x 13714          H5T_FLOAT
##   row_attrs   H5I_GROUP         <NA>               <NA>
##  row_graphs   H5I_GROUP         <NA>               <NA>
```

Example 13 (unknown):
```unknown
## Class: loom
## Filename: /__w/1/s/output/pbmc3k.loom
## Access type: H5F_ACC_RDWR
## Attributes: version, chunks, LOOM_SPEC_VERSION, assay, last_modified
## Listing:
##        name    obj_type dataset.dims dataset.type_class
##   col_attrs   H5I_GROUP         <NA>               <NA>
##  col_graphs   H5I_GROUP         <NA>               <NA>
##      layers   H5I_GROUP         <NA>               <NA>
##      matrix H5I_DATASET 2638 x 13714          H5T_FLOAT
##   row_attrs   H5I_GROUP         <NA>               <NA>
##  row_graphs   H5I_GROUP         <NA>               <NA>
```

Example 14 (r):
```r
# Always remember to close loom files when done
pbmc.loom$close_all()
```

Example 15 (r):
```r
# Always remember to close loom files when done
pbmc.loom$close_all()
```

Example 16 (r):
```r
# download from linnarson lab
# https://storage.googleapis.com/linnarsson-lab-loom/l6_r1_immune_cells.loom
l6.immune <- connect(filename = "../data/l6_r1_immune_cells.loom", mode = "r")
l6.immune
```

Example 17 (r):
```r
# download from linnarson lab
# https://storage.googleapis.com/linnarsson-lab-loom/l6_r1_immune_cells.loom
l6.immune <- connect(filename = "../data/l6_r1_immune_cells.loom", mode = "r")
l6.immune
```

Example 18 (unknown):
```unknown
## Class: loom
## Filename: /__w/1/s/data/l6_r1_immune_cells.loom
## Access type: H5F_ACC_RDONLY
## Attributes: CreationDate, last_modified
## Listing:
##        name    obj_type  dataset.dims dataset.type_class
##   col_attrs   H5I_GROUP          <NA>               <NA>
##  col_graphs   H5I_GROUP          <NA>               <NA>
##      layers   H5I_GROUP          <NA>               <NA>
##      matrix H5I_DATASET 14908 x 27998          H5T_FLOAT
##   row_attrs   H5I_GROUP          <NA>               <NA>
##  row_graphs   H5I_GROUP          <NA>               <NA>
```

Example 19 (unknown):
```unknown
## Class: loom
## Filename: /__w/1/s/data/l6_r1_immune_cells.loom
## Access type: H5F_ACC_RDONLY
## Attributes: CreationDate, last_modified
## Listing:
##        name    obj_type  dataset.dims dataset.type_class
##   col_attrs   H5I_GROUP          <NA>               <NA>
##  col_graphs   H5I_GROUP          <NA>               <NA>
##      layers   H5I_GROUP          <NA>               <NA>
##      matrix H5I_DATASET 14908 x 27998          H5T_FLOAT
##   row_attrs   H5I_GROUP          <NA>               <NA>
##  row_graphs   H5I_GROUP          <NA>               <NA>
```

Example 20 (r):
```r
l6.seurat <- as.Seurat(l6.immune)
VlnPlot(l6.seurat, features = c("Sparc", "Ftl1", "Junb", "Ccl4"), ncol = 2, pt.size = 0.1)
```

Example 21 (r):
```r
l6.seurat <- as.Seurat(l6.immune)
VlnPlot(l6.seurat, features = c("Sparc", "Ftl1", "Junb", "Ccl4"), ncol = 2, pt.size = 0.1)
```

Example 22 (r):
```r
# Always remember to close loom files when done
l6.immune$close_all()
```

Example 23 (r):
```r
# Always remember to close loom files when done
l6.immune$close_all()
```

Example 24 (r):
```r
# download from satija lab https://www.dropbox.com/s/ngs3p8n2i8y33hj/pbmc3k.h5ad?dl=0
pbmc3k <- ReadH5AD(file = "../data/pbmc3k.h5ad")
Idents(pbmc3k) <- "louvain"
p1 <- DimPlot(pbmc3k, label = TRUE)
p2 <- VlnPlot(pbmc3k, features = c("CST3", "NKG7", "PPBP"), combine = FALSE)
wrap_plots(c(list(p1), p2), ncol = 2) & NoLegend()
```

Example 25 (r):
```r
# download from satija lab https://www.dropbox.com/s/ngs3p8n2i8y33hj/pbmc3k.h5ad?dl=0
pbmc3k <- ReadH5AD(file = "../data/pbmc3k.h5ad")
Idents(pbmc3k) <- "louvain"
p1 <- DimPlot(pbmc3k, label = TRUE)
p2 <- VlnPlot(pbmc3k, features = c("CST3", "NKG7", "PPBP"), combine = FALSE)
wrap_plots(c(list(p1), p2), ncol = 2) & NoLegend()
```

---

## Analysis, visualization, and integration of Visium HD spatial datasets with Seurat • Seurat

**URL:** http://127.0.0.1:9173/articles_visiumhd_analysis_vignette.html

**Contents:**
- Analysis, visualization, and integration of Visium HD spatial datasets with Seurat
    - Compiled: 2024-05-06
- Visium HD support in Seurat
  - Install Seurat Update
  - Load Visium HD data
  - Normalize datasets
  - Visualize gene expression
  - Unsupervised clustering
  - Identifying spatially-defined tissue domains
  - Subset out anatomical regions
  - Integration with scRNA-seq data (deconvolution)
  - Unsupervised clustering: mouse intestine
- Contents

We have previously released support Seurat for sequencing-based spatial transcriptomic (ST) technologies, including 10x visium and SLIDE-seq. We have now updated Seurat to be compatible with the Visium HD technology, which performs profiling at substantially higher spatial resolution than previous versions.

Users can install the Visium HD-compatible release from Github. Existing Seurat workflows for clustering, visualization, and downstream analysis have been updated to support both Visium and Visium HD data.

We note that Visium HD data is generated from spatially patterned olignocleotides labeled in 2um x 2um bins. However, since the data from this resolution is sparse, adjacent bins are pooled together to create 8um and 16um resolutions. 10x recommends the use of 8um binned data for analysis, but Seurat supports in the simultaneous loading of multiple binnings - and stores them in a single object as multiple assays.

In this vignette, we provide an overview of some of the spatial workflows that Seurat supports for analyzing Visium HD data, in particular:

Please note that Visium HD is a new data type, and we expect to update this vignette as we test additional methods for spatial data analysis. We strongly encourage users to explore how different parameter settings affect their results, to analyze data iteratively (and in collaboration with biological experts), and to orthogonally validate unexpected or surprising biological findings.

We focus our analysis on a Visium HD dataset from the mouse brain, available to download here but also run clustering workflow on a dataset from the mouse intestine.

In this vignette we use standard log-normalization for spatial data. We note that the best normalization methods for spatial data are still being developed and evaluated, and encourage users to read manuscripts from the Phipson/Davis and Fan labs to learn more about potential caveats for spatial normalization.

While the standard scRNA-seq clustering workflow can also be applied to spatial datasets - we have observed that when working with Visium HD datasets, the Seurat v5 sketch clustering workflow exhibits improved performance, especially for identifying rare and spatially restricted groups.

As described in Hao et al, Nature Biotechnology 2023 and Hie et al, sketch-based analyses aim to ‘subsample’ large datasets in a way that preserves rare populations. Here, we sketch the Visium HD dataset, perform clustering on the subsampled cells, and then project the cluster labels back to the full dataset.

Details of the sketching procedure and workflow are described in Hao et al, Nature Biotechnology 2023 and the Seurat v5 sketch clustering vignette. Since the full Visium HD dataset fits in memory, we do not use any of the on-disk capabilities of Seurat v5 in this vignette.

Now we can project the cluster labels, and dimensional reductions (PCA and UMAP) that we learned from the 50,000 sketched cells - to the entire dataset, using the ProjectData function.

In the resulting object, for all cells:

We can visualize the clustering results for the sketched cells, as well as the projected clustering results for the full dataset:

Of course, we can now also visualize the unsupervised clusters based on their spatial location. Note that running SpatialDimPlot(object, interactive = TRUE), also enables interactive visualization and exploration.

When there are many different clusters (some of which are spatially restricted and others are mixed), plotting the spatial location of all clusters can be challenging to interpret. We find it helpful to plot the spatial location of different clusters individually. For example, we highlight the spatial localization of a few clusters below, which happen to correspond to different cortical layers:

We can also find and visualize the top gene expression markers for each cluster:

While the previous analyses consider each bin independently, spatial data enables cells to be defined not just by their neighborhood, but also by their broader spatial context.

In Singhal et al., the authors introduce BANKSY, Building Aggregates with a Neighborhood Kernel and Spatial Yardstick (BANKSY). BANKSY performs multiple tasks, but we find it particularly valuable for identifying and segmenting tissue domains. When performing clustering, BANKSY augments a spot’s expression pattern with both the mean and the gradient of gene expression levels in a spot’s broader neighborhood.

We thank the authors for enabling BANKSY to be compatible with Seurat via the SeuratWrappers framework, which requires separate installation of the BANKSY package:

Before running BANKSY, there are two important model parameters that users should consider:

The RunBanksy function creates a new BANKSY assay, which can be used for dimensional reduction and clustering:

As with unsupervised clustering, we can highlight the spatial location of each tissue domain individually:

Users may wish to segment or subset out a restricted region for further downstream analysis. For example, here we create a coordinate-defined segmentation mask marking cortical and hippocampal regions from the entire dataset using the CreateSegmentation function, and then identify cells that fall into this region with the Overlay function.

The list of coordinates is available for download here, and users can identify these boundaries when exploring their own datasets using the interactive=TRUE argument to SpatialDimPlot.

Seurat v5 also includes support for Robust Cell Type Decomposition, a computational approach to deconvolve spot-level data from spatial datasets, when provided with an scRNA-seq reference. RCTD has been shown to accurately annotate spatial data from a variety of technologies, including SLIDE-seq, Visium, and the 10x Xenium in-situ spatial platform. We observe good performance with Visium HD as well.

To run RCTD, we first install the spacexr package from GitHub which implements RCTD. When running RCTD, we follow the instructions from the RCTD vignette.

RCTD takes an scRNA-seq dataset as a reference, and a spatial dataset as a query. For a reference, we use a mouse scRNA-seq dataset from the Allen Brain Atlas, available for download here. The reference scRNAs-eq dataset has been reduced to 200,000 cells (and rare cell types <25 cells have been removed).

We use the cortex Visium HD object as the spatial query. For computational efficiency, we sketch the spatial query dataset, apply RCTD to deconvolute the ‘sketched’ cortical cells and annotate them, and then project these annotations to the full cortical dataset.

We can now look for associations between the scRNA-seq labels of individual bins, and their tissue domain identity (as assigned by BANKSY). By asking which domains the excitatory neuron cells fall in, we can rename the BANKSY clusters as neuronal layers:

Based on this plot, we can now assign cells (even if they are not excitatory neurons) to individual neuronal layers.

Finally, we can visualize the spatial distribution of other cell types, and ask which cortical layers they fall in. For example, in contrast to excitatory neurons, inhibitory (GABAergic) interneurons in the cortex are not spatially restricted to individual layers - but they do show biases.

In our previous analysis of STARmap data, and consistent with previous work, we found that SST and PV interneuron classes tend to be restricted to layers 4-6, while VIP and Lamp5 interneurons tend to be located in layers 2/3. These results were based on an in-situ imaging technology which captures single-cell profiles - and here we ask whether we can find the same result in Visium HD spot-based data.

We recapitulate the same findings, previously identified in in-situ imaging data, in the Visium HD dataset. This highlights that the 8um binning of Visium HD, even though it does not represent true single cell resolution, is capable of accurately localizing scRNA-seq-defined cell types, although we strongly encourage users to orthogonally validate unexpected or surprising biological findings.

We briefly demonstrate our sketch-clustering workflow on a second Visium HD dataset, from the Mouse Small Intestine (FFPE), available for download here. We identify clusters, visualize their spatial locations, and report their top gene expression markers:

We visualize the location of each cluster individually:

Developed by Madeline Kowalski, Harm Wessels.

Site built with pkgdown 2.0.7.

**Examples:**

Example 1 (unknown):
```unknown
vignettes/visiumhd_analysis_vignette.Rmd
```

Example 2 (unknown):
```unknown
visiumhd_analysis_vignette.Rmd
```

Example 3 (unknown):
```unknown
# packages required for Visium HD
install.packages("hdf5r")
install.packages("arrow")
```

Example 4 (r):
```r
# packages required for Visium HD
install.packages("hdf5r")
install.packages("arrow")
```

Example 5 (r):
```r
# packages required for Visium HD
install.packages("hdf5r")
install.packages("arrow")
```

Example 6 (unknown):
```unknown
library(Seurat)
library(ggplot2)
library(patchwork)
library(dplyr)
```

Example 7 (r):
```r
library(Seurat)
library(ggplot2)
library(patchwork)
library(dplyr)
```

Example 8 (r):
```r
library(Seurat)
library(ggplot2)
library(patchwork)
library(dplyr)
```

Example 9 (unknown):
```unknown
localdir <- "/brahms/lis/visium_hd/mouse/new_mousebrain/"
object <- Load10X_Spatial(data.dir = localdir, bin.size = c(8, 16))

# Setting default assay changes between 8um and 16um binning
Assays(object)
DefaultAssay(object) <- "Spatial.008um"
```

Example 10 (r):
```r
localdir <- "/brahms/lis/visium_hd/mouse/new_mousebrain/"
object <- Load10X_Spatial(data.dir = localdir, bin.size = c(8, 16))

# Setting default assay changes between 8um and 16um binning
Assays(object)
DefaultAssay(object) <- "Spatial.008um"
```

Example 11 (r):
```r
localdir <- "/brahms/lis/visium_hd/mouse/new_mousebrain/"
object <- Load10X_Spatial(data.dir = localdir, bin.size = c(8, 16))

# Setting default assay changes between 8um and 16um binning
Assays(object)
DefaultAssay(object) <- "Spatial.008um"
```

Example 12 (unknown):
```unknown
vln.plot <- VlnPlot(object, features = "nCount_Spatial.008um", pt.size = 0) + theme(axis.text = element_text(size = 4)) + NoLegend()
count.plot <- SpatialFeaturePlot(object, features = "nCount_Spatial.008um") + theme(legend.position = "right")

# note that many spots have very few counts, in-part
# due to low cellular density in certain tissue regions
vln.plot | count.plot
```

Example 13 (r):
```r
vln.plot <- VlnPlot(object, features = "nCount_Spatial.008um", pt.size = 0) + theme(axis.text = element_text(size = 4)) + NoLegend()
count.plot <- SpatialFeaturePlot(object, features = "nCount_Spatial.008um") + theme(legend.position = "right")

# note that many spots have very few counts, in-part
# due to low cellular density in certain tissue regions
vln.plot | count.plot
```

Example 14 (r):
```r
vln.plot <- VlnPlot(object, features = "nCount_Spatial.008um", pt.size = 0) + theme(axis.text = element_text(size = 4)) + NoLegend()
count.plot <- SpatialFeaturePlot(object, features = "nCount_Spatial.008um") + theme(legend.position = "right")

# note that many spots have very few counts, in-part
# due to low cellular density in certain tissue regions
vln.plot | count.plot
```

Example 15 (unknown):
```unknown
# normalize both 8um and 16um bins
DefaultAssay(object) <- "Spatial.008um"
object <- NormalizeData(object)

DefaultAssay(object) <- "Spatial.016um"
object <- NormalizeData(object)
```

Example 16 (r):
```r
# normalize both 8um and 16um bins
DefaultAssay(object) <- "Spatial.008um"
object <- NormalizeData(object)

DefaultAssay(object) <- "Spatial.016um"
object <- NormalizeData(object)
```

Example 17 (r):
```r
# normalize both 8um and 16um bins
DefaultAssay(object) <- "Spatial.008um"
object <- NormalizeData(object)

DefaultAssay(object) <- "Spatial.016um"
object <- NormalizeData(object)
```

Example 18 (unknown):
```unknown
pt.size.factor
```

Example 19 (python):
```python
# switch spatial resolution to 16um from 8um
DefaultAssay(object) <- "Spatial.016um"
p1 <- SpatialFeaturePlot(object, features = "Rorb") + ggtitle("Rorb expression (16um)")

# switch back to 8um
DefaultAssay(object) <- "Spatial.008um"
p2 <- SpatialFeaturePlot(object, features = "Hpca") + ggtitle("Hpca expression (8um)")

p1 | p2
```

Example 20 (r):
```r
# switch spatial resolution to 16um from 8um
DefaultAssay(object) <- "Spatial.016um"
p1 <- SpatialFeaturePlot(object, features = "Rorb") + ggtitle("Rorb expression (16um)")

# switch back to 8um
DefaultAssay(object) <- "Spatial.008um"
p2 <- SpatialFeaturePlot(object, features = "Hpca") + ggtitle("Hpca expression (8um)")

p1 | p2
```

Example 21 (r):
```r
# switch spatial resolution to 16um from 8um
DefaultAssay(object) <- "Spatial.016um"
p1 <- SpatialFeaturePlot(object, features = "Rorb") + ggtitle("Rorb expression (16um)")

# switch back to 8um
DefaultAssay(object) <- "Spatial.008um"
p2 <- SpatialFeaturePlot(object, features = "Hpca") + ggtitle("Hpca expression (8um)")

p1 | p2
```

Example 22 (unknown):
```unknown
# note that data is already normalized
DefaultAssay(object) <- "Spatial.008um"
object <- FindVariableFeatures(object)
object <- ScaleData(object)
# we select 50,0000 cells and create a new 'sketch' assay
object <- SketchData(
  object = object,
  ncells = 50000,
  method = "LeverageScore",
  sketched.assay = "sketch"
)
```

Example 23 (r):
```r
# note that data is already normalized
DefaultAssay(object) <- "Spatial.008um"
object <- FindVariableFeatures(object)
object <- ScaleData(object)
# we select 50,0000 cells and create a new 'sketch' assay
object <- SketchData(
  object = object,
  ncells = 50000,
  method = "LeverageScore",
  sketched.assay = "sketch"
)
```

Example 24 (r):
```r
# note that data is already normalized
DefaultAssay(object) <- "Spatial.008um"
object <- FindVariableFeatures(object)
object <- ScaleData(object)
# we select 50,0000 cells and create a new 'sketch' assay
object <- SketchData(
  object = object,
  ncells = 50000,
  method = "LeverageScore",
  sketched.assay = "sketch"
)
```

Example 25 (unknown):
```unknown
# switch analysis to sketched cells
DefaultAssay(object) <- "sketch"

# perform clustering workflow
object <- FindVariableFeatures(object)
object <- ScaleData(object)
object <- RunPCA(object, assay = "sketch", reduction.name = "pca.sketch")
object <- FindNeighbors(object, assay = "sketch", reduction = "pca.sketch", dims = 1:50)
object <- FindClusters(object, cluster.name = "seurat_cluster.sketched", resolution = 3)
object <- RunUMAP(object, reduction = "pca.sketch", reduction.name = "umap.sketch", return.model = T, dims = 1:50)
```

Example 26 (r):
```r
# switch analysis to sketched cells
DefaultAssay(object) <- "sketch"

# perform clustering workflow
object <- FindVariableFeatures(object)
object <- ScaleData(object)
object <- RunPCA(object, assay = "sketch", reduction.name = "pca.sketch")
object <- FindNeighbors(object, assay = "sketch", reduction = "pca.sketch", dims = 1:50)
object <- FindClusters(object, cluster.name = "seurat_cluster.sketched", resolution = 3)
object <- RunUMAP(object, reduction = "pca.sketch", reduction.name = "umap.sketch", return.model = T, dims = 1:50)
```

Example 27 (r):
```r
# switch analysis to sketched cells
DefaultAssay(object) <- "sketch"

# perform clustering workflow
object <- FindVariableFeatures(object)
object <- ScaleData(object)
object <- RunPCA(object, assay = "sketch", reduction.name = "pca.sketch")
object <- FindNeighbors(object, assay = "sketch", reduction = "pca.sketch", dims = 1:50)
object <- FindClusters(object, cluster.name = "seurat_cluster.sketched", resolution = 3)
object <- RunUMAP(object, reduction = "pca.sketch", reduction.name = "umap.sketch", return.model = T, dims = 1:50)
```

Example 28 (unknown):
```unknown
ProjectData
```

Example 29 (unknown):
```unknown
object$seurat_cluster.projected
```

Example 30 (unknown):
```unknown
object[["pca.008um"]]
```

Example 31 (unknown):
```unknown
object[["umap.sketch"]]
```

Example 32 (unknown):
```unknown
object <- ProjectData(
  object = object,
  assay = "Spatial.008um",
  full.reduction = "full.pca.sketch",
  sketched.assay = "sketch",
  sketched.reduction = "pca.sketch",
  umap.model = "umap.sketch",
  dims = 1:50,
  refdata = list(seurat_cluster.projected = "seurat_cluster.sketched")
)
```

Example 33 (r):
```r
object <- ProjectData(
  object = object,
  assay = "Spatial.008um",
  full.reduction = "full.pca.sketch",
  sketched.assay = "sketch",
  sketched.reduction = "pca.sketch",
  umap.model = "umap.sketch",
  dims = 1:50,
  refdata = list(seurat_cluster.projected = "seurat_cluster.sketched")
)
```

Example 34 (r):
```r
object <- ProjectData(
  object = object,
  assay = "Spatial.008um",
  full.reduction = "full.pca.sketch",
  sketched.assay = "sketch",
  sketched.reduction = "pca.sketch",
  umap.model = "umap.sketch",
  dims = 1:50,
  refdata = list(seurat_cluster.projected = "seurat_cluster.sketched")
)
```

Example 35 (unknown):
```unknown
DefaultAssay(object) <- "sketch"
Idents(object) <- "seurat_cluster.sketched"
p1 <- DimPlot(object, reduction = "umap.sketch", label = F) + ggtitle("Sketched clustering (50,000 cells)") + theme(legend.position = "bottom")

# switch to full dataset
DefaultAssay(object) <- "Spatial.008um"
Idents(object) <- "seurat_cluster.projected"
p2 <- DimPlot(object, reduction = "full.umap.sketch", label = F) + ggtitle("Projected clustering (full dataset)") + theme(legend.position = "bottom")

p1 | p2
```

Example 36 (r):
```r
DefaultAssay(object) <- "sketch"
Idents(object) <- "seurat_cluster.sketched"
p1 <- DimPlot(object, reduction = "umap.sketch", label = F) + ggtitle("Sketched clustering (50,000 cells)") + theme(legend.position = "bottom")

# switch to full dataset
DefaultAssay(object) <- "Spatial.008um"
Idents(object) <- "seurat_cluster.projected"
p2 <- DimPlot(object, reduction = "full.umap.sketch", label = F) + ggtitle("Projected clustering (full dataset)") + theme(legend.position = "bottom")

p1 | p2
```

Example 37 (r):
```r
DefaultAssay(object) <- "sketch"
Idents(object) <- "seurat_cluster.sketched"
p1 <- DimPlot(object, reduction = "umap.sketch", label = F) + ggtitle("Sketched clustering (50,000 cells)") + theme(legend.position = "bottom")

# switch to full dataset
DefaultAssay(object) <- "Spatial.008um"
Idents(object) <- "seurat_cluster.projected"
p2 <- DimPlot(object, reduction = "full.umap.sketch", label = F) + ggtitle("Projected clustering (full dataset)") + theme(legend.position = "bottom")

p1 | p2
```

Example 38 (unknown):
```unknown
SpatialDimPlot(object, interactive = TRUE)
```

Example 39 (unknown):
```unknown
SpatialDimPlot(object, label = T, repel = T, label.size = 4)
```

Example 40 (r):
```r
SpatialDimPlot(object, label = T, repel = T, label.size = 4)
```

Example 41 (r):
```r
SpatialDimPlot(object, label = T, repel = T, label.size = 4)
```

Example 42 (unknown):
```unknown
Idents(object) <- "seurat_cluster.projected"
cells <- CellsByIdentities(object, idents = c(0, 4, 32, 34, 35))
p <- SpatialDimPlot(object,
  cells.highlight = cells[setdiff(names(cells), "NA")],
  cols.highlight = c("#FFFF00", "grey50"), facet.highlight = T, combine = T
) + NoLegend()
p
```

Example 43 (r):
```r
Idents(object) <- "seurat_cluster.projected"
cells <- CellsByIdentities(object, idents = c(0, 4, 32, 34, 35))
p <- SpatialDimPlot(object,
  cells.highlight = cells[setdiff(names(cells), "NA")],
  cols.highlight = c("#FFFF00", "grey50"), facet.highlight = T, combine = T
) + NoLegend()
p
```

Example 44 (r):
```r
Idents(object) <- "seurat_cluster.projected"
cells <- CellsByIdentities(object, idents = c(0, 4, 32, 34, 35))
p <- SpatialDimPlot(object,
  cells.highlight = cells[setdiff(names(cells), "NA")],
  cols.highlight = c("#FFFF00", "grey50"), facet.highlight = T, combine = T
) + NoLegend()
p
```

Example 45 (unknown):
```unknown
# Crete downsampled object to make visualization either
DefaultAssay(object) <- "Spatial.008um"
Idents(object) <- "seurat_cluster.projected"
object_subset <- subset(object, cells = Cells(object[["Spatial.008um"]]), downsample = 1000)

# Order clusters by similarity
DefaultAssay(object_subset) <- "Spatial.008um"
Idents(object_subset) <- "seurat_cluster.projected"
object_subset <- BuildClusterTree(object_subset, assay = "Spatial.008um", reduction = "full.pca.sketch", reorder = T)

markers <- FindAllMarkers(object_subset, assay = "Spatial.008um", only.pos = TRUE)
markers %>%
  group_by(cluster) %>%
  dplyr::filter(avg_log2FC > 1) %>%
  slice_head(n = 5) %>%
  ungroup() -> top5

object_subset <- ScaleData(object_subset, assay = "Spatial.008um", features = top5$gene)
p <- DoHeatmap(object_subset, assay = "Spatial.008um", features = top5$gene, size = 2.5) + theme(axis.text = element_text(size = 5.5)) + NoLegend()
p
```

Example 46 (r):
```r
# Crete downsampled object to make visualization either
DefaultAssay(object) <- "Spatial.008um"
Idents(object) <- "seurat_cluster.projected"
object_subset <- subset(object, cells = Cells(object[["Spatial.008um"]]), downsample = 1000)

# Order clusters by similarity
DefaultAssay(object_subset) <- "Spatial.008um"
Idents(object_subset) <- "seurat_cluster.projected"
object_subset <- BuildClusterTree(object_subset, assay = "Spatial.008um", reduction = "full.pca.sketch", reorder = T)

markers <- FindAllMarkers(object_subset, assay = "Spatial.008um", only.pos = TRUE)
markers %>%
  group_by(cluster) %>%
  dplyr::filter(avg_log2FC > 1) %>%
  slice_head(n = 5) %>%
  ungroup() -> top5

object_subset <- ScaleData(object_subset, assay = "Spatial.008um", features = top5$gene)
p <- DoHeatmap(object_subset, assay = "Spatial.008um", features = top5$gene, size = 2.5) + theme(axis.text = element_text(size = 5.5)) + NoLegend()
p
```

Example 47 (r):
```r
# Crete downsampled object to make visualization either
DefaultAssay(object) <- "Spatial.008um"
Idents(object) <- "seurat_cluster.projected"
object_subset <- subset(object, cells = Cells(object[["Spatial.008um"]]), downsample = 1000)

# Order clusters by similarity
DefaultAssay(object_subset) <- "Spatial.008um"
Idents(object_subset) <- "seurat_cluster.projected"
object_subset <- BuildClusterTree(object_subset, assay = "Spatial.008um", reduction = "full.pca.sketch", reorder = T)

markers <- FindAllMarkers(object_subset, assay = "Spatial.008um", only.pos = TRUE)
markers %>%
  group_by(cluster) %>%
  dplyr::filter(avg_log2FC > 1) %>%
  slice_head(n = 5) %>%
  ungroup() -> top5

object_subset <- ScaleData(object_subset, assay = "Spatial.008um", features = top5$gene)
p <- DoHeatmap(object_subset, assay = "Spatial.008um", features = top5$gene, size = 2.5) + theme(axis.text = element_text(size = 5.5)) + NoLegend()
p
```

Example 48 (unknown):
```unknown
SeuratWrappers
```

Example 49 (unknown):
```unknown
if (!requireNamespace("Banksy", quietly = TRUE)) {
  remotes::install_github("prabhakarlab/Banksy@devel")
}
library(SeuratWrappers)
library(Banksy)
```

Example 50 (r):
```r
if (!requireNamespace("Banksy", quietly = TRUE)) {
  remotes::install_github("prabhakarlab/Banksy@devel")
}
library(SeuratWrappers)
library(Banksy)
```

Example 51 (r):
```r
if (!requireNamespace("Banksy", quietly = TRUE)) {
  remotes::install_github("prabhakarlab/Banksy@devel")
}
library(SeuratWrappers)
library(Banksy)
```

Example 52 (unknown):
```unknown
object <- RunBanksy(object,
  lambda = 0.8, verbose = TRUE,
  assay = "Spatial.008um", slot = "data", features = "variable",
  k_geom = 50
)
```

Example 53 (r):
```r
object <- RunBanksy(object,
  lambda = 0.8, verbose = TRUE,
  assay = "Spatial.008um", slot = "data", features = "variable",
  k_geom = 50
)
```

Example 54 (r):
```r
object <- RunBanksy(object,
  lambda = 0.8, verbose = TRUE,
  assay = "Spatial.008um", slot = "data", features = "variable",
  k_geom = 50
)
```

Example 55 (unknown):
```unknown
DefaultAssay(object) <- "BANKSY"
object <- RunPCA(object, assay = "BANKSY", reduction.name = "pca.banksy", features = rownames(object), npcs = 30)
object <- FindNeighbors(object, reduction = "pca.banksy", dims = 1:30)
object <- FindClusters(object, cluster.name = "banksy_cluster", resolution = 0.5)
```

Example 56 (r):
```r
DefaultAssay(object) <- "BANKSY"
object <- RunPCA(object, assay = "BANKSY", reduction.name = "pca.banksy", features = rownames(object), npcs = 30)
object <- FindNeighbors(object, reduction = "pca.banksy", dims = 1:30)
object <- FindClusters(object, cluster.name = "banksy_cluster", resolution = 0.5)
```

Example 57 (r):
```r
DefaultAssay(object) <- "BANKSY"
object <- RunPCA(object, assay = "BANKSY", reduction.name = "pca.banksy", features = rownames(object), npcs = 30)
object <- FindNeighbors(object, reduction = "pca.banksy", dims = 1:30)
object <- FindClusters(object, cluster.name = "banksy_cluster", resolution = 0.5)
```

Example 58 (unknown):
```unknown
Idents(object) <- "banksy_cluster"
p <- SpatialDimPlot(object, group.by = "banksy_cluster", label = T, repel = T, label.size = 4)
p
```

Example 59 (r):
```r
Idents(object) <- "banksy_cluster"
p <- SpatialDimPlot(object, group.by = "banksy_cluster", label = T, repel = T, label.size = 4)
p
```

Example 60 (r):
```r
Idents(object) <- "banksy_cluster"
p <- SpatialDimPlot(object, group.by = "banksy_cluster", label = T, repel = T, label.size = 4)
p
```

Example 61 (unknown):
```unknown
banksy_cells <- CellsByIdentities(object)
p <- SpatialDimPlot(object, cells.highlight = banksy_cells[setdiff(names(banksy_cells), "NA")], cols.highlight = c("#FFFF00", "grey50"), facet.highlight = T, combine = T) + NoLegend()
p
```

Example 62 (r):
```r
banksy_cells <- CellsByIdentities(object)
p <- SpatialDimPlot(object, cells.highlight = banksy_cells[setdiff(names(banksy_cells), "NA")], cols.highlight = c("#FFFF00", "grey50"), facet.highlight = T, combine = T) + NoLegend()
p
```

Example 63 (r):
```r
banksy_cells <- CellsByIdentities(object)
p <- SpatialDimPlot(object, cells.highlight = banksy_cells[setdiff(names(banksy_cells), "NA")], cols.highlight = c("#FFFF00", "grey50"), facet.highlight = T, combine = T) + NoLegend()
p
```

Example 64 (unknown):
```unknown
CreateSegmentation
```

Example 65 (unknown):
```unknown
interactive=TRUE
```

Example 66 (unknown):
```unknown
SpatialDimPlot
```

Example 67 (unknown):
```unknown
cortex.coordinates <- as.data.frame(read.csv("/brahms/lis/visium_hd/final_mouse/cortex-hippocampus_coordinates.csv"))
cortex <- CreateSegmentation(cortex.coordinates)

object[["cortex"]] <- Overlay(object[["slice1.008um"]], cortex)
cortex <- subset(object, cells = Cells(object[["cortex"]]))
```

Example 68 (r):
```r
cortex.coordinates <- as.data.frame(read.csv("/brahms/lis/visium_hd/final_mouse/cortex-hippocampus_coordinates.csv"))
cortex <- CreateSegmentation(cortex.coordinates)

object[["cortex"]] <- Overlay(object[["slice1.008um"]], cortex)
cortex <- subset(object, cells = Cells(object[["cortex"]]))
```

Example 69 (r):
```r
cortex.coordinates <- as.data.frame(read.csv("/brahms/lis/visium_hd/final_mouse/cortex-hippocampus_coordinates.csv"))
cortex <- CreateSegmentation(cortex.coordinates)

object[["cortex"]] <- Overlay(object[["slice1.008um"]], cortex)
cortex <- subset(object, cells = Cells(object[["cortex"]]))
```

Example 70 (unknown):
```unknown
if (!requireNamespace("spacexr", quietly = TRUE)) {
  devtools::install_github("dmcable/spacexr", build_vignettes = FALSE)
}
library(spacexr)
```

Example 71 (r):
```r
if (!requireNamespace("spacexr", quietly = TRUE)) {
  devtools::install_github("dmcable/spacexr", build_vignettes = FALSE)
}
library(spacexr)
```

Example 72 (r):
```r
if (!requireNamespace("spacexr", quietly = TRUE)) {
  devtools::install_github("dmcable/spacexr", build_vignettes = FALSE)
}
library(spacexr)
```

Example 73 (unknown):
```unknown
# sketch the cortical subset of the Visium HD dataset
DefaultAssay(cortex) <- "Spatial.008um"
cortex <- FindVariableFeatures(cortex)
cortex <- SketchData(
  object = cortex,
  ncells = 50000,
  method = "LeverageScore",
  sketched.assay = "sketch"
)

DefaultAssay(cortex) <- "sketch"
cortex <- ScaleData(cortex)
cortex <- RunPCA(cortex, assay = "sketch", reduction.name = "pca.cortex.sketch", verbose = T)
cortex <- FindNeighbors(cortex, reduction = "pca.cortex.sketch", dims = 1:50)
cortex <- RunUMAP(cortex, reduction = "pca.cortex.sketch", reduction.name = "umap.cortex.sketch", return.model = T, dims = 1:50, verbose = T)
```

Example 74 (r):
```r
# sketch the cortical subset of the Visium HD dataset
DefaultAssay(cortex) <- "Spatial.008um"
cortex <- FindVariableFeatures(cortex)
cortex <- SketchData(
  object = cortex,
  ncells = 50000,
  method = "LeverageScore",
  sketched.assay = "sketch"
)

DefaultAssay(cortex) <- "sketch"
cortex <- ScaleData(cortex)
cortex <- RunPCA(cortex, assay = "sketch", reduction.name = "pca.cortex.sketch", verbose = T)
cortex <- FindNeighbors(cortex, reduction = "pca.cortex.sketch", dims = 1:50)
cortex <- RunUMAP(cortex, reduction = "pca.cortex.sketch", reduction.name = "umap.cortex.sketch", return.model = T, dims = 1:50, verbose = T)
```

Example 75 (r):
```r
# sketch the cortical subset of the Visium HD dataset
DefaultAssay(cortex) <- "Spatial.008um"
cortex <- FindVariableFeatures(cortex)
cortex <- SketchData(
  object = cortex,
  ncells = 50000,
  method = "LeverageScore",
  sketched.assay = "sketch"
)

DefaultAssay(cortex) <- "sketch"
cortex <- ScaleData(cortex)
cortex <- RunPCA(cortex, assay = "sketch", reduction.name = "pca.cortex.sketch", verbose = T)
cortex <- FindNeighbors(cortex, reduction = "pca.cortex.sketch", dims = 1:50)
cortex <- RunUMAP(cortex, reduction = "pca.cortex.sketch", reduction.name = "umap.cortex.sketch", return.model = T, dims = 1:50, verbose = T)
```

Example 76 (unknown):
```unknown
# load in the reference scRNA-seq dataset
ref <- readRDS("/brahms/satijar/allen_scRNAseq_ref.Rds")
```

Example 77 (r):
```r
# load in the reference scRNA-seq dataset
ref <- readRDS("/brahms/satijar/allen_scRNAseq_ref.Rds")
```

Example 78 (r):
```r
# load in the reference scRNA-seq dataset
ref <- readRDS("/brahms/satijar/allen_scRNAseq_ref.Rds")
```

Example 79 (unknown):
```unknown
Idents(ref) <- "subclass_label"
counts <- ref[["RNA"]]$counts
cluster <- as.factor(ref$subclass_label)
nUMI <- ref$nCount_RNA
levels(cluster) <- gsub("/", "-", levels(cluster))
cluster <- droplevels(cluster)

# create the RCTD reference object
reference <- Reference(counts, cluster, nUMI)

counts_hd <- cortex[["sketch"]]$counts
cortex_cells_hd <- colnames(cortex[["sketch"]])
coords <- GetTissueCoordinates(cortex)[cortex_cells_hd, 1:2]

# create the RCTD query object
query <- SpatialRNA(coords, counts_hd, colSums(counts_hd))
```

Example 80 (r):
```r
Idents(ref) <- "subclass_label"
counts <- ref[["RNA"]]$counts
cluster <- as.factor(ref$subclass_label)
nUMI <- ref$nCount_RNA
levels(cluster) <- gsub("/", "-", levels(cluster))
cluster <- droplevels(cluster)

# create the RCTD reference object
reference <- Reference(counts, cluster, nUMI)

counts_hd <- cortex[["sketch"]]$counts
cortex_cells_hd <- colnames(cortex[["sketch"]])
coords <- GetTissueCoordinates(cortex)[cortex_cells_hd, 1:2]

# create the RCTD query object
query <- SpatialRNA(coords, counts_hd, colSums(counts_hd))
```

Example 81 (r):
```r
Idents(ref) <- "subclass_label"
counts <- ref[["RNA"]]$counts
cluster <- as.factor(ref$subclass_label)
nUMI <- ref$nCount_RNA
levels(cluster) <- gsub("/", "-", levels(cluster))
cluster <- droplevels(cluster)

# create the RCTD reference object
reference <- Reference(counts, cluster, nUMI)

counts_hd <- cortex[["sketch"]]$counts
cortex_cells_hd <- colnames(cortex[["sketch"]])
coords <- GetTissueCoordinates(cortex)[cortex_cells_hd, 1:2]

# create the RCTD query object
query <- SpatialRNA(coords, counts_hd, colSums(counts_hd))
```

Example 82 (python):
```python
# run RCTD
RCTD <- create.RCTD(query, reference, max_cores = 28)
RCTD <- run.RCTD(RCTD, doublet_mode = "doublet")
# add results back to Seurat object
cortex <- AddMetaData(cortex, metadata = RCTD@results$results_df)
```

Example 83 (r):
```r
# run RCTD
RCTD <- create.RCTD(query, reference, max_cores = 28)
RCTD <- run.RCTD(RCTD, doublet_mode = "doublet")
# add results back to Seurat object
cortex <- AddMetaData(cortex, metadata = RCTD@results$results_df)
```

Example 84 (r):
```r
# run RCTD
RCTD <- create.RCTD(query, reference, max_cores = 28)
RCTD <- run.RCTD(RCTD, doublet_mode = "doublet")
# add results back to Seurat object
cortex <- AddMetaData(cortex, metadata = RCTD@results$results_df)
```

Example 85 (python):
```python
# project RCTD labels from sketched cortical cells to all cortical cells
cortex$first_type <- as.character(cortex$first_type)
cortex$first_type[is.na(cortex$first_type)] <- "Unknown"
cortex <- ProjectData(
  object = cortex,
  assay = "Spatial.008um",
  full.reduction = "pca.cortex",
  sketched.assay = "sketch",
  sketched.reduction = "pca.cortex.sketch",
  umap.model = "umap.cortex.sketch",
  dims = 1:50,
  refdata = list(full_first_type = "first_type")
)
```

Example 86 (r):
```r
# project RCTD labels from sketched cortical cells to all cortical cells
cortex$first_type <- as.character(cortex$first_type)
cortex$first_type[is.na(cortex$first_type)] <- "Unknown"
cortex <- ProjectData(
  object = cortex,
  assay = "Spatial.008um",
  full.reduction = "pca.cortex",
  sketched.assay = "sketch",
  sketched.reduction = "pca.cortex.sketch",
  umap.model = "umap.cortex.sketch",
  dims = 1:50,
  refdata = list(full_first_type = "first_type")
)
```

Example 87 (r):
```r
# project RCTD labels from sketched cortical cells to all cortical cells
cortex$first_type <- as.character(cortex$first_type)
cortex$first_type[is.na(cortex$first_type)] <- "Unknown"
cortex <- ProjectData(
  object = cortex,
  assay = "Spatial.008um",
  full.reduction = "pca.cortex",
  sketched.assay = "sketch",
  sketched.reduction = "pca.cortex.sketch",
  umap.model = "umap.cortex.sketch",
  dims = 1:50,
  refdata = list(full_first_type = "first_type")
)
```

Example 88 (unknown):
```unknown
DefaultAssay(object) <- "Spatial.008um"

# we only ran RCTD on the cortical cells
# set labels to all other cells as "Unknown"
object[[]][, "full_first_type"] <- "Unknown"
object$full_first_type[Cells(cortex)] <- cortex$full_first_type[Cells(cortex)]
```

Example 89 (r):
```r
DefaultAssay(object) <- "Spatial.008um"

# we only ran RCTD on the cortical cells
# set labels to all other cells as "Unknown"
object[[]][, "full_first_type"] <- "Unknown"
object$full_first_type[Cells(cortex)] <- cortex$full_first_type[Cells(cortex)]
```

Example 90 (r):
```r
DefaultAssay(object) <- "Spatial.008um"

# we only ran RCTD on the cortical cells
# set labels to all other cells as "Unknown"
object[[]][, "full_first_type"] <- "Unknown"
object$full_first_type[Cells(cortex)] <- cortex$full_first_type[Cells(cortex)]
```

Example 91 (unknown):
```unknown
Idents(object) <- "full_first_type"

# now we can spatially map the location of any scRNA-seq cell type
# start with Layered (starts with L), excitatory neurons in the cortex
cells <- CellsByIdentities(object)
excitatory_names <- sort(grep("^L.* CTX", names(cells), value = TRUE))
p <- SpatialDimPlot(object, cells.highlight = cells[excitatory_names], cols.highlight = c("#FFFF00", "grey50"), facet.highlight = T, combine = T, ncol = 4)
p
```

Example 92 (r):
```r
Idents(object) <- "full_first_type"

# now we can spatially map the location of any scRNA-seq cell type
# start with Layered (starts with L), excitatory neurons in the cortex
cells <- CellsByIdentities(object)
excitatory_names <- sort(grep("^L.* CTX", names(cells), value = TRUE))
p <- SpatialDimPlot(object, cells.highlight = cells[excitatory_names], cols.highlight = c("#FFFF00", "grey50"), facet.highlight = T, combine = T, ncol = 4)
p
```

Example 93 (r):
```r
Idents(object) <- "full_first_type"

# now we can spatially map the location of any scRNA-seq cell type
# start with Layered (starts with L), excitatory neurons in the cortex
cells <- CellsByIdentities(object)
excitatory_names <- sort(grep("^L.* CTX", names(cells), value = TRUE))
p <- SpatialDimPlot(object, cells.highlight = cells[excitatory_names], cols.highlight = c("#FFFF00", "grey50"), facet.highlight = T, combine = T, ncol = 4)
p
```

Example 94 (javascript):
```javascript
plot_cell_types <- function(data, label) {
  p <- ggplot(data, aes(x = get(label), y = n, fill = full_first_type)) +
    geom_bar(stat = "identity", position = "stack") +
    geom_text(aes(label = ifelse(n >= min_count_to_show_label, full_first_type, "")), position = position_stack(vjust = 0.5), size = 2) +
    xlab(label) +
    ylab("# of Spots") +
    ggtitle(paste0("Distribution of Cell Types across ", label)) +
    theme_minimal()
}

cell_type_banksy_counts <- object[[]] %>%
  dplyr::filter(full_first_type %in% excitatory_names) %>%
  dplyr::count(full_first_type, banksy_cluster)

min_count_to_show_label <- 20

p <- plot_cell_types(cell_type_banksy_counts, "banksy_cluster")
p
```

Example 95 (r):
```r
plot_cell_types <- function(data, label) {
  p <- ggplot(data, aes(x = get(label), y = n, fill = full_first_type)) +
    geom_bar(stat = "identity", position = "stack") +
    geom_text(aes(label = ifelse(n >= min_count_to_show_label, full_first_type, "")), position = position_stack(vjust = 0.5), size = 2) +
    xlab(label) +
    ylab("# of Spots") +
    ggtitle(paste0("Distribution of Cell Types across ", label)) +
    theme_minimal()
}

cell_type_banksy_counts <- object[[]] %>%
  dplyr::filter(full_first_type %in% excitatory_names) %>%
  dplyr::count(full_first_type, banksy_cluster)

min_count_to_show_label <- 20

p <- plot_cell_types(cell_type_banksy_counts, "banksy_cluster")
p
```

Example 96 (r):
```r
plot_cell_types <- function(data, label) {
  p <- ggplot(data, aes(x = get(label), y = n, fill = full_first_type)) +
    geom_bar(stat = "identity", position = "stack") +
    geom_text(aes(label = ifelse(n >= min_count_to_show_label, full_first_type, "")), position = position_stack(vjust = 0.5), size = 2) +
    xlab(label) +
    ylab("# of Spots") +
    ggtitle(paste0("Distribution of Cell Types across ", label)) +
    theme_minimal()
}

cell_type_banksy_counts <- object[[]] %>%
  dplyr::filter(full_first_type %in% excitatory_names) %>%
  dplyr::count(full_first_type, banksy_cluster)

min_count_to_show_label <- 20

p <- plot_cell_types(cell_type_banksy_counts, "banksy_cluster")
p
```

Example 97 (unknown):
```unknown
Idents(object) <- "banksy_cluster"
object$layer_id <- "Unknown"
object$layer_id[WhichCells(object, idents = c(7))] <- "Layer 2/3"
object$layer_id[WhichCells(object, idents = c(15))] <- "Layer 4"
object$layer_id[WhichCells(object, idents = c(5))] <- "Layer 5"
object$layer_id[WhichCells(object, idents = c(1))] <- "Layer 6"
```

Example 98 (r):
```r
Idents(object) <- "banksy_cluster"
object$layer_id <- "Unknown"
object$layer_id[WhichCells(object, idents = c(7))] <- "Layer 2/3"
object$layer_id[WhichCells(object, idents = c(15))] <- "Layer 4"
object$layer_id[WhichCells(object, idents = c(5))] <- "Layer 5"
object$layer_id[WhichCells(object, idents = c(1))] <- "Layer 6"
```

Example 99 (r):
```r
Idents(object) <- "banksy_cluster"
object$layer_id <- "Unknown"
object$layer_id[WhichCells(object, idents = c(7))] <- "Layer 2/3"
object$layer_id[WhichCells(object, idents = c(15))] <- "Layer 4"
object$layer_id[WhichCells(object, idents = c(5))] <- "Layer 5"
object$layer_id[WhichCells(object, idents = c(1))] <- "Layer 6"
```

Example 100 (unknown):
```unknown
# set ID to RCTD label
Idents(object) <- "full_first_type"

# Visualize distribution of 4 interneuron subtypes
inhibitory_names <- c("Sst", "Pvalb", "Vip", "Lamp5")
cell_ids <- CellsByIdentities(object, idents = inhibitory_names)
p <- SpatialDimPlot(object, cells.highlight = cell_ids, cols.highlight = c("#FFFF00", "grey50"), facet.highlight = T, combine = T, ncol = 4)
p
```

Example 101 (r):
```r
# set ID to RCTD label
Idents(object) <- "full_first_type"

# Visualize distribution of 4 interneuron subtypes
inhibitory_names <- c("Sst", "Pvalb", "Vip", "Lamp5")
cell_ids <- CellsByIdentities(object, idents = inhibitory_names)
p <- SpatialDimPlot(object, cells.highlight = cell_ids, cols.highlight = c("#FFFF00", "grey50"), facet.highlight = T, combine = T, ncol = 4)
p
```

Example 102 (r):
```r
# set ID to RCTD label
Idents(object) <- "full_first_type"

# Visualize distribution of 4 interneuron subtypes
inhibitory_names <- c("Sst", "Pvalb", "Vip", "Lamp5")
cell_ids <- CellsByIdentities(object, idents = inhibitory_names)
p <- SpatialDimPlot(object, cells.highlight = cell_ids, cols.highlight = c("#FFFF00", "grey50"), facet.highlight = T, combine = T, ncol = 4)
p
```

Example 103 (unknown):
```unknown
# create barplot to show proportions of cell types of interest
layer_table <- table(object$full_first_type, object$layer_id)[inhibitory_names, 1:4]

neuron_props <- reshape2::melt(prop.table(layer_table), margin = 1)
ggplot(neuron_props, aes(x = Var1, y = value, fill = Var2)) +
  geom_bar(stat = "identity", position = "fill") +
  labs(x = "Cell type", y = "Proportion", fill = "Layer") +
  theme_classic()
```

Example 104 (r):
```r
# create barplot to show proportions of cell types of interest
layer_table <- table(object$full_first_type, object$layer_id)[inhibitory_names, 1:4]

neuron_props <- reshape2::melt(prop.table(layer_table), margin = 1)
ggplot(neuron_props, aes(x = Var1, y = value, fill = Var2)) +
  geom_bar(stat = "identity", position = "fill") +
  labs(x = "Cell type", y = "Proportion", fill = "Layer") +
  theme_classic()
```

Example 105 (r):
```r
# create barplot to show proportions of cell types of interest
layer_table <- table(object$full_first_type, object$layer_id)[inhibitory_names, 1:4]

neuron_props <- reshape2::melt(prop.table(layer_table), margin = 1)
ggplot(neuron_props, aes(x = Var1, y = value, fill = Var2)) +
  geom_bar(stat = "identity", position = "fill") +
  labs(x = "Cell type", y = "Proportion", fill = "Layer") +
  theme_classic()
```

Example 106 (unknown):
```unknown
localdir <- "/brahms/lis/visium_hd/Visium_HD_Public_Data/HD_public_data/Visium_HD_Mouse_Small_Intestine/outs"
object <- Load10X_Spatial(data.dir = localdir, bin.size = 8)
```

Example 107 (r):
```r
localdir <- "/brahms/lis/visium_hd/Visium_HD_Public_Data/HD_public_data/Visium_HD_Mouse_Small_Intestine/outs"
object <- Load10X_Spatial(data.dir = localdir, bin.size = 8)
```

Example 108 (r):
```r
localdir <- "/brahms/lis/visium_hd/Visium_HD_Public_Data/HD_public_data/Visium_HD_Mouse_Small_Intestine/outs"
object <- Load10X_Spatial(data.dir = localdir, bin.size = 8)
```

Example 109 (unknown):
```unknown
DefaultAssay(object) <- "Spatial.008um"
object <- NormalizeData(object)
object <- FindVariableFeatures(object)
object <- ScaleData(object)
```

Example 110 (r):
```r
DefaultAssay(object) <- "Spatial.008um"
object <- NormalizeData(object)
object <- FindVariableFeatures(object)
object <- ScaleData(object)
```

Example 111 (r):
```r
DefaultAssay(object) <- "Spatial.008um"
object <- NormalizeData(object)
object <- FindVariableFeatures(object)
object <- ScaleData(object)
```

Example 112 (unknown):
```unknown
object <- SketchData(
  object = object,
  ncells = 50000,
  method = "LeverageScore",
  sketched.assay = "sketch"
)
```

Example 113 (r):
```r
object <- SketchData(
  object = object,
  ncells = 50000,
  method = "LeverageScore",
  sketched.assay = "sketch"
)
```

Example 114 (r):
```r
object <- SketchData(
  object = object,
  ncells = 50000,
  method = "LeverageScore",
  sketched.assay = "sketch"
)
```

Example 115 (unknown):
```unknown
DefaultAssay(object) <- "sketch"
object <- FindVariableFeatures(object)
object <- ScaleData(object)
object <- RunPCA(object, assay = "sketch", reduction.name = "pca.sketch")
object <- FindNeighbors(object, assay = "sketch", reduction = "pca.sketch", dims = 1:50)
object <- FindClusters(object, cluster.name = "seurat_cluster.sketched", resolution = 3)
object <- RunUMAP(object, reduction = "pca.sketch", reduction.name = "umap.sketch", return.model = T, dims = 1:50)
```

Example 116 (r):
```r
DefaultAssay(object) <- "sketch"
object <- FindVariableFeatures(object)
object <- ScaleData(object)
object <- RunPCA(object, assay = "sketch", reduction.name = "pca.sketch")
object <- FindNeighbors(object, assay = "sketch", reduction = "pca.sketch", dims = 1:50)
object <- FindClusters(object, cluster.name = "seurat_cluster.sketched", resolution = 3)
object <- RunUMAP(object, reduction = "pca.sketch", reduction.name = "umap.sketch", return.model = T, dims = 1:50)
```

Example 117 (r):
```r
DefaultAssay(object) <- "sketch"
object <- FindVariableFeatures(object)
object <- ScaleData(object)
object <- RunPCA(object, assay = "sketch", reduction.name = "pca.sketch")
object <- FindNeighbors(object, assay = "sketch", reduction = "pca.sketch", dims = 1:50)
object <- FindClusters(object, cluster.name = "seurat_cluster.sketched", resolution = 3)
object <- RunUMAP(object, reduction = "pca.sketch", reduction.name = "umap.sketch", return.model = T, dims = 1:50)
```

Example 118 (unknown):
```unknown
object <- ProjectData(
  object = object,
  assay = "Spatial.008um",
  full.reduction = "full.pca.sketch",
  sketched.assay = "sketch",
  sketched.reduction = "pca.sketch",
  umap.model = "umap.sketch",
  dims = 1:50,
  refdata = list(seurat_cluster.projected = "seurat_cluster.sketched")
)
```

Example 119 (r):
```r
object <- ProjectData(
  object = object,
  assay = "Spatial.008um",
  full.reduction = "full.pca.sketch",
  sketched.assay = "sketch",
  sketched.reduction = "pca.sketch",
  umap.model = "umap.sketch",
  dims = 1:50,
  refdata = list(seurat_cluster.projected = "seurat_cluster.sketched")
)
```

Example 120 (r):
```r
object <- ProjectData(
  object = object,
  assay = "Spatial.008um",
  full.reduction = "full.pca.sketch",
  sketched.assay = "sketch",
  sketched.reduction = "pca.sketch",
  umap.model = "umap.sketch",
  dims = 1:50,
  refdata = list(seurat_cluster.projected = "seurat_cluster.sketched")
)
```

Example 121 (unknown):
```unknown
Idents(object) <- "seurat_cluster.projected"
DefaultAssay(object) <- "Spatial.008um"

p1 <- DimPlot(object, reduction = "umap.sketch", label = F) + theme(legend.position = "bottom")
p2 <- SpatialDimPlot(object, label = F) + theme(legend.position = "bottom")
p1 | p2
```

Example 122 (r):
```r
Idents(object) <- "seurat_cluster.projected"
DefaultAssay(object) <- "Spatial.008um"

p1 <- DimPlot(object, reduction = "umap.sketch", label = F) + theme(legend.position = "bottom")
p2 <- SpatialDimPlot(object, label = F) + theme(legend.position = "bottom")
p1 | p2
```

Example 123 (r):
```r
Idents(object) <- "seurat_cluster.projected"
DefaultAssay(object) <- "Spatial.008um"

p1 <- DimPlot(object, reduction = "umap.sketch", label = F) + theme(legend.position = "bottom")
p2 <- SpatialDimPlot(object, label = F) + theme(legend.position = "bottom")
p1 | p2
```

Example 124 (unknown):
```unknown
Idents(object) <- "seurat_cluster.projected"
cells <- CellsByIdentities(object, idents = c(1, 5, 18, 26))
p <- SpatialDimPlot(object, cells.highlight = cells[setdiff(names(cells), "NA")], cols.highlight = c("#FFFF00", "grey50"), facet.highlight = T, combine = T) + NoLegend()
p
```

Example 125 (r):
```r
Idents(object) <- "seurat_cluster.projected"
cells <- CellsByIdentities(object, idents = c(1, 5, 18, 26))
p <- SpatialDimPlot(object, cells.highlight = cells[setdiff(names(cells), "NA")], cols.highlight = c("#FFFF00", "grey50"), facet.highlight = T, combine = T) + NoLegend()
p
```

Example 126 (r):
```r
Idents(object) <- "seurat_cluster.projected"
cells <- CellsByIdentities(object, idents = c(1, 5, 18, 26))
p <- SpatialDimPlot(object, cells.highlight = cells[setdiff(names(cells), "NA")], cols.highlight = c("#FFFF00", "grey50"), facet.highlight = T, combine = T) + NoLegend()
p
```

Example 127 (unknown):
```unknown
DefaultAssay(object) <- "Spatial.008um"
Idents(object) <- "seurat_cluster.projected"
object_subset <- subset(object, cells = Cells(object[["Spatial.008um"]]), downsample = 1000)

DefaultAssay(object_subset) <- "Spatial.008um"
Idents(object_subset) <- "seurat_cluster.projected"
object_subset <- BuildClusterTree(object_subset, assay = "Spatial.008um", reduction = "full.pca.sketch", reorder = T)

markers <- FindAllMarkers(object_subset, assay = "Spatial.008um", only.pos = TRUE)
markers %>%
  group_by(cluster) %>%
  dplyr::filter(avg_log2FC > 1) %>%
  slice_head(n = 5) %>%
  ungroup() -> top5

object_subset <- ScaleData(object_subset, assay = "Spatial.008um", features = top5$gene)
p <- DoHeatmap(object_subset, assay = "Spatial.008um", features = top5$gene, size = 2.5) + theme(axis.text = element_text(size = 5.5)) + NoLegend()
p
```

Example 128 (r):
```r
DefaultAssay(object) <- "Spatial.008um"
Idents(object) <- "seurat_cluster.projected"
object_subset <- subset(object, cells = Cells(object[["Spatial.008um"]]), downsample = 1000)

DefaultAssay(object_subset) <- "Spatial.008um"
Idents(object_subset) <- "seurat_cluster.projected"
object_subset <- BuildClusterTree(object_subset, assay = "Spatial.008um", reduction = "full.pca.sketch", reorder = T)

markers <- FindAllMarkers(object_subset, assay = "Spatial.008um", only.pos = TRUE)
markers %>%
  group_by(cluster) %>%
  dplyr::filter(avg_log2FC > 1) %>%
  slice_head(n = 5) %>%
  ungroup() -> top5

object_subset <- ScaleData(object_subset, assay = "Spatial.008um", features = top5$gene)
p <- DoHeatmap(object_subset, assay = "Spatial.008um", features = top5$gene, size = 2.5) + theme(axis.text = element_text(size = 5.5)) + NoLegend()
p
```

Example 129 (r):
```r
DefaultAssay(object) <- "Spatial.008um"
Idents(object) <- "seurat_cluster.projected"
object_subset <- subset(object, cells = Cells(object[["Spatial.008um"]]), downsample = 1000)

DefaultAssay(object_subset) <- "Spatial.008um"
Idents(object_subset) <- "seurat_cluster.projected"
object_subset <- BuildClusterTree(object_subset, assay = "Spatial.008um", reduction = "full.pca.sketch", reorder = T)

markers <- FindAllMarkers(object_subset, assay = "Spatial.008um", only.pos = TRUE)
markers %>%
  group_by(cluster) %>%
  dplyr::filter(avg_log2FC > 1) %>%
  slice_head(n = 5) %>%
  ungroup() -> top5

object_subset <- ScaleData(object_subset, assay = "Spatial.008um", features = top5$gene)
p <- DoHeatmap(object_subset, assay = "Spatial.008um", features = top5$gene, size = 2.5) + theme(axis.text = element_text(size = 5.5)) + NoLegend()
p
```

Example 130 (unknown):
```unknown
sessionInfo()
```

Example 131 (r):
```r
sessionInfo()
```

Example 132 (r):
```r
sessionInfo()
```

Example 133 (unknown):
```unknown
## R version 4.3.2 (2023-10-31)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.6 LTS
## 
## Matrix products: default
## BLAS:   /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.9.0 
## LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.9.0
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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: America/New_York
## tzcode source: system (glibc)
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
## [1] dplyr_1.1.4             patchwork_1.2.0         ggplot2_3.5.0          
## [4] Seurat_5.1.0      testthat_3.2.1          SeuratObject_5.0.1.9011
## [7] sp_2.1-4               
## 
## loaded via a namespace (and not attached):
##   [1] RColorBrewer_1.1-3     rstudioapi_0.15.0      jsonlite_1.8.8        
##   [4] magrittr_2.0.3         ggbeeswarm_0.7.2       spatstat.utils_3.0-4  
##   [7] farver_2.1.1           rmarkdown_2.26         fs_1.6.3              
##  [10] ragg_1.2.7             vctrs_0.6.5            ROCR_1.0-11           
##  [13] memoise_2.0.1          spatstat.explore_3.2-6 htmltools_0.5.7       
##  [16] usethis_2.2.3          sass_0.4.8             sctransform_0.4.1     
##  [19] parallelly_1.37.1      KernSmooth_2.23-22     bslib_0.6.1           
##  [22] htmlwidgets_1.6.4      desc_1.4.3             ica_1.0-3             
##  [25] plyr_1.8.9             plotly_4.10.4          zoo_1.8-12            
##  [28] cachem_1.0.8           igraph_2.0.2           mime_0.12             
##  [31] lifecycle_1.0.4        pkgconfig_2.0.3        Matrix_1.6-5          
##  [34] R6_2.5.1               fastmap_1.1.1          fitdistrplus_1.1-11   
##  [37] future_1.33.1          shiny_1.8.0            digest_0.6.34         
##  [40] colorspace_2.1-0       tensor_1.5             rprojroot_2.0.4       
##  [43] RSpectra_0.16-1        irlba_2.3.5.1          pkgload_1.3.4         
##  [46] textshaping_0.3.7      labeling_0.4.3         progressr_0.14.0      
##  [49] fansi_1.0.6            spatstat.sparse_3.0-3  polyclip_1.10-6       
##  [52] abind_1.4-5            httr_1.4.7             compiler_4.3.2        
##  [55] remotes_2.4.2.1        withr_3.0.0            fastDummies_1.7.3     
##  [58] highr_0.10             pkgbuild_1.4.3         R.utils_2.12.3        
##  [61] MASS_7.3-60.0.1        sessioninfo_1.2.2      tools_4.3.2           
##  [64] vipor_0.4.7            lmtest_0.9-40          ape_5.7-1             
##  [67] beeswarm_0.4.0         httpuv_1.6.14          future.apply_1.11.1   
##  [70] goftest_1.2-3          R.oo_1.26.0            glue_1.7.0            
##  [73] nlme_3.1-164           R.cache_0.16.0         promises_1.2.1        
##  [76] grid_4.3.2             Rtsne_0.17             cluster_2.1.6         
##  [79] reshape2_1.4.4         generics_0.1.3         gtable_0.3.4          
##  [82] spatstat.data_3.0-4    R.methodsS3_1.8.2      tidyr_1.3.1           
##  [85] data.table_1.15.2      utf8_1.2.4             spatstat.geom_3.2-9   
##  [88] RcppAnnoy_0.0.22       ggrepel_0.9.5          RANN_2.6.1            
##  [91] pillar_1.9.0           stringr_1.5.1          limma_3.58.1          
##  [94] spam_2.10-0            RcppHNSW_0.6.0         later_1.3.2           
##  [97] splines_4.3.2          lattice_0.22-5         deldir_2.0-4          
## [100] survival_3.5-8         tidyselect_1.2.0       miniUI_0.1.1.1        
## [103] pbapply_1.7-2          knitr_1.45             gridExtra_2.3         
## [106] scattermore_1.2        xfun_0.42              statmod_1.5.0         
## [109] brio_1.1.4             devtools_2.4.5         matrixStats_1.2.0     
## [112] stringi_1.8.3          lazyeval_0.2.2         yaml_2.3.8            
## [115] evaluate_0.23          codetools_0.2-20       tibble_3.2.1          
## [118] cli_3.6.2              uwot_0.1.16            xtable_1.8-4          
## [121] reticulate_1.35.0      systemfonts_1.0.5      munsell_0.5.0         
## [124] jquerylib_0.1.4        styler_1.10.2          Rcpp_1.0.12           
## [127] spatstat.random_3.2-3  globals_0.16.2         png_0.1-8             
## [130] ggrastr_1.0.2          parallel_4.3.2         ellipsis_0.3.2        
## [133] pkgdown_2.0.7          presto_1.0.0           dotCall64_1.1-1       
## [136] profvis_0.3.8          urlchecker_1.0.1       listenv_0.9.1         
## [139] viridisLite_0.4.2      scales_1.3.0           ggridges_0.5.6        
## [142] leiden_0.4.3.1         purrr_1.0.2            rlang_1.1.3           
## [145] cowplot_1.1.3
```

Example 134 (unknown):
```unknown
## R version 4.3.2 (2023-10-31)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.6 LTS
## 
## Matrix products: default
## BLAS:   /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.9.0 
## LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.9.0
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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: America/New_York
## tzcode source: system (glibc)
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
## [1] dplyr_1.1.4             patchwork_1.2.0         ggplot2_3.5.0          
## [4] Seurat_5.1.0      testthat_3.2.1          SeuratObject_5.0.1.9011
## [7] sp_2.1-4               
## 
## loaded via a namespace (and not attached):
##   [1] RColorBrewer_1.1-3     rstudioapi_0.15.0      jsonlite_1.8.8        
##   [4] magrittr_2.0.3         ggbeeswarm_0.7.2       spatstat.utils_3.0-4  
##   [7] farver_2.1.1           rmarkdown_2.26         fs_1.6.3              
##  [10] ragg_1.2.7             vctrs_0.6.5            ROCR_1.0-11           
##  [13] memoise_2.0.1          spatstat.explore_3.2-6 htmltools_0.5.7       
##  [16] usethis_2.2.3          sass_0.4.8             sctransform_0.4.1     
##  [19] parallelly_1.37.1      KernSmooth_2.23-22     bslib_0.6.1           
##  [22] htmlwidgets_1.6.4      desc_1.4.3             ica_1.0-3             
##  [25] plyr_1.8.9             plotly_4.10.4          zoo_1.8-12            
##  [28] cachem_1.0.8           igraph_2.0.2           mime_0.12             
##  [31] lifecycle_1.0.4        pkgconfig_2.0.3        Matrix_1.6-5          
##  [34] R6_2.5.1               fastmap_1.1.1          fitdistrplus_1.1-11   
##  [37] future_1.33.1          shiny_1.8.0            digest_0.6.34         
##  [40] colorspace_2.1-0       tensor_1.5             rprojroot_2.0.4       
##  [43] RSpectra_0.16-1        irlba_2.3.5.1          pkgload_1.3.4         
##  [46] textshaping_0.3.7      labeling_0.4.3         progressr_0.14.0      
##  [49] fansi_1.0.6            spatstat.sparse_3.0-3  polyclip_1.10-6       
##  [52] abind_1.4-5            httr_1.4.7             compiler_4.3.2        
##  [55] remotes_2.4.2.1        withr_3.0.0            fastDummies_1.7.3     
##  [58] highr_0.10             pkgbuild_1.4.3         R.utils_2.12.3        
##  [61] MASS_7.3-60.0.1        sessioninfo_1.2.2      tools_4.3.2           
##  [64] vipor_0.4.7            lmtest_0.9-40          ape_5.7-1             
##  [67] beeswarm_0.4.0         httpuv_1.6.14          future.apply_1.11.1   
##  [70] goftest_1.2-3          R.oo_1.26.0            glue_1.7.0            
##  [73] nlme_3.1-164           R.cache_0.16.0         promises_1.2.1        
##  [76] grid_4.3.2             Rtsne_0.17             cluster_2.1.6         
##  [79] reshape2_1.4.4         generics_0.1.3         gtable_0.3.4          
##  [82] spatstat.data_3.0-4    R.methodsS3_1.8.2      tidyr_1.3.1           
##  [85] data.table_1.15.2      utf8_1.2.4             spatstat.geom_3.2-9   
##  [88] RcppAnnoy_0.0.22       ggrepel_0.9.5          RANN_2.6.1            
##  [91] pillar_1.9.0           stringr_1.5.1          limma_3.58.1          
##  [94] spam_2.10-0            RcppHNSW_0.6.0         later_1.3.2           
##  [97] splines_4.3.2          lattice_0.22-5         deldir_2.0-4          
## [100] survival_3.5-8         tidyselect_1.2.0       miniUI_0.1.1.1        
## [103] pbapply_1.7-2          knitr_1.45             gridExtra_2.3         
## [106] scattermore_1.2        xfun_0.42              statmod_1.5.0         
## [109] brio_1.1.4             devtools_2.4.5         matrixStats_1.2.0     
## [112] stringi_1.8.3          lazyeval_0.2.2         yaml_2.3.8            
## [115] evaluate_0.23          codetools_0.2-20       tibble_3.2.1          
## [118] cli_3.6.2              uwot_0.1.16            xtable_1.8-4          
## [121] reticulate_1.35.0      systemfonts_1.0.5      munsell_0.5.0         
## [124] jquerylib_0.1.4        styler_1.10.2          Rcpp_1.0.12           
## [127] spatstat.random_3.2-3  globals_0.16.2         png_0.1-8             
## [130] ggrastr_1.0.2          parallel_4.3.2         ellipsis_0.3.2        
## [133] pkgdown_2.0.7          presto_1.0.0           dotCall64_1.1-1       
## [136] profvis_0.3.8          urlchecker_1.0.1       listenv_0.9.1         
## [139] viridisLite_0.4.2      scales_1.3.0           ggridges_0.5.6        
## [142] leiden_0.4.3.1         purrr_1.0.2            rlang_1.1.3           
## [145] cowplot_1.1.3
```

---

## Introduction to scRNA-seq integration • Seurat

**URL:** http://127.0.0.1:9173/seurat/archive/v4.3/integration_introduction/index.html

**Contents:**
- Introduction to scRNA-seq integration
    - Compiled: March 27, 2023
- Introduction to scRNA-seq integration
  - Integration goals
  - Setup the Seurat objects
  - Perform integration
  - Perform an integrated analysis
  - Identify conserved cell type markers
    - Identify differential expressed genes across conditions
- Performing integration on datasets normalized with SCTransform
- Contents

The joint analysis of two or more single-cell datasets poses unique challenges. In particular, identifying cell populations that are present across multiple datasets can be problematic under standard workflows. Seurat v4 includes a set of methods to match (or ‘align’) shared cell populations across datasets. These methods first identify cross-dataset pairs of cells that are in a matched biological state (‘anchors’), can be used both to correct for technical differences between datasets (i.e. batch effect correction), and to perform comparative scRNA-seq analysis of across experimental conditions.Below, we demonstrate methods for scRNA-seq integration as described in Stuart*, Butler* et al, 2019 to perform a comparative analysis of human immune cells (PBMC) in either a resting or interferon-stimulated state.Integration goalsThe following tutorial is designed to give you an overview of the kinds of comparative analyses on complex cell types that are possible using the Seurat integration procedure. Here, we address a few key goals:Create an ‘integrated’ data assay for downstream analysisIdentify cell types that are present in both datasetsObtain cell type markers that are conserved in both control and stimulated cellsCompare the datasets to find cell-type specific responses to stimulationSetup the Seurat objectsFor convenience, we distribute this dataset through our SeuratData package. library(Seurat) library(SeuratData) library(patchwork) # install dataset InstallData("ifnb") # load dataset LoadData("ifnb") # split the dataset into a list of two seurat objects (stim and CTRL) ifnb.list <- SplitObject(ifnb, split.by = "stim") # normalize and identify variable features for each dataset independently ifnb.list <- lapply(X = ifnb.list, FUN = function(x) { x <- NormalizeData(x) x <- FindVariableFeatures(x, selection.method = "vst", nfeatures = 2000) }) # select features that are repeatedly variable across datasets for integration features <- SelectIntegrationFeatures(object.list = ifnb.list)Perform integrationWe then identify anchors using the FindIntegrationAnchors() function, which takes a list of Seurat objects as input, and use these anchors to integrate the two datasets together with IntegrateData(). immune.anchors <- FindIntegrationAnchors(object.list = ifnb.list, anchor.features = features) # this command creates an 'integrated' data assay immune.combined <- IntegrateData(anchorset = immune.anchors)Perform an integrated analysisNow we can run a single integrated analysis on all cells! # specify that we will perform downstream analysis on the corrected data note that the # original unmodified data still resides in the 'RNA' assay DefaultAssay(immune.combined) <- "integrated" # Run the standard workflow for visualization and clustering immune.combined <- ScaleData(immune.combined, verbose = FALSE) immune.combined <- RunPCA(immune.combined, npcs = 30, verbose = FALSE) immune.combined <- RunUMAP(immune.combined, reduction = "pca", dims = 1:30) immune.combined <- FindNeighbors(immune.combined, reduction = "pca", dims = 1:30) immune.combined <- FindClusters(immune.combined, resolution = 0.5) # Visualization p1 <- DimPlot(immune.combined, reduction = "umap", group.by = "stim") p2 <- DimPlot(immune.combined, reduction = "umap", label = TRUE, repel = TRUE) p1 + p2To visualize the two conditions side-by-side, we can use the split.by argument to show each condition colored by cluster. DimPlot(immune.combined, reduction = "umap", split.by = "stim")Identify conserved cell type markersTo identify canonical cell type marker genes that are conserved across conditions, we provide the FindConservedMarkers() function. This function performs differential gene expression testing for each dataset/group and combines the p-values using meta-analysis methods from the MetaDE R package. For example, we can calculated the genes that are conserved markers irrespective of stimulation condition in cluster 6 (NK cells). # For performing differential expression after integration, we switch back to the original # data DefaultAssay(immune.combined) <- "RNA" nk.markers <- FindConservedMarkers(immune.combined, ident.1 = 6, grouping.var = "stim", verbose = FALSE) head(nk.markers)## CTRL_p_val CTRL_avg_log2FC CTRL_pct.1 CTRL_pct.2 CTRL_p_val_adj ## GNLY 0 6.006173 0.944 0.045 0 ## FGFBP2 0 3.243588 0.505 0.020 0 ## CLIC3 0 3.461957 0.597 0.024 0 ## PRF1 0 2.650548 0.422 0.017 0 ## CTSW 0 2.987507 0.531 0.029 0 ## KLRD1 0 2.777231 0.495 0.019 0 ## STIM_p_val STIM_avg_log2FC STIM_pct.1 STIM_pct.2 STIM_p_val_adj ## GNLY 0.000000e+00 5.858634 0.954 0.059 0.000000e+00 ## FGFBP2 3.408448e-165 2.191113 0.261 0.015 4.789892e-161 ## CLIC3 0.000000e+00 3.536367 0.623 0.030 0.000000e+00 ## PRF1 0.000000e+00 4.094579 0.862 0.057 0.000000e+00 ## CTSW 0.000000e+00 3.128054 0.592 0.035 0.000000e+00 ## KLRD1 0.000000e+00 2.863797 0.552 0.027 0.000000e+00 ## max_pval minimump_p_val ## GNLY 0.000000e+00 0 ## FGFBP2 3.408448e-165 0 ## CLIC3 0.000000e+00 0 ## PRF1 0.000000e+00 0 ## CTSW 0.000000e+00 0 ## KLRD1 0.000000e+00 0We can explore these marker genes for each cluster and use them to annotate our clusters as specific cell types. FeaturePlot(immune.combined, features = c("CD3D", "SELL", "CREM", "CD8A", "GNLY", "CD79A", "FCGR3A", "CCL2", "PPBP"), min.cutoff = "q9") immune.combined <- RenameIdents(immune.combined, `0` = "CD14 Mono", `1` = "CD4 Naive T", `2` = "CD4 Memory T", `3` = "CD16 Mono", `4` = "B", `5` = "CD8 T", `6` = "NK", `7` = "T activated", `8` = "DC", `9` = "B Activated", `10` = "Mk", `11` = "pDC", `12` = "Eryth", `13` = "Mono/Mk Doublets", `14` = "HSPC") DimPlot(immune.combined, label = TRUE)The DotPlot() function with the split.by parameter can be useful for viewing conserved cell type markers across conditions, showing both the expression level and the percentage of cells in a cluster expressing any given gene. Here we plot 2-3 strong marker genes for each of our 14 clusters. Idents(immune.combined) <- factor(Idents(immune.combined), levels = c("HSPC", "Mono/Mk Doublets", "pDC", "Eryth", "Mk", "DC", "CD14 Mono", "CD16 Mono", "B Activated", "B", "CD8 T", "NK", "T activated", "CD4 Naive T", "CD4 Memory T")) markers.to.plot <- c("CD3D", "CREM", "HSPH1", "SELL", "GIMAP5", "CACYBP", "GNLY", "NKG7", "CCL5", "CD8A", "MS4A1", "CD79A", "MIR155HG", "NME1", "FCGR3A", "VMO1", "CCL2", "S100A9", "HLA-DQA1", "GPR183", "PPBP", "GNG11", "HBA2", "HBB", "TSPAN13", "IL3RA", "IGJ", "PRSS57") DotPlot(immune.combined, features = markers.to.plot, cols = c("blue", "red"), dot.scale = 8, split.by = "stim") + RotatedAxis()Identify differential expressed genes across conditionsNow that we’ve aligned the stimulated and control cells, we can start to do comparative analyses and look at the differences induced by stimulation. One way to look broadly at these changes is to plot the average expression of both the stimulated and control cells and look for genes that are visual outliers on a scatter plot. Here, we take the average expression of both the stimulated and control naive T cells and CD14 monocyte populations and generate the scatter plots, highlighting genes that exhibit dramatic responses to interferon stimulation. library(ggplot2) library(cowplot) theme_set(theme_cowplot()) t.cells <- subset(immune.combined, idents = "CD4 Naive T") Idents(t.cells) <- "stim" avg.t.cells <- as.data.frame(log1p(AverageExpression(t.cells, verbose = FALSE)$RNA)) avg.t.cells$gene <- rownames(avg.t.cells) cd14.mono <- subset(immune.combined, idents = "CD14 Mono") Idents(cd14.mono) <- "stim" avg.cd14.mono <- as.data.frame(log1p(AverageExpression(cd14.mono, verbose = FALSE)$RNA)) avg.cd14.mono$gene <- rownames(avg.cd14.mono) genes.to.label = c("ISG15", "LY6E", "IFI6", "ISG20", "MX1", "IFIT2", "IFIT1", "CXCL10", "CCL8") p1 <- ggplot(avg.t.cells, aes(CTRL, STIM)) + geom_point() + ggtitle("CD4 Naive T Cells") p1 <- LabelPoints(plot = p1, points = genes.to.label, repel = TRUE) p2 <- ggplot(avg.cd14.mono, aes(CTRL, STIM)) + geom_point() + ggtitle("CD14 Monocytes") p2 <- LabelPoints(plot = p2, points = genes.to.label, repel = TRUE) p1 + p2As you can see, many of the same genes are upregulated in both of these cell types and likely represent a conserved interferon response pathway.Because we are confident in having identified common cell types across condition, we can ask what genes change in different conditions for cells of the same type. First, we create a column in the meta.data slot to hold both the cell type and stimulation information and switch the current ident to that column. Then we use FindMarkers() to find the genes that are different between stimulated and control B cells. Notice that many of the top genes that show up here are the same as the ones we plotted earlier as core interferon response genes. Additionally, genes like CXCL10 which we saw were specific to monocyte and B cell interferon response show up as highly significant in this list as well. immune.combined$celltype.stim <- paste(Idents(immune.combined), immune.combined$stim, sep = "_") immune.combined$celltype <- Idents(immune.combined) Idents(immune.combined) <- "celltype.stim" b.interferon.response <- FindMarkers(immune.combined, ident.1 = "B_STIM", ident.2 = "B_CTRL", verbose = FALSE) head(b.interferon.response, n = 15)## p_val avg_log2FC pct.1 pct.2 p_val_adj ## ISG15 1.212995e-155 4.5997247 0.998 0.239 1.704622e-151 ## IFIT3 4.743486e-151 4.5017769 0.964 0.052 6.666020e-147 ## IFI6 1.680324e-150 4.2361116 0.969 0.080 2.361359e-146 ## ISG20 1.595574e-146 2.9452675 1.000 0.671 2.242260e-142 ## IFIT1 3.499460e-137 4.1278656 0.910 0.032 4.917791e-133 ## MX1 8.571983e-121 3.2876616 0.904 0.115 1.204621e-116 ## LY6E 1.359842e-117 3.1251242 0.895 0.152 1.910986e-113 ## TNFSF10 4.454596e-110 3.7816677 0.790 0.025 6.260044e-106 ## IFIT2 1.290640e-106 3.6584511 0.787 0.035 1.813736e-102 ## B2M 2.019314e-95 0.6073495 1.000 1.000 2.837741e-91 ## PLSCR1 1.464429e-93 2.8195675 0.794 0.117 2.057961e-89 ## IRF7 3.893097e-92 2.5867694 0.837 0.190 5.470969e-88 ## CXCL10 1.624151e-82 5.2608266 0.640 0.010 2.282419e-78 ## UBE2L6 2.482113e-81 2.1450306 0.852 0.299 3.488114e-77 ## PSMB9 5.977328e-77 1.6457686 0.940 0.571 8.399938e-73Another useful way to visualize these changes in gene expression is with the split.by option to the FeaturePlot() or VlnPlot() function. This will display FeaturePlots of the list of given genes, split by a grouping variable (stimulation condition here). Genes such as CD3D and GNLY are canonical cell type markers (for T cells and NK/CD8 T cells) that are virtually unaffected by interferon stimulation and display similar gene expression patterns in the control and stimulated group. IFI6 and ISG15, on the other hand, are core interferon response genes and are upregulated accordingly in all cell types. Finally, CD14 and CXCL10 are genes that show a cell type specific interferon response. CD14 expression decreases after stimulation in CD14 monocytes, which could lead to misclassification in a supervised analysis framework, underscoring the value of integrated analysis. CXCL10 shows a distinct upregulation in monocytes and B cells after interferon stimulation but not in other cell types. FeaturePlot(immune.combined, features = c("CD3D", "GNLY", "IFI6"), split.by = "stim", max.cutoff = 3, cols = c("grey", "red")) plots <- VlnPlot(immune.combined, features = c("LYZ", "ISG15", "CXCL10"), split.by = "stim", group.by = "celltype", pt.size = 0, combine = FALSE) wrap_plots(plots = plots, ncol = 1)

Below, we demonstrate methods for scRNA-seq integration as described in Stuart*, Butler* et al, 2019 to perform a comparative analysis of human immune cells (PBMC) in either a resting or interferon-stimulated state.Integration goalsThe following tutorial is designed to give you an overview of the kinds of comparative analyses on complex cell types that are possible using the Seurat integration procedure. Here, we address a few key goals:Create an ‘integrated’ data assay for downstream analysisIdentify cell types that are present in both datasetsObtain cell type markers that are conserved in both control and stimulated cellsCompare the datasets to find cell-type specific responses to stimulationSetup the Seurat objectsFor convenience, we distribute this dataset through our SeuratData package. library(Seurat) library(SeuratData) library(patchwork) # install dataset InstallData("ifnb") # load dataset LoadData("ifnb") # split the dataset into a list of two seurat objects (stim and CTRL) ifnb.list <- SplitObject(ifnb, split.by = "stim") # normalize and identify variable features for each dataset independently ifnb.list <- lapply(X = ifnb.list, FUN = function(x) { x <- NormalizeData(x) x <- FindVariableFeatures(x, selection.method = "vst", nfeatures = 2000) }) # select features that are repeatedly variable across datasets for integration features <- SelectIntegrationFeatures(object.list = ifnb.list)Perform integrationWe then identify anchors using the FindIntegrationAnchors() function, which takes a list of Seurat objects as input, and use these anchors to integrate the two datasets together with IntegrateData(). immune.anchors <- FindIntegrationAnchors(object.list = ifnb.list, anchor.features = features) # this command creates an 'integrated' data assay immune.combined <- IntegrateData(anchorset = immune.anchors)Perform an integrated analysisNow we can run a single integrated analysis on all cells! # specify that we will perform downstream analysis on the corrected data note that the # original unmodified data still resides in the 'RNA' assay DefaultAssay(immune.combined) <- "integrated" # Run the standard workflow for visualization and clustering immune.combined <- ScaleData(immune.combined, verbose = FALSE) immune.combined <- RunPCA(immune.combined, npcs = 30, verbose = FALSE) immune.combined <- RunUMAP(immune.combined, reduction = "pca", dims = 1:30) immune.combined <- FindNeighbors(immune.combined, reduction = "pca", dims = 1:30) immune.combined <- FindClusters(immune.combined, resolution = 0.5) # Visualization p1 <- DimPlot(immune.combined, reduction = "umap", group.by = "stim") p2 <- DimPlot(immune.combined, reduction = "umap", label = TRUE, repel = TRUE) p1 + p2To visualize the two conditions side-by-side, we can use the split.by argument to show each condition colored by cluster. DimPlot(immune.combined, reduction = "umap", split.by = "stim")Identify conserved cell type markersTo identify canonical cell type marker genes that are conserved across conditions, we provide the FindConservedMarkers() function. This function performs differential gene expression testing for each dataset/group and combines the p-values using meta-analysis methods from the MetaDE R package. For example, we can calculated the genes that are conserved markers irrespective of stimulation condition in cluster 6 (NK cells). # For performing differential expression after integration, we switch back to the original # data DefaultAssay(immune.combined) <- "RNA" nk.markers <- FindConservedMarkers(immune.combined, ident.1 = 6, grouping.var = "stim", verbose = FALSE) head(nk.markers)## CTRL_p_val CTRL_avg_log2FC CTRL_pct.1 CTRL_pct.2 CTRL_p_val_adj ## GNLY 0 6.006173 0.944 0.045 0 ## FGFBP2 0 3.243588 0.505 0.020 0 ## CLIC3 0 3.461957 0.597 0.024 0 ## PRF1 0 2.650548 0.422 0.017 0 ## CTSW 0 2.987507 0.531 0.029 0 ## KLRD1 0 2.777231 0.495 0.019 0 ## STIM_p_val STIM_avg_log2FC STIM_pct.1 STIM_pct.2 STIM_p_val_adj ## GNLY 0.000000e+00 5.858634 0.954 0.059 0.000000e+00 ## FGFBP2 3.408448e-165 2.191113 0.261 0.015 4.789892e-161 ## CLIC3 0.000000e+00 3.536367 0.623 0.030 0.000000e+00 ## PRF1 0.000000e+00 4.094579 0.862 0.057 0.000000e+00 ## CTSW 0.000000e+00 3.128054 0.592 0.035 0.000000e+00 ## KLRD1 0.000000e+00 2.863797 0.552 0.027 0.000000e+00 ## max_pval minimump_p_val ## GNLY 0.000000e+00 0 ## FGFBP2 3.408448e-165 0 ## CLIC3 0.000000e+00 0 ## PRF1 0.000000e+00 0 ## CTSW 0.000000e+00 0 ## KLRD1 0.000000e+00 0We can explore these marker genes for each cluster and use them to annotate our clusters as specific cell types. FeaturePlot(immune.combined, features = c("CD3D", "SELL", "CREM", "CD8A", "GNLY", "CD79A", "FCGR3A", "CCL2", "PPBP"), min.cutoff = "q9") immune.combined <- RenameIdents(immune.combined, `0` = "CD14 Mono", `1` = "CD4 Naive T", `2` = "CD4 Memory T", `3` = "CD16 Mono", `4` = "B", `5` = "CD8 T", `6` = "NK", `7` = "T activated", `8` = "DC", `9` = "B Activated", `10` = "Mk", `11` = "pDC", `12` = "Eryth", `13` = "Mono/Mk Doublets", `14` = "HSPC") DimPlot(immune.combined, label = TRUE)The DotPlot() function with the split.by parameter can be useful for viewing conserved cell type markers across conditions, showing both the expression level and the percentage of cells in a cluster expressing any given gene. Here we plot 2-3 strong marker genes for each of our 14 clusters. Idents(immune.combined) <- factor(Idents(immune.combined), levels = c("HSPC", "Mono/Mk Doublets", "pDC", "Eryth", "Mk", "DC", "CD14 Mono", "CD16 Mono", "B Activated", "B", "CD8 T", "NK", "T activated", "CD4 Naive T", "CD4 Memory T")) markers.to.plot <- c("CD3D", "CREM", "HSPH1", "SELL", "GIMAP5", "CACYBP", "GNLY", "NKG7", "CCL5", "CD8A", "MS4A1", "CD79A", "MIR155HG", "NME1", "FCGR3A", "VMO1", "CCL2", "S100A9", "HLA-DQA1", "GPR183", "PPBP", "GNG11", "HBA2", "HBB", "TSPAN13", "IL3RA", "IGJ", "PRSS57") DotPlot(immune.combined, features = markers.to.plot, cols = c("blue", "red"), dot.scale = 8, split.by = "stim") + RotatedAxis()Identify differential expressed genes across conditionsNow that we’ve aligned the stimulated and control cells, we can start to do comparative analyses and look at the differences induced by stimulation. One way to look broadly at these changes is to plot the average expression of both the stimulated and control cells and look for genes that are visual outliers on a scatter plot. Here, we take the average expression of both the stimulated and control naive T cells and CD14 monocyte populations and generate the scatter plots, highlighting genes that exhibit dramatic responses to interferon stimulation. library(ggplot2) library(cowplot) theme_set(theme_cowplot()) t.cells <- subset(immune.combined, idents = "CD4 Naive T") Idents(t.cells) <- "stim" avg.t.cells <- as.data.frame(log1p(AverageExpression(t.cells, verbose = FALSE)$RNA)) avg.t.cells$gene <- rownames(avg.t.cells) cd14.mono <- subset(immune.combined, idents = "CD14 Mono") Idents(cd14.mono) <- "stim" avg.cd14.mono <- as.data.frame(log1p(AverageExpression(cd14.mono, verbose = FALSE)$RNA)) avg.cd14.mono$gene <- rownames(avg.cd14.mono) genes.to.label = c("ISG15", "LY6E", "IFI6", "ISG20", "MX1", "IFIT2", "IFIT1", "CXCL10", "CCL8") p1 <- ggplot(avg.t.cells, aes(CTRL, STIM)) + geom_point() + ggtitle("CD4 Naive T Cells") p1 <- LabelPoints(plot = p1, points = genes.to.label, repel = TRUE) p2 <- ggplot(avg.cd14.mono, aes(CTRL, STIM)) + geom_point() + ggtitle("CD14 Monocytes") p2 <- LabelPoints(plot = p2, points = genes.to.label, repel = TRUE) p1 + p2As you can see, many of the same genes are upregulated in both of these cell types and likely represent a conserved interferon response pathway.Because we are confident in having identified common cell types across condition, we can ask what genes change in different conditions for cells of the same type. First, we create a column in the meta.data slot to hold both the cell type and stimulation information and switch the current ident to that column. Then we use FindMarkers() to find the genes that are different between stimulated and control B cells. Notice that many of the top genes that show up here are the same as the ones we plotted earlier as core interferon response genes. Additionally, genes like CXCL10 which we saw were specific to monocyte and B cell interferon response show up as highly significant in this list as well. immune.combined$celltype.stim <- paste(Idents(immune.combined), immune.combined$stim, sep = "_") immune.combined$celltype <- Idents(immune.combined) Idents(immune.combined) <- "celltype.stim" b.interferon.response <- FindMarkers(immune.combined, ident.1 = "B_STIM", ident.2 = "B_CTRL", verbose = FALSE) head(b.interferon.response, n = 15)## p_val avg_log2FC pct.1 pct.2 p_val_adj ## ISG15 1.212995e-155 4.5997247 0.998 0.239 1.704622e-151 ## IFIT3 4.743486e-151 4.5017769 0.964 0.052 6.666020e-147 ## IFI6 1.680324e-150 4.2361116 0.969 0.080 2.361359e-146 ## ISG20 1.595574e-146 2.9452675 1.000 0.671 2.242260e-142 ## IFIT1 3.499460e-137 4.1278656 0.910 0.032 4.917791e-133 ## MX1 8.571983e-121 3.2876616 0.904 0.115 1.204621e-116 ## LY6E 1.359842e-117 3.1251242 0.895 0.152 1.910986e-113 ## TNFSF10 4.454596e-110 3.7816677 0.790 0.025 6.260044e-106 ## IFIT2 1.290640e-106 3.6584511 0.787 0.035 1.813736e-102 ## B2M 2.019314e-95 0.6073495 1.000 1.000 2.837741e-91 ## PLSCR1 1.464429e-93 2.8195675 0.794 0.117 2.057961e-89 ## IRF7 3.893097e-92 2.5867694 0.837 0.190 5.470969e-88 ## CXCL10 1.624151e-82 5.2608266 0.640 0.010 2.282419e-78 ## UBE2L6 2.482113e-81 2.1450306 0.852 0.299 3.488114e-77 ## PSMB9 5.977328e-77 1.6457686 0.940 0.571 8.399938e-73Another useful way to visualize these changes in gene expression is with the split.by option to the FeaturePlot() or VlnPlot() function. This will display FeaturePlots of the list of given genes, split by a grouping variable (stimulation condition here). Genes such as CD3D and GNLY are canonical cell type markers (for T cells and NK/CD8 T cells) that are virtually unaffected by interferon stimulation and display similar gene expression patterns in the control and stimulated group. IFI6 and ISG15, on the other hand, are core interferon response genes and are upregulated accordingly in all cell types. Finally, CD14 and CXCL10 are genes that show a cell type specific interferon response. CD14 expression decreases after stimulation in CD14 monocytes, which could lead to misclassification in a supervised analysis framework, underscoring the value of integrated analysis. CXCL10 shows a distinct upregulation in monocytes and B cells after interferon stimulation but not in other cell types. FeaturePlot(immune.combined, features = c("CD3D", "GNLY", "IFI6"), split.by = "stim", max.cutoff = 3, cols = c("grey", "red")) plots <- VlnPlot(immune.combined, features = c("LYZ", "ISG15", "CXCL10"), split.by = "stim", group.by = "celltype", pt.size = 0, combine = FALSE) wrap_plots(plots = plots, ncol = 1)

The following tutorial is designed to give you an overview of the kinds of comparative analyses on complex cell types that are possible using the Seurat integration procedure. Here, we address a few key goals:Create an ‘integrated’ data assay for downstream analysisIdentify cell types that are present in both datasetsObtain cell type markers that are conserved in both control and stimulated cellsCompare the datasets to find cell-type specific responses to stimulation

For convenience, we distribute this dataset through our SeuratData package. library(Seurat) library(SeuratData) library(patchwork) # install dataset InstallData("ifnb") # load dataset LoadData("ifnb") # split the dataset into a list of two seurat objects (stim and CTRL) ifnb.list <- SplitObject(ifnb, split.by = "stim") # normalize and identify variable features for each dataset independently ifnb.list <- lapply(X = ifnb.list, FUN = function(x) { x <- NormalizeData(x) x <- FindVariableFeatures(x, selection.method = "vst", nfeatures = 2000) }) # select features that are repeatedly variable across datasets for integration features <- SelectIntegrationFeatures(object.list = ifnb.list)

We then identify anchors using the FindIntegrationAnchors() function, which takes a list of Seurat objects as input, and use these anchors to integrate the two datasets together with IntegrateData(). immune.anchors <- FindIntegrationAnchors(object.list = ifnb.list, anchor.features = features) # this command creates an 'integrated' data assay immune.combined <- IntegrateData(anchorset = immune.anchors)

Now we can run a single integrated analysis on all cells! # specify that we will perform downstream analysis on the corrected data note that the # original unmodified data still resides in the 'RNA' assay DefaultAssay(immune.combined) <- "integrated" # Run the standard workflow for visualization and clustering immune.combined <- ScaleData(immune.combined, verbose = FALSE) immune.combined <- RunPCA(immune.combined, npcs = 30, verbose = FALSE) immune.combined <- RunUMAP(immune.combined, reduction = "pca", dims = 1:30) immune.combined <- FindNeighbors(immune.combined, reduction = "pca", dims = 1:30) immune.combined <- FindClusters(immune.combined, resolution = 0.5) # Visualization p1 <- DimPlot(immune.combined, reduction = "umap", group.by = "stim") p2 <- DimPlot(immune.combined, reduction = "umap", label = TRUE, repel = TRUE) p1 + p2To visualize the two conditions side-by-side, we can use the split.by argument to show each condition colored by cluster. DimPlot(immune.combined, reduction = "umap", split.by = "stim")

To visualize the two conditions side-by-side, we can use the split.by argument to show each condition colored by cluster. DimPlot(immune.combined, reduction = "umap", split.by = "stim")

To visualize the two conditions side-by-side, we can use the split.by argument to show each condition colored by cluster. DimPlot(immune.combined, reduction = "umap", split.by = "stim")

To identify canonical cell type marker genes that are conserved across conditions, we provide the FindConservedMarkers() function. This function performs differential gene expression testing for each dataset/group and combines the p-values using meta-analysis methods from the MetaDE R package. For example, we can calculated the genes that are conserved markers irrespective of stimulation condition in cluster 6 (NK cells). # For performing differential expression after integration, we switch back to the original # data DefaultAssay(immune.combined) <- "RNA" nk.markers <- FindConservedMarkers(immune.combined, ident.1 = 6, grouping.var = "stim", verbose = FALSE) head(nk.markers)## CTRL_p_val CTRL_avg_log2FC CTRL_pct.1 CTRL_pct.2 CTRL_p_val_adj ## GNLY 0 6.006173 0.944 0.045 0 ## FGFBP2 0 3.243588 0.505 0.020 0 ## CLIC3 0 3.461957 0.597 0.024 0 ## PRF1 0 2.650548 0.422 0.017 0 ## CTSW 0 2.987507 0.531 0.029 0 ## KLRD1 0 2.777231 0.495 0.019 0 ## STIM_p_val STIM_avg_log2FC STIM_pct.1 STIM_pct.2 STIM_p_val_adj ## GNLY 0.000000e+00 5.858634 0.954 0.059 0.000000e+00 ## FGFBP2 3.408448e-165 2.191113 0.261 0.015 4.789892e-161 ## CLIC3 0.000000e+00 3.536367 0.623 0.030 0.000000e+00 ## PRF1 0.000000e+00 4.094579 0.862 0.057 0.000000e+00 ## CTSW 0.000000e+00 3.128054 0.592 0.035 0.000000e+00 ## KLRD1 0.000000e+00 2.863797 0.552 0.027 0.000000e+00 ## max_pval minimump_p_val ## GNLY 0.000000e+00 0 ## FGFBP2 3.408448e-165 0 ## CLIC3 0.000000e+00 0 ## PRF1 0.000000e+00 0 ## CTSW 0.000000e+00 0 ## KLRD1 0.000000e+00 0We can explore these marker genes for each cluster and use them to annotate our clusters as specific cell types. FeaturePlot(immune.combined, features = c("CD3D", "SELL", "CREM", "CD8A", "GNLY", "CD79A", "FCGR3A", "CCL2", "PPBP"), min.cutoff = "q9") immune.combined <- RenameIdents(immune.combined, `0` = "CD14 Mono", `1` = "CD4 Naive T", `2` = "CD4 Memory T", `3` = "CD16 Mono", `4` = "B", `5` = "CD8 T", `6` = "NK", `7` = "T activated", `8` = "DC", `9` = "B Activated", `10` = "Mk", `11` = "pDC", `12` = "Eryth", `13` = "Mono/Mk Doublets", `14` = "HSPC") DimPlot(immune.combined, label = TRUE)The DotPlot() function with the split.by parameter can be useful for viewing conserved cell type markers across conditions, showing both the expression level and the percentage of cells in a cluster expressing any given gene. Here we plot 2-3 strong marker genes for each of our 14 clusters. Idents(immune.combined) <- factor(Idents(immune.combined), levels = c("HSPC", "Mono/Mk Doublets", "pDC", "Eryth", "Mk", "DC", "CD14 Mono", "CD16 Mono", "B Activated", "B", "CD8 T", "NK", "T activated", "CD4 Naive T", "CD4 Memory T")) markers.to.plot <- c("CD3D", "CREM", "HSPH1", "SELL", "GIMAP5", "CACYBP", "GNLY", "NKG7", "CCL5", "CD8A", "MS4A1", "CD79A", "MIR155HG", "NME1", "FCGR3A", "VMO1", "CCL2", "S100A9", "HLA-DQA1", "GPR183", "PPBP", "GNG11", "HBA2", "HBB", "TSPAN13", "IL3RA", "IGJ", "PRSS57") DotPlot(immune.combined, features = markers.to.plot, cols = c("blue", "red"), dot.scale = 8, split.by = "stim") + RotatedAxis()Identify differential expressed genes across conditionsNow that we’ve aligned the stimulated and control cells, we can start to do comparative analyses and look at the differences induced by stimulation. One way to look broadly at these changes is to plot the average expression of both the stimulated and control cells and look for genes that are visual outliers on a scatter plot. Here, we take the average expression of both the stimulated and control naive T cells and CD14 monocyte populations and generate the scatter plots, highlighting genes that exhibit dramatic responses to interferon stimulation. library(ggplot2) library(cowplot) theme_set(theme_cowplot()) t.cells <- subset(immune.combined, idents = "CD4 Naive T") Idents(t.cells) <- "stim" avg.t.cells <- as.data.frame(log1p(AverageExpression(t.cells, verbose = FALSE)$RNA)) avg.t.cells$gene <- rownames(avg.t.cells) cd14.mono <- subset(immune.combined, idents = "CD14 Mono") Idents(cd14.mono) <- "stim" avg.cd14.mono <- as.data.frame(log1p(AverageExpression(cd14.mono, verbose = FALSE)$RNA)) avg.cd14.mono$gene <- rownames(avg.cd14.mono) genes.to.label = c("ISG15", "LY6E", "IFI6", "ISG20", "MX1", "IFIT2", "IFIT1", "CXCL10", "CCL8") p1 <- ggplot(avg.t.cells, aes(CTRL, STIM)) + geom_point() + ggtitle("CD4 Naive T Cells") p1 <- LabelPoints(plot = p1, points = genes.to.label, repel = TRUE) p2 <- ggplot(avg.cd14.mono, aes(CTRL, STIM)) + geom_point() + ggtitle("CD14 Monocytes") p2 <- LabelPoints(plot = p2, points = genes.to.label, repel = TRUE) p1 + p2As you can see, many of the same genes are upregulated in both of these cell types and likely represent a conserved interferon response pathway.Because we are confident in having identified common cell types across condition, we can ask what genes change in different conditions for cells of the same type. First, we create a column in the meta.data slot to hold both the cell type and stimulation information and switch the current ident to that column. Then we use FindMarkers() to find the genes that are different between stimulated and control B cells. Notice that many of the top genes that show up here are the same as the ones we plotted earlier as core interferon response genes. Additionally, genes like CXCL10 which we saw were specific to monocyte and B cell interferon response show up as highly significant in this list as well. immune.combined$celltype.stim <- paste(Idents(immune.combined), immune.combined$stim, sep = "_") immune.combined$celltype <- Idents(immune.combined) Idents(immune.combined) <- "celltype.stim" b.interferon.response <- FindMarkers(immune.combined, ident.1 = "B_STIM", ident.2 = "B_CTRL", verbose = FALSE) head(b.interferon.response, n = 15)## p_val avg_log2FC pct.1 pct.2 p_val_adj ## ISG15 1.212995e-155 4.5997247 0.998 0.239 1.704622e-151 ## IFIT3 4.743486e-151 4.5017769 0.964 0.052 6.666020e-147 ## IFI6 1.680324e-150 4.2361116 0.969 0.080 2.361359e-146 ## ISG20 1.595574e-146 2.9452675 1.000 0.671 2.242260e-142 ## IFIT1 3.499460e-137 4.1278656 0.910 0.032 4.917791e-133 ## MX1 8.571983e-121 3.2876616 0.904 0.115 1.204621e-116 ## LY6E 1.359842e-117 3.1251242 0.895 0.152 1.910986e-113 ## TNFSF10 4.454596e-110 3.7816677 0.790 0.025 6.260044e-106 ## IFIT2 1.290640e-106 3.6584511 0.787 0.035 1.813736e-102 ## B2M 2.019314e-95 0.6073495 1.000 1.000 2.837741e-91 ## PLSCR1 1.464429e-93 2.8195675 0.794 0.117 2.057961e-89 ## IRF7 3.893097e-92 2.5867694 0.837 0.190 5.470969e-88 ## CXCL10 1.624151e-82 5.2608266 0.640 0.010 2.282419e-78 ## UBE2L6 2.482113e-81 2.1450306 0.852 0.299 3.488114e-77 ## PSMB9 5.977328e-77 1.6457686 0.940 0.571 8.399938e-73Another useful way to visualize these changes in gene expression is with the split.by option to the FeaturePlot() or VlnPlot() function. This will display FeaturePlots of the list of given genes, split by a grouping variable (stimulation condition here). Genes such as CD3D and GNLY are canonical cell type markers (for T cells and NK/CD8 T cells) that are virtually unaffected by interferon stimulation and display similar gene expression patterns in the control and stimulated group. IFI6 and ISG15, on the other hand, are core interferon response genes and are upregulated accordingly in all cell types. Finally, CD14 and CXCL10 are genes that show a cell type specific interferon response. CD14 expression decreases after stimulation in CD14 monocytes, which could lead to misclassification in a supervised analysis framework, underscoring the value of integrated analysis. CXCL10 shows a distinct upregulation in monocytes and B cells after interferon stimulation but not in other cell types. FeaturePlot(immune.combined, features = c("CD3D", "GNLY", "IFI6"), split.by = "stim", max.cutoff = 3, cols = c("grey", "red")) plots <- VlnPlot(immune.combined, features = c("LYZ", "ISG15", "CXCL10"), split.by = "stim", group.by = "celltype", pt.size = 0, combine = FALSE) wrap_plots(plots = plots, ncol = 1)

We can explore these marker genes for each cluster and use them to annotate our clusters as specific cell types. FeaturePlot(immune.combined, features = c("CD3D", "SELL", "CREM", "CD8A", "GNLY", "CD79A", "FCGR3A", "CCL2", "PPBP"), min.cutoff = "q9") immune.combined <- RenameIdents(immune.combined, `0` = "CD14 Mono", `1` = "CD4 Naive T", `2` = "CD4 Memory T", `3` = "CD16 Mono", `4` = "B", `5` = "CD8 T", `6` = "NK", `7` = "T activated", `8` = "DC", `9` = "B Activated", `10` = "Mk", `11` = "pDC", `12` = "Eryth", `13` = "Mono/Mk Doublets", `14` = "HSPC") DimPlot(immune.combined, label = TRUE)The DotPlot() function with the split.by parameter can be useful for viewing conserved cell type markers across conditions, showing both the expression level and the percentage of cells in a cluster expressing any given gene. Here we plot 2-3 strong marker genes for each of our 14 clusters. Idents(immune.combined) <- factor(Idents(immune.combined), levels = c("HSPC", "Mono/Mk Doublets", "pDC", "Eryth", "Mk", "DC", "CD14 Mono", "CD16 Mono", "B Activated", "B", "CD8 T", "NK", "T activated", "CD4 Naive T", "CD4 Memory T")) markers.to.plot <- c("CD3D", "CREM", "HSPH1", "SELL", "GIMAP5", "CACYBP", "GNLY", "NKG7", "CCL5", "CD8A", "MS4A1", "CD79A", "MIR155HG", "NME1", "FCGR3A", "VMO1", "CCL2", "S100A9", "HLA-DQA1", "GPR183", "PPBP", "GNG11", "HBA2", "HBB", "TSPAN13", "IL3RA", "IGJ", "PRSS57") DotPlot(immune.combined, features = markers.to.plot, cols = c("blue", "red"), dot.scale = 8, split.by = "stim") + RotatedAxis()Identify differential expressed genes across conditionsNow that we’ve aligned the stimulated and control cells, we can start to do comparative analyses and look at the differences induced by stimulation. One way to look broadly at these changes is to plot the average expression of both the stimulated and control cells and look for genes that are visual outliers on a scatter plot. Here, we take the average expression of both the stimulated and control naive T cells and CD14 monocyte populations and generate the scatter plots, highlighting genes that exhibit dramatic responses to interferon stimulation. library(ggplot2) library(cowplot) theme_set(theme_cowplot()) t.cells <- subset(immune.combined, idents = "CD4 Naive T") Idents(t.cells) <- "stim" avg.t.cells <- as.data.frame(log1p(AverageExpression(t.cells, verbose = FALSE)$RNA)) avg.t.cells$gene <- rownames(avg.t.cells) cd14.mono <- subset(immune.combined, idents = "CD14 Mono") Idents(cd14.mono) <- "stim" avg.cd14.mono <- as.data.frame(log1p(AverageExpression(cd14.mono, verbose = FALSE)$RNA)) avg.cd14.mono$gene <- rownames(avg.cd14.mono) genes.to.label = c("ISG15", "LY6E", "IFI6", "ISG20", "MX1", "IFIT2", "IFIT1", "CXCL10", "CCL8") p1 <- ggplot(avg.t.cells, aes(CTRL, STIM)) + geom_point() + ggtitle("CD4 Naive T Cells") p1 <- LabelPoints(plot = p1, points = genes.to.label, repel = TRUE) p2 <- ggplot(avg.cd14.mono, aes(CTRL, STIM)) + geom_point() + ggtitle("CD14 Monocytes") p2 <- LabelPoints(plot = p2, points = genes.to.label, repel = TRUE) p1 + p2As you can see, many of the same genes are upregulated in both of these cell types and likely represent a conserved interferon response pathway.Because we are confident in having identified common cell types across condition, we can ask what genes change in different conditions for cells of the same type. First, we create a column in the meta.data slot to hold both the cell type and stimulation information and switch the current ident to that column. Then we use FindMarkers() to find the genes that are different between stimulated and control B cells. Notice that many of the top genes that show up here are the same as the ones we plotted earlier as core interferon response genes. Additionally, genes like CXCL10 which we saw were specific to monocyte and B cell interferon response show up as highly significant in this list as well. immune.combined$celltype.stim <- paste(Idents(immune.combined), immune.combined$stim, sep = "_") immune.combined$celltype <- Idents(immune.combined) Idents(immune.combined) <- "celltype.stim" b.interferon.response <- FindMarkers(immune.combined, ident.1 = "B_STIM", ident.2 = "B_CTRL", verbose = FALSE) head(b.interferon.response, n = 15)## p_val avg_log2FC pct.1 pct.2 p_val_adj ## ISG15 1.212995e-155 4.5997247 0.998 0.239 1.704622e-151 ## IFIT3 4.743486e-151 4.5017769 0.964 0.052 6.666020e-147 ## IFI6 1.680324e-150 4.2361116 0.969 0.080 2.361359e-146 ## ISG20 1.595574e-146 2.9452675 1.000 0.671 2.242260e-142 ## IFIT1 3.499460e-137 4.1278656 0.910 0.032 4.917791e-133 ## MX1 8.571983e-121 3.2876616 0.904 0.115 1.204621e-116 ## LY6E 1.359842e-117 3.1251242 0.895 0.152 1.910986e-113 ## TNFSF10 4.454596e-110 3.7816677 0.790 0.025 6.260044e-106 ## IFIT2 1.290640e-106 3.6584511 0.787 0.035 1.813736e-102 ## B2M 2.019314e-95 0.6073495 1.000 1.000 2.837741e-91 ## PLSCR1 1.464429e-93 2.8195675 0.794 0.117 2.057961e-89 ## IRF7 3.893097e-92 2.5867694 0.837 0.190 5.470969e-88 ## CXCL10 1.624151e-82 5.2608266 0.640 0.010 2.282419e-78 ## UBE2L6 2.482113e-81 2.1450306 0.852 0.299 3.488114e-77 ## PSMB9 5.977328e-77 1.6457686 0.940 0.571 8.399938e-73Another useful way to visualize these changes in gene expression is with the split.by option to the FeaturePlot() or VlnPlot() function. This will display FeaturePlots of the list of given genes, split by a grouping variable (stimulation condition here). Genes such as CD3D and GNLY are canonical cell type markers (for T cells and NK/CD8 T cells) that are virtually unaffected by interferon stimulation and display similar gene expression patterns in the control and stimulated group. IFI6 and ISG15, on the other hand, are core interferon response genes and are upregulated accordingly in all cell types. Finally, CD14 and CXCL10 are genes that show a cell type specific interferon response. CD14 expression decreases after stimulation in CD14 monocytes, which could lead to misclassification in a supervised analysis framework, underscoring the value of integrated analysis. CXCL10 shows a distinct upregulation in monocytes and B cells after interferon stimulation but not in other cell types. FeaturePlot(immune.combined, features = c("CD3D", "GNLY", "IFI6"), split.by = "stim", max.cutoff = 3, cols = c("grey", "red")) plots <- VlnPlot(immune.combined, features = c("LYZ", "ISG15", "CXCL10"), split.by = "stim", group.by = "celltype", pt.size = 0, combine = FALSE) wrap_plots(plots = plots, ncol = 1)

immune.combined <- RenameIdents(immune.combined, `0` = "CD14 Mono", `1` = "CD4 Naive T", `2` = "CD4 Memory T", `3` = "CD16 Mono", `4` = "B", `5` = "CD8 T", `6` = "NK", `7` = "T activated", `8` = "DC", `9` = "B Activated", `10` = "Mk", `11` = "pDC", `12` = "Eryth", `13` = "Mono/Mk Doublets", `14` = "HSPC") DimPlot(immune.combined, label = TRUE)The DotPlot() function with the split.by parameter can be useful for viewing conserved cell type markers across conditions, showing both the expression level and the percentage of cells in a cluster expressing any given gene. Here we plot 2-3 strong marker genes for each of our 14 clusters. Idents(immune.combined) <- factor(Idents(immune.combined), levels = c("HSPC", "Mono/Mk Doublets", "pDC", "Eryth", "Mk", "DC", "CD14 Mono", "CD16 Mono", "B Activated", "B", "CD8 T", "NK", "T activated", "CD4 Naive T", "CD4 Memory T")) markers.to.plot <- c("CD3D", "CREM", "HSPH1", "SELL", "GIMAP5", "CACYBP", "GNLY", "NKG7", "CCL5", "CD8A", "MS4A1", "CD79A", "MIR155HG", "NME1", "FCGR3A", "VMO1", "CCL2", "S100A9", "HLA-DQA1", "GPR183", "PPBP", "GNG11", "HBA2", "HBB", "TSPAN13", "IL3RA", "IGJ", "PRSS57") DotPlot(immune.combined, features = markers.to.plot, cols = c("blue", "red"), dot.scale = 8, split.by = "stim") + RotatedAxis()Identify differential expressed genes across conditionsNow that we’ve aligned the stimulated and control cells, we can start to do comparative analyses and look at the differences induced by stimulation. One way to look broadly at these changes is to plot the average expression of both the stimulated and control cells and look for genes that are visual outliers on a scatter plot. Here, we take the average expression of both the stimulated and control naive T cells and CD14 monocyte populations and generate the scatter plots, highlighting genes that exhibit dramatic responses to interferon stimulation. library(ggplot2) library(cowplot) theme_set(theme_cowplot()) t.cells <- subset(immune.combined, idents = "CD4 Naive T") Idents(t.cells) <- "stim" avg.t.cells <- as.data.frame(log1p(AverageExpression(t.cells, verbose = FALSE)$RNA)) avg.t.cells$gene <- rownames(avg.t.cells) cd14.mono <- subset(immune.combined, idents = "CD14 Mono") Idents(cd14.mono) <- "stim" avg.cd14.mono <- as.data.frame(log1p(AverageExpression(cd14.mono, verbose = FALSE)$RNA)) avg.cd14.mono$gene <- rownames(avg.cd14.mono) genes.to.label = c("ISG15", "LY6E", "IFI6", "ISG20", "MX1", "IFIT2", "IFIT1", "CXCL10", "CCL8") p1 <- ggplot(avg.t.cells, aes(CTRL, STIM)) + geom_point() + ggtitle("CD4 Naive T Cells") p1 <- LabelPoints(plot = p1, points = genes.to.label, repel = TRUE) p2 <- ggplot(avg.cd14.mono, aes(CTRL, STIM)) + geom_point() + ggtitle("CD14 Monocytes") p2 <- LabelPoints(plot = p2, points = genes.to.label, repel = TRUE) p1 + p2As you can see, many of the same genes are upregulated in both of these cell types and likely represent a conserved interferon response pathway.Because we are confident in having identified common cell types across condition, we can ask what genes change in different conditions for cells of the same type. First, we create a column in the meta.data slot to hold both the cell type and stimulation information and switch the current ident to that column. Then we use FindMarkers() to find the genes that are different between stimulated and control B cells. Notice that many of the top genes that show up here are the same as the ones we plotted earlier as core interferon response genes. Additionally, genes like CXCL10 which we saw were specific to monocyte and B cell interferon response show up as highly significant in this list as well. immune.combined$celltype.stim <- paste(Idents(immune.combined), immune.combined$stim, sep = "_") immune.combined$celltype <- Idents(immune.combined) Idents(immune.combined) <- "celltype.stim" b.interferon.response <- FindMarkers(immune.combined, ident.1 = "B_STIM", ident.2 = "B_CTRL", verbose = FALSE) head(b.interferon.response, n = 15)## p_val avg_log2FC pct.1 pct.2 p_val_adj ## ISG15 1.212995e-155 4.5997247 0.998 0.239 1.704622e-151 ## IFIT3 4.743486e-151 4.5017769 0.964 0.052 6.666020e-147 ## IFI6 1.680324e-150 4.2361116 0.969 0.080 2.361359e-146 ## ISG20 1.595574e-146 2.9452675 1.000 0.671 2.242260e-142 ## IFIT1 3.499460e-137 4.1278656 0.910 0.032 4.917791e-133 ## MX1 8.571983e-121 3.2876616 0.904 0.115 1.204621e-116 ## LY6E 1.359842e-117 3.1251242 0.895 0.152 1.910986e-113 ## TNFSF10 4.454596e-110 3.7816677 0.790 0.025 6.260044e-106 ## IFIT2 1.290640e-106 3.6584511 0.787 0.035 1.813736e-102 ## B2M 2.019314e-95 0.6073495 1.000 1.000 2.837741e-91 ## PLSCR1 1.464429e-93 2.8195675 0.794 0.117 2.057961e-89 ## IRF7 3.893097e-92 2.5867694 0.837 0.190 5.470969e-88 ## CXCL10 1.624151e-82 5.2608266 0.640 0.010 2.282419e-78 ## UBE2L6 2.482113e-81 2.1450306 0.852 0.299 3.488114e-77 ## PSMB9 5.977328e-77 1.6457686 0.940 0.571 8.399938e-73Another useful way to visualize these changes in gene expression is with the split.by option to the FeaturePlot() or VlnPlot() function. This will display FeaturePlots of the list of given genes, split by a grouping variable (stimulation condition here). Genes such as CD3D and GNLY are canonical cell type markers (for T cells and NK/CD8 T cells) that are virtually unaffected by interferon stimulation and display similar gene expression patterns in the control and stimulated group. IFI6 and ISG15, on the other hand, are core interferon response genes and are upregulated accordingly in all cell types. Finally, CD14 and CXCL10 are genes that show a cell type specific interferon response. CD14 expression decreases after stimulation in CD14 monocytes, which could lead to misclassification in a supervised analysis framework, underscoring the value of integrated analysis. CXCL10 shows a distinct upregulation in monocytes and B cells after interferon stimulation but not in other cell types. FeaturePlot(immune.combined, features = c("CD3D", "GNLY", "IFI6"), split.by = "stim", max.cutoff = 3, cols = c("grey", "red")) plots <- VlnPlot(immune.combined, features = c("LYZ", "ISG15", "CXCL10"), split.by = "stim", group.by = "celltype", pt.size = 0, combine = FALSE) wrap_plots(plots = plots, ncol = 1)

The DotPlot() function with the split.by parameter can be useful for viewing conserved cell type markers across conditions, showing both the expression level and the percentage of cells in a cluster expressing any given gene. Here we plot 2-3 strong marker genes for each of our 14 clusters. Idents(immune.combined) <- factor(Idents(immune.combined), levels = c("HSPC", "Mono/Mk Doublets", "pDC", "Eryth", "Mk", "DC", "CD14 Mono", "CD16 Mono", "B Activated", "B", "CD8 T", "NK", "T activated", "CD4 Naive T", "CD4 Memory T")) markers.to.plot <- c("CD3D", "CREM", "HSPH1", "SELL", "GIMAP5", "CACYBP", "GNLY", "NKG7", "CCL5", "CD8A", "MS4A1", "CD79A", "MIR155HG", "NME1", "FCGR3A", "VMO1", "CCL2", "S100A9", "HLA-DQA1", "GPR183", "PPBP", "GNG11", "HBA2", "HBB", "TSPAN13", "IL3RA", "IGJ", "PRSS57") DotPlot(immune.combined, features = markers.to.plot, cols = c("blue", "red"), dot.scale = 8, split.by = "stim") + RotatedAxis()Identify differential expressed genes across conditionsNow that we’ve aligned the stimulated and control cells, we can start to do comparative analyses and look at the differences induced by stimulation. One way to look broadly at these changes is to plot the average expression of both the stimulated and control cells and look for genes that are visual outliers on a scatter plot. Here, we take the average expression of both the stimulated and control naive T cells and CD14 monocyte populations and generate the scatter plots, highlighting genes that exhibit dramatic responses to interferon stimulation. library(ggplot2) library(cowplot) theme_set(theme_cowplot()) t.cells <- subset(immune.combined, idents = "CD4 Naive T") Idents(t.cells) <- "stim" avg.t.cells <- as.data.frame(log1p(AverageExpression(t.cells, verbose = FALSE)$RNA)) avg.t.cells$gene <- rownames(avg.t.cells) cd14.mono <- subset(immune.combined, idents = "CD14 Mono") Idents(cd14.mono) <- "stim" avg.cd14.mono <- as.data.frame(log1p(AverageExpression(cd14.mono, verbose = FALSE)$RNA)) avg.cd14.mono$gene <- rownames(avg.cd14.mono) genes.to.label = c("ISG15", "LY6E", "IFI6", "ISG20", "MX1", "IFIT2", "IFIT1", "CXCL10", "CCL8") p1 <- ggplot(avg.t.cells, aes(CTRL, STIM)) + geom_point() + ggtitle("CD4 Naive T Cells") p1 <- LabelPoints(plot = p1, points = genes.to.label, repel = TRUE) p2 <- ggplot(avg.cd14.mono, aes(CTRL, STIM)) + geom_point() + ggtitle("CD14 Monocytes") p2 <- LabelPoints(plot = p2, points = genes.to.label, repel = TRUE) p1 + p2As you can see, many of the same genes are upregulated in both of these cell types and likely represent a conserved interferon response pathway.Because we are confident in having identified common cell types across condition, we can ask what genes change in different conditions for cells of the same type. First, we create a column in the meta.data slot to hold both the cell type and stimulation information and switch the current ident to that column. Then we use FindMarkers() to find the genes that are different between stimulated and control B cells. Notice that many of the top genes that show up here are the same as the ones we plotted earlier as core interferon response genes. Additionally, genes like CXCL10 which we saw were specific to monocyte and B cell interferon response show up as highly significant in this list as well. immune.combined$celltype.stim <- paste(Idents(immune.combined), immune.combined$stim, sep = "_") immune.combined$celltype <- Idents(immune.combined) Idents(immune.combined) <- "celltype.stim" b.interferon.response <- FindMarkers(immune.combined, ident.1 = "B_STIM", ident.2 = "B_CTRL", verbose = FALSE) head(b.interferon.response, n = 15)## p_val avg_log2FC pct.1 pct.2 p_val_adj ## ISG15 1.212995e-155 4.5997247 0.998 0.239 1.704622e-151 ## IFIT3 4.743486e-151 4.5017769 0.964 0.052 6.666020e-147 ## IFI6 1.680324e-150 4.2361116 0.969 0.080 2.361359e-146 ## ISG20 1.595574e-146 2.9452675 1.000 0.671 2.242260e-142 ## IFIT1 3.499460e-137 4.1278656 0.910 0.032 4.917791e-133 ## MX1 8.571983e-121 3.2876616 0.904 0.115 1.204621e-116 ## LY6E 1.359842e-117 3.1251242 0.895 0.152 1.910986e-113 ## TNFSF10 4.454596e-110 3.7816677 0.790 0.025 6.260044e-106 ## IFIT2 1.290640e-106 3.6584511 0.787 0.035 1.813736e-102 ## B2M 2.019314e-95 0.6073495 1.000 1.000 2.837741e-91 ## PLSCR1 1.464429e-93 2.8195675 0.794 0.117 2.057961e-89 ## IRF7 3.893097e-92 2.5867694 0.837 0.190 5.470969e-88 ## CXCL10 1.624151e-82 5.2608266 0.640 0.010 2.282419e-78 ## UBE2L6 2.482113e-81 2.1450306 0.852 0.299 3.488114e-77 ## PSMB9 5.977328e-77 1.6457686 0.940 0.571 8.399938e-73Another useful way to visualize these changes in gene expression is with the split.by option to the FeaturePlot() or VlnPlot() function. This will display FeaturePlots of the list of given genes, split by a grouping variable (stimulation condition here). Genes such as CD3D and GNLY are canonical cell type markers (for T cells and NK/CD8 T cells) that are virtually unaffected by interferon stimulation and display similar gene expression patterns in the control and stimulated group. IFI6 and ISG15, on the other hand, are core interferon response genes and are upregulated accordingly in all cell types. Finally, CD14 and CXCL10 are genes that show a cell type specific interferon response. CD14 expression decreases after stimulation in CD14 monocytes, which could lead to misclassification in a supervised analysis framework, underscoring the value of integrated analysis. CXCL10 shows a distinct upregulation in monocytes and B cells after interferon stimulation but not in other cell types. FeaturePlot(immune.combined, features = c("CD3D", "GNLY", "IFI6"), split.by = "stim", max.cutoff = 3, cols = c("grey", "red")) plots <- VlnPlot(immune.combined, features = c("LYZ", "ISG15", "CXCL10"), split.by = "stim", group.by = "celltype", pt.size = 0, combine = FALSE) wrap_plots(plots = plots, ncol = 1)

The DotPlot() function with the split.by parameter can be useful for viewing conserved cell type markers across conditions, showing both the expression level and the percentage of cells in a cluster expressing any given gene. Here we plot 2-3 strong marker genes for each of our 14 clusters. Idents(immune.combined) <- factor(Idents(immune.combined), levels = c("HSPC", "Mono/Mk Doublets", "pDC", "Eryth", "Mk", "DC", "CD14 Mono", "CD16 Mono", "B Activated", "B", "CD8 T", "NK", "T activated", "CD4 Naive T", "CD4 Memory T")) markers.to.plot <- c("CD3D", "CREM", "HSPH1", "SELL", "GIMAP5", "CACYBP", "GNLY", "NKG7", "CCL5", "CD8A", "MS4A1", "CD79A", "MIR155HG", "NME1", "FCGR3A", "VMO1", "CCL2", "S100A9", "HLA-DQA1", "GPR183", "PPBP", "GNG11", "HBA2", "HBB", "TSPAN13", "IL3RA", "IGJ", "PRSS57") DotPlot(immune.combined, features = markers.to.plot, cols = c("blue", "red"), dot.scale = 8, split.by = "stim") + RotatedAxis()Identify differential expressed genes across conditionsNow that we’ve aligned the stimulated and control cells, we can start to do comparative analyses and look at the differences induced by stimulation. One way to look broadly at these changes is to plot the average expression of both the stimulated and control cells and look for genes that are visual outliers on a scatter plot. Here, we take the average expression of both the stimulated and control naive T cells and CD14 monocyte populations and generate the scatter plots, highlighting genes that exhibit dramatic responses to interferon stimulation. library(ggplot2) library(cowplot) theme_set(theme_cowplot()) t.cells <- subset(immune.combined, idents = "CD4 Naive T") Idents(t.cells) <- "stim" avg.t.cells <- as.data.frame(log1p(AverageExpression(t.cells, verbose = FALSE)$RNA)) avg.t.cells$gene <- rownames(avg.t.cells) cd14.mono <- subset(immune.combined, idents = "CD14 Mono") Idents(cd14.mono) <- "stim" avg.cd14.mono <- as.data.frame(log1p(AverageExpression(cd14.mono, verbose = FALSE)$RNA)) avg.cd14.mono$gene <- rownames(avg.cd14.mono) genes.to.label = c("ISG15", "LY6E", "IFI6", "ISG20", "MX1", "IFIT2", "IFIT1", "CXCL10", "CCL8") p1 <- ggplot(avg.t.cells, aes(CTRL, STIM)) + geom_point() + ggtitle("CD4 Naive T Cells") p1 <- LabelPoints(plot = p1, points = genes.to.label, repel = TRUE) p2 <- ggplot(avg.cd14.mono, aes(CTRL, STIM)) + geom_point() + ggtitle("CD14 Monocytes") p2 <- LabelPoints(plot = p2, points = genes.to.label, repel = TRUE) p1 + p2As you can see, many of the same genes are upregulated in both of these cell types and likely represent a conserved interferon response pathway.Because we are confident in having identified common cell types across condition, we can ask what genes change in different conditions for cells of the same type. First, we create a column in the meta.data slot to hold both the cell type and stimulation information and switch the current ident to that column. Then we use FindMarkers() to find the genes that are different between stimulated and control B cells. Notice that many of the top genes that show up here are the same as the ones we plotted earlier as core interferon response genes. Additionally, genes like CXCL10 which we saw were specific to monocyte and B cell interferon response show up as highly significant in this list as well. immune.combined$celltype.stim <- paste(Idents(immune.combined), immune.combined$stim, sep = "_") immune.combined$celltype <- Idents(immune.combined) Idents(immune.combined) <- "celltype.stim" b.interferon.response <- FindMarkers(immune.combined, ident.1 = "B_STIM", ident.2 = "B_CTRL", verbose = FALSE) head(b.interferon.response, n = 15)## p_val avg_log2FC pct.1 pct.2 p_val_adj ## ISG15 1.212995e-155 4.5997247 0.998 0.239 1.704622e-151 ## IFIT3 4.743486e-151 4.5017769 0.964 0.052 6.666020e-147 ## IFI6 1.680324e-150 4.2361116 0.969 0.080 2.361359e-146 ## ISG20 1.595574e-146 2.9452675 1.000 0.671 2.242260e-142 ## IFIT1 3.499460e-137 4.1278656 0.910 0.032 4.917791e-133 ## MX1 8.571983e-121 3.2876616 0.904 0.115 1.204621e-116 ## LY6E 1.359842e-117 3.1251242 0.895 0.152 1.910986e-113 ## TNFSF10 4.454596e-110 3.7816677 0.790 0.025 6.260044e-106 ## IFIT2 1.290640e-106 3.6584511 0.787 0.035 1.813736e-102 ## B2M 2.019314e-95 0.6073495 1.000 1.000 2.837741e-91 ## PLSCR1 1.464429e-93 2.8195675 0.794 0.117 2.057961e-89 ## IRF7 3.893097e-92 2.5867694 0.837 0.190 5.470969e-88 ## CXCL10 1.624151e-82 5.2608266 0.640 0.010 2.282419e-78 ## UBE2L6 2.482113e-81 2.1450306 0.852 0.299 3.488114e-77 ## PSMB9 5.977328e-77 1.6457686 0.940 0.571 8.399938e-73Another useful way to visualize these changes in gene expression is with the split.by option to the FeaturePlot() or VlnPlot() function. This will display FeaturePlots of the list of given genes, split by a grouping variable (stimulation condition here). Genes such as CD3D and GNLY are canonical cell type markers (for T cells and NK/CD8 T cells) that are virtually unaffected by interferon stimulation and display similar gene expression patterns in the control and stimulated group. IFI6 and ISG15, on the other hand, are core interferon response genes and are upregulated accordingly in all cell types. Finally, CD14 and CXCL10 are genes that show a cell type specific interferon response. CD14 expression decreases after stimulation in CD14 monocytes, which could lead to misclassification in a supervised analysis framework, underscoring the value of integrated analysis. CXCL10 shows a distinct upregulation in monocytes and B cells after interferon stimulation but not in other cell types. FeaturePlot(immune.combined, features = c("CD3D", "GNLY", "IFI6"), split.by = "stim", max.cutoff = 3, cols = c("grey", "red")) plots <- VlnPlot(immune.combined, features = c("LYZ", "ISG15", "CXCL10"), split.by = "stim", group.by = "celltype", pt.size = 0, combine = FALSE) wrap_plots(plots = plots, ncol = 1)

Identify differential expressed genes across conditionsNow that we’ve aligned the stimulated and control cells, we can start to do comparative analyses and look at the differences induced by stimulation. One way to look broadly at these changes is to plot the average expression of both the stimulated and control cells and look for genes that are visual outliers on a scatter plot. Here, we take the average expression of both the stimulated and control naive T cells and CD14 monocyte populations and generate the scatter plots, highlighting genes that exhibit dramatic responses to interferon stimulation. library(ggplot2) library(cowplot) theme_set(theme_cowplot()) t.cells <- subset(immune.combined, idents = "CD4 Naive T") Idents(t.cells) <- "stim" avg.t.cells <- as.data.frame(log1p(AverageExpression(t.cells, verbose = FALSE)$RNA)) avg.t.cells$gene <- rownames(avg.t.cells) cd14.mono <- subset(immune.combined, idents = "CD14 Mono") Idents(cd14.mono) <- "stim" avg.cd14.mono <- as.data.frame(log1p(AverageExpression(cd14.mono, verbose = FALSE)$RNA)) avg.cd14.mono$gene <- rownames(avg.cd14.mono) genes.to.label = c("ISG15", "LY6E", "IFI6", "ISG20", "MX1", "IFIT2", "IFIT1", "CXCL10", "CCL8") p1 <- ggplot(avg.t.cells, aes(CTRL, STIM)) + geom_point() + ggtitle("CD4 Naive T Cells") p1 <- LabelPoints(plot = p1, points = genes.to.label, repel = TRUE) p2 <- ggplot(avg.cd14.mono, aes(CTRL, STIM)) + geom_point() + ggtitle("CD14 Monocytes") p2 <- LabelPoints(plot = p2, points = genes.to.label, repel = TRUE) p1 + p2As you can see, many of the same genes are upregulated in both of these cell types and likely represent a conserved interferon response pathway.Because we are confident in having identified common cell types across condition, we can ask what genes change in different conditions for cells of the same type. First, we create a column in the meta.data slot to hold both the cell type and stimulation information and switch the current ident to that column. Then we use FindMarkers() to find the genes that are different between stimulated and control B cells. Notice that many of the top genes that show up here are the same as the ones we plotted earlier as core interferon response genes. Additionally, genes like CXCL10 which we saw were specific to monocyte and B cell interferon response show up as highly significant in this list as well. immune.combined$celltype.stim <- paste(Idents(immune.combined), immune.combined$stim, sep = "_") immune.combined$celltype <- Idents(immune.combined) Idents(immune.combined) <- "celltype.stim" b.interferon.response <- FindMarkers(immune.combined, ident.1 = "B_STIM", ident.2 = "B_CTRL", verbose = FALSE) head(b.interferon.response, n = 15)## p_val avg_log2FC pct.1 pct.2 p_val_adj ## ISG15 1.212995e-155 4.5997247 0.998 0.239 1.704622e-151 ## IFIT3 4.743486e-151 4.5017769 0.964 0.052 6.666020e-147 ## IFI6 1.680324e-150 4.2361116 0.969 0.080 2.361359e-146 ## ISG20 1.595574e-146 2.9452675 1.000 0.671 2.242260e-142 ## IFIT1 3.499460e-137 4.1278656 0.910 0.032 4.917791e-133 ## MX1 8.571983e-121 3.2876616 0.904 0.115 1.204621e-116 ## LY6E 1.359842e-117 3.1251242 0.895 0.152 1.910986e-113 ## TNFSF10 4.454596e-110 3.7816677 0.790 0.025 6.260044e-106 ## IFIT2 1.290640e-106 3.6584511 0.787 0.035 1.813736e-102 ## B2M 2.019314e-95 0.6073495 1.000 1.000 2.837741e-91 ## PLSCR1 1.464429e-93 2.8195675 0.794 0.117 2.057961e-89 ## IRF7 3.893097e-92 2.5867694 0.837 0.190 5.470969e-88 ## CXCL10 1.624151e-82 5.2608266 0.640 0.010 2.282419e-78 ## UBE2L6 2.482113e-81 2.1450306 0.852 0.299 3.488114e-77 ## PSMB9 5.977328e-77 1.6457686 0.940 0.571 8.399938e-73Another useful way to visualize these changes in gene expression is with the split.by option to the FeaturePlot() or VlnPlot() function. This will display FeaturePlots of the list of given genes, split by a grouping variable (stimulation condition here). Genes such as CD3D and GNLY are canonical cell type markers (for T cells and NK/CD8 T cells) that are virtually unaffected by interferon stimulation and display similar gene expression patterns in the control and stimulated group. IFI6 and ISG15, on the other hand, are core interferon response genes and are upregulated accordingly in all cell types. Finally, CD14 and CXCL10 are genes that show a cell type specific interferon response. CD14 expression decreases after stimulation in CD14 monocytes, which could lead to misclassification in a supervised analysis framework, underscoring the value of integrated analysis. CXCL10 shows a distinct upregulation in monocytes and B cells after interferon stimulation but not in other cell types. FeaturePlot(immune.combined, features = c("CD3D", "GNLY", "IFI6"), split.by = "stim", max.cutoff = 3, cols = c("grey", "red")) plots <- VlnPlot(immune.combined, features = c("LYZ", "ISG15", "CXCL10"), split.by = "stim", group.by = "celltype", pt.size = 0, combine = FALSE) wrap_plots(plots = plots, ncol = 1)

Now that we’ve aligned the stimulated and control cells, we can start to do comparative analyses and look at the differences induced by stimulation. One way to look broadly at these changes is to plot the average expression of both the stimulated and control cells and look for genes that are visual outliers on a scatter plot. Here, we take the average expression of both the stimulated and control naive T cells and CD14 monocyte populations and generate the scatter plots, highlighting genes that exhibit dramatic responses to interferon stimulation. library(ggplot2) library(cowplot) theme_set(theme_cowplot()) t.cells <- subset(immune.combined, idents = "CD4 Naive T") Idents(t.cells) <- "stim" avg.t.cells <- as.data.frame(log1p(AverageExpression(t.cells, verbose = FALSE)$RNA)) avg.t.cells$gene <- rownames(avg.t.cells) cd14.mono <- subset(immune.combined, idents = "CD14 Mono") Idents(cd14.mono) <- "stim" avg.cd14.mono <- as.data.frame(log1p(AverageExpression(cd14.mono, verbose = FALSE)$RNA)) avg.cd14.mono$gene <- rownames(avg.cd14.mono) genes.to.label = c("ISG15", "LY6E", "IFI6", "ISG20", "MX1", "IFIT2", "IFIT1", "CXCL10", "CCL8") p1 <- ggplot(avg.t.cells, aes(CTRL, STIM)) + geom_point() + ggtitle("CD4 Naive T Cells") p1 <- LabelPoints(plot = p1, points = genes.to.label, repel = TRUE) p2 <- ggplot(avg.cd14.mono, aes(CTRL, STIM)) + geom_point() + ggtitle("CD14 Monocytes") p2 <- LabelPoints(plot = p2, points = genes.to.label, repel = TRUE) p1 + p2As you can see, many of the same genes are upregulated in both of these cell types and likely represent a conserved interferon response pathway.Because we are confident in having identified common cell types across condition, we can ask what genes change in different conditions for cells of the same type. First, we create a column in the meta.data slot to hold both the cell type and stimulation information and switch the current ident to that column. Then we use FindMarkers() to find the genes that are different between stimulated and control B cells. Notice that many of the top genes that show up here are the same as the ones we plotted earlier as core interferon response genes. Additionally, genes like CXCL10 which we saw were specific to monocyte and B cell interferon response show up as highly significant in this list as well. immune.combined$celltype.stim <- paste(Idents(immune.combined), immune.combined$stim, sep = "_") immune.combined$celltype <- Idents(immune.combined) Idents(immune.combined) <- "celltype.stim" b.interferon.response <- FindMarkers(immune.combined, ident.1 = "B_STIM", ident.2 = "B_CTRL", verbose = FALSE) head(b.interferon.response, n = 15)## p_val avg_log2FC pct.1 pct.2 p_val_adj ## ISG15 1.212995e-155 4.5997247 0.998 0.239 1.704622e-151 ## IFIT3 4.743486e-151 4.5017769 0.964 0.052 6.666020e-147 ## IFI6 1.680324e-150 4.2361116 0.969 0.080 2.361359e-146 ## ISG20 1.595574e-146 2.9452675 1.000 0.671 2.242260e-142 ## IFIT1 3.499460e-137 4.1278656 0.910 0.032 4.917791e-133 ## MX1 8.571983e-121 3.2876616 0.904 0.115 1.204621e-116 ## LY6E 1.359842e-117 3.1251242 0.895 0.152 1.910986e-113 ## TNFSF10 4.454596e-110 3.7816677 0.790 0.025 6.260044e-106 ## IFIT2 1.290640e-106 3.6584511 0.787 0.035 1.813736e-102 ## B2M 2.019314e-95 0.6073495 1.000 1.000 2.837741e-91 ## PLSCR1 1.464429e-93 2.8195675 0.794 0.117 2.057961e-89 ## IRF7 3.893097e-92 2.5867694 0.837 0.190 5.470969e-88 ## CXCL10 1.624151e-82 5.2608266 0.640 0.010 2.282419e-78 ## UBE2L6 2.482113e-81 2.1450306 0.852 0.299 3.488114e-77 ## PSMB9 5.977328e-77 1.6457686 0.940 0.571 8.399938e-73Another useful way to visualize these changes in gene expression is with the split.by option to the FeaturePlot() or VlnPlot() function. This will display FeaturePlots of the list of given genes, split by a grouping variable (stimulation condition here). Genes such as CD3D and GNLY are canonical cell type markers (for T cells and NK/CD8 T cells) that are virtually unaffected by interferon stimulation and display similar gene expression patterns in the control and stimulated group. IFI6 and ISG15, on the other hand, are core interferon response genes and are upregulated accordingly in all cell types. Finally, CD14 and CXCL10 are genes that show a cell type specific interferon response. CD14 expression decreases after stimulation in CD14 monocytes, which could lead to misclassification in a supervised analysis framework, underscoring the value of integrated analysis. CXCL10 shows a distinct upregulation in monocytes and B cells after interferon stimulation but not in other cell types. FeaturePlot(immune.combined, features = c("CD3D", "GNLY", "IFI6"), split.by = "stim", max.cutoff = 3, cols = c("grey", "red")) plots <- VlnPlot(immune.combined, features = c("LYZ", "ISG15", "CXCL10"), split.by = "stim", group.by = "celltype", pt.size = 0, combine = FALSE) wrap_plots(plots = plots, ncol = 1)

As you can see, many of the same genes are upregulated in both of these cell types and likely represent a conserved interferon response pathway.Because we are confident in having identified common cell types across condition, we can ask what genes change in different conditions for cells of the same type. First, we create a column in the meta.data slot to hold both the cell type and stimulation information and switch the current ident to that column. Then we use FindMarkers() to find the genes that are different between stimulated and control B cells. Notice that many of the top genes that show up here are the same as the ones we plotted earlier as core interferon response genes. Additionally, genes like CXCL10 which we saw were specific to monocyte and B cell interferon response show up as highly significant in this list as well. immune.combined$celltype.stim <- paste(Idents(immune.combined), immune.combined$stim, sep = "_") immune.combined$celltype <- Idents(immune.combined) Idents(immune.combined) <- "celltype.stim" b.interferon.response <- FindMarkers(immune.combined, ident.1 = "B_STIM", ident.2 = "B_CTRL", verbose = FALSE) head(b.interferon.response, n = 15)## p_val avg_log2FC pct.1 pct.2 p_val_adj ## ISG15 1.212995e-155 4.5997247 0.998 0.239 1.704622e-151 ## IFIT3 4.743486e-151 4.5017769 0.964 0.052 6.666020e-147 ## IFI6 1.680324e-150 4.2361116 0.969 0.080 2.361359e-146 ## ISG20 1.595574e-146 2.9452675 1.000 0.671 2.242260e-142 ## IFIT1 3.499460e-137 4.1278656 0.910 0.032 4.917791e-133 ## MX1 8.571983e-121 3.2876616 0.904 0.115 1.204621e-116 ## LY6E 1.359842e-117 3.1251242 0.895 0.152 1.910986e-113 ## TNFSF10 4.454596e-110 3.7816677 0.790 0.025 6.260044e-106 ## IFIT2 1.290640e-106 3.6584511 0.787 0.035 1.813736e-102 ## B2M 2.019314e-95 0.6073495 1.000 1.000 2.837741e-91 ## PLSCR1 1.464429e-93 2.8195675 0.794 0.117 2.057961e-89 ## IRF7 3.893097e-92 2.5867694 0.837 0.190 5.470969e-88 ## CXCL10 1.624151e-82 5.2608266 0.640 0.010 2.282419e-78 ## UBE2L6 2.482113e-81 2.1450306 0.852 0.299 3.488114e-77 ## PSMB9 5.977328e-77 1.6457686 0.940 0.571 8.399938e-73Another useful way to visualize these changes in gene expression is with the split.by option to the FeaturePlot() or VlnPlot() function. This will display FeaturePlots of the list of given genes, split by a grouping variable (stimulation condition here). Genes such as CD3D and GNLY are canonical cell type markers (for T cells and NK/CD8 T cells) that are virtually unaffected by interferon stimulation and display similar gene expression patterns in the control and stimulated group. IFI6 and ISG15, on the other hand, are core interferon response genes and are upregulated accordingly in all cell types. Finally, CD14 and CXCL10 are genes that show a cell type specific interferon response. CD14 expression decreases after stimulation in CD14 monocytes, which could lead to misclassification in a supervised analysis framework, underscoring the value of integrated analysis. CXCL10 shows a distinct upregulation in monocytes and B cells after interferon stimulation but not in other cell types. FeaturePlot(immune.combined, features = c("CD3D", "GNLY", "IFI6"), split.by = "stim", max.cutoff = 3, cols = c("grey", "red")) plots <- VlnPlot(immune.combined, features = c("LYZ", "ISG15", "CXCL10"), split.by = "stim", group.by = "celltype", pt.size = 0, combine = FALSE) wrap_plots(plots = plots, ncol = 1)

As you can see, many of the same genes are upregulated in both of these cell types and likely represent a conserved interferon response pathway.Because we are confident in having identified common cell types across condition, we can ask what genes change in different conditions for cells of the same type. First, we create a column in the meta.data slot to hold both the cell type and stimulation information and switch the current ident to that column. Then we use FindMarkers() to find the genes that are different between stimulated and control B cells. Notice that many of the top genes that show up here are the same as the ones we plotted earlier as core interferon response genes. Additionally, genes like CXCL10 which we saw were specific to monocyte and B cell interferon response show up as highly significant in this list as well. immune.combined$celltype.stim <- paste(Idents(immune.combined), immune.combined$stim, sep = "_") immune.combined$celltype <- Idents(immune.combined) Idents(immune.combined) <- "celltype.stim" b.interferon.response <- FindMarkers(immune.combined, ident.1 = "B_STIM", ident.2 = "B_CTRL", verbose = FALSE) head(b.interferon.response, n = 15)## p_val avg_log2FC pct.1 pct.2 p_val_adj ## ISG15 1.212995e-155 4.5997247 0.998 0.239 1.704622e-151 ## IFIT3 4.743486e-151 4.5017769 0.964 0.052 6.666020e-147 ## IFI6 1.680324e-150 4.2361116 0.969 0.080 2.361359e-146 ## ISG20 1.595574e-146 2.9452675 1.000 0.671 2.242260e-142 ## IFIT1 3.499460e-137 4.1278656 0.910 0.032 4.917791e-133 ## MX1 8.571983e-121 3.2876616 0.904 0.115 1.204621e-116 ## LY6E 1.359842e-117 3.1251242 0.895 0.152 1.910986e-113 ## TNFSF10 4.454596e-110 3.7816677 0.790 0.025 6.260044e-106 ## IFIT2 1.290640e-106 3.6584511 0.787 0.035 1.813736e-102 ## B2M 2.019314e-95 0.6073495 1.000 1.000 2.837741e-91 ## PLSCR1 1.464429e-93 2.8195675 0.794 0.117 2.057961e-89 ## IRF7 3.893097e-92 2.5867694 0.837 0.190 5.470969e-88 ## CXCL10 1.624151e-82 5.2608266 0.640 0.010 2.282419e-78 ## UBE2L6 2.482113e-81 2.1450306 0.852 0.299 3.488114e-77 ## PSMB9 5.977328e-77 1.6457686 0.940 0.571 8.399938e-73Another useful way to visualize these changes in gene expression is with the split.by option to the FeaturePlot() or VlnPlot() function. This will display FeaturePlots of the list of given genes, split by a grouping variable (stimulation condition here). Genes such as CD3D and GNLY are canonical cell type markers (for T cells and NK/CD8 T cells) that are virtually unaffected by interferon stimulation and display similar gene expression patterns in the control and stimulated group. IFI6 and ISG15, on the other hand, are core interferon response genes and are upregulated accordingly in all cell types. Finally, CD14 and CXCL10 are genes that show a cell type specific interferon response. CD14 expression decreases after stimulation in CD14 monocytes, which could lead to misclassification in a supervised analysis framework, underscoring the value of integrated analysis. CXCL10 shows a distinct upregulation in monocytes and B cells after interferon stimulation but not in other cell types. FeaturePlot(immune.combined, features = c("CD3D", "GNLY", "IFI6"), split.by = "stim", max.cutoff = 3, cols = c("grey", "red")) plots <- VlnPlot(immune.combined, features = c("LYZ", "ISG15", "CXCL10"), split.by = "stim", group.by = "celltype", pt.size = 0, combine = FALSE) wrap_plots(plots = plots, ncol = 1)

Because we are confident in having identified common cell types across condition, we can ask what genes change in different conditions for cells of the same type. First, we create a column in the meta.data slot to hold both the cell type and stimulation information and switch the current ident to that column. Then we use FindMarkers() to find the genes that are different between stimulated and control B cells. Notice that many of the top genes that show up here are the same as the ones we plotted earlier as core interferon response genes. Additionally, genes like CXCL10 which we saw were specific to monocyte and B cell interferon response show up as highly significant in this list as well. immune.combined$celltype.stim <- paste(Idents(immune.combined), immune.combined$stim, sep = "_") immune.combined$celltype <- Idents(immune.combined) Idents(immune.combined) <- "celltype.stim" b.interferon.response <- FindMarkers(immune.combined, ident.1 = "B_STIM", ident.2 = "B_CTRL", verbose = FALSE) head(b.interferon.response, n = 15)## p_val avg_log2FC pct.1 pct.2 p_val_adj ## ISG15 1.212995e-155 4.5997247 0.998 0.239 1.704622e-151 ## IFIT3 4.743486e-151 4.5017769 0.964 0.052 6.666020e-147 ## IFI6 1.680324e-150 4.2361116 0.969 0.080 2.361359e-146 ## ISG20 1.595574e-146 2.9452675 1.000 0.671 2.242260e-142 ## IFIT1 3.499460e-137 4.1278656 0.910 0.032 4.917791e-133 ## MX1 8.571983e-121 3.2876616 0.904 0.115 1.204621e-116 ## LY6E 1.359842e-117 3.1251242 0.895 0.152 1.910986e-113 ## TNFSF10 4.454596e-110 3.7816677 0.790 0.025 6.260044e-106 ## IFIT2 1.290640e-106 3.6584511 0.787 0.035 1.813736e-102 ## B2M 2.019314e-95 0.6073495 1.000 1.000 2.837741e-91 ## PLSCR1 1.464429e-93 2.8195675 0.794 0.117 2.057961e-89 ## IRF7 3.893097e-92 2.5867694 0.837 0.190 5.470969e-88 ## CXCL10 1.624151e-82 5.2608266 0.640 0.010 2.282419e-78 ## UBE2L6 2.482113e-81 2.1450306 0.852 0.299 3.488114e-77 ## PSMB9 5.977328e-77 1.6457686 0.940 0.571 8.399938e-73Another useful way to visualize these changes in gene expression is with the split.by option to the FeaturePlot() or VlnPlot() function. This will display FeaturePlots of the list of given genes, split by a grouping variable (stimulation condition here). Genes such as CD3D and GNLY are canonical cell type markers (for T cells and NK/CD8 T cells) that are virtually unaffected by interferon stimulation and display similar gene expression patterns in the control and stimulated group. IFI6 and ISG15, on the other hand, are core interferon response genes and are upregulated accordingly in all cell types. Finally, CD14 and CXCL10 are genes that show a cell type specific interferon response. CD14 expression decreases after stimulation in CD14 monocytes, which could lead to misclassification in a supervised analysis framework, underscoring the value of integrated analysis. CXCL10 shows a distinct upregulation in monocytes and B cells after interferon stimulation but not in other cell types. FeaturePlot(immune.combined, features = c("CD3D", "GNLY", "IFI6"), split.by = "stim", max.cutoff = 3, cols = c("grey", "red")) plots <- VlnPlot(immune.combined, features = c("LYZ", "ISG15", "CXCL10"), split.by = "stim", group.by = "celltype", pt.size = 0, combine = FALSE) wrap_plots(plots = plots, ncol = 1)

Another useful way to visualize these changes in gene expression is with the split.by option to the FeaturePlot() or VlnPlot() function. This will display FeaturePlots of the list of given genes, split by a grouping variable (stimulation condition here). Genes such as CD3D and GNLY are canonical cell type markers (for T cells and NK/CD8 T cells) that are virtually unaffected by interferon stimulation and display similar gene expression patterns in the control and stimulated group. IFI6 and ISG15, on the other hand, are core interferon response genes and are upregulated accordingly in all cell types. Finally, CD14 and CXCL10 are genes that show a cell type specific interferon response. CD14 expression decreases after stimulation in CD14 monocytes, which could lead to misclassification in a supervised analysis framework, underscoring the value of integrated analysis. CXCL10 shows a distinct upregulation in monocytes and B cells after interferon stimulation but not in other cell types. FeaturePlot(immune.combined, features = c("CD3D", "GNLY", "IFI6"), split.by = "stim", max.cutoff = 3, cols = c("grey", "red")) plots <- VlnPlot(immune.combined, features = c("LYZ", "ISG15", "CXCL10"), split.by = "stim", group.by = "celltype", pt.size = 0, combine = FALSE) wrap_plots(plots = plots, ncol = 1)

plots <- VlnPlot(immune.combined, features = c("LYZ", "ISG15", "CXCL10"), split.by = "stim", group.by = "celltype", pt.size = 0, combine = FALSE) wrap_plots(plots = plots, ncol = 1)

In Hafemeister and Satija, 2019, we introduced an improved method for the normalization of scRNA-seq, based on regularized negative binomial regression. The method is named ‘sctransform’, and avoids some of the pitfalls of standard normalization workflows, including the addition of a pseudocount, and log-transformation. You can read more about sctransform in the manuscript or our SCTransform vignette.Below, we demonstrate how to modify the Seurat integration workflow for datasets that have been normalized with the sctransform workflow. The commands are largely similar, with a few key differences:Normalize datasets individually by SCTransform(), instead of NormalizeData() prior to integrationAs discussed further in our SCTransform vignette, we typically use 3,000 or more features for analysis downstream of sctransform.Run the PrepSCTIntegration() function prior to identifying anchorsWhen running FindIntegrationAnchors(), and IntegrateData(), set the normalization.method parameter to the value SCT.When running sctransform-based workflows, including integration, do not run the ScaleData() function LoadData("ifnb") ifnb.list <- SplitObject(ifnb, split.by = "stim") ifnb.list <- lapply(X = ifnb.list, FUN = SCTransform) features <- SelectIntegrationFeatures(object.list = ifnb.list, nfeatures = 3000) ifnb.list <- PrepSCTIntegration(object.list = ifnb.list, anchor.features = features) immune.anchors <- FindIntegrationAnchors(object.list = ifnb.list, normalization.method = "SCT", anchor.features = features) immune.combined.sct <- IntegrateData(anchorset = immune.anchors, normalization.method = "SCT") immune.combined.sct <- RunPCA(immune.combined.sct, verbose = FALSE) immune.combined.sct <- RunUMAP(immune.combined.sct, reduction = "pca", dims = 1:30) p1 <- DimPlot(immune.combined.sct, reduction = "umap", group.by = "stim") p2 <- DimPlot(immune.combined.sct, reduction = "umap", group.by = "seurat_annotations", label = TRUE, repel = TRUE) p1 + p2Now that the datasets have been integrated, you can follow the previous steps in this vignette identify cell types and cell type-specific responses.Session Info sessionInfo()## R version 4.2.0 (2022-04-22) ## Platform: x86_64-pc-linux-gnu (64-bit) ## Running under: Ubuntu 20.04.5 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/liblapack.so.3 ## ## locale: ## [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C ## [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8 ## [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 ## ## attached base packages: ## [1] stats graphics grDevices utils datasets methods base ## ## other attached packages: ## [1] cowplot_1.1.1 ggplot2_3.4.1 ## [3] patchwork_1.1.2 thp1.eccite.SeuratData_3.1.5 ## [5] stxBrain.SeuratData_0.1.1 ssHippo.SeuratData_3.1.4 ## [7] pbmcsca.SeuratData_3.0.0 pbmcMultiome.SeuratData_0.1.2 ## [9] pbmc3k.SeuratData_3.1.4 panc8.SeuratData_3.0.2 ## [11] ifnb.SeuratData_3.1.0 hcabm40k.SeuratData_3.0.0 ## [13] bmcite.SeuratData_0.3.0 SeuratData_0.2.2 ## [15] SeuratObject_4.1.3 Seurat_4.3.0 ## ## loaded via a namespace (and not attached): ## [1] systemfonts_1.0.4 sn_2.1.0 plyr_1.8.8 ## [4] igraph_1.4.1 lazyeval_0.2.2 sp_1.6-0 ## [7] splines_4.2.0 listenv_0.9.0 scattermore_0.8 ## [10] qqconf_1.3.1 TH.data_1.1-1 digest_0.6.31 ## [13] htmltools_0.5.4 fansi_1.0.4 magrittr_2.0.3 ## [16] memoise_2.0.1 tensor_1.5 cluster_2.1.3 ## [19] ROCR_1.0-11 limma_3.54.1 globals_0.16.2 ## [22] matrixStats_0.63.0 sandwich_3.0-2 pkgdown_2.0.7 ## [25] spatstat.sparse_3.0-0 colorspace_2.1-0 rappdirs_0.3.3 ## [28] ggrepel_0.9.3 rbibutils_2.2.13 textshaping_0.3.6 ## [31] xfun_0.37 dplyr_1.1.0 crayon_1.5.2 ## [34] jsonlite_1.8.4 progressr_0.13.0 spatstat.data_3.0-0 ## [37] survival_3.3-1 zoo_1.8-11 glue_1.6.2 ## [40] polyclip_1.10-4 gtable_0.3.1 leiden_0.4.3 ## [43] future.apply_1.10.0 BiocGenerics_0.44.0 abind_1.4-5 ## [46] scales_1.2.1 mvtnorm_1.1-3 spatstat.random_3.1-3 ## [49] miniUI_0.1.1.1 Rcpp_1.0.10 plotrix_3.8-2 ## [52] metap_1.8 viridisLite_0.4.1 xtable_1.8-4 ## [55] reticulate_1.28 stats4_4.2.0 htmlwidgets_1.6.1 ## [58] httr_1.4.5 RColorBrewer_1.1-3 TFisher_0.2.0 ## [61] ellipsis_0.3.2 ica_1.0-3 farver_2.1.1 ## [64] pkgconfig_2.0.3 sass_0.4.5 uwot_0.1.14 ## [67] deldir_1.0-6 utf8_1.2.3 tidyselect_1.2.0 ## [70] labeling_0.4.2 rlang_1.0.6 reshape2_1.4.4 ## [73] later_1.3.0 munsell_0.5.0 tools_4.2.0 ## [76] cachem_1.0.7 cli_3.6.0 generics_0.1.3 ## [79] mathjaxr_1.6-0 ggridges_0.5.4 evaluate_0.20 ## [82] stringr_1.5.0 fastmap_1.1.1 yaml_2.3.7 ## [85] ragg_1.2.5 goftest_1.2-3 knitr_1.42 ## [88] fs_1.6.1 fitdistrplus_1.1-8 purrr_1.0.1 ## [91] RANN_2.6.1 pbapply_1.7-0 future_1.31.0 ## [94] nlme_3.1-157 mime_0.12 formatR_1.14 ## [97] compiler_4.2.0 plotly_4.10.1 png_0.1-8 ## [100] spatstat.utils_3.0-1 tibble_3.1.8 bslib_0.4.2 ## [103] stringi_1.7.12 highr_0.10 desc_1.4.2 ## [106] lattice_0.20-45 Matrix_1.5-3 multtest_2.54.0 ## [109] vctrs_0.5.2 mutoss_0.1-12 pillar_1.8.1 ## [112] lifecycle_1.0.3 Rdpack_2.4 spatstat.geom_3.0-6 ## [115] lmtest_0.9-40 jquerylib_0.1.4 RcppAnnoy_0.0.20 ## [118] data.table_1.14.8 irlba_2.3.5.1 httpuv_1.6.9 ## [121] R6_2.5.1 promises_1.2.0.1 KernSmooth_2.23-20 ## [124] gridExtra_2.3 parallelly_1.34.0 codetools_0.2-18 ## [127] MASS_7.3-56 rprojroot_2.0.3 withr_2.5.0 ## [130] mnormt_2.1.1 sctransform_0.3.5 multcomp_1.4-22 ## [133] parallel_4.2.0 grid_4.2.0 tidyr_1.3.0 ## [136] rmarkdown_2.20 Rtsne_0.16 spatstat.explore_3.0-6 ## [139] Biobase_2.58.0 numDeriv_2016.8-1.1 shiny_1.7.4

Below, we demonstrate how to modify the Seurat integration workflow for datasets that have been normalized with the sctransform workflow. The commands are largely similar, with a few key differences:Normalize datasets individually by SCTransform(), instead of NormalizeData() prior to integrationAs discussed further in our SCTransform vignette, we typically use 3,000 or more features for analysis downstream of sctransform.Run the PrepSCTIntegration() function prior to identifying anchorsWhen running FindIntegrationAnchors(), and IntegrateData(), set the normalization.method parameter to the value SCT.When running sctransform-based workflows, including integration, do not run the ScaleData() function LoadData("ifnb") ifnb.list <- SplitObject(ifnb, split.by = "stim") ifnb.list <- lapply(X = ifnb.list, FUN = SCTransform) features <- SelectIntegrationFeatures(object.list = ifnb.list, nfeatures = 3000) ifnb.list <- PrepSCTIntegration(object.list = ifnb.list, anchor.features = features) immune.anchors <- FindIntegrationAnchors(object.list = ifnb.list, normalization.method = "SCT", anchor.features = features) immune.combined.sct <- IntegrateData(anchorset = immune.anchors, normalization.method = "SCT") immune.combined.sct <- RunPCA(immune.combined.sct, verbose = FALSE) immune.combined.sct <- RunUMAP(immune.combined.sct, reduction = "pca", dims = 1:30) p1 <- DimPlot(immune.combined.sct, reduction = "umap", group.by = "stim") p2 <- DimPlot(immune.combined.sct, reduction = "umap", group.by = "seurat_annotations", label = TRUE, repel = TRUE) p1 + p2Now that the datasets have been integrated, you can follow the previous steps in this vignette identify cell types and cell type-specific responses.Session Info sessionInfo()## R version 4.2.0 (2022-04-22) ## Platform: x86_64-pc-linux-gnu (64-bit) ## Running under: Ubuntu 20.04.5 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/liblapack.so.3 ## ## locale: ## [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C ## [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8 ## [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 ## ## attached base packages: ## [1] stats graphics grDevices utils datasets methods base ## ## other attached packages: ## [1] cowplot_1.1.1 ggplot2_3.4.1 ## [3] patchwork_1.1.2 thp1.eccite.SeuratData_3.1.5 ## [5] stxBrain.SeuratData_0.1.1 ssHippo.SeuratData_3.1.4 ## [7] pbmcsca.SeuratData_3.0.0 pbmcMultiome.SeuratData_0.1.2 ## [9] pbmc3k.SeuratData_3.1.4 panc8.SeuratData_3.0.2 ## [11] ifnb.SeuratData_3.1.0 hcabm40k.SeuratData_3.0.0 ## [13] bmcite.SeuratData_0.3.0 SeuratData_0.2.2 ## [15] SeuratObject_4.1.3 Seurat_4.3.0 ## ## loaded via a namespace (and not attached): ## [1] systemfonts_1.0.4 sn_2.1.0 plyr_1.8.8 ## [4] igraph_1.4.1 lazyeval_0.2.2 sp_1.6-0 ## [7] splines_4.2.0 listenv_0.9.0 scattermore_0.8 ## [10] qqconf_1.3.1 TH.data_1.1-1 digest_0.6.31 ## [13] htmltools_0.5.4 fansi_1.0.4 magrittr_2.0.3 ## [16] memoise_2.0.1 tensor_1.5 cluster_2.1.3 ## [19] ROCR_1.0-11 limma_3.54.1 globals_0.16.2 ## [22] matrixStats_0.63.0 sandwich_3.0-2 pkgdown_2.0.7 ## [25] spatstat.sparse_3.0-0 colorspace_2.1-0 rappdirs_0.3.3 ## [28] ggrepel_0.9.3 rbibutils_2.2.13 textshaping_0.3.6 ## [31] xfun_0.37 dplyr_1.1.0 crayon_1.5.2 ## [34] jsonlite_1.8.4 progressr_0.13.0 spatstat.data_3.0-0 ## [37] survival_3.3-1 zoo_1.8-11 glue_1.6.2 ## [40] polyclip_1.10-4 gtable_0.3.1 leiden_0.4.3 ## [43] future.apply_1.10.0 BiocGenerics_0.44.0 abind_1.4-5 ## [46] scales_1.2.1 mvtnorm_1.1-3 spatstat.random_3.1-3 ## [49] miniUI_0.1.1.1 Rcpp_1.0.10 plotrix_3.8-2 ## [52] metap_1.8 viridisLite_0.4.1 xtable_1.8-4 ## [55] reticulate_1.28 stats4_4.2.0 htmlwidgets_1.6.1 ## [58] httr_1.4.5 RColorBrewer_1.1-3 TFisher_0.2.0 ## [61] ellipsis_0.3.2 ica_1.0-3 farver_2.1.1 ## [64] pkgconfig_2.0.3 sass_0.4.5 uwot_0.1.14 ## [67] deldir_1.0-6 utf8_1.2.3 tidyselect_1.2.0 ## [70] labeling_0.4.2 rlang_1.0.6 reshape2_1.4.4 ## [73] later_1.3.0 munsell_0.5.0 tools_4.2.0 ## [76] cachem_1.0.7 cli_3.6.0 generics_0.1.3 ## [79] mathjaxr_1.6-0 ggridges_0.5.4 evaluate_0.20 ## [82] stringr_1.5.0 fastmap_1.1.1 yaml_2.3.7 ## [85] ragg_1.2.5 goftest_1.2-3 knitr_1.42 ## [88] fs_1.6.1 fitdistrplus_1.1-8 purrr_1.0.1 ## [91] RANN_2.6.1 pbapply_1.7-0 future_1.31.0 ## [94] nlme_3.1-157 mime_0.12 formatR_1.14 ## [97] compiler_4.2.0 plotly_4.10.1 png_0.1-8 ## [100] spatstat.utils_3.0-1 tibble_3.1.8 bslib_0.4.2 ## [103] stringi_1.7.12 highr_0.10 desc_1.4.2 ## [106] lattice_0.20-45 Matrix_1.5-3 multtest_2.54.0 ## [109] vctrs_0.5.2 mutoss_0.1-12 pillar_1.8.1 ## [112] lifecycle_1.0.3 Rdpack_2.4 spatstat.geom_3.0-6 ## [115] lmtest_0.9-40 jquerylib_0.1.4 RcppAnnoy_0.0.20 ## [118] data.table_1.14.8 irlba_2.3.5.1 httpuv_1.6.9 ## [121] R6_2.5.1 promises_1.2.0.1 KernSmooth_2.23-20 ## [124] gridExtra_2.3 parallelly_1.34.0 codetools_0.2-18 ## [127] MASS_7.3-56 rprojroot_2.0.3 withr_2.5.0 ## [130] mnormt_2.1.1 sctransform_0.3.5 multcomp_1.4-22 ## [133] parallel_4.2.0 grid_4.2.0 tidyr_1.3.0 ## [136] rmarkdown_2.20 Rtsne_0.16 spatstat.explore_3.0-6 ## [139] Biobase_2.58.0 numDeriv_2016.8-1.1 shiny_1.7.4

Now that the datasets have been integrated, you can follow the previous steps in this vignette identify cell types and cell type-specific responses.Session Info sessionInfo()## R version 4.2.0 (2022-04-22) ## Platform: x86_64-pc-linux-gnu (64-bit) ## Running under: Ubuntu 20.04.5 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/liblapack.so.3 ## ## locale: ## [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C ## [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8 ## [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 ## ## attached base packages: ## [1] stats graphics grDevices utils datasets methods base ## ## other attached packages: ## [1] cowplot_1.1.1 ggplot2_3.4.1 ## [3] patchwork_1.1.2 thp1.eccite.SeuratData_3.1.5 ## [5] stxBrain.SeuratData_0.1.1 ssHippo.SeuratData_3.1.4 ## [7] pbmcsca.SeuratData_3.0.0 pbmcMultiome.SeuratData_0.1.2 ## [9] pbmc3k.SeuratData_3.1.4 panc8.SeuratData_3.0.2 ## [11] ifnb.SeuratData_3.1.0 hcabm40k.SeuratData_3.0.0 ## [13] bmcite.SeuratData_0.3.0 SeuratData_0.2.2 ## [15] SeuratObject_4.1.3 Seurat_4.3.0 ## ## loaded via a namespace (and not attached): ## [1] systemfonts_1.0.4 sn_2.1.0 plyr_1.8.8 ## [4] igraph_1.4.1 lazyeval_0.2.2 sp_1.6-0 ## [7] splines_4.2.0 listenv_0.9.0 scattermore_0.8 ## [10] qqconf_1.3.1 TH.data_1.1-1 digest_0.6.31 ## [13] htmltools_0.5.4 fansi_1.0.4 magrittr_2.0.3 ## [16] memoise_2.0.1 tensor_1.5 cluster_2.1.3 ## [19] ROCR_1.0-11 limma_3.54.1 globals_0.16.2 ## [22] matrixStats_0.63.0 sandwich_3.0-2 pkgdown_2.0.7 ## [25] spatstat.sparse_3.0-0 colorspace_2.1-0 rappdirs_0.3.3 ## [28] ggrepel_0.9.3 rbibutils_2.2.13 textshaping_0.3.6 ## [31] xfun_0.37 dplyr_1.1.0 crayon_1.5.2 ## [34] jsonlite_1.8.4 progressr_0.13.0 spatstat.data_3.0-0 ## [37] survival_3.3-1 zoo_1.8-11 glue_1.6.2 ## [40] polyclip_1.10-4 gtable_0.3.1 leiden_0.4.3 ## [43] future.apply_1.10.0 BiocGenerics_0.44.0 abind_1.4-5 ## [46] scales_1.2.1 mvtnorm_1.1-3 spatstat.random_3.1-3 ## [49] miniUI_0.1.1.1 Rcpp_1.0.10 plotrix_3.8-2 ## [52] metap_1.8 viridisLite_0.4.1 xtable_1.8-4 ## [55] reticulate_1.28 stats4_4.2.0 htmlwidgets_1.6.1 ## [58] httr_1.4.5 RColorBrewer_1.1-3 TFisher_0.2.0 ## [61] ellipsis_0.3.2 ica_1.0-3 farver_2.1.1 ## [64] pkgconfig_2.0.3 sass_0.4.5 uwot_0.1.14 ## [67] deldir_1.0-6 utf8_1.2.3 tidyselect_1.2.0 ## [70] labeling_0.4.2 rlang_1.0.6 reshape2_1.4.4 ## [73] later_1.3.0 munsell_0.5.0 tools_4.2.0 ## [76] cachem_1.0.7 cli_3.6.0 generics_0.1.3 ## [79] mathjaxr_1.6-0 ggridges_0.5.4 evaluate_0.20 ## [82] stringr_1.5.0 fastmap_1.1.1 yaml_2.3.7 ## [85] ragg_1.2.5 goftest_1.2-3 knitr_1.42 ## [88] fs_1.6.1 fitdistrplus_1.1-8 purrr_1.0.1 ## [91] RANN_2.6.1 pbapply_1.7-0 future_1.31.0 ## [94] nlme_3.1-157 mime_0.12 formatR_1.14 ## [97] compiler_4.2.0 plotly_4.10.1 png_0.1-8 ## [100] spatstat.utils_3.0-1 tibble_3.1.8 bslib_0.4.2 ## [103] stringi_1.7.12 highr_0.10 desc_1.4.2 ## [106] lattice_0.20-45 Matrix_1.5-3 multtest_2.54.0 ## [109] vctrs_0.5.2 mutoss_0.1-12 pillar_1.8.1 ## [112] lifecycle_1.0.3 Rdpack_2.4 spatstat.geom_3.0-6 ## [115] lmtest_0.9-40 jquerylib_0.1.4 RcppAnnoy_0.0.20 ## [118] data.table_1.14.8 irlba_2.3.5.1 httpuv_1.6.9 ## [121] R6_2.5.1 promises_1.2.0.1 KernSmooth_2.23-20 ## [124] gridExtra_2.3 parallelly_1.34.0 codetools_0.2-18 ## [127] MASS_7.3-56 rprojroot_2.0.3 withr_2.5.0 ## [130] mnormt_2.1.1 sctransform_0.3.5 multcomp_1.4-22 ## [133] parallel_4.2.0 grid_4.2.0 tidyr_1.3.0 ## [136] rmarkdown_2.20 Rtsne_0.16 spatstat.explore_3.0-6 ## [139] Biobase_2.58.0 numDeriv_2016.8-1.1 shiny_1.7.4

Now that the datasets have been integrated, you can follow the previous steps in this vignette identify cell types and cell type-specific responses.Session Info sessionInfo()## R version 4.2.0 (2022-04-22) ## Platform: x86_64-pc-linux-gnu (64-bit) ## Running under: Ubuntu 20.04.5 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/liblapack.so.3 ## ## locale: ## [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C ## [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8 ## [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 ## ## attached base packages: ## [1] stats graphics grDevices utils datasets methods base ## ## other attached packages: ## [1] cowplot_1.1.1 ggplot2_3.4.1 ## [3] patchwork_1.1.2 thp1.eccite.SeuratData_3.1.5 ## [5] stxBrain.SeuratData_0.1.1 ssHippo.SeuratData_3.1.4 ## [7] pbmcsca.SeuratData_3.0.0 pbmcMultiome.SeuratData_0.1.2 ## [9] pbmc3k.SeuratData_3.1.4 panc8.SeuratData_3.0.2 ## [11] ifnb.SeuratData_3.1.0 hcabm40k.SeuratData_3.0.0 ## [13] bmcite.SeuratData_0.3.0 SeuratData_0.2.2 ## [15] SeuratObject_4.1.3 Seurat_4.3.0 ## ## loaded via a namespace (and not attached): ## [1] systemfonts_1.0.4 sn_2.1.0 plyr_1.8.8 ## [4] igraph_1.4.1 lazyeval_0.2.2 sp_1.6-0 ## [7] splines_4.2.0 listenv_0.9.0 scattermore_0.8 ## [10] qqconf_1.3.1 TH.data_1.1-1 digest_0.6.31 ## [13] htmltools_0.5.4 fansi_1.0.4 magrittr_2.0.3 ## [16] memoise_2.0.1 tensor_1.5 cluster_2.1.3 ## [19] ROCR_1.0-11 limma_3.54.1 globals_0.16.2 ## [22] matrixStats_0.63.0 sandwich_3.0-2 pkgdown_2.0.7 ## [25] spatstat.sparse_3.0-0 colorspace_2.1-0 rappdirs_0.3.3 ## [28] ggrepel_0.9.3 rbibutils_2.2.13 textshaping_0.3.6 ## [31] xfun_0.37 dplyr_1.1.0 crayon_1.5.2 ## [34] jsonlite_1.8.4 progressr_0.13.0 spatstat.data_3.0-0 ## [37] survival_3.3-1 zoo_1.8-11 glue_1.6.2 ## [40] polyclip_1.10-4 gtable_0.3.1 leiden_0.4.3 ## [43] future.apply_1.10.0 BiocGenerics_0.44.0 abind_1.4-5 ## [46] scales_1.2.1 mvtnorm_1.1-3 spatstat.random_3.1-3 ## [49] miniUI_0.1.1.1 Rcpp_1.0.10 plotrix_3.8-2 ## [52] metap_1.8 viridisLite_0.4.1 xtable_1.8-4 ## [55] reticulate_1.28 stats4_4.2.0 htmlwidgets_1.6.1 ## [58] httr_1.4.5 RColorBrewer_1.1-3 TFisher_0.2.0 ## [61] ellipsis_0.3.2 ica_1.0-3 farver_2.1.1 ## [64] pkgconfig_2.0.3 sass_0.4.5 uwot_0.1.14 ## [67] deldir_1.0-6 utf8_1.2.3 tidyselect_1.2.0 ## [70] labeling_0.4.2 rlang_1.0.6 reshape2_1.4.4 ## [73] later_1.3.0 munsell_0.5.0 tools_4.2.0 ## [76] cachem_1.0.7 cli_3.6.0 generics_0.1.3 ## [79] mathjaxr_1.6-0 ggridges_0.5.4 evaluate_0.20 ## [82] stringr_1.5.0 fastmap_1.1.1 yaml_2.3.7 ## [85] ragg_1.2.5 goftest_1.2-3 knitr_1.42 ## [88] fs_1.6.1 fitdistrplus_1.1-8 purrr_1.0.1 ## [91] RANN_2.6.1 pbapply_1.7-0 future_1.31.0 ## [94] nlme_3.1-157 mime_0.12 formatR_1.14 ## [97] compiler_4.2.0 plotly_4.10.1 png_0.1-8 ## [100] spatstat.utils_3.0-1 tibble_3.1.8 bslib_0.4.2 ## [103] stringi_1.7.12 highr_0.10 desc_1.4.2 ## [106] lattice_0.20-45 Matrix_1.5-3 multtest_2.54.0 ## [109] vctrs_0.5.2 mutoss_0.1-12 pillar_1.8.1 ## [112] lifecycle_1.0.3 Rdpack_2.4 spatstat.geom_3.0-6 ## [115] lmtest_0.9-40 jquerylib_0.1.4 RcppAnnoy_0.0.20 ## [118] data.table_1.14.8 irlba_2.3.5.1 httpuv_1.6.9 ## [121] R6_2.5.1 promises_1.2.0.1 KernSmooth_2.23-20 ## [124] gridExtra_2.3 parallelly_1.34.0 codetools_0.2-18 ## [127] MASS_7.3-56 rprojroot_2.0.3 withr_2.5.0 ## [130] mnormt_2.1.1 sctransform_0.3.5 multcomp_1.4-22 ## [133] parallel_4.2.0 grid_4.2.0 tidyr_1.3.0 ## [136] rmarkdown_2.20 Rtsne_0.16 spatstat.explore_3.0-6 ## [139] Biobase_2.58.0 numDeriv_2016.8-1.1 shiny_1.7.4

sessionInfo()## R version 4.2.0 (2022-04-22) ## Platform: x86_64-pc-linux-gnu (64-bit) ## Running under: Ubuntu 20.04.5 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/liblapack.so.3 ## ## locale: ## [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C ## [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8 ## [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 ## ## attached base packages: ## [1] stats graphics grDevices utils datasets methods base ## ## other attached packages: ## [1] cowplot_1.1.1 ggplot2_3.4.1 ## [3] patchwork_1.1.2 thp1.eccite.SeuratData_3.1.5 ## [5] stxBrain.SeuratData_0.1.1 ssHippo.SeuratData_3.1.4 ## [7] pbmcsca.SeuratData_3.0.0 pbmcMultiome.SeuratData_0.1.2 ## [9] pbmc3k.SeuratData_3.1.4 panc8.SeuratData_3.0.2 ## [11] ifnb.SeuratData_3.1.0 hcabm40k.SeuratData_3.0.0 ## [13] bmcite.SeuratData_0.3.0 SeuratData_0.2.2 ## [15] SeuratObject_4.1.3 Seurat_4.3.0 ## ## loaded via a namespace (and not attached): ## [1] systemfonts_1.0.4 sn_2.1.0 plyr_1.8.8 ## [4] igraph_1.4.1 lazyeval_0.2.2 sp_1.6-0 ## [7] splines_4.2.0 listenv_0.9.0 scattermore_0.8 ## [10] qqconf_1.3.1 TH.data_1.1-1 digest_0.6.31 ## [13] htmltools_0.5.4 fansi_1.0.4 magrittr_2.0.3 ## [16] memoise_2.0.1 tensor_1.5 cluster_2.1.3 ## [19] ROCR_1.0-11 limma_3.54.1 globals_0.16.2 ## [22] matrixStats_0.63.0 sandwich_3.0-2 pkgdown_2.0.7 ## [25] spatstat.sparse_3.0-0 colorspace_2.1-0 rappdirs_0.3.3 ## [28] ggrepel_0.9.3 rbibutils_2.2.13 textshaping_0.3.6 ## [31] xfun_0.37 dplyr_1.1.0 crayon_1.5.2 ## [34] jsonlite_1.8.4 progressr_0.13.0 spatstat.data_3.0-0 ## [37] survival_3.3-1 zoo_1.8-11 glue_1.6.2 ## [40] polyclip_1.10-4 gtable_0.3.1 leiden_0.4.3 ## [43] future.apply_1.10.0 BiocGenerics_0.44.0 abind_1.4-5 ## [46] scales_1.2.1 mvtnorm_1.1-3 spatstat.random_3.1-3 ## [49] miniUI_0.1.1.1 Rcpp_1.0.10 plotrix_3.8-2 ## [52] metap_1.8 viridisLite_0.4.1 xtable_1.8-4 ## [55] reticulate_1.28 stats4_4.2.0 htmlwidgets_1.6.1 ## [58] httr_1.4.5 RColorBrewer_1.1-3 TFisher_0.2.0 ## [61] ellipsis_0.3.2 ica_1.0-3 farver_2.1.1 ## [64] pkgconfig_2.0.3 sass_0.4.5 uwot_0.1.14 ## [67] deldir_1.0-6 utf8_1.2.3 tidyselect_1.2.0 ## [70] labeling_0.4.2 rlang_1.0.6 reshape2_1.4.4 ## [73] later_1.3.0 munsell_0.5.0 tools_4.2.0 ## [76] cachem_1.0.7 cli_3.6.0 generics_0.1.3 ## [79] mathjaxr_1.6-0 ggridges_0.5.4 evaluate_0.20 ## [82] stringr_1.5.0 fastmap_1.1.1 yaml_2.3.7 ## [85] ragg_1.2.5 goftest_1.2-3 knitr_1.42 ## [88] fs_1.6.1 fitdistrplus_1.1-8 purrr_1.0.1 ## [91] RANN_2.6.1 pbapply_1.7-0 future_1.31.0 ## [94] nlme_3.1-157 mime_0.12 formatR_1.14 ## [97] compiler_4.2.0 plotly_4.10.1 png_0.1-8 ## [100] spatstat.utils_3.0-1 tibble_3.1.8 bslib_0.4.2 ## [103] stringi_1.7.12 highr_0.10 desc_1.4.2 ## [106] lattice_0.20-45 Matrix_1.5-3 multtest_2.54.0 ## [109] vctrs_0.5.2 mutoss_0.1-12 pillar_1.8.1 ## [112] lifecycle_1.0.3 Rdpack_2.4 spatstat.geom_3.0-6 ## [115] lmtest_0.9-40 jquerylib_0.1.4 RcppAnnoy_0.0.20 ## [118] data.table_1.14.8 irlba_2.3.5.1 httpuv_1.6.9 ## [121] R6_2.5.1 promises_1.2.0.1 KernSmooth_2.23-20 ## [124] gridExtra_2.3 parallelly_1.34.0 codetools_0.2-18 ## [127] MASS_7.3-56 rprojroot_2.0.3 withr_2.5.0 ## [130] mnormt_2.1.1 sctransform_0.3.5 multcomp_1.4-22 ## [133] parallel_4.2.0 grid_4.2.0 tidyr_1.3.0 ## [136] rmarkdown_2.20 Rtsne_0.16 spatstat.explore_3.0-6 ## [139] Biobase_2.58.0 numDeriv_2016.8-1.1 shiny_1.7.4

Developed by Paul Hoffman, Satija Lab and Collaborators.

Developed by Paul Hoffman, Satija Lab and Collaborators.

Site built with pkgdown 2.0.7.

Site built with pkgdown 2.0.7.

**Examples:**

Example 1 (unknown):
```unknown
vignettes/integration_introduction.Rmd
```

Example 2 (unknown):
```unknown
integration_introduction.Rmd
```

Example 3 (unknown):
```unknown
library(Seurat)
library(SeuratData)
library(patchwork)
```

Example 4 (r):
```r
library(Seurat)
library(SeuratData)
library(patchwork)
```

Example 5 (r):
```r
library(Seurat)
library(SeuratData)
library(patchwork)
```

Example 6 (unknown):
```unknown
# install dataset
InstallData("ifnb")
```

Example 7 (r):
```r
# install dataset
InstallData("ifnb")
```

Example 8 (r):
```r
# install dataset
InstallData("ifnb")
```

Example 9 (javascript):
```javascript
# load dataset
LoadData("ifnb")

# split the dataset into a list of two seurat objects (stim and CTRL)
ifnb.list <- SplitObject(ifnb, split.by = "stim")

# normalize and identify variable features for each dataset independently
ifnb.list <- lapply(X = ifnb.list, FUN = function(x) {
    x <- NormalizeData(x)
    x <- FindVariableFeatures(x, selection.method = "vst", nfeatures = 2000)
})

# select features that are repeatedly variable across datasets for integration
features <- SelectIntegrationFeatures(object.list = ifnb.list)
```

Example 10 (r):
```r
# load dataset
LoadData("ifnb")

# split the dataset into a list of two seurat objects (stim and CTRL)
ifnb.list <- SplitObject(ifnb, split.by = "stim")

# normalize and identify variable features for each dataset independently
ifnb.list <- lapply(X = ifnb.list, FUN = function(x) {
    x <- NormalizeData(x)
    x <- FindVariableFeatures(x, selection.method = "vst", nfeatures = 2000)
})

# select features that are repeatedly variable across datasets for integration
features <- SelectIntegrationFeatures(object.list = ifnb.list)
```

Example 11 (r):
```r
# load dataset
LoadData("ifnb")

# split the dataset into a list of two seurat objects (stim and CTRL)
ifnb.list <- SplitObject(ifnb, split.by = "stim")

# normalize and identify variable features for each dataset independently
ifnb.list <- lapply(X = ifnb.list, FUN = function(x) {
    x <- NormalizeData(x)
    x <- FindVariableFeatures(x, selection.method = "vst", nfeatures = 2000)
})

# select features that are repeatedly variable across datasets for integration
features <- SelectIntegrationFeatures(object.list = ifnb.list)
```

Example 12 (unknown):
```unknown
FindIntegrationAnchors()
```

Example 13 (unknown):
```unknown
IntegrateData()
```

Example 14 (unknown):
```unknown
immune.anchors <- FindIntegrationAnchors(object.list = ifnb.list, anchor.features = features)
```

Example 15 (r):
```r
immune.anchors <- FindIntegrationAnchors(object.list = ifnb.list, anchor.features = features)
```

Example 16 (r):
```r
immune.anchors <- FindIntegrationAnchors(object.list = ifnb.list, anchor.features = features)
```

Example 17 (unknown):
```unknown
# this command creates an 'integrated' data assay
immune.combined <- IntegrateData(anchorset = immune.anchors)
```

Example 18 (r):
```r
# this command creates an 'integrated' data assay
immune.combined <- IntegrateData(anchorset = immune.anchors)
```

Example 19 (r):
```r
# this command creates an 'integrated' data assay
immune.combined <- IntegrateData(anchorset = immune.anchors)
```

Example 20 (unknown):
```unknown
# specify that we will perform downstream analysis on the corrected data note that the
# original unmodified data still resides in the 'RNA' assay
DefaultAssay(immune.combined) <- "integrated"

# Run the standard workflow for visualization and clustering
immune.combined <- ScaleData(immune.combined, verbose = FALSE)
immune.combined <- RunPCA(immune.combined, npcs = 30, verbose = FALSE)
immune.combined <- RunUMAP(immune.combined, reduction = "pca", dims = 1:30)
immune.combined <- FindNeighbors(immune.combined, reduction = "pca", dims = 1:30)
immune.combined <- FindClusters(immune.combined, resolution = 0.5)
```

Example 21 (r):
```r
# specify that we will perform downstream analysis on the corrected data note that the
# original unmodified data still resides in the 'RNA' assay
DefaultAssay(immune.combined) <- "integrated"

# Run the standard workflow for visualization and clustering
immune.combined <- ScaleData(immune.combined, verbose = FALSE)
immune.combined <- RunPCA(immune.combined, npcs = 30, verbose = FALSE)
immune.combined <- RunUMAP(immune.combined, reduction = "pca", dims = 1:30)
immune.combined <- FindNeighbors(immune.combined, reduction = "pca", dims = 1:30)
immune.combined <- FindClusters(immune.combined, resolution = 0.5)
```

Example 22 (r):
```r
# specify that we will perform downstream analysis on the corrected data note that the
# original unmodified data still resides in the 'RNA' assay
DefaultAssay(immune.combined) <- "integrated"

# Run the standard workflow for visualization and clustering
immune.combined <- ScaleData(immune.combined, verbose = FALSE)
immune.combined <- RunPCA(immune.combined, npcs = 30, verbose = FALSE)
immune.combined <- RunUMAP(immune.combined, reduction = "pca", dims = 1:30)
immune.combined <- FindNeighbors(immune.combined, reduction = "pca", dims = 1:30)
immune.combined <- FindClusters(immune.combined, resolution = 0.5)
```

Example 23 (unknown):
```unknown
# Visualization
p1 <- DimPlot(immune.combined, reduction = "umap", group.by = "stim")
p2 <- DimPlot(immune.combined, reduction = "umap", label = TRUE, repel = TRUE)
p1 + p2
```

Example 24 (r):
```r
# Visualization
p1 <- DimPlot(immune.combined, reduction = "umap", group.by = "stim")
p2 <- DimPlot(immune.combined, reduction = "umap", label = TRUE, repel = TRUE)
p1 + p2
```

Example 25 (r):
```r
# Visualization
p1 <- DimPlot(immune.combined, reduction = "umap", group.by = "stim")
p2 <- DimPlot(immune.combined, reduction = "umap", label = TRUE, repel = TRUE)
p1 + p2
```

Example 26 (unknown):
```unknown
DimPlot(immune.combined, reduction = "umap", split.by = "stim")
```

Example 27 (r):
```r
DimPlot(immune.combined, reduction = "umap", split.by = "stim")
```

Example 28 (r):
```r
DimPlot(immune.combined, reduction = "umap", split.by = "stim")
```

Example 29 (unknown):
```unknown
FindConservedMarkers()
```

Example 30 (unknown):
```unknown
# For performing differential expression after integration, we switch back to the original
# data
DefaultAssay(immune.combined) <- "RNA"
nk.markers <- FindConservedMarkers(immune.combined, ident.1 = 6, grouping.var = "stim", verbose = FALSE)
head(nk.markers)
```

Example 31 (r):
```r
# For performing differential expression after integration, we switch back to the original
# data
DefaultAssay(immune.combined) <- "RNA"
nk.markers <- FindConservedMarkers(immune.combined, ident.1 = 6, grouping.var = "stim", verbose = FALSE)
head(nk.markers)
```

Example 32 (r):
```r
# For performing differential expression after integration, we switch back to the original
# data
DefaultAssay(immune.combined) <- "RNA"
nk.markers <- FindConservedMarkers(immune.combined, ident.1 = 6, grouping.var = "stim", verbose = FALSE)
head(nk.markers)
```

Example 33 (unknown):
```unknown
##        CTRL_p_val CTRL_avg_log2FC CTRL_pct.1 CTRL_pct.2 CTRL_p_val_adj
## GNLY            0        6.006173      0.944      0.045              0
## FGFBP2          0        3.243588      0.505      0.020              0
## CLIC3           0        3.461957      0.597      0.024              0
## PRF1            0        2.650548      0.422      0.017              0
## CTSW            0        2.987507      0.531      0.029              0
## KLRD1           0        2.777231      0.495      0.019              0
##           STIM_p_val STIM_avg_log2FC STIM_pct.1 STIM_pct.2 STIM_p_val_adj
## GNLY    0.000000e+00        5.858634      0.954      0.059   0.000000e+00
## FGFBP2 3.408448e-165        2.191113      0.261      0.015  4.789892e-161
## CLIC3   0.000000e+00        3.536367      0.623      0.030   0.000000e+00
## PRF1    0.000000e+00        4.094579      0.862      0.057   0.000000e+00
## CTSW    0.000000e+00        3.128054      0.592      0.035   0.000000e+00
## KLRD1   0.000000e+00        2.863797      0.552      0.027   0.000000e+00
##             max_pval minimump_p_val
## GNLY    0.000000e+00              0
## FGFBP2 3.408448e-165              0
## CLIC3   0.000000e+00              0
## PRF1    0.000000e+00              0
## CTSW    0.000000e+00              0
## KLRD1   0.000000e+00              0
```

Example 34 (unknown):
```unknown
##        CTRL_p_val CTRL_avg_log2FC CTRL_pct.1 CTRL_pct.2 CTRL_p_val_adj
## GNLY            0        6.006173      0.944      0.045              0
## FGFBP2          0        3.243588      0.505      0.020              0
## CLIC3           0        3.461957      0.597      0.024              0
## PRF1            0        2.650548      0.422      0.017              0
## CTSW            0        2.987507      0.531      0.029              0
## KLRD1           0        2.777231      0.495      0.019              0
##           STIM_p_val STIM_avg_log2FC STIM_pct.1 STIM_pct.2 STIM_p_val_adj
## GNLY    0.000000e+00        5.858634      0.954      0.059   0.000000e+00
## FGFBP2 3.408448e-165        2.191113      0.261      0.015  4.789892e-161
## CLIC3   0.000000e+00        3.536367      0.623      0.030   0.000000e+00
## PRF1    0.000000e+00        4.094579      0.862      0.057   0.000000e+00
## CTSW    0.000000e+00        3.128054      0.592      0.035   0.000000e+00
## KLRD1   0.000000e+00        2.863797      0.552      0.027   0.000000e+00
##             max_pval minimump_p_val
## GNLY    0.000000e+00              0
## FGFBP2 3.408448e-165              0
## CLIC3   0.000000e+00              0
## PRF1    0.000000e+00              0
## CTSW    0.000000e+00              0
## KLRD1   0.000000e+00              0
```

Example 35 (unknown):
```unknown
FeaturePlot(immune.combined, features = c("CD3D", "SELL", "CREM", "CD8A", "GNLY", "CD79A", "FCGR3A",
    "CCL2", "PPBP"), min.cutoff = "q9")
```

Example 36 (r):
```r
FeaturePlot(immune.combined, features = c("CD3D", "SELL", "CREM", "CD8A", "GNLY", "CD79A", "FCGR3A",
    "CCL2", "PPBP"), min.cutoff = "q9")
```

Example 37 (r):
```r
FeaturePlot(immune.combined, features = c("CD3D", "SELL", "CREM", "CD8A", "GNLY", "CD79A", "FCGR3A",
    "CCL2", "PPBP"), min.cutoff = "q9")
```

Example 38 (unknown):
```unknown
immune.combined <- RenameIdents(immune.combined, `0` = "CD14 Mono", `1` = "CD4 Naive T", `2` = "CD4 Memory T",
    `3` = "CD16 Mono", `4` = "B", `5` = "CD8 T", `6` = "NK", `7` = "T activated", `8` = "DC", `9` = "B Activated",
    `10` = "Mk", `11` = "pDC", `12` = "Eryth", `13` = "Mono/Mk Doublets", `14` = "HSPC")
DimPlot(immune.combined, label = TRUE)
```

Example 39 (r):
```r
immune.combined <- RenameIdents(immune.combined, `0` = "CD14 Mono", `1` = "CD4 Naive T", `2` = "CD4 Memory T",
    `3` = "CD16 Mono", `4` = "B", `5` = "CD8 T", `6` = "NK", `7` = "T activated", `8` = "DC", `9` = "B Activated",
    `10` = "Mk", `11` = "pDC", `12` = "Eryth", `13` = "Mono/Mk Doublets", `14` = "HSPC")
DimPlot(immune.combined, label = TRUE)
```

Example 40 (r):
```r
immune.combined <- RenameIdents(immune.combined, `0` = "CD14 Mono", `1` = "CD4 Naive T", `2` = "CD4 Memory T",
    `3` = "CD16 Mono", `4` = "B", `5` = "CD8 T", `6` = "NK", `7` = "T activated", `8` = "DC", `9` = "B Activated",
    `10` = "Mk", `11` = "pDC", `12` = "Eryth", `13` = "Mono/Mk Doublets", `14` = "HSPC")
DimPlot(immune.combined, label = TRUE)
```

Example 41 (unknown):
```unknown
Idents(immune.combined) <- factor(Idents(immune.combined), levels = c("HSPC", "Mono/Mk Doublets",
    "pDC", "Eryth", "Mk", "DC", "CD14 Mono", "CD16 Mono", "B Activated", "B", "CD8 T", "NK", "T activated",
    "CD4 Naive T", "CD4 Memory T"))
markers.to.plot <- c("CD3D", "CREM", "HSPH1", "SELL", "GIMAP5", "CACYBP", "GNLY", "NKG7", "CCL5",
    "CD8A", "MS4A1", "CD79A", "MIR155HG", "NME1", "FCGR3A", "VMO1", "CCL2", "S100A9", "HLA-DQA1",
    "GPR183", "PPBP", "GNG11", "HBA2", "HBB", "TSPAN13", "IL3RA", "IGJ", "PRSS57")
DotPlot(immune.combined, features = markers.to.plot, cols = c("blue", "red"), dot.scale = 8, split.by = "stim") +
    RotatedAxis()
```

Example 42 (r):
```r
Idents(immune.combined) <- factor(Idents(immune.combined), levels = c("HSPC", "Mono/Mk Doublets",
    "pDC", "Eryth", "Mk", "DC", "CD14 Mono", "CD16 Mono", "B Activated", "B", "CD8 T", "NK", "T activated",
    "CD4 Naive T", "CD4 Memory T"))
markers.to.plot <- c("CD3D", "CREM", "HSPH1", "SELL", "GIMAP5", "CACYBP", "GNLY", "NKG7", "CCL5",
    "CD8A", "MS4A1", "CD79A", "MIR155HG", "NME1", "FCGR3A", "VMO1", "CCL2", "S100A9", "HLA-DQA1",
    "GPR183", "PPBP", "GNG11", "HBA2", "HBB", "TSPAN13", "IL3RA", "IGJ", "PRSS57")
DotPlot(immune.combined, features = markers.to.plot, cols = c("blue", "red"), dot.scale = 8, split.by = "stim") +
    RotatedAxis()
```

Example 43 (r):
```r
Idents(immune.combined) <- factor(Idents(immune.combined), levels = c("HSPC", "Mono/Mk Doublets",
    "pDC", "Eryth", "Mk", "DC", "CD14 Mono", "CD16 Mono", "B Activated", "B", "CD8 T", "NK", "T activated",
    "CD4 Naive T", "CD4 Memory T"))
markers.to.plot <- c("CD3D", "CREM", "HSPH1", "SELL", "GIMAP5", "CACYBP", "GNLY", "NKG7", "CCL5",
    "CD8A", "MS4A1", "CD79A", "MIR155HG", "NME1", "FCGR3A", "VMO1", "CCL2", "S100A9", "HLA-DQA1",
    "GPR183", "PPBP", "GNG11", "HBA2", "HBB", "TSPAN13", "IL3RA", "IGJ", "PRSS57")
DotPlot(immune.combined, features = markers.to.plot, cols = c("blue", "red"), dot.scale = 8, split.by = "stim") +
    RotatedAxis()
```

Example 44 (unknown):
```unknown
library(ggplot2)
library(cowplot)
theme_set(theme_cowplot())
t.cells <- subset(immune.combined, idents = "CD4 Naive T")
Idents(t.cells) <- "stim"
avg.t.cells <- as.data.frame(log1p(AverageExpression(t.cells, verbose = FALSE)$RNA))
avg.t.cells$gene <- rownames(avg.t.cells)

cd14.mono <- subset(immune.combined, idents = "CD14 Mono")
Idents(cd14.mono) <- "stim"
avg.cd14.mono <- as.data.frame(log1p(AverageExpression(cd14.mono, verbose = FALSE)$RNA))
avg.cd14.mono$gene <- rownames(avg.cd14.mono)

genes.to.label = c("ISG15", "LY6E", "IFI6", "ISG20", "MX1", "IFIT2", "IFIT1", "CXCL10", "CCL8")
p1 <- ggplot(avg.t.cells, aes(CTRL, STIM)) + geom_point() + ggtitle("CD4 Naive T Cells")
p1 <- LabelPoints(plot = p1, points = genes.to.label, repel = TRUE)
p2 <- ggplot(avg.cd14.mono, aes(CTRL, STIM)) + geom_point() + ggtitle("CD14 Monocytes")
p2 <- LabelPoints(plot = p2, points = genes.to.label, repel = TRUE)
p1 + p2
```

Example 45 (r):
```r
library(ggplot2)
library(cowplot)
theme_set(theme_cowplot())
t.cells <- subset(immune.combined, idents = "CD4 Naive T")
Idents(t.cells) <- "stim"
avg.t.cells <- as.data.frame(log1p(AverageExpression(t.cells, verbose = FALSE)$RNA))
avg.t.cells$gene <- rownames(avg.t.cells)

cd14.mono <- subset(immune.combined, idents = "CD14 Mono")
Idents(cd14.mono) <- "stim"
avg.cd14.mono <- as.data.frame(log1p(AverageExpression(cd14.mono, verbose = FALSE)$RNA))
avg.cd14.mono$gene <- rownames(avg.cd14.mono)

genes.to.label = c("ISG15", "LY6E", "IFI6", "ISG20", "MX1", "IFIT2", "IFIT1", "CXCL10", "CCL8")
p1 <- ggplot(avg.t.cells, aes(CTRL, STIM)) + geom_point() + ggtitle("CD4 Naive T Cells")
p1 <- LabelPoints(plot = p1, points = genes.to.label, repel = TRUE)
p2 <- ggplot(avg.cd14.mono, aes(CTRL, STIM)) + geom_point() + ggtitle("CD14 Monocytes")
p2 <- LabelPoints(plot = p2, points = genes.to.label, repel = TRUE)
p1 + p2
```

Example 46 (r):
```r
library(ggplot2)
library(cowplot)
theme_set(theme_cowplot())
t.cells <- subset(immune.combined, idents = "CD4 Naive T")
Idents(t.cells) <- "stim"
avg.t.cells <- as.data.frame(log1p(AverageExpression(t.cells, verbose = FALSE)$RNA))
avg.t.cells$gene <- rownames(avg.t.cells)

cd14.mono <- subset(immune.combined, idents = "CD14 Mono")
Idents(cd14.mono) <- "stim"
avg.cd14.mono <- as.data.frame(log1p(AverageExpression(cd14.mono, verbose = FALSE)$RNA))
avg.cd14.mono$gene <- rownames(avg.cd14.mono)

genes.to.label = c("ISG15", "LY6E", "IFI6", "ISG20", "MX1", "IFIT2", "IFIT1", "CXCL10", "CCL8")
p1 <- ggplot(avg.t.cells, aes(CTRL, STIM)) + geom_point() + ggtitle("CD4 Naive T Cells")
p1 <- LabelPoints(plot = p1, points = genes.to.label, repel = TRUE)
p2 <- ggplot(avg.cd14.mono, aes(CTRL, STIM)) + geom_point() + ggtitle("CD14 Monocytes")
p2 <- LabelPoints(plot = p2, points = genes.to.label, repel = TRUE)
p1 + p2
```

Example 47 (unknown):
```unknown
FindMarkers()
```

Example 48 (unknown):
```unknown
immune.combined$celltype.stim <- paste(Idents(immune.combined), immune.combined$stim, sep = "_")
immune.combined$celltype <- Idents(immune.combined)
Idents(immune.combined) <- "celltype.stim"
b.interferon.response <- FindMarkers(immune.combined, ident.1 = "B_STIM", ident.2 = "B_CTRL", verbose = FALSE)
head(b.interferon.response, n = 15)
```

Example 49 (r):
```r
immune.combined$celltype.stim <- paste(Idents(immune.combined), immune.combined$stim, sep = "_")
immune.combined$celltype <- Idents(immune.combined)
Idents(immune.combined) <- "celltype.stim"
b.interferon.response <- FindMarkers(immune.combined, ident.1 = "B_STIM", ident.2 = "B_CTRL", verbose = FALSE)
head(b.interferon.response, n = 15)
```

Example 50 (r):
```r
immune.combined$celltype.stim <- paste(Idents(immune.combined), immune.combined$stim, sep = "_")
immune.combined$celltype <- Idents(immune.combined)
Idents(immune.combined) <- "celltype.stim"
b.interferon.response <- FindMarkers(immune.combined, ident.1 = "B_STIM", ident.2 = "B_CTRL", verbose = FALSE)
head(b.interferon.response, n = 15)
```

Example 51 (unknown):
```unknown
##                 p_val avg_log2FC pct.1 pct.2     p_val_adj
## ISG15   1.212995e-155  4.5997247 0.998 0.239 1.704622e-151
## IFIT3   4.743486e-151  4.5017769 0.964 0.052 6.666020e-147
## IFI6    1.680324e-150  4.2361116 0.969 0.080 2.361359e-146
## ISG20   1.595574e-146  2.9452675 1.000 0.671 2.242260e-142
## IFIT1   3.499460e-137  4.1278656 0.910 0.032 4.917791e-133
## MX1     8.571983e-121  3.2876616 0.904 0.115 1.204621e-116
## LY6E    1.359842e-117  3.1251242 0.895 0.152 1.910986e-113
## TNFSF10 4.454596e-110  3.7816677 0.790 0.025 6.260044e-106
## IFIT2   1.290640e-106  3.6584511 0.787 0.035 1.813736e-102
## B2M      2.019314e-95  0.6073495 1.000 1.000  2.837741e-91
## PLSCR1   1.464429e-93  2.8195675 0.794 0.117  2.057961e-89
## IRF7     3.893097e-92  2.5867694 0.837 0.190  5.470969e-88
## CXCL10   1.624151e-82  5.2608266 0.640 0.010  2.282419e-78
## UBE2L6   2.482113e-81  2.1450306 0.852 0.299  3.488114e-77
## PSMB9    5.977328e-77  1.6457686 0.940 0.571  8.399938e-73
```

Example 52 (unknown):
```unknown
##                 p_val avg_log2FC pct.1 pct.2     p_val_adj
## ISG15   1.212995e-155  4.5997247 0.998 0.239 1.704622e-151
## IFIT3   4.743486e-151  4.5017769 0.964 0.052 6.666020e-147
## IFI6    1.680324e-150  4.2361116 0.969 0.080 2.361359e-146
## ISG20   1.595574e-146  2.9452675 1.000 0.671 2.242260e-142
## IFIT1   3.499460e-137  4.1278656 0.910 0.032 4.917791e-133
## MX1     8.571983e-121  3.2876616 0.904 0.115 1.204621e-116
## LY6E    1.359842e-117  3.1251242 0.895 0.152 1.910986e-113
## TNFSF10 4.454596e-110  3.7816677 0.790 0.025 6.260044e-106
## IFIT2   1.290640e-106  3.6584511 0.787 0.035 1.813736e-102
## B2M      2.019314e-95  0.6073495 1.000 1.000  2.837741e-91
## PLSCR1   1.464429e-93  2.8195675 0.794 0.117  2.057961e-89
## IRF7     3.893097e-92  2.5867694 0.837 0.190  5.470969e-88
## CXCL10   1.624151e-82  5.2608266 0.640 0.010  2.282419e-78
## UBE2L6   2.482113e-81  2.1450306 0.852 0.299  3.488114e-77
## PSMB9    5.977328e-77  1.6457686 0.940 0.571  8.399938e-73
```

Example 53 (unknown):
```unknown
FeaturePlot()
```

Example 54 (unknown):
```unknown
FeaturePlot(immune.combined, features = c("CD3D", "GNLY", "IFI6"), split.by = "stim", max.cutoff = 3,
    cols = c("grey", "red"))
```

Example 55 (r):
```r
FeaturePlot(immune.combined, features = c("CD3D", "GNLY", "IFI6"), split.by = "stim", max.cutoff = 3,
    cols = c("grey", "red"))
```

Example 56 (r):
```r
FeaturePlot(immune.combined, features = c("CD3D", "GNLY", "IFI6"), split.by = "stim", max.cutoff = 3,
    cols = c("grey", "red"))
```

Example 57 (unknown):
```unknown
plots <- VlnPlot(immune.combined, features = c("LYZ", "ISG15", "CXCL10"), split.by = "stim", group.by = "celltype",
    pt.size = 0, combine = FALSE)
wrap_plots(plots = plots, ncol = 1)
```

Example 58 (r):
```r
plots <- VlnPlot(immune.combined, features = c("LYZ", "ISG15", "CXCL10"), split.by = "stim", group.by = "celltype",
    pt.size = 0, combine = FALSE)
wrap_plots(plots = plots, ncol = 1)
```

Example 59 (r):
```r
plots <- VlnPlot(immune.combined, features = c("LYZ", "ISG15", "CXCL10"), split.by = "stim", group.by = "celltype",
    pt.size = 0, combine = FALSE)
wrap_plots(plots = plots, ncol = 1)
```

Example 60 (unknown):
```unknown
SCTransform()
```

Example 61 (unknown):
```unknown
NormalizeData()
```

Example 62 (unknown):
```unknown
PrepSCTIntegration()
```

Example 63 (unknown):
```unknown
FindIntegrationAnchors()
```

Example 64 (unknown):
```unknown
IntegrateData()
```

Example 65 (unknown):
```unknown
normalization.method
```

Example 66 (unknown):
```unknown
ScaleData()
```

Example 67 (unknown):
```unknown
LoadData("ifnb")
ifnb.list <- SplitObject(ifnb, split.by = "stim")
ifnb.list <- lapply(X = ifnb.list, FUN = SCTransform)
features <- SelectIntegrationFeatures(object.list = ifnb.list, nfeatures = 3000)
ifnb.list <- PrepSCTIntegration(object.list = ifnb.list, anchor.features = features)
```

Example 68 (r):
```r
LoadData("ifnb")
ifnb.list <- SplitObject(ifnb, split.by = "stim")
ifnb.list <- lapply(X = ifnb.list, FUN = SCTransform)
features <- SelectIntegrationFeatures(object.list = ifnb.list, nfeatures = 3000)
ifnb.list <- PrepSCTIntegration(object.list = ifnb.list, anchor.features = features)
```

Example 69 (r):
```r
LoadData("ifnb")
ifnb.list <- SplitObject(ifnb, split.by = "stim")
ifnb.list <- lapply(X = ifnb.list, FUN = SCTransform)
features <- SelectIntegrationFeatures(object.list = ifnb.list, nfeatures = 3000)
ifnb.list <- PrepSCTIntegration(object.list = ifnb.list, anchor.features = features)
```

Example 70 (unknown):
```unknown
immune.anchors <- FindIntegrationAnchors(object.list = ifnb.list, normalization.method = "SCT",
    anchor.features = features)
immune.combined.sct <- IntegrateData(anchorset = immune.anchors, normalization.method = "SCT")
```

Example 71 (r):
```r
immune.anchors <- FindIntegrationAnchors(object.list = ifnb.list, normalization.method = "SCT",
    anchor.features = features)
immune.combined.sct <- IntegrateData(anchorset = immune.anchors, normalization.method = "SCT")
```

Example 72 (r):
```r
immune.anchors <- FindIntegrationAnchors(object.list = ifnb.list, normalization.method = "SCT",
    anchor.features = features)
immune.combined.sct <- IntegrateData(anchorset = immune.anchors, normalization.method = "SCT")
```

Example 73 (unknown):
```unknown
immune.combined.sct <- RunPCA(immune.combined.sct, verbose = FALSE)
immune.combined.sct <- RunUMAP(immune.combined.sct, reduction = "pca", dims = 1:30)
```

Example 74 (r):
```r
immune.combined.sct <- RunPCA(immune.combined.sct, verbose = FALSE)
immune.combined.sct <- RunUMAP(immune.combined.sct, reduction = "pca", dims = 1:30)
```

Example 75 (r):
```r
immune.combined.sct <- RunPCA(immune.combined.sct, verbose = FALSE)
immune.combined.sct <- RunUMAP(immune.combined.sct, reduction = "pca", dims = 1:30)
```

Example 76 (unknown):
```unknown
p1 <- DimPlot(immune.combined.sct, reduction = "umap", group.by = "stim")
p2 <- DimPlot(immune.combined.sct, reduction = "umap", group.by = "seurat_annotations", label = TRUE,
    repel = TRUE)
p1 + p2
```

Example 77 (r):
```r
p1 <- DimPlot(immune.combined.sct, reduction = "umap", group.by = "stim")
p2 <- DimPlot(immune.combined.sct, reduction = "umap", group.by = "seurat_annotations", label = TRUE,
    repel = TRUE)
p1 + p2
```

Example 78 (r):
```r
p1 <- DimPlot(immune.combined.sct, reduction = "umap", group.by = "stim")
p2 <- DimPlot(immune.combined.sct, reduction = "umap", group.by = "seurat_annotations", label = TRUE,
    repel = TRUE)
p1 + p2
```

Example 79 (unknown):
```unknown
sessionInfo()
```

Example 80 (r):
```r
sessionInfo()
```

Example 81 (r):
```r
sessionInfo()
```

Example 82 (unknown):
```unknown
## R version 4.2.0 (2022-04-22)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.5 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/liblapack.so.3
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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       
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
##  [1] cowplot_1.1.1                 ggplot2_3.4.1                
##  [3] patchwork_1.1.2               thp1.eccite.SeuratData_3.1.5 
##  [5] stxBrain.SeuratData_0.1.1     ssHippo.SeuratData_3.1.4     
##  [7] pbmcsca.SeuratData_3.0.0      pbmcMultiome.SeuratData_0.1.2
##  [9] pbmc3k.SeuratData_3.1.4       panc8.SeuratData_3.0.2       
## [11] ifnb.SeuratData_3.1.0         hcabm40k.SeuratData_3.0.0    
## [13] bmcite.SeuratData_0.3.0       SeuratData_0.2.2             
## [15] SeuratObject_4.1.3            Seurat_4.3.0                 
## 
## loaded via a namespace (and not attached):
##   [1] systemfonts_1.0.4      sn_2.1.0               plyr_1.8.8            
##   [4] igraph_1.4.1           lazyeval_0.2.2         sp_1.6-0              
##   [7] splines_4.2.0          listenv_0.9.0          scattermore_0.8       
##  [10] qqconf_1.3.1           TH.data_1.1-1          digest_0.6.31         
##  [13] htmltools_0.5.4        fansi_1.0.4            magrittr_2.0.3        
##  [16] memoise_2.0.1          tensor_1.5             cluster_2.1.3         
##  [19] ROCR_1.0-11            limma_3.54.1           globals_0.16.2        
##  [22] matrixStats_0.63.0     sandwich_3.0-2         pkgdown_2.0.7         
##  [25] spatstat.sparse_3.0-0  colorspace_2.1-0       rappdirs_0.3.3        
##  [28] ggrepel_0.9.3          rbibutils_2.2.13       textshaping_0.3.6     
##  [31] xfun_0.37              dplyr_1.1.0            crayon_1.5.2          
##  [34] jsonlite_1.8.4         progressr_0.13.0       spatstat.data_3.0-0   
##  [37] survival_3.3-1         zoo_1.8-11             glue_1.6.2            
##  [40] polyclip_1.10-4        gtable_0.3.1           leiden_0.4.3          
##  [43] future.apply_1.10.0    BiocGenerics_0.44.0    abind_1.4-5           
##  [46] scales_1.2.1           mvtnorm_1.1-3          spatstat.random_3.1-3 
##  [49] miniUI_0.1.1.1         Rcpp_1.0.10            plotrix_3.8-2         
##  [52] metap_1.8              viridisLite_0.4.1      xtable_1.8-4          
##  [55] reticulate_1.28        stats4_4.2.0           htmlwidgets_1.6.1     
##  [58] httr_1.4.5             RColorBrewer_1.1-3     TFisher_0.2.0         
##  [61] ellipsis_0.3.2         ica_1.0-3              farver_2.1.1          
##  [64] pkgconfig_2.0.3        sass_0.4.5             uwot_0.1.14           
##  [67] deldir_1.0-6           utf8_1.2.3             tidyselect_1.2.0      
##  [70] labeling_0.4.2         rlang_1.0.6            reshape2_1.4.4        
##  [73] later_1.3.0            munsell_0.5.0          tools_4.2.0           
##  [76] cachem_1.0.7           cli_3.6.0              generics_0.1.3        
##  [79] mathjaxr_1.6-0         ggridges_0.5.4         evaluate_0.20         
##  [82] stringr_1.5.0          fastmap_1.1.1          yaml_2.3.7            
##  [85] ragg_1.2.5             goftest_1.2-3          knitr_1.42            
##  [88] fs_1.6.1               fitdistrplus_1.1-8     purrr_1.0.1           
##  [91] RANN_2.6.1             pbapply_1.7-0          future_1.31.0         
##  [94] nlme_3.1-157           mime_0.12              formatR_1.14          
##  [97] compiler_4.2.0         plotly_4.10.1          png_0.1-8             
## [100] spatstat.utils_3.0-1   tibble_3.1.8           bslib_0.4.2           
## [103] stringi_1.7.12         highr_0.10             desc_1.4.2            
## [106] lattice_0.20-45        Matrix_1.5-3           multtest_2.54.0       
## [109] vctrs_0.5.2            mutoss_0.1-12          pillar_1.8.1          
## [112] lifecycle_1.0.3        Rdpack_2.4             spatstat.geom_3.0-6   
## [115] lmtest_0.9-40          jquerylib_0.1.4        RcppAnnoy_0.0.20      
## [118] data.table_1.14.8      irlba_2.3.5.1          httpuv_1.6.9          
## [121] R6_2.5.1               promises_1.2.0.1       KernSmooth_2.23-20    
## [124] gridExtra_2.3          parallelly_1.34.0      codetools_0.2-18      
## [127] MASS_7.3-56            rprojroot_2.0.3        withr_2.5.0           
## [130] mnormt_2.1.1           sctransform_0.3.5      multcomp_1.4-22       
## [133] parallel_4.2.0         grid_4.2.0             tidyr_1.3.0           
## [136] rmarkdown_2.20         Rtsne_0.16             spatstat.explore_3.0-6
## [139] Biobase_2.58.0         numDeriv_2016.8-1.1    shiny_1.7.4
```

Example 83 (unknown):
```unknown
## R version 4.2.0 (2022-04-22)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.5 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/liblapack.so.3
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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       
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
##  [1] cowplot_1.1.1                 ggplot2_3.4.1                
##  [3] patchwork_1.1.2               thp1.eccite.SeuratData_3.1.5 
##  [5] stxBrain.SeuratData_0.1.1     ssHippo.SeuratData_3.1.4     
##  [7] pbmcsca.SeuratData_3.0.0      pbmcMultiome.SeuratData_0.1.2
##  [9] pbmc3k.SeuratData_3.1.4       panc8.SeuratData_3.0.2       
## [11] ifnb.SeuratData_3.1.0         hcabm40k.SeuratData_3.0.0    
## [13] bmcite.SeuratData_0.3.0       SeuratData_0.2.2             
## [15] SeuratObject_4.1.3            Seurat_4.3.0                 
## 
## loaded via a namespace (and not attached):
##   [1] systemfonts_1.0.4      sn_2.1.0               plyr_1.8.8            
##   [4] igraph_1.4.1           lazyeval_0.2.2         sp_1.6-0              
##   [7] splines_4.2.0          listenv_0.9.0          scattermore_0.8       
##  [10] qqconf_1.3.1           TH.data_1.1-1          digest_0.6.31         
##  [13] htmltools_0.5.4        fansi_1.0.4            magrittr_2.0.3        
##  [16] memoise_2.0.1          tensor_1.5             cluster_2.1.3         
##  [19] ROCR_1.0-11            limma_3.54.1           globals_0.16.2        
##  [22] matrixStats_0.63.0     sandwich_3.0-2         pkgdown_2.0.7         
##  [25] spatstat.sparse_3.0-0  colorspace_2.1-0       rappdirs_0.3.3        
##  [28] ggrepel_0.9.3          rbibutils_2.2.13       textshaping_0.3.6     
##  [31] xfun_0.37              dplyr_1.1.0            crayon_1.5.2          
##  [34] jsonlite_1.8.4         progressr_0.13.0       spatstat.data_3.0-0   
##  [37] survival_3.3-1         zoo_1.8-11             glue_1.6.2            
##  [40] polyclip_1.10-4        gtable_0.3.1           leiden_0.4.3          
##  [43] future.apply_1.10.0    BiocGenerics_0.44.0    abind_1.4-5           
##  [46] scales_1.2.1           mvtnorm_1.1-3          spatstat.random_3.1-3 
##  [49] miniUI_0.1.1.1         Rcpp_1.0.10            plotrix_3.8-2         
##  [52] metap_1.8              viridisLite_0.4.1      xtable_1.8-4          
##  [55] reticulate_1.28        stats4_4.2.0           htmlwidgets_1.6.1     
##  [58] httr_1.4.5             RColorBrewer_1.1-3     TFisher_0.2.0         
##  [61] ellipsis_0.3.2         ica_1.0-3              farver_2.1.1          
##  [64] pkgconfig_2.0.3        sass_0.4.5             uwot_0.1.14           
##  [67] deldir_1.0-6           utf8_1.2.3             tidyselect_1.2.0      
##  [70] labeling_0.4.2         rlang_1.0.6            reshape2_1.4.4        
##  [73] later_1.3.0            munsell_0.5.0          tools_4.2.0           
##  [76] cachem_1.0.7           cli_3.6.0              generics_0.1.3        
##  [79] mathjaxr_1.6-0         ggridges_0.5.4         evaluate_0.20         
##  [82] stringr_1.5.0          fastmap_1.1.1          yaml_2.3.7            
##  [85] ragg_1.2.5             goftest_1.2-3          knitr_1.42            
##  [88] fs_1.6.1               fitdistrplus_1.1-8     purrr_1.0.1           
##  [91] RANN_2.6.1             pbapply_1.7-0          future_1.31.0         
##  [94] nlme_3.1-157           mime_0.12              formatR_1.14          
##  [97] compiler_4.2.0         plotly_4.10.1          png_0.1-8             
## [100] spatstat.utils_3.0-1   tibble_3.1.8           bslib_0.4.2           
## [103] stringi_1.7.12         highr_0.10             desc_1.4.2            
## [106] lattice_0.20-45        Matrix_1.5-3           multtest_2.54.0       
## [109] vctrs_0.5.2            mutoss_0.1-12          pillar_1.8.1          
## [112] lifecycle_1.0.3        Rdpack_2.4             spatstat.geom_3.0-6   
## [115] lmtest_0.9-40          jquerylib_0.1.4        RcppAnnoy_0.0.20      
## [118] data.table_1.14.8      irlba_2.3.5.1          httpuv_1.6.9          
## [121] R6_2.5.1               promises_1.2.0.1       KernSmooth_2.23-20    
## [124] gridExtra_2.3          parallelly_1.34.0      codetools_0.2-18      
## [127] MASS_7.3-56            rprojroot_2.0.3        withr_2.5.0           
## [130] mnormt_2.1.1           sctransform_0.3.5      multcomp_1.4-22       
## [133] parallel_4.2.0         grid_4.2.0             tidyr_1.3.0           
## [136] rmarkdown_2.20         Rtsne_0.16             spatstat.explore_3.0-6
## [139] Biobase_2.58.0         numDeriv_2016.8-1.1    shiny_1.7.4
```

---

## Weighted Nearest Neighbor Analysis • Seurat

**URL:** http://127.0.0.1:9173/seurat/archive/v4.3/weighted_nearest_neighbor_analysis/index.html

**Contents:**
- Weighted Nearest Neighbor Analysis
    - Compiled: March 27, 2023
- WNN analysis of CITE-seq, RNA + ADT
- WNN analysis of 10x Multiome, RNA + ATAC
- Contents

The simultaneous measurement of multiple modalities, known as multimodal analysis, represents an exciting frontier for single-cell genomics and necessitates new computational methods that can define cellular states based on multiple data types. The varying information content of each modality, even across cells in the same dataset, represents a pressing challenge for the analysis and integration of multimodal datasets. In (Hao*, Hao* et al, Cell 2021), we introduce ‘weighted-nearest neighbor’ (WNN) analysis, an unsupervised framework to learn the relative utility of each data type in each cell, enabling an integrative analysis of multiple modalities.This vignette introduces the WNN workflow for the analysis of multimodal single-cell datasets. The workflow consists of three stepsIndependent preprocessing and dimensional reduction of each modality individuallyLearning cell-specific modality ‘weights’, and constructing a WNN graph that integrates the modalitiesDownstream analysis (i.e. visualization, clustering, etc.) of the WNN graphWe demonstrate the use of WNN analysis to two single-cell multimodal technologies: CITE-seq and 10x multiome. We define the cellular states based on both modalities, instead of either individual modality.WNN analysis of CITE-seq, RNA + ADTWe use the CITE-seq dataset from (Stuart*, Butler* et al, Cell 2019), which consists of 30,672 scRNA-seq profiles measured alongside a panel of 25 antibodies from bone marrow. The object contains two assays, RNA and antibody-derived tags (ADT).To run this vignette please install Seurat v4, available on CRAN, and SeuratData, available on GitHub. install.packages("Seurat") library(Seurat) library(SeuratData) library(cowplot) library(dplyr) InstallData("bmcite") bm <- LoadData(ds = "bmcite")We first perform pre-processing and dimensional reduction on both assays independently. We use standard normalization, but you can also use SCTransform or any alternative method. DefaultAssay(bm) <- 'RNA' bm <- NormalizeData(bm) %>% FindVariableFeatures() %>% ScaleData() %>% RunPCA() DefaultAssay(bm) <- 'ADT' # we will use all ADT features for dimensional reduction # we set a dimensional reduction name to avoid overwriting the VariableFeatures(bm) <- rownames(bm[["ADT"]]) bm <- NormalizeData(bm, normalization.method = 'CLR', margin = 2) %>% ScaleData() %>% RunPCA(reduction.name = 'apca')For each cell, we calculate its closest neighbors in the dataset based on a weighted combination of RNA and protein similarities. The cell-specific modality weights and multimodal neighbors are calculated in a single function, which takes ~2 minutes to run on this dataset. We specify the dimensionality of each modality (similar to specifying the number of PCs to include in scRNA-seq clustering), but you can vary these settings to see that small changes have minimal effect on the overall results. # Identify multimodal neighbors. These will be stored in the neighbors slot, # and can be accessed using bm[['weighted.nn']] # The WNN graph can be accessed at bm[["wknn"]], # and the SNN graph used for clustering at bm[["wsnn"]] # Cell-specific modality weights can be accessed at bm$RNA.weight bm <- FindMultiModalNeighbors( bm, reduction.list = list("pca", "apca"), dims.list = list(1:30, 1:18), modality.weight.name = "RNA.weight" )We can now use these results for downstream analysis, such as visualization and clustering. For example, we can create a UMAP visualization of the data based on a weighted combination of RNA and protein data We can also perform graph-based clustering and visualize these results on the UMAP, alongside a set of cell annotations. bm <- RunUMAP(bm, nn.name = "weighted.nn", reduction.name = "wnn.umap", reduction.key = "wnnUMAP_") bm <- FindClusters(bm, graph.name = "wsnn", algorithm = 3, resolution = 2, verbose = FALSE) p1 <- DimPlot(bm, reduction = 'wnn.umap', label = TRUE, repel = TRUE, label.size = 2.5) + NoLegend() p2 <- DimPlot(bm, reduction = 'wnn.umap', group.by = 'celltype.l2', label = TRUE, repel = TRUE, label.size = 2.5) + NoLegend() p1 + p2We can also compute UMAP visualization based on only the RNA and protein data and compare. We find that the RNA analysis is more informative than the ADT analysis in identifying progenitor states (the ADT panel contains markers for differentiated cells), while the converse is true of T cell states (where the ADT analysis outperforms RNA). bm <- RunUMAP(bm, reduction = 'pca', dims = 1:30, assay = 'RNA', reduction.name = 'rna.umap', reduction.key = 'rnaUMAP_') bm <- RunUMAP(bm, reduction = 'apca', dims = 1:18, assay = 'ADT', reduction.name = 'adt.umap', reduction.key = 'adtUMAP_') p3 <- DimPlot(bm, reduction = 'rna.umap', group.by = 'celltype.l2', label = TRUE, repel = TRUE, label.size = 2.5) + NoLegend() p4 <- DimPlot(bm, reduction = 'adt.umap', group.by = 'celltype.l2', label = TRUE, repel = TRUE, label.size = 2.5) + NoLegend() p3 + p4We can visualize the expression of canonical marker genes and proteins on the multimodal UMAP, which can assist in verifying the provided annotations: p5 <- FeaturePlot(bm, features = c("adt_CD45RA","adt_CD16","adt_CD161"), reduction = 'wnn.umap', max.cutoff = 2, cols = c("lightgrey","darkgreen"), ncol = 3) p6 <- FeaturePlot(bm, features = c("rna_TRDC","rna_MPO","rna_AVP"), reduction = 'wnn.umap', max.cutoff = 3, ncol = 3) p5 / p6Finally, we can visualize the modality weights that were learned for each cell. Each of the populations with the highest RNA weights represent progenitor cells, while the populations with the highest protein weights represent T cells. This is in line with our biological expectations, as the antibody panel does not contain markers that can distinguish between different progenitor populations. VlnPlot(bm, features = "RNA.weight", group.by = 'celltype.l2', sort = TRUE, pt.size = 0.1) + NoLegend()WNN analysis of 10x Multiome, RNA + ATACHere, we demonstrate the use of WNN analysis to a second multimodal technology, the 10x multiome RNA+ATAC kit. We use a dataset that is publicly available on the 10x website, where paired transcriptomes and ATAC-seq profiles are measured in 10,412 PBMCs.We use the same WNN methods as we use in the previous tab, where we apply integrated multimodal analysis to a CITE-seq dataset. In this example we will demonstrate how to:Create a multimodal Seurat object with paired transcriptome and ATAC-seq profilesPerform weighted neighbor clustering on RNA+ATAC data in single cellsLeverage both modalities to identify putative regulators of different cell types and statesYou can download the dataset from the 10x Genomics website here. Please make sure to download the following files:Filtered feature barcode matrix (HDF5)ATAC Per fragment information file (TSV.GZ)ATAC Per fragment information index (TSV.GZ index)Finally, in order to run the vignette, make sure the following packages are installed:Seurat v4Signac for the analysis of single-cell chromatin datasetsEnsDb.Hsapiens.v86 for a set of annotations for hg38dplyr to help manipulate data tables library(Seurat) library(Signac) library(EnsDb.Hsapiens.v86) library(dplyr) library(ggplot2)We’ll create a Seurat object based on the gene expression data, and then add in the ATAC-seq data as a second assay. You can explore the Signac getting started vignette for more information on the creation and processing of a ChromatinAssay object. # the 10x hdf5 file contains both data types. inputdata.10x <- Read10X_h5("../data/pbmc_granulocyte_sorted_10k_filtered_feature_bc_matrix.h5") # extract RNA and ATAC data rna_counts <- inputdata.10x$`Gene Expression` atac_counts <- inputdata.10x$Peaks # Create Seurat object pbmc <- CreateSeuratObject(counts = rna_counts) pbmc[["percent.mt"]] <- PercentageFeatureSet(pbmc, pattern = "^MT-") # Now add in the ATAC-seq data # we'll only use peaks in standard chromosomes grange.counts <- StringToGRanges(rownames(atac_counts), sep = c(":", "-")) grange.use <- seqnames(grange.counts) %in% standardChromosomes(grange.counts) atac_counts <- atac_counts[as.vector(grange.use), ] annotations <- GetGRangesFromEnsDb(ensdb = EnsDb.Hsapiens.v86) seqlevelsStyle(annotations) <- 'UCSC' genome(annotations) <- "hg38" frag.file <- "../data/pbmc_granulocyte_sorted_10k_atac_fragments.tsv.gz" chrom_assay <- CreateChromatinAssay( counts = atac_counts, sep = c(":", "-"), genome = 'hg38', fragments = frag.file, min.cells = 10, annotation = annotations ) pbmc[["ATAC"]] <- chrom_assayWe perform basic QC based on the number of detected molecules for each modality as well as mitochondrial percentage. VlnPlot(pbmc, features = c("nCount_ATAC", "nCount_RNA","percent.mt"), ncol = 3, log = TRUE, pt.size = 0) + NoLegend() pbmc <- subset( x = pbmc, subset = nCount_ATAC < 7e4 & nCount_ATAC > 5e3 & nCount_RNA < 25000 & nCount_RNA > 1000 & percent.mt < 20 )We next perform pre-processing and dimensional reduction on both assays independently, using standard approaches for RNA and ATAC-seq data. # RNA analysis DefaultAssay(pbmc) <- "RNA" pbmc <- SCTransform(pbmc, verbose = FALSE) %>% RunPCA() %>% RunUMAP(dims = 1:50, reduction.name = 'umap.rna', reduction.key = 'rnaUMAP_') # ATAC analysis # We exclude the first dimension as this is typically correlated with sequencing depth DefaultAssay(pbmc) <- "ATAC" pbmc <- RunTFIDF(pbmc) pbmc <- FindTopFeatures(pbmc, min.cutoff = 'q0') pbmc <- RunSVD(pbmc) pbmc <- RunUMAP(pbmc, reduction = 'lsi', dims = 2:50, reduction.name = "umap.atac", reduction.key = "atacUMAP_")We calculate a WNN graph, representing a weighted combination of RNA and ATAC-seq modalities. We use this graph for UMAP visualization and clustering pbmc <- FindMultiModalNeighbors(pbmc, reduction.list = list("pca", "lsi"), dims.list = list(1:50, 2:50)) pbmc <- RunUMAP(pbmc, nn.name = "weighted.nn", reduction.name = "wnn.umap", reduction.key = "wnnUMAP_") pbmc <- FindClusters(pbmc, graph.name = "wsnn", algorithm = 3, verbose = FALSE)We annotate the clusters below. Note that you could also annotate the dataset using our supervised mapping pipelines, using either our vignette, or automated web tool, Azimuth. # perform sub-clustering on cluster 6 to find additional structure pbmc <- FindSubCluster(pbmc, cluster = 6, graph.name = "wsnn", algorithm = 3) Idents(pbmc) <- "sub.cluster" # add annotations pbmc <- RenameIdents(pbmc, '19' = 'pDC','20' = 'HSPC','15' = 'cDC') pbmc <- RenameIdents(pbmc, '0' = 'CD14 Mono', '9' ='CD14 Mono', '5' = 'CD16 Mono') pbmc <- RenameIdents(pbmc, '10' = 'Naive B', '11' = 'Intermediate B', '17' = 'Memory B', '21' = 'Plasma') pbmc <- RenameIdents(pbmc, '7' = 'NK') pbmc <- RenameIdents(pbmc, '4' = 'CD4 TCM', '13'= "CD4 TEM", '3' = "CD4 TCM", '16' ="Treg", '1' ="CD4 Naive", '14' = "CD4 Naive") pbmc <- RenameIdents(pbmc, '2' = 'CD8 Naive', '8'= "CD8 Naive", '12' = 'CD8 TEM_1', '6_0' = 'CD8 TEM_2', '6_1' ='CD8 TEM_2', '6_4' ='CD8 TEM_2') pbmc <- RenameIdents(pbmc, '18' = 'MAIT') pbmc <- RenameIdents(pbmc, '6_2' ='gdT', '6_3' = 'gdT') pbmc$celltype <- Idents(pbmc)We can visualize clustering based on gene expression, ATAC-seq, or WNN analysis. The differences are more subtle than in the previous analysis (you can explore the weights, which are more evenly split than in our CITE-seq example), but we find that WNN provides the clearest separation of cell states. p1 <- DimPlot(pbmc, reduction = "umap.rna", group.by = "celltype", label = TRUE, label.size = 2.5, repel = TRUE) + ggtitle("RNA") p2 <- DimPlot(pbmc, reduction = "umap.atac", group.by = "celltype", label = TRUE, label.size = 2.5, repel = TRUE) + ggtitle("ATAC") p3 <- DimPlot(pbmc, reduction = "wnn.umap", group.by = "celltype", label = TRUE, label.size = 2.5, repel = TRUE) + ggtitle("WNN") p1 + p2 + p3 & NoLegend() & theme(plot.title = element_text(hjust = 0.5))For example, the ATAC-seq data assists in the separation of CD4 and CD8 T cell states. This is due to the presence of multiple loci that exhibit differential accessibility between different T cell subtypes. For example, we can visualize ‘pseudobulk’ tracks of the CD8A locus alongside violin plots of gene expression levels, using tools in the Signac visualization vignette. ## to make the visualization easier, subset T cell clusters celltype.names <- levels(pbmc) tcell.names <- grep("CD4|CD8|Treg", celltype.names,value = TRUE) tcells <- subset(pbmc, idents = tcell.names) CoveragePlot(tcells, region = 'CD8A', features = 'CD8A', assay = 'ATAC', expression.assay = 'SCT', peaks = FALSE)Next, we will examine the accessible regions of each cell to determine enriched motifs. As described in the Signac motifs vignette, there are a few ways to do this, but we will use the chromVAR package from the Greenleaf lab. This calculates a per-cell accessibility score for known motifs, and adds these scores as a third assay (chromvar) in the Seurat object.To continue, please make sure you have the following packages installed.chromVAR for the analysis of motif accessibility in scATAC-seqpresto for fast differential expression analyses.TFBSTools for TFBS analysisJASPAR2020 for JASPAR motif modelsmotifmatchr for motif matchingBSgenome.Hsapiens.UCSC.hg38 for chromVARInstall command for all dependencies remotes::install_github("immunogenomics/presto") BiocManager::install(c("chromVAR", "TFBSTools", "JASPAR2020", "motifmatchr", "BSgenome.Hsapiens.UCSC.hg38")) library(chromVAR) library(JASPAR2020) library(TFBSTools) library(motifmatchr) library(BSgenome.Hsapiens.UCSC.hg38) # Scan the DNA sequence of each peak for the presence of each motif, and create a Motif object DefaultAssay(pbmc) <- "ATAC" pwm_set <- getMatrixSet(x = JASPAR2020, opts = list(species = 9606, all_versions = FALSE)) motif.matrix <- CreateMotifMatrix(features = granges(pbmc), pwm = pwm_set, genome = 'hg38', use.counts = FALSE) motif.object <- CreateMotifObject(data = motif.matrix, pwm = pwm_set) pbmc <- SetAssayData(pbmc, assay = 'ATAC', slot = 'motifs', new.data = motif.object) # Note that this step can take 30-60 minutes pbmc <- RunChromVAR( object = pbmc, genome = BSgenome.Hsapiens.UCSC.hg38 )Finally, we explore the multimodal dataset to identify key regulators of each cell state. Paired data provides a unique opportunity to identify transcription factors (TFs) that satisfy multiple criteria, helping to narrow down the list of putative regulators to the most likely candidates. We aim to identify TFs whose expression is enriched in multiple cell types in the RNA measurements, but also have enriched accessibility for their motifs in the ATAC measurements.As an example and positive control, the CCAAT Enhancer Binding Protein (CEBP) family of proteins, including the TF CEBPB, have been repeatedly shown to play important roles in the differentiation and function of myeloid cells including monocytes and dendritic cells. We can see that both the expression of the CEBPB, and the accessibility of the MA0466.2.4 motif (which encodes the binding site for CEBPB), are both enriched in monocytes. #returns MA0466.2 motif.name <- ConvertMotifID(pbmc, name = 'CEBPB') gene_plot <- FeaturePlot(pbmc, features = "sct_CEBPB", reduction = 'wnn.umap') motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap') gene_plot | motif_plotWe’d like to quantify this relationship, and search across all cell types to find similar examples. To do so, we will use the presto package to perform fast differential expression. We run two tests: one using gene expression data, and the other using chromVAR motif accessibilities. presto calculates a p-value based on the Wilcox rank sum test, which is also the default test in Seurat, and we restrict our search to TFs that return significant results in both tests.presto also calculates an “AUC” statistic, which reflects the power of each gene (or motif) to serve as a marker of cell type. A maximum AUC value of 1 indicates a perfect marker. Since the AUC statistic is on the same scale for both genes and motifs, we take the average of the AUC values from the two tests, and use this to rank TFs for each cell type: markers_rna <- presto:::wilcoxauc.Seurat(X = pbmc, group_by = 'celltype', assay = 'data', seurat_assay = 'SCT') markers_motifs <- presto:::wilcoxauc.Seurat(X = pbmc, group_by = 'celltype', assay = 'data', seurat_assay = 'chromvar') motif.names <- markers_motifs$feature colnames(markers_rna) <- paste0("RNA.", colnames(markers_rna)) colnames(markers_motifs) <- paste0("motif.", colnames(markers_motifs)) markers_rna$gene <- markers_rna$RNA.feature markers_motifs$gene <- ConvertMotifID(pbmc, id = motif.names) # a simple function to implement the procedure above topTFs <- function(celltype, padj.cutoff = 1e-2) { ctmarkers_rna <- dplyr::filter( markers_rna, RNA.group == celltype, RNA.padj < padj.cutoff, RNA.logFC > 0) %>% arrange(-RNA.auc) ctmarkers_motif <- dplyr::filter( markers_motifs, motif.group == celltype, motif.padj < padj.cutoff, motif.logFC > 0) %>% arrange(-motif.auc) top_tfs <- inner_join( x = ctmarkers_rna[, c(2, 11, 6, 7)], y = ctmarkers_motif[, c(2, 1, 11, 6, 7)], by = "gene" ) top_tfs$avg_auc <- (top_tfs$RNA.auc + top_tfs$motif.auc) / 2 top_tfs <- arrange(top_tfs, -avg_auc) return(top_tfs) }We can now compute, and visualize, putative regulators for any cell type. We recover well-established regulators, including TBX21 for NK cells, IRF4 for plasma cells, SOX4 for hematopoietic progenitors, EBF1 and PAX5 for B cells, IRF8 and TCF4 for pDC. We believe that similar strategies can be used to help focus on a set of putative regulators in diverse systems. # identify top markers in NK and visualize head(topTFs("NK"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 NK TBX21 0.7270859 0.000000e+00 NK MA0690.1 0.9139614 ## 2 NK EOMES 0.5886774 2.411013e-98 NK MA0800.1 0.9214773 ## 3 NK RUNX3 0.7705661 5.977716e-120 NK MA0684.2 0.6769022 ## motif.pval avg_auc ## 1 1.097940e-202 0.8205237 ## 2 4.903866e-210 0.7550774 ## 3 1.560061e-38 0.7237341 motif.name <- ConvertMotifID(pbmc, name = 'TBX21') gene_plot <- FeaturePlot(pbmc, features = "sct_TBX21", reduction = 'wnn.umap') motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap') gene_plot | motif_plot # identify top markers in pDC and visualize head(topTFs("pDC"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 pDC TCF4 0.9998815 1.120711e-162 pDC MA0830.2 0.9965481 ## 2 pDC IRF8 0.9904457 1.308164e-123 pDC MA0652.1 0.8833112 ## 3 pDC SPIB 0.9115207 0.000000e+00 pDC MA0081.2 0.9068540 ## motif.pval avg_auc ## 1 1.785897e-69 0.9982148 ## 2 3.982413e-42 0.9368785 ## 3 3.083509e-47 0.9091874 motif.name <- ConvertMotifID(pbmc, name = 'TCF4') gene_plot <- FeaturePlot(pbmc, features = "sct_TCF4", reduction = 'wnn.umap') motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap') gene_plot | motif_plot # identify top markers in HSPC and visualize head(topTFs("CD16 Mono"),3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 CD16 Mono SPI1 0.8793172 1.666810e-296 CD16 Mono MA0080.5 0.8880908 ## 2 CD16 Mono CEBPB 0.8685933 1.625472e-294 CD16 Mono MA0466.2 0.7840422 ## 3 CD16 Mono MEF2C 0.7129910 2.727252e-79 CD16 Mono MA0497.1 0.8059373 ## motif.pval avg_auc ## 1 4.762491e-194 0.8837040 ## 2 7.049764e-105 0.8263177 ## 3 2.345716e-121 0.7594641 motif.name <- ConvertMotifID(pbmc, name = 'SPI1') gene_plot <- FeaturePlot(pbmc, features = "sct_SPI1", reduction = 'wnn.umap') motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap') gene_plot | motif_plot # identify top markers in other cell types head(topTFs("Naive B"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 Naive B MEF2C 0.8802747 1.890065e-182 Naive B MA0497.1 0.6789079 ## 2 Naive B PAX5 0.9436648 0.000000e+00 Naive B MA0014.3 0.5827061 ## 3 Naive B POU2F2 0.6029377 2.892216e-13 Naive B MA0507.1 0.8912268 ## motif.pval avg_auc ## 1 9.815118e-32 0.7795913 ## 2 5.995185e-08 0.7631854 ## 3 6.471677e-145 0.7470822 head(topTFs("HSPC"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 HSPC SOX4 0.9869406 5.524832e-71 HSPC MA0867.2 0.6830497 ## 2 HSPC GATA2 0.7884615 0.000000e+00 HSPC MA0036.3 0.8275008 ## 3 HSPC MEIS1 0.8638496 0.000000e+00 HSPC MA0498.2 0.6924225 ## motif.pval avg_auc ## 1 1.241915e-03 0.8349951 ## 2 7.591798e-09 0.8079812 ## 3 6.877492e-04 0.7781361 head(topTFs("Plasma"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 Plasma IRF4 0.8189687 5.261955e-35 Plasma MA1419.1 0.9776046 ## 2 Plasma MEF2C 0.9111213 2.977155e-12 Plasma MA0497.1 0.7596637 ## 3 Plasma TCF4 0.8049409 6.810635e-12 Plasma MA0830.2 0.7840848 ## motif.pval avg_auc ## 1 2.334627e-12 0.8982867 ## 2 1.374353e-04 0.8353925 ## 3 3.028306e-05 0.7945129Session Info sessionInfo()## R version 4.2.0 (2022-04-22) ## Platform: x86_64-pc-linux-gnu (64-bit) ## Running under: Ubuntu 20.04.5 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/liblapack.so.3 ## ## locale: ## [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C ## [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8 ## [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 ## ## attached base packages: ## [1] stats4 stats graphics grDevices utils datasets methods ## [8] base ## ## other attached packages: ## [1] BSgenome.Hsapiens.UCSC.hg38_1.4.5 BSgenome_1.66.3 ## [3] rtracklayer_1.58.0 Biostrings_2.66.0 ## [5] XVector_0.38.0 motifmatchr_1.20.0 ## [7] TFBSTools_1.36.0 JASPAR2020_0.99.10 ## [9] chromVAR_1.20.2 EnsDb.Hsapiens.v86_2.99.0 ## [11] ensembldb_2.22.0 AnnotationFilter_1.22.0 ## [13] GenomicFeatures_1.50.4 AnnotationDbi_1.60.0 ## [15] Biobase_2.58.0 GenomicRanges_1.50.2 ## [17] GenomeInfoDb_1.35.16 IRanges_2.32.0 ## [19] S4Vectors_0.36.2 BiocGenerics_0.44.0 ## [21] Signac_1.9.0 ggplot2_3.4.1 ## [23] dplyr_1.1.1 cowplot_1.1.1 ## [25] thp1.eccite.SeuratData_3.1.5 stxBrain.SeuratData_0.1.1 ## [27] ssHippo.SeuratData_3.1.4 pbmcsca.SeuratData_3.0.0 ## [29] pbmcMultiome.SeuratData_0.1.2 pbmc3k.SeuratData_3.1.4 ## [31] panc8.SeuratData_3.0.2 ifnb.SeuratData_3.1.0 ## [33] hcabm40k.SeuratData_3.0.0 bmcite.SeuratData_0.3.0 ## [35] SeuratData_0.2.2 SeuratObject_4.1.3 ## [37] Seurat_4.2.1.9001 ## ## loaded via a namespace (and not attached): ## [1] rappdirs_0.3.3 scattermore_0.8 ## [3] R.methodsS3_1.8.2 ragg_1.2.5 ## [5] nabor_0.5.0 tidyr_1.3.0 ## [7] bit64_4.0.5 knitr_1.42 ## [9] R.utils_2.12.2 irlba_2.3.5.1 ## [11] DelayedArray_0.24.0 data.table_1.14.8 ## [13] rpart_4.1.16 KEGGREST_1.38.0 ## [15] RCurl_1.98-1.12 generics_0.1.3 ## [17] RSQLite_2.3.0 RANN_2.6.1 ## [19] future_1.32.0 tzdb_0.3.0 ## [21] bit_4.0.5 spatstat.data_3.0-1 ## [23] xml2_1.3.3 httpuv_1.6.9 ## [25] SummarizedExperiment_1.28.0 DirichletMultinomial_1.40.0 ## [27] xfun_0.38 hms_1.1.2 ## [29] jquerylib_0.1.4 evaluate_0.20 ## [31] promises_1.2.0.1 fansi_1.0.4 ## [33] restfulr_0.0.15 progress_1.2.2 ## [35] caTools_1.18.2 dbplyr_2.3.1 ## [37] igraph_1.4.1 DBI_1.1.3 ## [39] htmlwidgets_1.6.2 spatstat.geom_3.1-0 ## [41] purrr_1.0.1 ellipsis_0.3.2 ## [43] backports_1.4.1 annotate_1.76.0 ## [45] biomaRt_2.54.0 deldir_1.0-6 ## [47] MatrixGenerics_1.10.0 vctrs_0.6.1 ## [49] ROCR_1.0-11 abind_1.4-5 ## [51] cachem_1.0.7 withr_2.5.0 ## [53] progressr_0.13.0 presto_1.0.0 ## [55] checkmate_2.1.0 sctransform_0.3.5 ## [57] GenomicAlignments_1.34.0 prettyunits_1.1.1 ## [59] goftest_1.2-3 cluster_2.1.3 ## [61] seqLogo_1.64.0 lazyeval_0.2.2 ## [63] crayon_1.5.2 hdf5r_1.3.8 ## [65] spatstat.explore_3.1-0 pkgconfig_2.0.3 ## [67] labeling_0.4.2 nlme_3.1-157 ## [69] ProtGenerics_1.30.0 nnet_7.3-17 ## [71] rlang_1.1.0 globals_0.16.2 ## [73] lifecycle_1.0.3 miniUI_0.1.1.1 ## [75] filelock_1.0.2 BiocFileCache_2.6.1 ## [77] dichromat_2.0-0.1 rprojroot_2.0.3 ## [79] polyclip_1.10-4 matrixStats_0.63.0 ## [81] lmtest_0.9-40 Matrix_1.5-3 ## [83] zoo_1.8-11 base64enc_0.1-3 ## [85] ggridges_0.5.4 png_0.1-8 ## [87] viridisLite_0.4.1 rjson_0.2.21 ## [89] bitops_1.0-7 R.oo_1.25.0 ## [91] KernSmooth_2.23-20 blob_1.2.3 ## [93] stringr_1.5.0 parallelly_1.35.0 ## [95] spatstat.random_3.1-4 readr_2.1.4 ## [97] jpeg_0.1-10 CNEr_1.34.0 ## [99] scales_1.2.1 memoise_2.0.1 ## [101] magrittr_2.0.3 plyr_1.8.8 ## [103] ica_1.0-3 zlibbioc_1.44.0 ## [105] compiler_4.2.0 BiocIO_1.8.0 ## [107] RColorBrewer_1.1-3 fitdistrplus_1.1-8 ## [109] Rsamtools_2.14.0 cli_3.6.1 ## [111] listenv_0.9.0 patchwork_1.1.2 ## [113] pbapply_1.7-0 htmlTable_2.4.1 ## [115] Formula_1.2-5 MASS_7.3-56 ## [117] tidyselect_1.2.0 stringi_1.7.12 ## [119] textshaping_0.3.6 highr_0.10 ## [121] yaml_2.3.7 latticeExtra_0.6-30 ## [123] ggrepel_0.9.3 grid_4.2.0 ## [125] sass_0.4.5 VariantAnnotation_1.44.1 ## [127] fastmatch_1.1-3 tools_4.2.0 ## [129] future.apply_1.10.0 parallel_4.2.0 ## [131] rstudioapi_0.14 TFMPvalue_0.0.9 ## [133] foreign_0.8-82 gridExtra_2.3 ## [135] farver_2.1.1 Rtsne_0.16 ## [137] digest_0.6.31 pracma_2.4.2 ## [139] shiny_1.7.4 Rcpp_1.0.10 ## [141] later_1.3.0 RcppAnnoy_0.0.20 ## [143] httr_1.4.5 biovizBase_1.46.0 ## [145] colorspace_2.1-0 XML_3.99-0.13 ## [147] fs_1.6.1 tensor_1.5 ## [149] reticulate_1.28 splines_4.2.0 ## [151] uwot_0.1.14 RcppRoll_0.3.0 ## [153] spatstat.utils_3.0-2 pkgdown_2.0.7 ## [155] sp_1.6-0 plotly_4.10.1 ## [157] systemfonts_1.0.4 xtable_1.8-4 ## [159] poweRlaw_0.70.6 jsonlite_1.8.4 ## [161] R6_2.5.1 Hmisc_4.8-0 ## [163] pillar_1.9.0 htmltools_0.5.5 ## [165] mime_0.12 DT_0.27 ## [167] glue_1.6.2 fastmap_1.1.1 ## [169] BiocParallel_1.32.5 codetools_0.2-18 ## [171] utf8_1.2.3 lattice_0.20-45 ## [173] bslib_0.4.2 spatstat.sparse_3.0-1 ## [175] tibble_3.2.1 curl_5.0.0 ## [177] leiden_0.4.3 gtools_3.9.4 ## [179] GO.db_3.16.0 interp_1.1-3 ## [181] survival_3.3-1 rmarkdown_2.21 ## [183] desc_1.4.2 munsell_0.5.0 ## [185] GenomeInfoDbData_1.2.9 reshape2_1.4.4 ## [187] gtable_0.3.3

This vignette introduces the WNN workflow for the analysis of multimodal single-cell datasets. The workflow consists of three stepsIndependent preprocessing and dimensional reduction of each modality individuallyLearning cell-specific modality ‘weights’, and constructing a WNN graph that integrates the modalitiesDownstream analysis (i.e. visualization, clustering, etc.) of the WNN graphWe demonstrate the use of WNN analysis to two single-cell multimodal technologies: CITE-seq and 10x multiome. We define the cellular states based on both modalities, instead of either individual modality.WNN analysis of CITE-seq, RNA + ADTWe use the CITE-seq dataset from (Stuart*, Butler* et al, Cell 2019), which consists of 30,672 scRNA-seq profiles measured alongside a panel of 25 antibodies from bone marrow. The object contains two assays, RNA and antibody-derived tags (ADT).To run this vignette please install Seurat v4, available on CRAN, and SeuratData, available on GitHub. install.packages("Seurat") library(Seurat) library(SeuratData) library(cowplot) library(dplyr) InstallData("bmcite") bm <- LoadData(ds = "bmcite")We first perform pre-processing and dimensional reduction on both assays independently. We use standard normalization, but you can also use SCTransform or any alternative method. DefaultAssay(bm) <- 'RNA' bm <- NormalizeData(bm) %>% FindVariableFeatures() %>% ScaleData() %>% RunPCA() DefaultAssay(bm) <- 'ADT' # we will use all ADT features for dimensional reduction # we set a dimensional reduction name to avoid overwriting the VariableFeatures(bm) <- rownames(bm[["ADT"]]) bm <- NormalizeData(bm, normalization.method = 'CLR', margin = 2) %>% ScaleData() %>% RunPCA(reduction.name = 'apca')For each cell, we calculate its closest neighbors in the dataset based on a weighted combination of RNA and protein similarities. The cell-specific modality weights and multimodal neighbors are calculated in a single function, which takes ~2 minutes to run on this dataset. We specify the dimensionality of each modality (similar to specifying the number of PCs to include in scRNA-seq clustering), but you can vary these settings to see that small changes have minimal effect on the overall results. # Identify multimodal neighbors. These will be stored in the neighbors slot, # and can be accessed using bm[['weighted.nn']] # The WNN graph can be accessed at bm[["wknn"]], # and the SNN graph used for clustering at bm[["wsnn"]] # Cell-specific modality weights can be accessed at bm$RNA.weight bm <- FindMultiModalNeighbors( bm, reduction.list = list("pca", "apca"), dims.list = list(1:30, 1:18), modality.weight.name = "RNA.weight" )We can now use these results for downstream analysis, such as visualization and clustering. For example, we can create a UMAP visualization of the data based on a weighted combination of RNA and protein data We can also perform graph-based clustering and visualize these results on the UMAP, alongside a set of cell annotations. bm <- RunUMAP(bm, nn.name = "weighted.nn", reduction.name = "wnn.umap", reduction.key = "wnnUMAP_") bm <- FindClusters(bm, graph.name = "wsnn", algorithm = 3, resolution = 2, verbose = FALSE) p1 <- DimPlot(bm, reduction = 'wnn.umap', label = TRUE, repel = TRUE, label.size = 2.5) + NoLegend() p2 <- DimPlot(bm, reduction = 'wnn.umap', group.by = 'celltype.l2', label = TRUE, repel = TRUE, label.size = 2.5) + NoLegend() p1 + p2We can also compute UMAP visualization based on only the RNA and protein data and compare. We find that the RNA analysis is more informative than the ADT analysis in identifying progenitor states (the ADT panel contains markers for differentiated cells), while the converse is true of T cell states (where the ADT analysis outperforms RNA). bm <- RunUMAP(bm, reduction = 'pca', dims = 1:30, assay = 'RNA', reduction.name = 'rna.umap', reduction.key = 'rnaUMAP_') bm <- RunUMAP(bm, reduction = 'apca', dims = 1:18, assay = 'ADT', reduction.name = 'adt.umap', reduction.key = 'adtUMAP_') p3 <- DimPlot(bm, reduction = 'rna.umap', group.by = 'celltype.l2', label = TRUE, repel = TRUE, label.size = 2.5) + NoLegend() p4 <- DimPlot(bm, reduction = 'adt.umap', group.by = 'celltype.l2', label = TRUE, repel = TRUE, label.size = 2.5) + NoLegend() p3 + p4We can visualize the expression of canonical marker genes and proteins on the multimodal UMAP, which can assist in verifying the provided annotations: p5 <- FeaturePlot(bm, features = c("adt_CD45RA","adt_CD16","adt_CD161"), reduction = 'wnn.umap', max.cutoff = 2, cols = c("lightgrey","darkgreen"), ncol = 3) p6 <- FeaturePlot(bm, features = c("rna_TRDC","rna_MPO","rna_AVP"), reduction = 'wnn.umap', max.cutoff = 3, ncol = 3) p5 / p6Finally, we can visualize the modality weights that were learned for each cell. Each of the populations with the highest RNA weights represent progenitor cells, while the populations with the highest protein weights represent T cells. This is in line with our biological expectations, as the antibody panel does not contain markers that can distinguish between different progenitor populations. VlnPlot(bm, features = "RNA.weight", group.by = 'celltype.l2', sort = TRUE, pt.size = 0.1) + NoLegend()WNN analysis of 10x Multiome, RNA + ATACHere, we demonstrate the use of WNN analysis to a second multimodal technology, the 10x multiome RNA+ATAC kit. We use a dataset that is publicly available on the 10x website, where paired transcriptomes and ATAC-seq profiles are measured in 10,412 PBMCs.We use the same WNN methods as we use in the previous tab, where we apply integrated multimodal analysis to a CITE-seq dataset. In this example we will demonstrate how to:Create a multimodal Seurat object with paired transcriptome and ATAC-seq profilesPerform weighted neighbor clustering on RNA+ATAC data in single cellsLeverage both modalities to identify putative regulators of different cell types and statesYou can download the dataset from the 10x Genomics website here. Please make sure to download the following files:Filtered feature barcode matrix (HDF5)ATAC Per fragment information file (TSV.GZ)ATAC Per fragment information index (TSV.GZ index)Finally, in order to run the vignette, make sure the following packages are installed:Seurat v4Signac for the analysis of single-cell chromatin datasetsEnsDb.Hsapiens.v86 for a set of annotations for hg38dplyr to help manipulate data tables library(Seurat) library(Signac) library(EnsDb.Hsapiens.v86) library(dplyr) library(ggplot2)We’ll create a Seurat object based on the gene expression data, and then add in the ATAC-seq data as a second assay. You can explore the Signac getting started vignette for more information on the creation and processing of a ChromatinAssay object. # the 10x hdf5 file contains both data types. inputdata.10x <- Read10X_h5("../data/pbmc_granulocyte_sorted_10k_filtered_feature_bc_matrix.h5") # extract RNA and ATAC data rna_counts <- inputdata.10x$`Gene Expression` atac_counts <- inputdata.10x$Peaks # Create Seurat object pbmc <- CreateSeuratObject(counts = rna_counts) pbmc[["percent.mt"]] <- PercentageFeatureSet(pbmc, pattern = "^MT-") # Now add in the ATAC-seq data # we'll only use peaks in standard chromosomes grange.counts <- StringToGRanges(rownames(atac_counts), sep = c(":", "-")) grange.use <- seqnames(grange.counts) %in% standardChromosomes(grange.counts) atac_counts <- atac_counts[as.vector(grange.use), ] annotations <- GetGRangesFromEnsDb(ensdb = EnsDb.Hsapiens.v86) seqlevelsStyle(annotations) <- 'UCSC' genome(annotations) <- "hg38" frag.file <- "../data/pbmc_granulocyte_sorted_10k_atac_fragments.tsv.gz" chrom_assay <- CreateChromatinAssay( counts = atac_counts, sep = c(":", "-"), genome = 'hg38', fragments = frag.file, min.cells = 10, annotation = annotations ) pbmc[["ATAC"]] <- chrom_assayWe perform basic QC based on the number of detected molecules for each modality as well as mitochondrial percentage. VlnPlot(pbmc, features = c("nCount_ATAC", "nCount_RNA","percent.mt"), ncol = 3, log = TRUE, pt.size = 0) + NoLegend() pbmc <- subset( x = pbmc, subset = nCount_ATAC < 7e4 & nCount_ATAC > 5e3 & nCount_RNA < 25000 & nCount_RNA > 1000 & percent.mt < 20 )We next perform pre-processing and dimensional reduction on both assays independently, using standard approaches for RNA and ATAC-seq data. # RNA analysis DefaultAssay(pbmc) <- "RNA" pbmc <- SCTransform(pbmc, verbose = FALSE) %>% RunPCA() %>% RunUMAP(dims = 1:50, reduction.name = 'umap.rna', reduction.key = 'rnaUMAP_') # ATAC analysis # We exclude the first dimension as this is typically correlated with sequencing depth DefaultAssay(pbmc) <- "ATAC" pbmc <- RunTFIDF(pbmc) pbmc <- FindTopFeatures(pbmc, min.cutoff = 'q0') pbmc <- RunSVD(pbmc) pbmc <- RunUMAP(pbmc, reduction = 'lsi', dims = 2:50, reduction.name = "umap.atac", reduction.key = "atacUMAP_")We calculate a WNN graph, representing a weighted combination of RNA and ATAC-seq modalities. We use this graph for UMAP visualization and clustering pbmc <- FindMultiModalNeighbors(pbmc, reduction.list = list("pca", "lsi"), dims.list = list(1:50, 2:50)) pbmc <- RunUMAP(pbmc, nn.name = "weighted.nn", reduction.name = "wnn.umap", reduction.key = "wnnUMAP_") pbmc <- FindClusters(pbmc, graph.name = "wsnn", algorithm = 3, verbose = FALSE)We annotate the clusters below. Note that you could also annotate the dataset using our supervised mapping pipelines, using either our vignette, or automated web tool, Azimuth. # perform sub-clustering on cluster 6 to find additional structure pbmc <- FindSubCluster(pbmc, cluster = 6, graph.name = "wsnn", algorithm = 3) Idents(pbmc) <- "sub.cluster" # add annotations pbmc <- RenameIdents(pbmc, '19' = 'pDC','20' = 'HSPC','15' = 'cDC') pbmc <- RenameIdents(pbmc, '0' = 'CD14 Mono', '9' ='CD14 Mono', '5' = 'CD16 Mono') pbmc <- RenameIdents(pbmc, '10' = 'Naive B', '11' = 'Intermediate B', '17' = 'Memory B', '21' = 'Plasma') pbmc <- RenameIdents(pbmc, '7' = 'NK') pbmc <- RenameIdents(pbmc, '4' = 'CD4 TCM', '13'= "CD4 TEM", '3' = "CD4 TCM", '16' ="Treg", '1' ="CD4 Naive", '14' = "CD4 Naive") pbmc <- RenameIdents(pbmc, '2' = 'CD8 Naive', '8'= "CD8 Naive", '12' = 'CD8 TEM_1', '6_0' = 'CD8 TEM_2', '6_1' ='CD8 TEM_2', '6_4' ='CD8 TEM_2') pbmc <- RenameIdents(pbmc, '18' = 'MAIT') pbmc <- RenameIdents(pbmc, '6_2' ='gdT', '6_3' = 'gdT') pbmc$celltype <- Idents(pbmc)We can visualize clustering based on gene expression, ATAC-seq, or WNN analysis. The differences are more subtle than in the previous analysis (you can explore the weights, which are more evenly split than in our CITE-seq example), but we find that WNN provides the clearest separation of cell states. p1 <- DimPlot(pbmc, reduction = "umap.rna", group.by = "celltype", label = TRUE, label.size = 2.5, repel = TRUE) + ggtitle("RNA") p2 <- DimPlot(pbmc, reduction = "umap.atac", group.by = "celltype", label = TRUE, label.size = 2.5, repel = TRUE) + ggtitle("ATAC") p3 <- DimPlot(pbmc, reduction = "wnn.umap", group.by = "celltype", label = TRUE, label.size = 2.5, repel = TRUE) + ggtitle("WNN") p1 + p2 + p3 & NoLegend() & theme(plot.title = element_text(hjust = 0.5))For example, the ATAC-seq data assists in the separation of CD4 and CD8 T cell states. This is due to the presence of multiple loci that exhibit differential accessibility between different T cell subtypes. For example, we can visualize ‘pseudobulk’ tracks of the CD8A locus alongside violin plots of gene expression levels, using tools in the Signac visualization vignette. ## to make the visualization easier, subset T cell clusters celltype.names <- levels(pbmc) tcell.names <- grep("CD4|CD8|Treg", celltype.names,value = TRUE) tcells <- subset(pbmc, idents = tcell.names) CoveragePlot(tcells, region = 'CD8A', features = 'CD8A', assay = 'ATAC', expression.assay = 'SCT', peaks = FALSE)Next, we will examine the accessible regions of each cell to determine enriched motifs. As described in the Signac motifs vignette, there are a few ways to do this, but we will use the chromVAR package from the Greenleaf lab. This calculates a per-cell accessibility score for known motifs, and adds these scores as a third assay (chromvar) in the Seurat object.To continue, please make sure you have the following packages installed.chromVAR for the analysis of motif accessibility in scATAC-seqpresto for fast differential expression analyses.TFBSTools for TFBS analysisJASPAR2020 for JASPAR motif modelsmotifmatchr for motif matchingBSgenome.Hsapiens.UCSC.hg38 for chromVARInstall command for all dependencies remotes::install_github("immunogenomics/presto") BiocManager::install(c("chromVAR", "TFBSTools", "JASPAR2020", "motifmatchr", "BSgenome.Hsapiens.UCSC.hg38")) library(chromVAR) library(JASPAR2020) library(TFBSTools) library(motifmatchr) library(BSgenome.Hsapiens.UCSC.hg38) # Scan the DNA sequence of each peak for the presence of each motif, and create a Motif object DefaultAssay(pbmc) <- "ATAC" pwm_set <- getMatrixSet(x = JASPAR2020, opts = list(species = 9606, all_versions = FALSE)) motif.matrix <- CreateMotifMatrix(features = granges(pbmc), pwm = pwm_set, genome = 'hg38', use.counts = FALSE) motif.object <- CreateMotifObject(data = motif.matrix, pwm = pwm_set) pbmc <- SetAssayData(pbmc, assay = 'ATAC', slot = 'motifs', new.data = motif.object) # Note that this step can take 30-60 minutes pbmc <- RunChromVAR( object = pbmc, genome = BSgenome.Hsapiens.UCSC.hg38 )Finally, we explore the multimodal dataset to identify key regulators of each cell state. Paired data provides a unique opportunity to identify transcription factors (TFs) that satisfy multiple criteria, helping to narrow down the list of putative regulators to the most likely candidates. We aim to identify TFs whose expression is enriched in multiple cell types in the RNA measurements, but also have enriched accessibility for their motifs in the ATAC measurements.As an example and positive control, the CCAAT Enhancer Binding Protein (CEBP) family of proteins, including the TF CEBPB, have been repeatedly shown to play important roles in the differentiation and function of myeloid cells including monocytes and dendritic cells. We can see that both the expression of the CEBPB, and the accessibility of the MA0466.2.4 motif (which encodes the binding site for CEBPB), are both enriched in monocytes. #returns MA0466.2 motif.name <- ConvertMotifID(pbmc, name = 'CEBPB') gene_plot <- FeaturePlot(pbmc, features = "sct_CEBPB", reduction = 'wnn.umap') motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap') gene_plot | motif_plotWe’d like to quantify this relationship, and search across all cell types to find similar examples. To do so, we will use the presto package to perform fast differential expression. We run two tests: one using gene expression data, and the other using chromVAR motif accessibilities. presto calculates a p-value based on the Wilcox rank sum test, which is also the default test in Seurat, and we restrict our search to TFs that return significant results in both tests.presto also calculates an “AUC” statistic, which reflects the power of each gene (or motif) to serve as a marker of cell type. A maximum AUC value of 1 indicates a perfect marker. Since the AUC statistic is on the same scale for both genes and motifs, we take the average of the AUC values from the two tests, and use this to rank TFs for each cell type: markers_rna <- presto:::wilcoxauc.Seurat(X = pbmc, group_by = 'celltype', assay = 'data', seurat_assay = 'SCT') markers_motifs <- presto:::wilcoxauc.Seurat(X = pbmc, group_by = 'celltype', assay = 'data', seurat_assay = 'chromvar') motif.names <- markers_motifs$feature colnames(markers_rna) <- paste0("RNA.", colnames(markers_rna)) colnames(markers_motifs) <- paste0("motif.", colnames(markers_motifs)) markers_rna$gene <- markers_rna$RNA.feature markers_motifs$gene <- ConvertMotifID(pbmc, id = motif.names) # a simple function to implement the procedure above topTFs <- function(celltype, padj.cutoff = 1e-2) { ctmarkers_rna <- dplyr::filter( markers_rna, RNA.group == celltype, RNA.padj < padj.cutoff, RNA.logFC > 0) %>% arrange(-RNA.auc) ctmarkers_motif <- dplyr::filter( markers_motifs, motif.group == celltype, motif.padj < padj.cutoff, motif.logFC > 0) %>% arrange(-motif.auc) top_tfs <- inner_join( x = ctmarkers_rna[, c(2, 11, 6, 7)], y = ctmarkers_motif[, c(2, 1, 11, 6, 7)], by = "gene" ) top_tfs$avg_auc <- (top_tfs$RNA.auc + top_tfs$motif.auc) / 2 top_tfs <- arrange(top_tfs, -avg_auc) return(top_tfs) }We can now compute, and visualize, putative regulators for any cell type. We recover well-established regulators, including TBX21 for NK cells, IRF4 for plasma cells, SOX4 for hematopoietic progenitors, EBF1 and PAX5 for B cells, IRF8 and TCF4 for pDC. We believe that similar strategies can be used to help focus on a set of putative regulators in diverse systems. # identify top markers in NK and visualize head(topTFs("NK"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 NK TBX21 0.7270859 0.000000e+00 NK MA0690.1 0.9139614 ## 2 NK EOMES 0.5886774 2.411013e-98 NK MA0800.1 0.9214773 ## 3 NK RUNX3 0.7705661 5.977716e-120 NK MA0684.2 0.6769022 ## motif.pval avg_auc ## 1 1.097940e-202 0.8205237 ## 2 4.903866e-210 0.7550774 ## 3 1.560061e-38 0.7237341 motif.name <- ConvertMotifID(pbmc, name = 'TBX21') gene_plot <- FeaturePlot(pbmc, features = "sct_TBX21", reduction = 'wnn.umap') motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap') gene_plot | motif_plot # identify top markers in pDC and visualize head(topTFs("pDC"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 pDC TCF4 0.9998815 1.120711e-162 pDC MA0830.2 0.9965481 ## 2 pDC IRF8 0.9904457 1.308164e-123 pDC MA0652.1 0.8833112 ## 3 pDC SPIB 0.9115207 0.000000e+00 pDC MA0081.2 0.9068540 ## motif.pval avg_auc ## 1 1.785897e-69 0.9982148 ## 2 3.982413e-42 0.9368785 ## 3 3.083509e-47 0.9091874 motif.name <- ConvertMotifID(pbmc, name = 'TCF4') gene_plot <- FeaturePlot(pbmc, features = "sct_TCF4", reduction = 'wnn.umap') motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap') gene_plot | motif_plot # identify top markers in HSPC and visualize head(topTFs("CD16 Mono"),3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 CD16 Mono SPI1 0.8793172 1.666810e-296 CD16 Mono MA0080.5 0.8880908 ## 2 CD16 Mono CEBPB 0.8685933 1.625472e-294 CD16 Mono MA0466.2 0.7840422 ## 3 CD16 Mono MEF2C 0.7129910 2.727252e-79 CD16 Mono MA0497.1 0.8059373 ## motif.pval avg_auc ## 1 4.762491e-194 0.8837040 ## 2 7.049764e-105 0.8263177 ## 3 2.345716e-121 0.7594641 motif.name <- ConvertMotifID(pbmc, name = 'SPI1') gene_plot <- FeaturePlot(pbmc, features = "sct_SPI1", reduction = 'wnn.umap') motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap') gene_plot | motif_plot # identify top markers in other cell types head(topTFs("Naive B"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 Naive B MEF2C 0.8802747 1.890065e-182 Naive B MA0497.1 0.6789079 ## 2 Naive B PAX5 0.9436648 0.000000e+00 Naive B MA0014.3 0.5827061 ## 3 Naive B POU2F2 0.6029377 2.892216e-13 Naive B MA0507.1 0.8912268 ## motif.pval avg_auc ## 1 9.815118e-32 0.7795913 ## 2 5.995185e-08 0.7631854 ## 3 6.471677e-145 0.7470822 head(topTFs("HSPC"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 HSPC SOX4 0.9869406 5.524832e-71 HSPC MA0867.2 0.6830497 ## 2 HSPC GATA2 0.7884615 0.000000e+00 HSPC MA0036.3 0.8275008 ## 3 HSPC MEIS1 0.8638496 0.000000e+00 HSPC MA0498.2 0.6924225 ## motif.pval avg_auc ## 1 1.241915e-03 0.8349951 ## 2 7.591798e-09 0.8079812 ## 3 6.877492e-04 0.7781361 head(topTFs("Plasma"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 Plasma IRF4 0.8189687 5.261955e-35 Plasma MA1419.1 0.9776046 ## 2 Plasma MEF2C 0.9111213 2.977155e-12 Plasma MA0497.1 0.7596637 ## 3 Plasma TCF4 0.8049409 6.810635e-12 Plasma MA0830.2 0.7840848 ## motif.pval avg_auc ## 1 2.334627e-12 0.8982867 ## 2 1.374353e-04 0.8353925 ## 3 3.028306e-05 0.7945129Session Info sessionInfo()## R version 4.2.0 (2022-04-22) ## Platform: x86_64-pc-linux-gnu (64-bit) ## Running under: Ubuntu 20.04.5 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/liblapack.so.3 ## ## locale: ## [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C ## [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8 ## [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 ## ## attached base packages: ## [1] stats4 stats graphics grDevices utils datasets methods ## [8] base ## ## other attached packages: ## [1] BSgenome.Hsapiens.UCSC.hg38_1.4.5 BSgenome_1.66.3 ## [3] rtracklayer_1.58.0 Biostrings_2.66.0 ## [5] XVector_0.38.0 motifmatchr_1.20.0 ## [7] TFBSTools_1.36.0 JASPAR2020_0.99.10 ## [9] chromVAR_1.20.2 EnsDb.Hsapiens.v86_2.99.0 ## [11] ensembldb_2.22.0 AnnotationFilter_1.22.0 ## [13] GenomicFeatures_1.50.4 AnnotationDbi_1.60.0 ## [15] Biobase_2.58.0 GenomicRanges_1.50.2 ## [17] GenomeInfoDb_1.35.16 IRanges_2.32.0 ## [19] S4Vectors_0.36.2 BiocGenerics_0.44.0 ## [21] Signac_1.9.0 ggplot2_3.4.1 ## [23] dplyr_1.1.1 cowplot_1.1.1 ## [25] thp1.eccite.SeuratData_3.1.5 stxBrain.SeuratData_0.1.1 ## [27] ssHippo.SeuratData_3.1.4 pbmcsca.SeuratData_3.0.0 ## [29] pbmcMultiome.SeuratData_0.1.2 pbmc3k.SeuratData_3.1.4 ## [31] panc8.SeuratData_3.0.2 ifnb.SeuratData_3.1.0 ## [33] hcabm40k.SeuratData_3.0.0 bmcite.SeuratData_0.3.0 ## [35] SeuratData_0.2.2 SeuratObject_4.1.3 ## [37] Seurat_4.2.1.9001 ## ## loaded via a namespace (and not attached): ## [1] rappdirs_0.3.3 scattermore_0.8 ## [3] R.methodsS3_1.8.2 ragg_1.2.5 ## [5] nabor_0.5.0 tidyr_1.3.0 ## [7] bit64_4.0.5 knitr_1.42 ## [9] R.utils_2.12.2 irlba_2.3.5.1 ## [11] DelayedArray_0.24.0 data.table_1.14.8 ## [13] rpart_4.1.16 KEGGREST_1.38.0 ## [15] RCurl_1.98-1.12 generics_0.1.3 ## [17] RSQLite_2.3.0 RANN_2.6.1 ## [19] future_1.32.0 tzdb_0.3.0 ## [21] bit_4.0.5 spatstat.data_3.0-1 ## [23] xml2_1.3.3 httpuv_1.6.9 ## [25] SummarizedExperiment_1.28.0 DirichletMultinomial_1.40.0 ## [27] xfun_0.38 hms_1.1.2 ## [29] jquerylib_0.1.4 evaluate_0.20 ## [31] promises_1.2.0.1 fansi_1.0.4 ## [33] restfulr_0.0.15 progress_1.2.2 ## [35] caTools_1.18.2 dbplyr_2.3.1 ## [37] igraph_1.4.1 DBI_1.1.3 ## [39] htmlwidgets_1.6.2 spatstat.geom_3.1-0 ## [41] purrr_1.0.1 ellipsis_0.3.2 ## [43] backports_1.4.1 annotate_1.76.0 ## [45] biomaRt_2.54.0 deldir_1.0-6 ## [47] MatrixGenerics_1.10.0 vctrs_0.6.1 ## [49] ROCR_1.0-11 abind_1.4-5 ## [51] cachem_1.0.7 withr_2.5.0 ## [53] progressr_0.13.0 presto_1.0.0 ## [55] checkmate_2.1.0 sctransform_0.3.5 ## [57] GenomicAlignments_1.34.0 prettyunits_1.1.1 ## [59] goftest_1.2-3 cluster_2.1.3 ## [61] seqLogo_1.64.0 lazyeval_0.2.2 ## [63] crayon_1.5.2 hdf5r_1.3.8 ## [65] spatstat.explore_3.1-0 pkgconfig_2.0.3 ## [67] labeling_0.4.2 nlme_3.1-157 ## [69] ProtGenerics_1.30.0 nnet_7.3-17 ## [71] rlang_1.1.0 globals_0.16.2 ## [73] lifecycle_1.0.3 miniUI_0.1.1.1 ## [75] filelock_1.0.2 BiocFileCache_2.6.1 ## [77] dichromat_2.0-0.1 rprojroot_2.0.3 ## [79] polyclip_1.10-4 matrixStats_0.63.0 ## [81] lmtest_0.9-40 Matrix_1.5-3 ## [83] zoo_1.8-11 base64enc_0.1-3 ## [85] ggridges_0.5.4 png_0.1-8 ## [87] viridisLite_0.4.1 rjson_0.2.21 ## [89] bitops_1.0-7 R.oo_1.25.0 ## [91] KernSmooth_2.23-20 blob_1.2.3 ## [93] stringr_1.5.0 parallelly_1.35.0 ## [95] spatstat.random_3.1-4 readr_2.1.4 ## [97] jpeg_0.1-10 CNEr_1.34.0 ## [99] scales_1.2.1 memoise_2.0.1 ## [101] magrittr_2.0.3 plyr_1.8.8 ## [103] ica_1.0-3 zlibbioc_1.44.0 ## [105] compiler_4.2.0 BiocIO_1.8.0 ## [107] RColorBrewer_1.1-3 fitdistrplus_1.1-8 ## [109] Rsamtools_2.14.0 cli_3.6.1 ## [111] listenv_0.9.0 patchwork_1.1.2 ## [113] pbapply_1.7-0 htmlTable_2.4.1 ## [115] Formula_1.2-5 MASS_7.3-56 ## [117] tidyselect_1.2.0 stringi_1.7.12 ## [119] textshaping_0.3.6 highr_0.10 ## [121] yaml_2.3.7 latticeExtra_0.6-30 ## [123] ggrepel_0.9.3 grid_4.2.0 ## [125] sass_0.4.5 VariantAnnotation_1.44.1 ## [127] fastmatch_1.1-3 tools_4.2.0 ## [129] future.apply_1.10.0 parallel_4.2.0 ## [131] rstudioapi_0.14 TFMPvalue_0.0.9 ## [133] foreign_0.8-82 gridExtra_2.3 ## [135] farver_2.1.1 Rtsne_0.16 ## [137] digest_0.6.31 pracma_2.4.2 ## [139] shiny_1.7.4 Rcpp_1.0.10 ## [141] later_1.3.0 RcppAnnoy_0.0.20 ## [143] httr_1.4.5 biovizBase_1.46.0 ## [145] colorspace_2.1-0 XML_3.99-0.13 ## [147] fs_1.6.1 tensor_1.5 ## [149] reticulate_1.28 splines_4.2.0 ## [151] uwot_0.1.14 RcppRoll_0.3.0 ## [153] spatstat.utils_3.0-2 pkgdown_2.0.7 ## [155] sp_1.6-0 plotly_4.10.1 ## [157] systemfonts_1.0.4 xtable_1.8-4 ## [159] poweRlaw_0.70.6 jsonlite_1.8.4 ## [161] R6_2.5.1 Hmisc_4.8-0 ## [163] pillar_1.9.0 htmltools_0.5.5 ## [165] mime_0.12 DT_0.27 ## [167] glue_1.6.2 fastmap_1.1.1 ## [169] BiocParallel_1.32.5 codetools_0.2-18 ## [171] utf8_1.2.3 lattice_0.20-45 ## [173] bslib_0.4.2 spatstat.sparse_3.0-1 ## [175] tibble_3.2.1 curl_5.0.0 ## [177] leiden_0.4.3 gtools_3.9.4 ## [179] GO.db_3.16.0 interp_1.1-3 ## [181] survival_3.3-1 rmarkdown_2.21 ## [183] desc_1.4.2 munsell_0.5.0 ## [185] GenomeInfoDbData_1.2.9 reshape2_1.4.4 ## [187] gtable_0.3.3

We demonstrate the use of WNN analysis to two single-cell multimodal technologies: CITE-seq and 10x multiome. We define the cellular states based on both modalities, instead of either individual modality.WNN analysis of CITE-seq, RNA + ADTWe use the CITE-seq dataset from (Stuart*, Butler* et al, Cell 2019), which consists of 30,672 scRNA-seq profiles measured alongside a panel of 25 antibodies from bone marrow. The object contains two assays, RNA and antibody-derived tags (ADT).To run this vignette please install Seurat v4, available on CRAN, and SeuratData, available on GitHub. install.packages("Seurat") library(Seurat) library(SeuratData) library(cowplot) library(dplyr) InstallData("bmcite") bm <- LoadData(ds = "bmcite")We first perform pre-processing and dimensional reduction on both assays independently. We use standard normalization, but you can also use SCTransform or any alternative method. DefaultAssay(bm) <- 'RNA' bm <- NormalizeData(bm) %>% FindVariableFeatures() %>% ScaleData() %>% RunPCA() DefaultAssay(bm) <- 'ADT' # we will use all ADT features for dimensional reduction # we set a dimensional reduction name to avoid overwriting the VariableFeatures(bm) <- rownames(bm[["ADT"]]) bm <- NormalizeData(bm, normalization.method = 'CLR', margin = 2) %>% ScaleData() %>% RunPCA(reduction.name = 'apca')For each cell, we calculate its closest neighbors in the dataset based on a weighted combination of RNA and protein similarities. The cell-specific modality weights and multimodal neighbors are calculated in a single function, which takes ~2 minutes to run on this dataset. We specify the dimensionality of each modality (similar to specifying the number of PCs to include in scRNA-seq clustering), but you can vary these settings to see that small changes have minimal effect on the overall results. # Identify multimodal neighbors. These will be stored in the neighbors slot, # and can be accessed using bm[['weighted.nn']] # The WNN graph can be accessed at bm[["wknn"]], # and the SNN graph used for clustering at bm[["wsnn"]] # Cell-specific modality weights can be accessed at bm$RNA.weight bm <- FindMultiModalNeighbors( bm, reduction.list = list("pca", "apca"), dims.list = list(1:30, 1:18), modality.weight.name = "RNA.weight" )We can now use these results for downstream analysis, such as visualization and clustering. For example, we can create a UMAP visualization of the data based on a weighted combination of RNA and protein data We can also perform graph-based clustering and visualize these results on the UMAP, alongside a set of cell annotations. bm <- RunUMAP(bm, nn.name = "weighted.nn", reduction.name = "wnn.umap", reduction.key = "wnnUMAP_") bm <- FindClusters(bm, graph.name = "wsnn", algorithm = 3, resolution = 2, verbose = FALSE) p1 <- DimPlot(bm, reduction = 'wnn.umap', label = TRUE, repel = TRUE, label.size = 2.5) + NoLegend() p2 <- DimPlot(bm, reduction = 'wnn.umap', group.by = 'celltype.l2', label = TRUE, repel = TRUE, label.size = 2.5) + NoLegend() p1 + p2We can also compute UMAP visualization based on only the RNA and protein data and compare. We find that the RNA analysis is more informative than the ADT analysis in identifying progenitor states (the ADT panel contains markers for differentiated cells), while the converse is true of T cell states (where the ADT analysis outperforms RNA). bm <- RunUMAP(bm, reduction = 'pca', dims = 1:30, assay = 'RNA', reduction.name = 'rna.umap', reduction.key = 'rnaUMAP_') bm <- RunUMAP(bm, reduction = 'apca', dims = 1:18, assay = 'ADT', reduction.name = 'adt.umap', reduction.key = 'adtUMAP_') p3 <- DimPlot(bm, reduction = 'rna.umap', group.by = 'celltype.l2', label = TRUE, repel = TRUE, label.size = 2.5) + NoLegend() p4 <- DimPlot(bm, reduction = 'adt.umap', group.by = 'celltype.l2', label = TRUE, repel = TRUE, label.size = 2.5) + NoLegend() p3 + p4We can visualize the expression of canonical marker genes and proteins on the multimodal UMAP, which can assist in verifying the provided annotations: p5 <- FeaturePlot(bm, features = c("adt_CD45RA","adt_CD16","adt_CD161"), reduction = 'wnn.umap', max.cutoff = 2, cols = c("lightgrey","darkgreen"), ncol = 3) p6 <- FeaturePlot(bm, features = c("rna_TRDC","rna_MPO","rna_AVP"), reduction = 'wnn.umap', max.cutoff = 3, ncol = 3) p5 / p6Finally, we can visualize the modality weights that were learned for each cell. Each of the populations with the highest RNA weights represent progenitor cells, while the populations with the highest protein weights represent T cells. This is in line with our biological expectations, as the antibody panel does not contain markers that can distinguish between different progenitor populations. VlnPlot(bm, features = "RNA.weight", group.by = 'celltype.l2', sort = TRUE, pt.size = 0.1) + NoLegend()WNN analysis of 10x Multiome, RNA + ATACHere, we demonstrate the use of WNN analysis to a second multimodal technology, the 10x multiome RNA+ATAC kit. We use a dataset that is publicly available on the 10x website, where paired transcriptomes and ATAC-seq profiles are measured in 10,412 PBMCs.We use the same WNN methods as we use in the previous tab, where we apply integrated multimodal analysis to a CITE-seq dataset. In this example we will demonstrate how to:Create a multimodal Seurat object with paired transcriptome and ATAC-seq profilesPerform weighted neighbor clustering on RNA+ATAC data in single cellsLeverage both modalities to identify putative regulators of different cell types and statesYou can download the dataset from the 10x Genomics website here. Please make sure to download the following files:Filtered feature barcode matrix (HDF5)ATAC Per fragment information file (TSV.GZ)ATAC Per fragment information index (TSV.GZ index)Finally, in order to run the vignette, make sure the following packages are installed:Seurat v4Signac for the analysis of single-cell chromatin datasetsEnsDb.Hsapiens.v86 for a set of annotations for hg38dplyr to help manipulate data tables library(Seurat) library(Signac) library(EnsDb.Hsapiens.v86) library(dplyr) library(ggplot2)We’ll create a Seurat object based on the gene expression data, and then add in the ATAC-seq data as a second assay. You can explore the Signac getting started vignette for more information on the creation and processing of a ChromatinAssay object. # the 10x hdf5 file contains both data types. inputdata.10x <- Read10X_h5("../data/pbmc_granulocyte_sorted_10k_filtered_feature_bc_matrix.h5") # extract RNA and ATAC data rna_counts <- inputdata.10x$`Gene Expression` atac_counts <- inputdata.10x$Peaks # Create Seurat object pbmc <- CreateSeuratObject(counts = rna_counts) pbmc[["percent.mt"]] <- PercentageFeatureSet(pbmc, pattern = "^MT-") # Now add in the ATAC-seq data # we'll only use peaks in standard chromosomes grange.counts <- StringToGRanges(rownames(atac_counts), sep = c(":", "-")) grange.use <- seqnames(grange.counts) %in% standardChromosomes(grange.counts) atac_counts <- atac_counts[as.vector(grange.use), ] annotations <- GetGRangesFromEnsDb(ensdb = EnsDb.Hsapiens.v86) seqlevelsStyle(annotations) <- 'UCSC' genome(annotations) <- "hg38" frag.file <- "../data/pbmc_granulocyte_sorted_10k_atac_fragments.tsv.gz" chrom_assay <- CreateChromatinAssay( counts = atac_counts, sep = c(":", "-"), genome = 'hg38', fragments = frag.file, min.cells = 10, annotation = annotations ) pbmc[["ATAC"]] <- chrom_assayWe perform basic QC based on the number of detected molecules for each modality as well as mitochondrial percentage. VlnPlot(pbmc, features = c("nCount_ATAC", "nCount_RNA","percent.mt"), ncol = 3, log = TRUE, pt.size = 0) + NoLegend() pbmc <- subset( x = pbmc, subset = nCount_ATAC < 7e4 & nCount_ATAC > 5e3 & nCount_RNA < 25000 & nCount_RNA > 1000 & percent.mt < 20 )We next perform pre-processing and dimensional reduction on both assays independently, using standard approaches for RNA and ATAC-seq data. # RNA analysis DefaultAssay(pbmc) <- "RNA" pbmc <- SCTransform(pbmc, verbose = FALSE) %>% RunPCA() %>% RunUMAP(dims = 1:50, reduction.name = 'umap.rna', reduction.key = 'rnaUMAP_') # ATAC analysis # We exclude the first dimension as this is typically correlated with sequencing depth DefaultAssay(pbmc) <- "ATAC" pbmc <- RunTFIDF(pbmc) pbmc <- FindTopFeatures(pbmc, min.cutoff = 'q0') pbmc <- RunSVD(pbmc) pbmc <- RunUMAP(pbmc, reduction = 'lsi', dims = 2:50, reduction.name = "umap.atac", reduction.key = "atacUMAP_")We calculate a WNN graph, representing a weighted combination of RNA and ATAC-seq modalities. We use this graph for UMAP visualization and clustering pbmc <- FindMultiModalNeighbors(pbmc, reduction.list = list("pca", "lsi"), dims.list = list(1:50, 2:50)) pbmc <- RunUMAP(pbmc, nn.name = "weighted.nn", reduction.name = "wnn.umap", reduction.key = "wnnUMAP_") pbmc <- FindClusters(pbmc, graph.name = "wsnn", algorithm = 3, verbose = FALSE)We annotate the clusters below. Note that you could also annotate the dataset using our supervised mapping pipelines, using either our vignette, or automated web tool, Azimuth. # perform sub-clustering on cluster 6 to find additional structure pbmc <- FindSubCluster(pbmc, cluster = 6, graph.name = "wsnn", algorithm = 3) Idents(pbmc) <- "sub.cluster" # add annotations pbmc <- RenameIdents(pbmc, '19' = 'pDC','20' = 'HSPC','15' = 'cDC') pbmc <- RenameIdents(pbmc, '0' = 'CD14 Mono', '9' ='CD14 Mono', '5' = 'CD16 Mono') pbmc <- RenameIdents(pbmc, '10' = 'Naive B', '11' = 'Intermediate B', '17' = 'Memory B', '21' = 'Plasma') pbmc <- RenameIdents(pbmc, '7' = 'NK') pbmc <- RenameIdents(pbmc, '4' = 'CD4 TCM', '13'= "CD4 TEM", '3' = "CD4 TCM", '16' ="Treg", '1' ="CD4 Naive", '14' = "CD4 Naive") pbmc <- RenameIdents(pbmc, '2' = 'CD8 Naive', '8'= "CD8 Naive", '12' = 'CD8 TEM_1', '6_0' = 'CD8 TEM_2', '6_1' ='CD8 TEM_2', '6_4' ='CD8 TEM_2') pbmc <- RenameIdents(pbmc, '18' = 'MAIT') pbmc <- RenameIdents(pbmc, '6_2' ='gdT', '6_3' = 'gdT') pbmc$celltype <- Idents(pbmc)We can visualize clustering based on gene expression, ATAC-seq, or WNN analysis. The differences are more subtle than in the previous analysis (you can explore the weights, which are more evenly split than in our CITE-seq example), but we find that WNN provides the clearest separation of cell states. p1 <- DimPlot(pbmc, reduction = "umap.rna", group.by = "celltype", label = TRUE, label.size = 2.5, repel = TRUE) + ggtitle("RNA") p2 <- DimPlot(pbmc, reduction = "umap.atac", group.by = "celltype", label = TRUE, label.size = 2.5, repel = TRUE) + ggtitle("ATAC") p3 <- DimPlot(pbmc, reduction = "wnn.umap", group.by = "celltype", label = TRUE, label.size = 2.5, repel = TRUE) + ggtitle("WNN") p1 + p2 + p3 & NoLegend() & theme(plot.title = element_text(hjust = 0.5))For example, the ATAC-seq data assists in the separation of CD4 and CD8 T cell states. This is due to the presence of multiple loci that exhibit differential accessibility between different T cell subtypes. For example, we can visualize ‘pseudobulk’ tracks of the CD8A locus alongside violin plots of gene expression levels, using tools in the Signac visualization vignette. ## to make the visualization easier, subset T cell clusters celltype.names <- levels(pbmc) tcell.names <- grep("CD4|CD8|Treg", celltype.names,value = TRUE) tcells <- subset(pbmc, idents = tcell.names) CoveragePlot(tcells, region = 'CD8A', features = 'CD8A', assay = 'ATAC', expression.assay = 'SCT', peaks = FALSE)Next, we will examine the accessible regions of each cell to determine enriched motifs. As described in the Signac motifs vignette, there are a few ways to do this, but we will use the chromVAR package from the Greenleaf lab. This calculates a per-cell accessibility score for known motifs, and adds these scores as a third assay (chromvar) in the Seurat object.To continue, please make sure you have the following packages installed.chromVAR for the analysis of motif accessibility in scATAC-seqpresto for fast differential expression analyses.TFBSTools for TFBS analysisJASPAR2020 for JASPAR motif modelsmotifmatchr for motif matchingBSgenome.Hsapiens.UCSC.hg38 for chromVARInstall command for all dependencies remotes::install_github("immunogenomics/presto") BiocManager::install(c("chromVAR", "TFBSTools", "JASPAR2020", "motifmatchr", "BSgenome.Hsapiens.UCSC.hg38")) library(chromVAR) library(JASPAR2020) library(TFBSTools) library(motifmatchr) library(BSgenome.Hsapiens.UCSC.hg38) # Scan the DNA sequence of each peak for the presence of each motif, and create a Motif object DefaultAssay(pbmc) <- "ATAC" pwm_set <- getMatrixSet(x = JASPAR2020, opts = list(species = 9606, all_versions = FALSE)) motif.matrix <- CreateMotifMatrix(features = granges(pbmc), pwm = pwm_set, genome = 'hg38', use.counts = FALSE) motif.object <- CreateMotifObject(data = motif.matrix, pwm = pwm_set) pbmc <- SetAssayData(pbmc, assay = 'ATAC', slot = 'motifs', new.data = motif.object) # Note that this step can take 30-60 minutes pbmc <- RunChromVAR( object = pbmc, genome = BSgenome.Hsapiens.UCSC.hg38 )Finally, we explore the multimodal dataset to identify key regulators of each cell state. Paired data provides a unique opportunity to identify transcription factors (TFs) that satisfy multiple criteria, helping to narrow down the list of putative regulators to the most likely candidates. We aim to identify TFs whose expression is enriched in multiple cell types in the RNA measurements, but also have enriched accessibility for their motifs in the ATAC measurements.As an example and positive control, the CCAAT Enhancer Binding Protein (CEBP) family of proteins, including the TF CEBPB, have been repeatedly shown to play important roles in the differentiation and function of myeloid cells including monocytes and dendritic cells. We can see that both the expression of the CEBPB, and the accessibility of the MA0466.2.4 motif (which encodes the binding site for CEBPB), are both enriched in monocytes. #returns MA0466.2 motif.name <- ConvertMotifID(pbmc, name = 'CEBPB') gene_plot <- FeaturePlot(pbmc, features = "sct_CEBPB", reduction = 'wnn.umap') motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap') gene_plot | motif_plotWe’d like to quantify this relationship, and search across all cell types to find similar examples. To do so, we will use the presto package to perform fast differential expression. We run two tests: one using gene expression data, and the other using chromVAR motif accessibilities. presto calculates a p-value based on the Wilcox rank sum test, which is also the default test in Seurat, and we restrict our search to TFs that return significant results in both tests.presto also calculates an “AUC” statistic, which reflects the power of each gene (or motif) to serve as a marker of cell type. A maximum AUC value of 1 indicates a perfect marker. Since the AUC statistic is on the same scale for both genes and motifs, we take the average of the AUC values from the two tests, and use this to rank TFs for each cell type: markers_rna <- presto:::wilcoxauc.Seurat(X = pbmc, group_by = 'celltype', assay = 'data', seurat_assay = 'SCT') markers_motifs <- presto:::wilcoxauc.Seurat(X = pbmc, group_by = 'celltype', assay = 'data', seurat_assay = 'chromvar') motif.names <- markers_motifs$feature colnames(markers_rna) <- paste0("RNA.", colnames(markers_rna)) colnames(markers_motifs) <- paste0("motif.", colnames(markers_motifs)) markers_rna$gene <- markers_rna$RNA.feature markers_motifs$gene <- ConvertMotifID(pbmc, id = motif.names) # a simple function to implement the procedure above topTFs <- function(celltype, padj.cutoff = 1e-2) { ctmarkers_rna <- dplyr::filter( markers_rna, RNA.group == celltype, RNA.padj < padj.cutoff, RNA.logFC > 0) %>% arrange(-RNA.auc) ctmarkers_motif <- dplyr::filter( markers_motifs, motif.group == celltype, motif.padj < padj.cutoff, motif.logFC > 0) %>% arrange(-motif.auc) top_tfs <- inner_join( x = ctmarkers_rna[, c(2, 11, 6, 7)], y = ctmarkers_motif[, c(2, 1, 11, 6, 7)], by = "gene" ) top_tfs$avg_auc <- (top_tfs$RNA.auc + top_tfs$motif.auc) / 2 top_tfs <- arrange(top_tfs, -avg_auc) return(top_tfs) }We can now compute, and visualize, putative regulators for any cell type. We recover well-established regulators, including TBX21 for NK cells, IRF4 for plasma cells, SOX4 for hematopoietic progenitors, EBF1 and PAX5 for B cells, IRF8 and TCF4 for pDC. We believe that similar strategies can be used to help focus on a set of putative regulators in diverse systems. # identify top markers in NK and visualize head(topTFs("NK"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 NK TBX21 0.7270859 0.000000e+00 NK MA0690.1 0.9139614 ## 2 NK EOMES 0.5886774 2.411013e-98 NK MA0800.1 0.9214773 ## 3 NK RUNX3 0.7705661 5.977716e-120 NK MA0684.2 0.6769022 ## motif.pval avg_auc ## 1 1.097940e-202 0.8205237 ## 2 4.903866e-210 0.7550774 ## 3 1.560061e-38 0.7237341 motif.name <- ConvertMotifID(pbmc, name = 'TBX21') gene_plot <- FeaturePlot(pbmc, features = "sct_TBX21", reduction = 'wnn.umap') motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap') gene_plot | motif_plot # identify top markers in pDC and visualize head(topTFs("pDC"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 pDC TCF4 0.9998815 1.120711e-162 pDC MA0830.2 0.9965481 ## 2 pDC IRF8 0.9904457 1.308164e-123 pDC MA0652.1 0.8833112 ## 3 pDC SPIB 0.9115207 0.000000e+00 pDC MA0081.2 0.9068540 ## motif.pval avg_auc ## 1 1.785897e-69 0.9982148 ## 2 3.982413e-42 0.9368785 ## 3 3.083509e-47 0.9091874 motif.name <- ConvertMotifID(pbmc, name = 'TCF4') gene_plot <- FeaturePlot(pbmc, features = "sct_TCF4", reduction = 'wnn.umap') motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap') gene_plot | motif_plot # identify top markers in HSPC and visualize head(topTFs("CD16 Mono"),3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 CD16 Mono SPI1 0.8793172 1.666810e-296 CD16 Mono MA0080.5 0.8880908 ## 2 CD16 Mono CEBPB 0.8685933 1.625472e-294 CD16 Mono MA0466.2 0.7840422 ## 3 CD16 Mono MEF2C 0.7129910 2.727252e-79 CD16 Mono MA0497.1 0.8059373 ## motif.pval avg_auc ## 1 4.762491e-194 0.8837040 ## 2 7.049764e-105 0.8263177 ## 3 2.345716e-121 0.7594641 motif.name <- ConvertMotifID(pbmc, name = 'SPI1') gene_plot <- FeaturePlot(pbmc, features = "sct_SPI1", reduction = 'wnn.umap') motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap') gene_plot | motif_plot # identify top markers in other cell types head(topTFs("Naive B"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 Naive B MEF2C 0.8802747 1.890065e-182 Naive B MA0497.1 0.6789079 ## 2 Naive B PAX5 0.9436648 0.000000e+00 Naive B MA0014.3 0.5827061 ## 3 Naive B POU2F2 0.6029377 2.892216e-13 Naive B MA0507.1 0.8912268 ## motif.pval avg_auc ## 1 9.815118e-32 0.7795913 ## 2 5.995185e-08 0.7631854 ## 3 6.471677e-145 0.7470822 head(topTFs("HSPC"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 HSPC SOX4 0.9869406 5.524832e-71 HSPC MA0867.2 0.6830497 ## 2 HSPC GATA2 0.7884615 0.000000e+00 HSPC MA0036.3 0.8275008 ## 3 HSPC MEIS1 0.8638496 0.000000e+00 HSPC MA0498.2 0.6924225 ## motif.pval avg_auc ## 1 1.241915e-03 0.8349951 ## 2 7.591798e-09 0.8079812 ## 3 6.877492e-04 0.7781361 head(topTFs("Plasma"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 Plasma IRF4 0.8189687 5.261955e-35 Plasma MA1419.1 0.9776046 ## 2 Plasma MEF2C 0.9111213 2.977155e-12 Plasma MA0497.1 0.7596637 ## 3 Plasma TCF4 0.8049409 6.810635e-12 Plasma MA0830.2 0.7840848 ## motif.pval avg_auc ## 1 2.334627e-12 0.8982867 ## 2 1.374353e-04 0.8353925 ## 3 3.028306e-05 0.7945129Session Info sessionInfo()## R version 4.2.0 (2022-04-22) ## Platform: x86_64-pc-linux-gnu (64-bit) ## Running under: Ubuntu 20.04.5 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/liblapack.so.3 ## ## locale: ## [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C ## [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8 ## [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 ## ## attached base packages: ## [1] stats4 stats graphics grDevices utils datasets methods ## [8] base ## ## other attached packages: ## [1] BSgenome.Hsapiens.UCSC.hg38_1.4.5 BSgenome_1.66.3 ## [3] rtracklayer_1.58.0 Biostrings_2.66.0 ## [5] XVector_0.38.0 motifmatchr_1.20.0 ## [7] TFBSTools_1.36.0 JASPAR2020_0.99.10 ## [9] chromVAR_1.20.2 EnsDb.Hsapiens.v86_2.99.0 ## [11] ensembldb_2.22.0 AnnotationFilter_1.22.0 ## [13] GenomicFeatures_1.50.4 AnnotationDbi_1.60.0 ## [15] Biobase_2.58.0 GenomicRanges_1.50.2 ## [17] GenomeInfoDb_1.35.16 IRanges_2.32.0 ## [19] S4Vectors_0.36.2 BiocGenerics_0.44.0 ## [21] Signac_1.9.0 ggplot2_3.4.1 ## [23] dplyr_1.1.1 cowplot_1.1.1 ## [25] thp1.eccite.SeuratData_3.1.5 stxBrain.SeuratData_0.1.1 ## [27] ssHippo.SeuratData_3.1.4 pbmcsca.SeuratData_3.0.0 ## [29] pbmcMultiome.SeuratData_0.1.2 pbmc3k.SeuratData_3.1.4 ## [31] panc8.SeuratData_3.0.2 ifnb.SeuratData_3.1.0 ## [33] hcabm40k.SeuratData_3.0.0 bmcite.SeuratData_0.3.0 ## [35] SeuratData_0.2.2 SeuratObject_4.1.3 ## [37] Seurat_4.2.1.9001 ## ## loaded via a namespace (and not attached): ## [1] rappdirs_0.3.3 scattermore_0.8 ## [3] R.methodsS3_1.8.2 ragg_1.2.5 ## [5] nabor_0.5.0 tidyr_1.3.0 ## [7] bit64_4.0.5 knitr_1.42 ## [9] R.utils_2.12.2 irlba_2.3.5.1 ## [11] DelayedArray_0.24.0 data.table_1.14.8 ## [13] rpart_4.1.16 KEGGREST_1.38.0 ## [15] RCurl_1.98-1.12 generics_0.1.3 ## [17] RSQLite_2.3.0 RANN_2.6.1 ## [19] future_1.32.0 tzdb_0.3.0 ## [21] bit_4.0.5 spatstat.data_3.0-1 ## [23] xml2_1.3.3 httpuv_1.6.9 ## [25] SummarizedExperiment_1.28.0 DirichletMultinomial_1.40.0 ## [27] xfun_0.38 hms_1.1.2 ## [29] jquerylib_0.1.4 evaluate_0.20 ## [31] promises_1.2.0.1 fansi_1.0.4 ## [33] restfulr_0.0.15 progress_1.2.2 ## [35] caTools_1.18.2 dbplyr_2.3.1 ## [37] igraph_1.4.1 DBI_1.1.3 ## [39] htmlwidgets_1.6.2 spatstat.geom_3.1-0 ## [41] purrr_1.0.1 ellipsis_0.3.2 ## [43] backports_1.4.1 annotate_1.76.0 ## [45] biomaRt_2.54.0 deldir_1.0-6 ## [47] MatrixGenerics_1.10.0 vctrs_0.6.1 ## [49] ROCR_1.0-11 abind_1.4-5 ## [51] cachem_1.0.7 withr_2.5.0 ## [53] progressr_0.13.0 presto_1.0.0 ## [55] checkmate_2.1.0 sctransform_0.3.5 ## [57] GenomicAlignments_1.34.0 prettyunits_1.1.1 ## [59] goftest_1.2-3 cluster_2.1.3 ## [61] seqLogo_1.64.0 lazyeval_0.2.2 ## [63] crayon_1.5.2 hdf5r_1.3.8 ## [65] spatstat.explore_3.1-0 pkgconfig_2.0.3 ## [67] labeling_0.4.2 nlme_3.1-157 ## [69] ProtGenerics_1.30.0 nnet_7.3-17 ## [71] rlang_1.1.0 globals_0.16.2 ## [73] lifecycle_1.0.3 miniUI_0.1.1.1 ## [75] filelock_1.0.2 BiocFileCache_2.6.1 ## [77] dichromat_2.0-0.1 rprojroot_2.0.3 ## [79] polyclip_1.10-4 matrixStats_0.63.0 ## [81] lmtest_0.9-40 Matrix_1.5-3 ## [83] zoo_1.8-11 base64enc_0.1-3 ## [85] ggridges_0.5.4 png_0.1-8 ## [87] viridisLite_0.4.1 rjson_0.2.21 ## [89] bitops_1.0-7 R.oo_1.25.0 ## [91] KernSmooth_2.23-20 blob_1.2.3 ## [93] stringr_1.5.0 parallelly_1.35.0 ## [95] spatstat.random_3.1-4 readr_2.1.4 ## [97] jpeg_0.1-10 CNEr_1.34.0 ## [99] scales_1.2.1 memoise_2.0.1 ## [101] magrittr_2.0.3 plyr_1.8.8 ## [103] ica_1.0-3 zlibbioc_1.44.0 ## [105] compiler_4.2.0 BiocIO_1.8.0 ## [107] RColorBrewer_1.1-3 fitdistrplus_1.1-8 ## [109] Rsamtools_2.14.0 cli_3.6.1 ## [111] listenv_0.9.0 patchwork_1.1.2 ## [113] pbapply_1.7-0 htmlTable_2.4.1 ## [115] Formula_1.2-5 MASS_7.3-56 ## [117] tidyselect_1.2.0 stringi_1.7.12 ## [119] textshaping_0.3.6 highr_0.10 ## [121] yaml_2.3.7 latticeExtra_0.6-30 ## [123] ggrepel_0.9.3 grid_4.2.0 ## [125] sass_0.4.5 VariantAnnotation_1.44.1 ## [127] fastmatch_1.1-3 tools_4.2.0 ## [129] future.apply_1.10.0 parallel_4.2.0 ## [131] rstudioapi_0.14 TFMPvalue_0.0.9 ## [133] foreign_0.8-82 gridExtra_2.3 ## [135] farver_2.1.1 Rtsne_0.16 ## [137] digest_0.6.31 pracma_2.4.2 ## [139] shiny_1.7.4 Rcpp_1.0.10 ## [141] later_1.3.0 RcppAnnoy_0.0.20 ## [143] httr_1.4.5 biovizBase_1.46.0 ## [145] colorspace_2.1-0 XML_3.99-0.13 ## [147] fs_1.6.1 tensor_1.5 ## [149] reticulate_1.28 splines_4.2.0 ## [151] uwot_0.1.14 RcppRoll_0.3.0 ## [153] spatstat.utils_3.0-2 pkgdown_2.0.7 ## [155] sp_1.6-0 plotly_4.10.1 ## [157] systemfonts_1.0.4 xtable_1.8-4 ## [159] poweRlaw_0.70.6 jsonlite_1.8.4 ## [161] R6_2.5.1 Hmisc_4.8-0 ## [163] pillar_1.9.0 htmltools_0.5.5 ## [165] mime_0.12 DT_0.27 ## [167] glue_1.6.2 fastmap_1.1.1 ## [169] BiocParallel_1.32.5 codetools_0.2-18 ## [171] utf8_1.2.3 lattice_0.20-45 ## [173] bslib_0.4.2 spatstat.sparse_3.0-1 ## [175] tibble_3.2.1 curl_5.0.0 ## [177] leiden_0.4.3 gtools_3.9.4 ## [179] GO.db_3.16.0 interp_1.1-3 ## [181] survival_3.3-1 rmarkdown_2.21 ## [183] desc_1.4.2 munsell_0.5.0 ## [185] GenomeInfoDbData_1.2.9 reshape2_1.4.4 ## [187] gtable_0.3.3

We use the CITE-seq dataset from (Stuart*, Butler* et al, Cell 2019), which consists of 30,672 scRNA-seq profiles measured alongside a panel of 25 antibodies from bone marrow. The object contains two assays, RNA and antibody-derived tags (ADT).To run this vignette please install Seurat v4, available on CRAN, and SeuratData, available on GitHub. install.packages("Seurat") library(Seurat) library(SeuratData) library(cowplot) library(dplyr) InstallData("bmcite") bm <- LoadData(ds = "bmcite")We first perform pre-processing and dimensional reduction on both assays independently. We use standard normalization, but you can also use SCTransform or any alternative method. DefaultAssay(bm) <- 'RNA' bm <- NormalizeData(bm) %>% FindVariableFeatures() %>% ScaleData() %>% RunPCA() DefaultAssay(bm) <- 'ADT' # we will use all ADT features for dimensional reduction # we set a dimensional reduction name to avoid overwriting the VariableFeatures(bm) <- rownames(bm[["ADT"]]) bm <- NormalizeData(bm, normalization.method = 'CLR', margin = 2) %>% ScaleData() %>% RunPCA(reduction.name = 'apca')For each cell, we calculate its closest neighbors in the dataset based on a weighted combination of RNA and protein similarities. The cell-specific modality weights and multimodal neighbors are calculated in a single function, which takes ~2 minutes to run on this dataset. We specify the dimensionality of each modality (similar to specifying the number of PCs to include in scRNA-seq clustering), but you can vary these settings to see that small changes have minimal effect on the overall results. # Identify multimodal neighbors. These will be stored in the neighbors slot, # and can be accessed using bm[['weighted.nn']] # The WNN graph can be accessed at bm[["wknn"]], # and the SNN graph used for clustering at bm[["wsnn"]] # Cell-specific modality weights can be accessed at bm$RNA.weight bm <- FindMultiModalNeighbors( bm, reduction.list = list("pca", "apca"), dims.list = list(1:30, 1:18), modality.weight.name = "RNA.weight" )We can now use these results for downstream analysis, such as visualization and clustering. For example, we can create a UMAP visualization of the data based on a weighted combination of RNA and protein data We can also perform graph-based clustering and visualize these results on the UMAP, alongside a set of cell annotations. bm <- RunUMAP(bm, nn.name = "weighted.nn", reduction.name = "wnn.umap", reduction.key = "wnnUMAP_") bm <- FindClusters(bm, graph.name = "wsnn", algorithm = 3, resolution = 2, verbose = FALSE) p1 <- DimPlot(bm, reduction = 'wnn.umap', label = TRUE, repel = TRUE, label.size = 2.5) + NoLegend() p2 <- DimPlot(bm, reduction = 'wnn.umap', group.by = 'celltype.l2', label = TRUE, repel = TRUE, label.size = 2.5) + NoLegend() p1 + p2We can also compute UMAP visualization based on only the RNA and protein data and compare. We find that the RNA analysis is more informative than the ADT analysis in identifying progenitor states (the ADT panel contains markers for differentiated cells), while the converse is true of T cell states (where the ADT analysis outperforms RNA). bm <- RunUMAP(bm, reduction = 'pca', dims = 1:30, assay = 'RNA', reduction.name = 'rna.umap', reduction.key = 'rnaUMAP_') bm <- RunUMAP(bm, reduction = 'apca', dims = 1:18, assay = 'ADT', reduction.name = 'adt.umap', reduction.key = 'adtUMAP_') p3 <- DimPlot(bm, reduction = 'rna.umap', group.by = 'celltype.l2', label = TRUE, repel = TRUE, label.size = 2.5) + NoLegend() p4 <- DimPlot(bm, reduction = 'adt.umap', group.by = 'celltype.l2', label = TRUE, repel = TRUE, label.size = 2.5) + NoLegend() p3 + p4We can visualize the expression of canonical marker genes and proteins on the multimodal UMAP, which can assist in verifying the provided annotations: p5 <- FeaturePlot(bm, features = c("adt_CD45RA","adt_CD16","adt_CD161"), reduction = 'wnn.umap', max.cutoff = 2, cols = c("lightgrey","darkgreen"), ncol = 3) p6 <- FeaturePlot(bm, features = c("rna_TRDC","rna_MPO","rna_AVP"), reduction = 'wnn.umap', max.cutoff = 3, ncol = 3) p5 / p6Finally, we can visualize the modality weights that were learned for each cell. Each of the populations with the highest RNA weights represent progenitor cells, while the populations with the highest protein weights represent T cells. This is in line with our biological expectations, as the antibody panel does not contain markers that can distinguish between different progenitor populations. VlnPlot(bm, features = "RNA.weight", group.by = 'celltype.l2', sort = TRUE, pt.size = 0.1) + NoLegend()

To run this vignette please install Seurat v4, available on CRAN, and SeuratData, available on GitHub. install.packages("Seurat") library(Seurat) library(SeuratData) library(cowplot) library(dplyr) InstallData("bmcite") bm <- LoadData(ds = "bmcite")We first perform pre-processing and dimensional reduction on both assays independently. We use standard normalization, but you can also use SCTransform or any alternative method. DefaultAssay(bm) <- 'RNA' bm <- NormalizeData(bm) %>% FindVariableFeatures() %>% ScaleData() %>% RunPCA() DefaultAssay(bm) <- 'ADT' # we will use all ADT features for dimensional reduction # we set a dimensional reduction name to avoid overwriting the VariableFeatures(bm) <- rownames(bm[["ADT"]]) bm <- NormalizeData(bm, normalization.method = 'CLR', margin = 2) %>% ScaleData() %>% RunPCA(reduction.name = 'apca')For each cell, we calculate its closest neighbors in the dataset based on a weighted combination of RNA and protein similarities. The cell-specific modality weights and multimodal neighbors are calculated in a single function, which takes ~2 minutes to run on this dataset. We specify the dimensionality of each modality (similar to specifying the number of PCs to include in scRNA-seq clustering), but you can vary these settings to see that small changes have minimal effect on the overall results. # Identify multimodal neighbors. These will be stored in the neighbors slot, # and can be accessed using bm[['weighted.nn']] # The WNN graph can be accessed at bm[["wknn"]], # and the SNN graph used for clustering at bm[["wsnn"]] # Cell-specific modality weights can be accessed at bm$RNA.weight bm <- FindMultiModalNeighbors( bm, reduction.list = list("pca", "apca"), dims.list = list(1:30, 1:18), modality.weight.name = "RNA.weight" )We can now use these results for downstream analysis, such as visualization and clustering. For example, we can create a UMAP visualization of the data based on a weighted combination of RNA and protein data We can also perform graph-based clustering and visualize these results on the UMAP, alongside a set of cell annotations. bm <- RunUMAP(bm, nn.name = "weighted.nn", reduction.name = "wnn.umap", reduction.key = "wnnUMAP_") bm <- FindClusters(bm, graph.name = "wsnn", algorithm = 3, resolution = 2, verbose = FALSE) p1 <- DimPlot(bm, reduction = 'wnn.umap', label = TRUE, repel = TRUE, label.size = 2.5) + NoLegend() p2 <- DimPlot(bm, reduction = 'wnn.umap', group.by = 'celltype.l2', label = TRUE, repel = TRUE, label.size = 2.5) + NoLegend() p1 + p2We can also compute UMAP visualization based on only the RNA and protein data and compare. We find that the RNA analysis is more informative than the ADT analysis in identifying progenitor states (the ADT panel contains markers for differentiated cells), while the converse is true of T cell states (where the ADT analysis outperforms RNA). bm <- RunUMAP(bm, reduction = 'pca', dims = 1:30, assay = 'RNA', reduction.name = 'rna.umap', reduction.key = 'rnaUMAP_') bm <- RunUMAP(bm, reduction = 'apca', dims = 1:18, assay = 'ADT', reduction.name = 'adt.umap', reduction.key = 'adtUMAP_') p3 <- DimPlot(bm, reduction = 'rna.umap', group.by = 'celltype.l2', label = TRUE, repel = TRUE, label.size = 2.5) + NoLegend() p4 <- DimPlot(bm, reduction = 'adt.umap', group.by = 'celltype.l2', label = TRUE, repel = TRUE, label.size = 2.5) + NoLegend() p3 + p4We can visualize the expression of canonical marker genes and proteins on the multimodal UMAP, which can assist in verifying the provided annotations: p5 <- FeaturePlot(bm, features = c("adt_CD45RA","adt_CD16","adt_CD161"), reduction = 'wnn.umap', max.cutoff = 2, cols = c("lightgrey","darkgreen"), ncol = 3) p6 <- FeaturePlot(bm, features = c("rna_TRDC","rna_MPO","rna_AVP"), reduction = 'wnn.umap', max.cutoff = 3, ncol = 3) p5 / p6Finally, we can visualize the modality weights that were learned for each cell. Each of the populations with the highest RNA weights represent progenitor cells, while the populations with the highest protein weights represent T cells. This is in line with our biological expectations, as the antibody panel does not contain markers that can distinguish between different progenitor populations. VlnPlot(bm, features = "RNA.weight", group.by = 'celltype.l2', sort = TRUE, pt.size = 0.1) + NoLegend()

We first perform pre-processing and dimensional reduction on both assays independently. We use standard normalization, but you can also use SCTransform or any alternative method. DefaultAssay(bm) <- 'RNA' bm <- NormalizeData(bm) %>% FindVariableFeatures() %>% ScaleData() %>% RunPCA() DefaultAssay(bm) <- 'ADT' # we will use all ADT features for dimensional reduction # we set a dimensional reduction name to avoid overwriting the VariableFeatures(bm) <- rownames(bm[["ADT"]]) bm <- NormalizeData(bm, normalization.method = 'CLR', margin = 2) %>% ScaleData() %>% RunPCA(reduction.name = 'apca')For each cell, we calculate its closest neighbors in the dataset based on a weighted combination of RNA and protein similarities. The cell-specific modality weights and multimodal neighbors are calculated in a single function, which takes ~2 minutes to run on this dataset. We specify the dimensionality of each modality (similar to specifying the number of PCs to include in scRNA-seq clustering), but you can vary these settings to see that small changes have minimal effect on the overall results. # Identify multimodal neighbors. These will be stored in the neighbors slot, # and can be accessed using bm[['weighted.nn']] # The WNN graph can be accessed at bm[["wknn"]], # and the SNN graph used for clustering at bm[["wsnn"]] # Cell-specific modality weights can be accessed at bm$RNA.weight bm <- FindMultiModalNeighbors( bm, reduction.list = list("pca", "apca"), dims.list = list(1:30, 1:18), modality.weight.name = "RNA.weight" )We can now use these results for downstream analysis, such as visualization and clustering. For example, we can create a UMAP visualization of the data based on a weighted combination of RNA and protein data We can also perform graph-based clustering and visualize these results on the UMAP, alongside a set of cell annotations. bm <- RunUMAP(bm, nn.name = "weighted.nn", reduction.name = "wnn.umap", reduction.key = "wnnUMAP_") bm <- FindClusters(bm, graph.name = "wsnn", algorithm = 3, resolution = 2, verbose = FALSE) p1 <- DimPlot(bm, reduction = 'wnn.umap', label = TRUE, repel = TRUE, label.size = 2.5) + NoLegend() p2 <- DimPlot(bm, reduction = 'wnn.umap', group.by = 'celltype.l2', label = TRUE, repel = TRUE, label.size = 2.5) + NoLegend() p1 + p2We can also compute UMAP visualization based on only the RNA and protein data and compare. We find that the RNA analysis is more informative than the ADT analysis in identifying progenitor states (the ADT panel contains markers for differentiated cells), while the converse is true of T cell states (where the ADT analysis outperforms RNA). bm <- RunUMAP(bm, reduction = 'pca', dims = 1:30, assay = 'RNA', reduction.name = 'rna.umap', reduction.key = 'rnaUMAP_') bm <- RunUMAP(bm, reduction = 'apca', dims = 1:18, assay = 'ADT', reduction.name = 'adt.umap', reduction.key = 'adtUMAP_') p3 <- DimPlot(bm, reduction = 'rna.umap', group.by = 'celltype.l2', label = TRUE, repel = TRUE, label.size = 2.5) + NoLegend() p4 <- DimPlot(bm, reduction = 'adt.umap', group.by = 'celltype.l2', label = TRUE, repel = TRUE, label.size = 2.5) + NoLegend() p3 + p4We can visualize the expression of canonical marker genes and proteins on the multimodal UMAP, which can assist in verifying the provided annotations: p5 <- FeaturePlot(bm, features = c("adt_CD45RA","adt_CD16","adt_CD161"), reduction = 'wnn.umap', max.cutoff = 2, cols = c("lightgrey","darkgreen"), ncol = 3) p6 <- FeaturePlot(bm, features = c("rna_TRDC","rna_MPO","rna_AVP"), reduction = 'wnn.umap', max.cutoff = 3, ncol = 3) p5 / p6Finally, we can visualize the modality weights that were learned for each cell. Each of the populations with the highest RNA weights represent progenitor cells, while the populations with the highest protein weights represent T cells. This is in line with our biological expectations, as the antibody panel does not contain markers that can distinguish between different progenitor populations. VlnPlot(bm, features = "RNA.weight", group.by = 'celltype.l2', sort = TRUE, pt.size = 0.1) + NoLegend()

For each cell, we calculate its closest neighbors in the dataset based on a weighted combination of RNA and protein similarities. The cell-specific modality weights and multimodal neighbors are calculated in a single function, which takes ~2 minutes to run on this dataset. We specify the dimensionality of each modality (similar to specifying the number of PCs to include in scRNA-seq clustering), but you can vary these settings to see that small changes have minimal effect on the overall results. # Identify multimodal neighbors. These will be stored in the neighbors slot, # and can be accessed using bm[['weighted.nn']] # The WNN graph can be accessed at bm[["wknn"]], # and the SNN graph used for clustering at bm[["wsnn"]] # Cell-specific modality weights can be accessed at bm$RNA.weight bm <- FindMultiModalNeighbors( bm, reduction.list = list("pca", "apca"), dims.list = list(1:30, 1:18), modality.weight.name = "RNA.weight" )We can now use these results for downstream analysis, such as visualization and clustering. For example, we can create a UMAP visualization of the data based on a weighted combination of RNA and protein data We can also perform graph-based clustering and visualize these results on the UMAP, alongside a set of cell annotations. bm <- RunUMAP(bm, nn.name = "weighted.nn", reduction.name = "wnn.umap", reduction.key = "wnnUMAP_") bm <- FindClusters(bm, graph.name = "wsnn", algorithm = 3, resolution = 2, verbose = FALSE) p1 <- DimPlot(bm, reduction = 'wnn.umap', label = TRUE, repel = TRUE, label.size = 2.5) + NoLegend() p2 <- DimPlot(bm, reduction = 'wnn.umap', group.by = 'celltype.l2', label = TRUE, repel = TRUE, label.size = 2.5) + NoLegend() p1 + p2We can also compute UMAP visualization based on only the RNA and protein data and compare. We find that the RNA analysis is more informative than the ADT analysis in identifying progenitor states (the ADT panel contains markers for differentiated cells), while the converse is true of T cell states (where the ADT analysis outperforms RNA). bm <- RunUMAP(bm, reduction = 'pca', dims = 1:30, assay = 'RNA', reduction.name = 'rna.umap', reduction.key = 'rnaUMAP_') bm <- RunUMAP(bm, reduction = 'apca', dims = 1:18, assay = 'ADT', reduction.name = 'adt.umap', reduction.key = 'adtUMAP_') p3 <- DimPlot(bm, reduction = 'rna.umap', group.by = 'celltype.l2', label = TRUE, repel = TRUE, label.size = 2.5) + NoLegend() p4 <- DimPlot(bm, reduction = 'adt.umap', group.by = 'celltype.l2', label = TRUE, repel = TRUE, label.size = 2.5) + NoLegend() p3 + p4We can visualize the expression of canonical marker genes and proteins on the multimodal UMAP, which can assist in verifying the provided annotations: p5 <- FeaturePlot(bm, features = c("adt_CD45RA","adt_CD16","adt_CD161"), reduction = 'wnn.umap', max.cutoff = 2, cols = c("lightgrey","darkgreen"), ncol = 3) p6 <- FeaturePlot(bm, features = c("rna_TRDC","rna_MPO","rna_AVP"), reduction = 'wnn.umap', max.cutoff = 3, ncol = 3) p5 / p6Finally, we can visualize the modality weights that were learned for each cell. Each of the populations with the highest RNA weights represent progenitor cells, while the populations with the highest protein weights represent T cells. This is in line with our biological expectations, as the antibody panel does not contain markers that can distinguish between different progenitor populations. VlnPlot(bm, features = "RNA.weight", group.by = 'celltype.l2', sort = TRUE, pt.size = 0.1) + NoLegend()

We can now use these results for downstream analysis, such as visualization and clustering. For example, we can create a UMAP visualization of the data based on a weighted combination of RNA and protein data We can also perform graph-based clustering and visualize these results on the UMAP, alongside a set of cell annotations. bm <- RunUMAP(bm, nn.name = "weighted.nn", reduction.name = "wnn.umap", reduction.key = "wnnUMAP_") bm <- FindClusters(bm, graph.name = "wsnn", algorithm = 3, resolution = 2, verbose = FALSE) p1 <- DimPlot(bm, reduction = 'wnn.umap', label = TRUE, repel = TRUE, label.size = 2.5) + NoLegend() p2 <- DimPlot(bm, reduction = 'wnn.umap', group.by = 'celltype.l2', label = TRUE, repel = TRUE, label.size = 2.5) + NoLegend() p1 + p2We can also compute UMAP visualization based on only the RNA and protein data and compare. We find that the RNA analysis is more informative than the ADT analysis in identifying progenitor states (the ADT panel contains markers for differentiated cells), while the converse is true of T cell states (where the ADT analysis outperforms RNA). bm <- RunUMAP(bm, reduction = 'pca', dims = 1:30, assay = 'RNA', reduction.name = 'rna.umap', reduction.key = 'rnaUMAP_') bm <- RunUMAP(bm, reduction = 'apca', dims = 1:18, assay = 'ADT', reduction.name = 'adt.umap', reduction.key = 'adtUMAP_') p3 <- DimPlot(bm, reduction = 'rna.umap', group.by = 'celltype.l2', label = TRUE, repel = TRUE, label.size = 2.5) + NoLegend() p4 <- DimPlot(bm, reduction = 'adt.umap', group.by = 'celltype.l2', label = TRUE, repel = TRUE, label.size = 2.5) + NoLegend() p3 + p4We can visualize the expression of canonical marker genes and proteins on the multimodal UMAP, which can assist in verifying the provided annotations: p5 <- FeaturePlot(bm, features = c("adt_CD45RA","adt_CD16","adt_CD161"), reduction = 'wnn.umap', max.cutoff = 2, cols = c("lightgrey","darkgreen"), ncol = 3) p6 <- FeaturePlot(bm, features = c("rna_TRDC","rna_MPO","rna_AVP"), reduction = 'wnn.umap', max.cutoff = 3, ncol = 3) p5 / p6Finally, we can visualize the modality weights that were learned for each cell. Each of the populations with the highest RNA weights represent progenitor cells, while the populations with the highest protein weights represent T cells. This is in line with our biological expectations, as the antibody panel does not contain markers that can distinguish between different progenitor populations. VlnPlot(bm, features = "RNA.weight", group.by = 'celltype.l2', sort = TRUE, pt.size = 0.1) + NoLegend()

We can also compute UMAP visualization based on only the RNA and protein data and compare. We find that the RNA analysis is more informative than the ADT analysis in identifying progenitor states (the ADT panel contains markers for differentiated cells), while the converse is true of T cell states (where the ADT analysis outperforms RNA). bm <- RunUMAP(bm, reduction = 'pca', dims = 1:30, assay = 'RNA', reduction.name = 'rna.umap', reduction.key = 'rnaUMAP_') bm <- RunUMAP(bm, reduction = 'apca', dims = 1:18, assay = 'ADT', reduction.name = 'adt.umap', reduction.key = 'adtUMAP_') p3 <- DimPlot(bm, reduction = 'rna.umap', group.by = 'celltype.l2', label = TRUE, repel = TRUE, label.size = 2.5) + NoLegend() p4 <- DimPlot(bm, reduction = 'adt.umap', group.by = 'celltype.l2', label = TRUE, repel = TRUE, label.size = 2.5) + NoLegend() p3 + p4We can visualize the expression of canonical marker genes and proteins on the multimodal UMAP, which can assist in verifying the provided annotations: p5 <- FeaturePlot(bm, features = c("adt_CD45RA","adt_CD16","adt_CD161"), reduction = 'wnn.umap', max.cutoff = 2, cols = c("lightgrey","darkgreen"), ncol = 3) p6 <- FeaturePlot(bm, features = c("rna_TRDC","rna_MPO","rna_AVP"), reduction = 'wnn.umap', max.cutoff = 3, ncol = 3) p5 / p6Finally, we can visualize the modality weights that were learned for each cell. Each of the populations with the highest RNA weights represent progenitor cells, while the populations with the highest protein weights represent T cells. This is in line with our biological expectations, as the antibody panel does not contain markers that can distinguish between different progenitor populations. VlnPlot(bm, features = "RNA.weight", group.by = 'celltype.l2', sort = TRUE, pt.size = 0.1) + NoLegend()

We can also compute UMAP visualization based on only the RNA and protein data and compare. We find that the RNA analysis is more informative than the ADT analysis in identifying progenitor states (the ADT panel contains markers for differentiated cells), while the converse is true of T cell states (where the ADT analysis outperforms RNA). bm <- RunUMAP(bm, reduction = 'pca', dims = 1:30, assay = 'RNA', reduction.name = 'rna.umap', reduction.key = 'rnaUMAP_') bm <- RunUMAP(bm, reduction = 'apca', dims = 1:18, assay = 'ADT', reduction.name = 'adt.umap', reduction.key = 'adtUMAP_') p3 <- DimPlot(bm, reduction = 'rna.umap', group.by = 'celltype.l2', label = TRUE, repel = TRUE, label.size = 2.5) + NoLegend() p4 <- DimPlot(bm, reduction = 'adt.umap', group.by = 'celltype.l2', label = TRUE, repel = TRUE, label.size = 2.5) + NoLegend() p3 + p4We can visualize the expression of canonical marker genes and proteins on the multimodal UMAP, which can assist in verifying the provided annotations: p5 <- FeaturePlot(bm, features = c("adt_CD45RA","adt_CD16","adt_CD161"), reduction = 'wnn.umap', max.cutoff = 2, cols = c("lightgrey","darkgreen"), ncol = 3) p6 <- FeaturePlot(bm, features = c("rna_TRDC","rna_MPO","rna_AVP"), reduction = 'wnn.umap', max.cutoff = 3, ncol = 3) p5 / p6Finally, we can visualize the modality weights that were learned for each cell. Each of the populations with the highest RNA weights represent progenitor cells, while the populations with the highest protein weights represent T cells. This is in line with our biological expectations, as the antibody panel does not contain markers that can distinguish between different progenitor populations. VlnPlot(bm, features = "RNA.weight", group.by = 'celltype.l2', sort = TRUE, pt.size = 0.1) + NoLegend()

We can visualize the expression of canonical marker genes and proteins on the multimodal UMAP, which can assist in verifying the provided annotations: p5 <- FeaturePlot(bm, features = c("adt_CD45RA","adt_CD16","adt_CD161"), reduction = 'wnn.umap', max.cutoff = 2, cols = c("lightgrey","darkgreen"), ncol = 3) p6 <- FeaturePlot(bm, features = c("rna_TRDC","rna_MPO","rna_AVP"), reduction = 'wnn.umap', max.cutoff = 3, ncol = 3) p5 / p6Finally, we can visualize the modality weights that were learned for each cell. Each of the populations with the highest RNA weights represent progenitor cells, while the populations with the highest protein weights represent T cells. This is in line with our biological expectations, as the antibody panel does not contain markers that can distinguish between different progenitor populations. VlnPlot(bm, features = "RNA.weight", group.by = 'celltype.l2', sort = TRUE, pt.size = 0.1) + NoLegend()

We can visualize the expression of canonical marker genes and proteins on the multimodal UMAP, which can assist in verifying the provided annotations: p5 <- FeaturePlot(bm, features = c("adt_CD45RA","adt_CD16","adt_CD161"), reduction = 'wnn.umap', max.cutoff = 2, cols = c("lightgrey","darkgreen"), ncol = 3) p6 <- FeaturePlot(bm, features = c("rna_TRDC","rna_MPO","rna_AVP"), reduction = 'wnn.umap', max.cutoff = 3, ncol = 3) p5 / p6Finally, we can visualize the modality weights that were learned for each cell. Each of the populations with the highest RNA weights represent progenitor cells, while the populations with the highest protein weights represent T cells. This is in line with our biological expectations, as the antibody panel does not contain markers that can distinguish between different progenitor populations. VlnPlot(bm, features = "RNA.weight", group.by = 'celltype.l2', sort = TRUE, pt.size = 0.1) + NoLegend()

Finally, we can visualize the modality weights that were learned for each cell. Each of the populations with the highest RNA weights represent progenitor cells, while the populations with the highest protein weights represent T cells. This is in line with our biological expectations, as the antibody panel does not contain markers that can distinguish between different progenitor populations. VlnPlot(bm, features = "RNA.weight", group.by = 'celltype.l2', sort = TRUE, pt.size = 0.1) + NoLegend()

Finally, we can visualize the modality weights that were learned for each cell. Each of the populations with the highest RNA weights represent progenitor cells, while the populations with the highest protein weights represent T cells. This is in line with our biological expectations, as the antibody panel does not contain markers that can distinguish between different progenitor populations. VlnPlot(bm, features = "RNA.weight", group.by = 'celltype.l2', sort = TRUE, pt.size = 0.1) + NoLegend()

Here, we demonstrate the use of WNN analysis to a second multimodal technology, the 10x multiome RNA+ATAC kit. We use a dataset that is publicly available on the 10x website, where paired transcriptomes and ATAC-seq profiles are measured in 10,412 PBMCs.We use the same WNN methods as we use in the previous tab, where we apply integrated multimodal analysis to a CITE-seq dataset. In this example we will demonstrate how to:Create a multimodal Seurat object with paired transcriptome and ATAC-seq profilesPerform weighted neighbor clustering on RNA+ATAC data in single cellsLeverage both modalities to identify putative regulators of different cell types and statesYou can download the dataset from the 10x Genomics website here. Please make sure to download the following files:Filtered feature barcode matrix (HDF5)ATAC Per fragment information file (TSV.GZ)ATAC Per fragment information index (TSV.GZ index)Finally, in order to run the vignette, make sure the following packages are installed:Seurat v4Signac for the analysis of single-cell chromatin datasetsEnsDb.Hsapiens.v86 for a set of annotations for hg38dplyr to help manipulate data tables library(Seurat) library(Signac) library(EnsDb.Hsapiens.v86) library(dplyr) library(ggplot2)We’ll create a Seurat object based on the gene expression data, and then add in the ATAC-seq data as a second assay. You can explore the Signac getting started vignette for more information on the creation and processing of a ChromatinAssay object. # the 10x hdf5 file contains both data types. inputdata.10x <- Read10X_h5("../data/pbmc_granulocyte_sorted_10k_filtered_feature_bc_matrix.h5") # extract RNA and ATAC data rna_counts <- inputdata.10x$`Gene Expression` atac_counts <- inputdata.10x$Peaks # Create Seurat object pbmc <- CreateSeuratObject(counts = rna_counts) pbmc[["percent.mt"]] <- PercentageFeatureSet(pbmc, pattern = "^MT-") # Now add in the ATAC-seq data # we'll only use peaks in standard chromosomes grange.counts <- StringToGRanges(rownames(atac_counts), sep = c(":", "-")) grange.use <- seqnames(grange.counts) %in% standardChromosomes(grange.counts) atac_counts <- atac_counts[as.vector(grange.use), ] annotations <- GetGRangesFromEnsDb(ensdb = EnsDb.Hsapiens.v86) seqlevelsStyle(annotations) <- 'UCSC' genome(annotations) <- "hg38" frag.file <- "../data/pbmc_granulocyte_sorted_10k_atac_fragments.tsv.gz" chrom_assay <- CreateChromatinAssay( counts = atac_counts, sep = c(":", "-"), genome = 'hg38', fragments = frag.file, min.cells = 10, annotation = annotations ) pbmc[["ATAC"]] <- chrom_assayWe perform basic QC based on the number of detected molecules for each modality as well as mitochondrial percentage. VlnPlot(pbmc, features = c("nCount_ATAC", "nCount_RNA","percent.mt"), ncol = 3, log = TRUE, pt.size = 0) + NoLegend() pbmc <- subset( x = pbmc, subset = nCount_ATAC < 7e4 & nCount_ATAC > 5e3 & nCount_RNA < 25000 & nCount_RNA > 1000 & percent.mt < 20 )We next perform pre-processing and dimensional reduction on both assays independently, using standard approaches for RNA and ATAC-seq data. # RNA analysis DefaultAssay(pbmc) <- "RNA" pbmc <- SCTransform(pbmc, verbose = FALSE) %>% RunPCA() %>% RunUMAP(dims = 1:50, reduction.name = 'umap.rna', reduction.key = 'rnaUMAP_') # ATAC analysis # We exclude the first dimension as this is typically correlated with sequencing depth DefaultAssay(pbmc) <- "ATAC" pbmc <- RunTFIDF(pbmc) pbmc <- FindTopFeatures(pbmc, min.cutoff = 'q0') pbmc <- RunSVD(pbmc) pbmc <- RunUMAP(pbmc, reduction = 'lsi', dims = 2:50, reduction.name = "umap.atac", reduction.key = "atacUMAP_")We calculate a WNN graph, representing a weighted combination of RNA and ATAC-seq modalities. We use this graph for UMAP visualization and clustering pbmc <- FindMultiModalNeighbors(pbmc, reduction.list = list("pca", "lsi"), dims.list = list(1:50, 2:50)) pbmc <- RunUMAP(pbmc, nn.name = "weighted.nn", reduction.name = "wnn.umap", reduction.key = "wnnUMAP_") pbmc <- FindClusters(pbmc, graph.name = "wsnn", algorithm = 3, verbose = FALSE)We annotate the clusters below. Note that you could also annotate the dataset using our supervised mapping pipelines, using either our vignette, or automated web tool, Azimuth. # perform sub-clustering on cluster 6 to find additional structure pbmc <- FindSubCluster(pbmc, cluster = 6, graph.name = "wsnn", algorithm = 3) Idents(pbmc) <- "sub.cluster" # add annotations pbmc <- RenameIdents(pbmc, '19' = 'pDC','20' = 'HSPC','15' = 'cDC') pbmc <- RenameIdents(pbmc, '0' = 'CD14 Mono', '9' ='CD14 Mono', '5' = 'CD16 Mono') pbmc <- RenameIdents(pbmc, '10' = 'Naive B', '11' = 'Intermediate B', '17' = 'Memory B', '21' = 'Plasma') pbmc <- RenameIdents(pbmc, '7' = 'NK') pbmc <- RenameIdents(pbmc, '4' = 'CD4 TCM', '13'= "CD4 TEM", '3' = "CD4 TCM", '16' ="Treg", '1' ="CD4 Naive", '14' = "CD4 Naive") pbmc <- RenameIdents(pbmc, '2' = 'CD8 Naive', '8'= "CD8 Naive", '12' = 'CD8 TEM_1', '6_0' = 'CD8 TEM_2', '6_1' ='CD8 TEM_2', '6_4' ='CD8 TEM_2') pbmc <- RenameIdents(pbmc, '18' = 'MAIT') pbmc <- RenameIdents(pbmc, '6_2' ='gdT', '6_3' = 'gdT') pbmc$celltype <- Idents(pbmc)We can visualize clustering based on gene expression, ATAC-seq, or WNN analysis. The differences are more subtle than in the previous analysis (you can explore the weights, which are more evenly split than in our CITE-seq example), but we find that WNN provides the clearest separation of cell states. p1 <- DimPlot(pbmc, reduction = "umap.rna", group.by = "celltype", label = TRUE, label.size = 2.5, repel = TRUE) + ggtitle("RNA") p2 <- DimPlot(pbmc, reduction = "umap.atac", group.by = "celltype", label = TRUE, label.size = 2.5, repel = TRUE) + ggtitle("ATAC") p3 <- DimPlot(pbmc, reduction = "wnn.umap", group.by = "celltype", label = TRUE, label.size = 2.5, repel = TRUE) + ggtitle("WNN") p1 + p2 + p3 & NoLegend() & theme(plot.title = element_text(hjust = 0.5))For example, the ATAC-seq data assists in the separation of CD4 and CD8 T cell states. This is due to the presence of multiple loci that exhibit differential accessibility between different T cell subtypes. For example, we can visualize ‘pseudobulk’ tracks of the CD8A locus alongside violin plots of gene expression levels, using tools in the Signac visualization vignette. ## to make the visualization easier, subset T cell clusters celltype.names <- levels(pbmc) tcell.names <- grep("CD4|CD8|Treg", celltype.names,value = TRUE) tcells <- subset(pbmc, idents = tcell.names) CoveragePlot(tcells, region = 'CD8A', features = 'CD8A', assay = 'ATAC', expression.assay = 'SCT', peaks = FALSE)Next, we will examine the accessible regions of each cell to determine enriched motifs. As described in the Signac motifs vignette, there are a few ways to do this, but we will use the chromVAR package from the Greenleaf lab. This calculates a per-cell accessibility score for known motifs, and adds these scores as a third assay (chromvar) in the Seurat object.To continue, please make sure you have the following packages installed.chromVAR for the analysis of motif accessibility in scATAC-seqpresto for fast differential expression analyses.TFBSTools for TFBS analysisJASPAR2020 for JASPAR motif modelsmotifmatchr for motif matchingBSgenome.Hsapiens.UCSC.hg38 for chromVARInstall command for all dependencies remotes::install_github("immunogenomics/presto") BiocManager::install(c("chromVAR", "TFBSTools", "JASPAR2020", "motifmatchr", "BSgenome.Hsapiens.UCSC.hg38")) library(chromVAR) library(JASPAR2020) library(TFBSTools) library(motifmatchr) library(BSgenome.Hsapiens.UCSC.hg38) # Scan the DNA sequence of each peak for the presence of each motif, and create a Motif object DefaultAssay(pbmc) <- "ATAC" pwm_set <- getMatrixSet(x = JASPAR2020, opts = list(species = 9606, all_versions = FALSE)) motif.matrix <- CreateMotifMatrix(features = granges(pbmc), pwm = pwm_set, genome = 'hg38', use.counts = FALSE) motif.object <- CreateMotifObject(data = motif.matrix, pwm = pwm_set) pbmc <- SetAssayData(pbmc, assay = 'ATAC', slot = 'motifs', new.data = motif.object) # Note that this step can take 30-60 minutes pbmc <- RunChromVAR( object = pbmc, genome = BSgenome.Hsapiens.UCSC.hg38 )Finally, we explore the multimodal dataset to identify key regulators of each cell state. Paired data provides a unique opportunity to identify transcription factors (TFs) that satisfy multiple criteria, helping to narrow down the list of putative regulators to the most likely candidates. We aim to identify TFs whose expression is enriched in multiple cell types in the RNA measurements, but also have enriched accessibility for their motifs in the ATAC measurements.As an example and positive control, the CCAAT Enhancer Binding Protein (CEBP) family of proteins, including the TF CEBPB, have been repeatedly shown to play important roles in the differentiation and function of myeloid cells including monocytes and dendritic cells. We can see that both the expression of the CEBPB, and the accessibility of the MA0466.2.4 motif (which encodes the binding site for CEBPB), are both enriched in monocytes. #returns MA0466.2 motif.name <- ConvertMotifID(pbmc, name = 'CEBPB') gene_plot <- FeaturePlot(pbmc, features = "sct_CEBPB", reduction = 'wnn.umap') motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap') gene_plot | motif_plotWe’d like to quantify this relationship, and search across all cell types to find similar examples. To do so, we will use the presto package to perform fast differential expression. We run two tests: one using gene expression data, and the other using chromVAR motif accessibilities. presto calculates a p-value based on the Wilcox rank sum test, which is also the default test in Seurat, and we restrict our search to TFs that return significant results in both tests.presto also calculates an “AUC” statistic, which reflects the power of each gene (or motif) to serve as a marker of cell type. A maximum AUC value of 1 indicates a perfect marker. Since the AUC statistic is on the same scale for both genes and motifs, we take the average of the AUC values from the two tests, and use this to rank TFs for each cell type: markers_rna <- presto:::wilcoxauc.Seurat(X = pbmc, group_by = 'celltype', assay = 'data', seurat_assay = 'SCT') markers_motifs <- presto:::wilcoxauc.Seurat(X = pbmc, group_by = 'celltype', assay = 'data', seurat_assay = 'chromvar') motif.names <- markers_motifs$feature colnames(markers_rna) <- paste0("RNA.", colnames(markers_rna)) colnames(markers_motifs) <- paste0("motif.", colnames(markers_motifs)) markers_rna$gene <- markers_rna$RNA.feature markers_motifs$gene <- ConvertMotifID(pbmc, id = motif.names) # a simple function to implement the procedure above topTFs <- function(celltype, padj.cutoff = 1e-2) { ctmarkers_rna <- dplyr::filter( markers_rna, RNA.group == celltype, RNA.padj < padj.cutoff, RNA.logFC > 0) %>% arrange(-RNA.auc) ctmarkers_motif <- dplyr::filter( markers_motifs, motif.group == celltype, motif.padj < padj.cutoff, motif.logFC > 0) %>% arrange(-motif.auc) top_tfs <- inner_join( x = ctmarkers_rna[, c(2, 11, 6, 7)], y = ctmarkers_motif[, c(2, 1, 11, 6, 7)], by = "gene" ) top_tfs$avg_auc <- (top_tfs$RNA.auc + top_tfs$motif.auc) / 2 top_tfs <- arrange(top_tfs, -avg_auc) return(top_tfs) }We can now compute, and visualize, putative regulators for any cell type. We recover well-established regulators, including TBX21 for NK cells, IRF4 for plasma cells, SOX4 for hematopoietic progenitors, EBF1 and PAX5 for B cells, IRF8 and TCF4 for pDC. We believe that similar strategies can be used to help focus on a set of putative regulators in diverse systems. # identify top markers in NK and visualize head(topTFs("NK"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 NK TBX21 0.7270859 0.000000e+00 NK MA0690.1 0.9139614 ## 2 NK EOMES 0.5886774 2.411013e-98 NK MA0800.1 0.9214773 ## 3 NK RUNX3 0.7705661 5.977716e-120 NK MA0684.2 0.6769022 ## motif.pval avg_auc ## 1 1.097940e-202 0.8205237 ## 2 4.903866e-210 0.7550774 ## 3 1.560061e-38 0.7237341 motif.name <- ConvertMotifID(pbmc, name = 'TBX21') gene_plot <- FeaturePlot(pbmc, features = "sct_TBX21", reduction = 'wnn.umap') motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap') gene_plot | motif_plot # identify top markers in pDC and visualize head(topTFs("pDC"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 pDC TCF4 0.9998815 1.120711e-162 pDC MA0830.2 0.9965481 ## 2 pDC IRF8 0.9904457 1.308164e-123 pDC MA0652.1 0.8833112 ## 3 pDC SPIB 0.9115207 0.000000e+00 pDC MA0081.2 0.9068540 ## motif.pval avg_auc ## 1 1.785897e-69 0.9982148 ## 2 3.982413e-42 0.9368785 ## 3 3.083509e-47 0.9091874 motif.name <- ConvertMotifID(pbmc, name = 'TCF4') gene_plot <- FeaturePlot(pbmc, features = "sct_TCF4", reduction = 'wnn.umap') motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap') gene_plot | motif_plot # identify top markers in HSPC and visualize head(topTFs("CD16 Mono"),3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 CD16 Mono SPI1 0.8793172 1.666810e-296 CD16 Mono MA0080.5 0.8880908 ## 2 CD16 Mono CEBPB 0.8685933 1.625472e-294 CD16 Mono MA0466.2 0.7840422 ## 3 CD16 Mono MEF2C 0.7129910 2.727252e-79 CD16 Mono MA0497.1 0.8059373 ## motif.pval avg_auc ## 1 4.762491e-194 0.8837040 ## 2 7.049764e-105 0.8263177 ## 3 2.345716e-121 0.7594641 motif.name <- ConvertMotifID(pbmc, name = 'SPI1') gene_plot <- FeaturePlot(pbmc, features = "sct_SPI1", reduction = 'wnn.umap') motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap') gene_plot | motif_plot # identify top markers in other cell types head(topTFs("Naive B"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 Naive B MEF2C 0.8802747 1.890065e-182 Naive B MA0497.1 0.6789079 ## 2 Naive B PAX5 0.9436648 0.000000e+00 Naive B MA0014.3 0.5827061 ## 3 Naive B POU2F2 0.6029377 2.892216e-13 Naive B MA0507.1 0.8912268 ## motif.pval avg_auc ## 1 9.815118e-32 0.7795913 ## 2 5.995185e-08 0.7631854 ## 3 6.471677e-145 0.7470822 head(topTFs("HSPC"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 HSPC SOX4 0.9869406 5.524832e-71 HSPC MA0867.2 0.6830497 ## 2 HSPC GATA2 0.7884615 0.000000e+00 HSPC MA0036.3 0.8275008 ## 3 HSPC MEIS1 0.8638496 0.000000e+00 HSPC MA0498.2 0.6924225 ## motif.pval avg_auc ## 1 1.241915e-03 0.8349951 ## 2 7.591798e-09 0.8079812 ## 3 6.877492e-04 0.7781361 head(topTFs("Plasma"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 Plasma IRF4 0.8189687 5.261955e-35 Plasma MA1419.1 0.9776046 ## 2 Plasma MEF2C 0.9111213 2.977155e-12 Plasma MA0497.1 0.7596637 ## 3 Plasma TCF4 0.8049409 6.810635e-12 Plasma MA0830.2 0.7840848 ## motif.pval avg_auc ## 1 2.334627e-12 0.8982867 ## 2 1.374353e-04 0.8353925 ## 3 3.028306e-05 0.7945129Session Info sessionInfo()## R version 4.2.0 (2022-04-22) ## Platform: x86_64-pc-linux-gnu (64-bit) ## Running under: Ubuntu 20.04.5 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/liblapack.so.3 ## ## locale: ## [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C ## [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8 ## [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 ## ## attached base packages: ## [1] stats4 stats graphics grDevices utils datasets methods ## [8] base ## ## other attached packages: ## [1] BSgenome.Hsapiens.UCSC.hg38_1.4.5 BSgenome_1.66.3 ## [3] rtracklayer_1.58.0 Biostrings_2.66.0 ## [5] XVector_0.38.0 motifmatchr_1.20.0 ## [7] TFBSTools_1.36.0 JASPAR2020_0.99.10 ## [9] chromVAR_1.20.2 EnsDb.Hsapiens.v86_2.99.0 ## [11] ensembldb_2.22.0 AnnotationFilter_1.22.0 ## [13] GenomicFeatures_1.50.4 AnnotationDbi_1.60.0 ## [15] Biobase_2.58.0 GenomicRanges_1.50.2 ## [17] GenomeInfoDb_1.35.16 IRanges_2.32.0 ## [19] S4Vectors_0.36.2 BiocGenerics_0.44.0 ## [21] Signac_1.9.0 ggplot2_3.4.1 ## [23] dplyr_1.1.1 cowplot_1.1.1 ## [25] thp1.eccite.SeuratData_3.1.5 stxBrain.SeuratData_0.1.1 ## [27] ssHippo.SeuratData_3.1.4 pbmcsca.SeuratData_3.0.0 ## [29] pbmcMultiome.SeuratData_0.1.2 pbmc3k.SeuratData_3.1.4 ## [31] panc8.SeuratData_3.0.2 ifnb.SeuratData_3.1.0 ## [33] hcabm40k.SeuratData_3.0.0 bmcite.SeuratData_0.3.0 ## [35] SeuratData_0.2.2 SeuratObject_4.1.3 ## [37] Seurat_4.2.1.9001 ## ## loaded via a namespace (and not attached): ## [1] rappdirs_0.3.3 scattermore_0.8 ## [3] R.methodsS3_1.8.2 ragg_1.2.5 ## [5] nabor_0.5.0 tidyr_1.3.0 ## [7] bit64_4.0.5 knitr_1.42 ## [9] R.utils_2.12.2 irlba_2.3.5.1 ## [11] DelayedArray_0.24.0 data.table_1.14.8 ## [13] rpart_4.1.16 KEGGREST_1.38.0 ## [15] RCurl_1.98-1.12 generics_0.1.3 ## [17] RSQLite_2.3.0 RANN_2.6.1 ## [19] future_1.32.0 tzdb_0.3.0 ## [21] bit_4.0.5 spatstat.data_3.0-1 ## [23] xml2_1.3.3 httpuv_1.6.9 ## [25] SummarizedExperiment_1.28.0 DirichletMultinomial_1.40.0 ## [27] xfun_0.38 hms_1.1.2 ## [29] jquerylib_0.1.4 evaluate_0.20 ## [31] promises_1.2.0.1 fansi_1.0.4 ## [33] restfulr_0.0.15 progress_1.2.2 ## [35] caTools_1.18.2 dbplyr_2.3.1 ## [37] igraph_1.4.1 DBI_1.1.3 ## [39] htmlwidgets_1.6.2 spatstat.geom_3.1-0 ## [41] purrr_1.0.1 ellipsis_0.3.2 ## [43] backports_1.4.1 annotate_1.76.0 ## [45] biomaRt_2.54.0 deldir_1.0-6 ## [47] MatrixGenerics_1.10.0 vctrs_0.6.1 ## [49] ROCR_1.0-11 abind_1.4-5 ## [51] cachem_1.0.7 withr_2.5.0 ## [53] progressr_0.13.0 presto_1.0.0 ## [55] checkmate_2.1.0 sctransform_0.3.5 ## [57] GenomicAlignments_1.34.0 prettyunits_1.1.1 ## [59] goftest_1.2-3 cluster_2.1.3 ## [61] seqLogo_1.64.0 lazyeval_0.2.2 ## [63] crayon_1.5.2 hdf5r_1.3.8 ## [65] spatstat.explore_3.1-0 pkgconfig_2.0.3 ## [67] labeling_0.4.2 nlme_3.1-157 ## [69] ProtGenerics_1.30.0 nnet_7.3-17 ## [71] rlang_1.1.0 globals_0.16.2 ## [73] lifecycle_1.0.3 miniUI_0.1.1.1 ## [75] filelock_1.0.2 BiocFileCache_2.6.1 ## [77] dichromat_2.0-0.1 rprojroot_2.0.3 ## [79] polyclip_1.10-4 matrixStats_0.63.0 ## [81] lmtest_0.9-40 Matrix_1.5-3 ## [83] zoo_1.8-11 base64enc_0.1-3 ## [85] ggridges_0.5.4 png_0.1-8 ## [87] viridisLite_0.4.1 rjson_0.2.21 ## [89] bitops_1.0-7 R.oo_1.25.0 ## [91] KernSmooth_2.23-20 blob_1.2.3 ## [93] stringr_1.5.0 parallelly_1.35.0 ## [95] spatstat.random_3.1-4 readr_2.1.4 ## [97] jpeg_0.1-10 CNEr_1.34.0 ## [99] scales_1.2.1 memoise_2.0.1 ## [101] magrittr_2.0.3 plyr_1.8.8 ## [103] ica_1.0-3 zlibbioc_1.44.0 ## [105] compiler_4.2.0 BiocIO_1.8.0 ## [107] RColorBrewer_1.1-3 fitdistrplus_1.1-8 ## [109] Rsamtools_2.14.0 cli_3.6.1 ## [111] listenv_0.9.0 patchwork_1.1.2 ## [113] pbapply_1.7-0 htmlTable_2.4.1 ## [115] Formula_1.2-5 MASS_7.3-56 ## [117] tidyselect_1.2.0 stringi_1.7.12 ## [119] textshaping_0.3.6 highr_0.10 ## [121] yaml_2.3.7 latticeExtra_0.6-30 ## [123] ggrepel_0.9.3 grid_4.2.0 ## [125] sass_0.4.5 VariantAnnotation_1.44.1 ## [127] fastmatch_1.1-3 tools_4.2.0 ## [129] future.apply_1.10.0 parallel_4.2.0 ## [131] rstudioapi_0.14 TFMPvalue_0.0.9 ## [133] foreign_0.8-82 gridExtra_2.3 ## [135] farver_2.1.1 Rtsne_0.16 ## [137] digest_0.6.31 pracma_2.4.2 ## [139] shiny_1.7.4 Rcpp_1.0.10 ## [141] later_1.3.0 RcppAnnoy_0.0.20 ## [143] httr_1.4.5 biovizBase_1.46.0 ## [145] colorspace_2.1-0 XML_3.99-0.13 ## [147] fs_1.6.1 tensor_1.5 ## [149] reticulate_1.28 splines_4.2.0 ## [151] uwot_0.1.14 RcppRoll_0.3.0 ## [153] spatstat.utils_3.0-2 pkgdown_2.0.7 ## [155] sp_1.6-0 plotly_4.10.1 ## [157] systemfonts_1.0.4 xtable_1.8-4 ## [159] poweRlaw_0.70.6 jsonlite_1.8.4 ## [161] R6_2.5.1 Hmisc_4.8-0 ## [163] pillar_1.9.0 htmltools_0.5.5 ## [165] mime_0.12 DT_0.27 ## [167] glue_1.6.2 fastmap_1.1.1 ## [169] BiocParallel_1.32.5 codetools_0.2-18 ## [171] utf8_1.2.3 lattice_0.20-45 ## [173] bslib_0.4.2 spatstat.sparse_3.0-1 ## [175] tibble_3.2.1 curl_5.0.0 ## [177] leiden_0.4.3 gtools_3.9.4 ## [179] GO.db_3.16.0 interp_1.1-3 ## [181] survival_3.3-1 rmarkdown_2.21 ## [183] desc_1.4.2 munsell_0.5.0 ## [185] GenomeInfoDbData_1.2.9 reshape2_1.4.4 ## [187] gtable_0.3.3

We use the same WNN methods as we use in the previous tab, where we apply integrated multimodal analysis to a CITE-seq dataset. In this example we will demonstrate how to:Create a multimodal Seurat object with paired transcriptome and ATAC-seq profilesPerform weighted neighbor clustering on RNA+ATAC data in single cellsLeverage both modalities to identify putative regulators of different cell types and statesYou can download the dataset from the 10x Genomics website here. Please make sure to download the following files:Filtered feature barcode matrix (HDF5)ATAC Per fragment information file (TSV.GZ)ATAC Per fragment information index (TSV.GZ index)Finally, in order to run the vignette, make sure the following packages are installed:Seurat v4Signac for the analysis of single-cell chromatin datasetsEnsDb.Hsapiens.v86 for a set of annotations for hg38dplyr to help manipulate data tables library(Seurat) library(Signac) library(EnsDb.Hsapiens.v86) library(dplyr) library(ggplot2)We’ll create a Seurat object based on the gene expression data, and then add in the ATAC-seq data as a second assay. You can explore the Signac getting started vignette for more information on the creation and processing of a ChromatinAssay object. # the 10x hdf5 file contains both data types. inputdata.10x <- Read10X_h5("../data/pbmc_granulocyte_sorted_10k_filtered_feature_bc_matrix.h5") # extract RNA and ATAC data rna_counts <- inputdata.10x$`Gene Expression` atac_counts <- inputdata.10x$Peaks # Create Seurat object pbmc <- CreateSeuratObject(counts = rna_counts) pbmc[["percent.mt"]] <- PercentageFeatureSet(pbmc, pattern = "^MT-") # Now add in the ATAC-seq data # we'll only use peaks in standard chromosomes grange.counts <- StringToGRanges(rownames(atac_counts), sep = c(":", "-")) grange.use <- seqnames(grange.counts) %in% standardChromosomes(grange.counts) atac_counts <- atac_counts[as.vector(grange.use), ] annotations <- GetGRangesFromEnsDb(ensdb = EnsDb.Hsapiens.v86) seqlevelsStyle(annotations) <- 'UCSC' genome(annotations) <- "hg38" frag.file <- "../data/pbmc_granulocyte_sorted_10k_atac_fragments.tsv.gz" chrom_assay <- CreateChromatinAssay( counts = atac_counts, sep = c(":", "-"), genome = 'hg38', fragments = frag.file, min.cells = 10, annotation = annotations ) pbmc[["ATAC"]] <- chrom_assayWe perform basic QC based on the number of detected molecules for each modality as well as mitochondrial percentage. VlnPlot(pbmc, features = c("nCount_ATAC", "nCount_RNA","percent.mt"), ncol = 3, log = TRUE, pt.size = 0) + NoLegend() pbmc <- subset( x = pbmc, subset = nCount_ATAC < 7e4 & nCount_ATAC > 5e3 & nCount_RNA < 25000 & nCount_RNA > 1000 & percent.mt < 20 )We next perform pre-processing and dimensional reduction on both assays independently, using standard approaches for RNA and ATAC-seq data. # RNA analysis DefaultAssay(pbmc) <- "RNA" pbmc <- SCTransform(pbmc, verbose = FALSE) %>% RunPCA() %>% RunUMAP(dims = 1:50, reduction.name = 'umap.rna', reduction.key = 'rnaUMAP_') # ATAC analysis # We exclude the first dimension as this is typically correlated with sequencing depth DefaultAssay(pbmc) <- "ATAC" pbmc <- RunTFIDF(pbmc) pbmc <- FindTopFeatures(pbmc, min.cutoff = 'q0') pbmc <- RunSVD(pbmc) pbmc <- RunUMAP(pbmc, reduction = 'lsi', dims = 2:50, reduction.name = "umap.atac", reduction.key = "atacUMAP_")We calculate a WNN graph, representing a weighted combination of RNA and ATAC-seq modalities. We use this graph for UMAP visualization and clustering pbmc <- FindMultiModalNeighbors(pbmc, reduction.list = list("pca", "lsi"), dims.list = list(1:50, 2:50)) pbmc <- RunUMAP(pbmc, nn.name = "weighted.nn", reduction.name = "wnn.umap", reduction.key = "wnnUMAP_") pbmc <- FindClusters(pbmc, graph.name = "wsnn", algorithm = 3, verbose = FALSE)We annotate the clusters below. Note that you could also annotate the dataset using our supervised mapping pipelines, using either our vignette, or automated web tool, Azimuth. # perform sub-clustering on cluster 6 to find additional structure pbmc <- FindSubCluster(pbmc, cluster = 6, graph.name = "wsnn", algorithm = 3) Idents(pbmc) <- "sub.cluster" # add annotations pbmc <- RenameIdents(pbmc, '19' = 'pDC','20' = 'HSPC','15' = 'cDC') pbmc <- RenameIdents(pbmc, '0' = 'CD14 Mono', '9' ='CD14 Mono', '5' = 'CD16 Mono') pbmc <- RenameIdents(pbmc, '10' = 'Naive B', '11' = 'Intermediate B', '17' = 'Memory B', '21' = 'Plasma') pbmc <- RenameIdents(pbmc, '7' = 'NK') pbmc <- RenameIdents(pbmc, '4' = 'CD4 TCM', '13'= "CD4 TEM", '3' = "CD4 TCM", '16' ="Treg", '1' ="CD4 Naive", '14' = "CD4 Naive") pbmc <- RenameIdents(pbmc, '2' = 'CD8 Naive', '8'= "CD8 Naive", '12' = 'CD8 TEM_1', '6_0' = 'CD8 TEM_2', '6_1' ='CD8 TEM_2', '6_4' ='CD8 TEM_2') pbmc <- RenameIdents(pbmc, '18' = 'MAIT') pbmc <- RenameIdents(pbmc, '6_2' ='gdT', '6_3' = 'gdT') pbmc$celltype <- Idents(pbmc)We can visualize clustering based on gene expression, ATAC-seq, or WNN analysis. The differences are more subtle than in the previous analysis (you can explore the weights, which are more evenly split than in our CITE-seq example), but we find that WNN provides the clearest separation of cell states. p1 <- DimPlot(pbmc, reduction = "umap.rna", group.by = "celltype", label = TRUE, label.size = 2.5, repel = TRUE) + ggtitle("RNA") p2 <- DimPlot(pbmc, reduction = "umap.atac", group.by = "celltype", label = TRUE, label.size = 2.5, repel = TRUE) + ggtitle("ATAC") p3 <- DimPlot(pbmc, reduction = "wnn.umap", group.by = "celltype", label = TRUE, label.size = 2.5, repel = TRUE) + ggtitle("WNN") p1 + p2 + p3 & NoLegend() & theme(plot.title = element_text(hjust = 0.5))For example, the ATAC-seq data assists in the separation of CD4 and CD8 T cell states. This is due to the presence of multiple loci that exhibit differential accessibility between different T cell subtypes. For example, we can visualize ‘pseudobulk’ tracks of the CD8A locus alongside violin plots of gene expression levels, using tools in the Signac visualization vignette. ## to make the visualization easier, subset T cell clusters celltype.names <- levels(pbmc) tcell.names <- grep("CD4|CD8|Treg", celltype.names,value = TRUE) tcells <- subset(pbmc, idents = tcell.names) CoveragePlot(tcells, region = 'CD8A', features = 'CD8A', assay = 'ATAC', expression.assay = 'SCT', peaks = FALSE)Next, we will examine the accessible regions of each cell to determine enriched motifs. As described in the Signac motifs vignette, there are a few ways to do this, but we will use the chromVAR package from the Greenleaf lab. This calculates a per-cell accessibility score for known motifs, and adds these scores as a third assay (chromvar) in the Seurat object.To continue, please make sure you have the following packages installed.chromVAR for the analysis of motif accessibility in scATAC-seqpresto for fast differential expression analyses.TFBSTools for TFBS analysisJASPAR2020 for JASPAR motif modelsmotifmatchr for motif matchingBSgenome.Hsapiens.UCSC.hg38 for chromVARInstall command for all dependencies remotes::install_github("immunogenomics/presto") BiocManager::install(c("chromVAR", "TFBSTools", "JASPAR2020", "motifmatchr", "BSgenome.Hsapiens.UCSC.hg38")) library(chromVAR) library(JASPAR2020) library(TFBSTools) library(motifmatchr) library(BSgenome.Hsapiens.UCSC.hg38) # Scan the DNA sequence of each peak for the presence of each motif, and create a Motif object DefaultAssay(pbmc) <- "ATAC" pwm_set <- getMatrixSet(x = JASPAR2020, opts = list(species = 9606, all_versions = FALSE)) motif.matrix <- CreateMotifMatrix(features = granges(pbmc), pwm = pwm_set, genome = 'hg38', use.counts = FALSE) motif.object <- CreateMotifObject(data = motif.matrix, pwm = pwm_set) pbmc <- SetAssayData(pbmc, assay = 'ATAC', slot = 'motifs', new.data = motif.object) # Note that this step can take 30-60 minutes pbmc <- RunChromVAR( object = pbmc, genome = BSgenome.Hsapiens.UCSC.hg38 )Finally, we explore the multimodal dataset to identify key regulators of each cell state. Paired data provides a unique opportunity to identify transcription factors (TFs) that satisfy multiple criteria, helping to narrow down the list of putative regulators to the most likely candidates. We aim to identify TFs whose expression is enriched in multiple cell types in the RNA measurements, but also have enriched accessibility for their motifs in the ATAC measurements.As an example and positive control, the CCAAT Enhancer Binding Protein (CEBP) family of proteins, including the TF CEBPB, have been repeatedly shown to play important roles in the differentiation and function of myeloid cells including monocytes and dendritic cells. We can see that both the expression of the CEBPB, and the accessibility of the MA0466.2.4 motif (which encodes the binding site for CEBPB), are both enriched in monocytes. #returns MA0466.2 motif.name <- ConvertMotifID(pbmc, name = 'CEBPB') gene_plot <- FeaturePlot(pbmc, features = "sct_CEBPB", reduction = 'wnn.umap') motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap') gene_plot | motif_plotWe’d like to quantify this relationship, and search across all cell types to find similar examples. To do so, we will use the presto package to perform fast differential expression. We run two tests: one using gene expression data, and the other using chromVAR motif accessibilities. presto calculates a p-value based on the Wilcox rank sum test, which is also the default test in Seurat, and we restrict our search to TFs that return significant results in both tests.presto also calculates an “AUC” statistic, which reflects the power of each gene (or motif) to serve as a marker of cell type. A maximum AUC value of 1 indicates a perfect marker. Since the AUC statistic is on the same scale for both genes and motifs, we take the average of the AUC values from the two tests, and use this to rank TFs for each cell type: markers_rna <- presto:::wilcoxauc.Seurat(X = pbmc, group_by = 'celltype', assay = 'data', seurat_assay = 'SCT') markers_motifs <- presto:::wilcoxauc.Seurat(X = pbmc, group_by = 'celltype', assay = 'data', seurat_assay = 'chromvar') motif.names <- markers_motifs$feature colnames(markers_rna) <- paste0("RNA.", colnames(markers_rna)) colnames(markers_motifs) <- paste0("motif.", colnames(markers_motifs)) markers_rna$gene <- markers_rna$RNA.feature markers_motifs$gene <- ConvertMotifID(pbmc, id = motif.names) # a simple function to implement the procedure above topTFs <- function(celltype, padj.cutoff = 1e-2) { ctmarkers_rna <- dplyr::filter( markers_rna, RNA.group == celltype, RNA.padj < padj.cutoff, RNA.logFC > 0) %>% arrange(-RNA.auc) ctmarkers_motif <- dplyr::filter( markers_motifs, motif.group == celltype, motif.padj < padj.cutoff, motif.logFC > 0) %>% arrange(-motif.auc) top_tfs <- inner_join( x = ctmarkers_rna[, c(2, 11, 6, 7)], y = ctmarkers_motif[, c(2, 1, 11, 6, 7)], by = "gene" ) top_tfs$avg_auc <- (top_tfs$RNA.auc + top_tfs$motif.auc) / 2 top_tfs <- arrange(top_tfs, -avg_auc) return(top_tfs) }We can now compute, and visualize, putative regulators for any cell type. We recover well-established regulators, including TBX21 for NK cells, IRF4 for plasma cells, SOX4 for hematopoietic progenitors, EBF1 and PAX5 for B cells, IRF8 and TCF4 for pDC. We believe that similar strategies can be used to help focus on a set of putative regulators in diverse systems. # identify top markers in NK and visualize head(topTFs("NK"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 NK TBX21 0.7270859 0.000000e+00 NK MA0690.1 0.9139614 ## 2 NK EOMES 0.5886774 2.411013e-98 NK MA0800.1 0.9214773 ## 3 NK RUNX3 0.7705661 5.977716e-120 NK MA0684.2 0.6769022 ## motif.pval avg_auc ## 1 1.097940e-202 0.8205237 ## 2 4.903866e-210 0.7550774 ## 3 1.560061e-38 0.7237341 motif.name <- ConvertMotifID(pbmc, name = 'TBX21') gene_plot <- FeaturePlot(pbmc, features = "sct_TBX21", reduction = 'wnn.umap') motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap') gene_plot | motif_plot # identify top markers in pDC and visualize head(topTFs("pDC"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 pDC TCF4 0.9998815 1.120711e-162 pDC MA0830.2 0.9965481 ## 2 pDC IRF8 0.9904457 1.308164e-123 pDC MA0652.1 0.8833112 ## 3 pDC SPIB 0.9115207 0.000000e+00 pDC MA0081.2 0.9068540 ## motif.pval avg_auc ## 1 1.785897e-69 0.9982148 ## 2 3.982413e-42 0.9368785 ## 3 3.083509e-47 0.9091874 motif.name <- ConvertMotifID(pbmc, name = 'TCF4') gene_plot <- FeaturePlot(pbmc, features = "sct_TCF4", reduction = 'wnn.umap') motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap') gene_plot | motif_plot # identify top markers in HSPC and visualize head(topTFs("CD16 Mono"),3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 CD16 Mono SPI1 0.8793172 1.666810e-296 CD16 Mono MA0080.5 0.8880908 ## 2 CD16 Mono CEBPB 0.8685933 1.625472e-294 CD16 Mono MA0466.2 0.7840422 ## 3 CD16 Mono MEF2C 0.7129910 2.727252e-79 CD16 Mono MA0497.1 0.8059373 ## motif.pval avg_auc ## 1 4.762491e-194 0.8837040 ## 2 7.049764e-105 0.8263177 ## 3 2.345716e-121 0.7594641 motif.name <- ConvertMotifID(pbmc, name = 'SPI1') gene_plot <- FeaturePlot(pbmc, features = "sct_SPI1", reduction = 'wnn.umap') motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap') gene_plot | motif_plot # identify top markers in other cell types head(topTFs("Naive B"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 Naive B MEF2C 0.8802747 1.890065e-182 Naive B MA0497.1 0.6789079 ## 2 Naive B PAX5 0.9436648 0.000000e+00 Naive B MA0014.3 0.5827061 ## 3 Naive B POU2F2 0.6029377 2.892216e-13 Naive B MA0507.1 0.8912268 ## motif.pval avg_auc ## 1 9.815118e-32 0.7795913 ## 2 5.995185e-08 0.7631854 ## 3 6.471677e-145 0.7470822 head(topTFs("HSPC"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 HSPC SOX4 0.9869406 5.524832e-71 HSPC MA0867.2 0.6830497 ## 2 HSPC GATA2 0.7884615 0.000000e+00 HSPC MA0036.3 0.8275008 ## 3 HSPC MEIS1 0.8638496 0.000000e+00 HSPC MA0498.2 0.6924225 ## motif.pval avg_auc ## 1 1.241915e-03 0.8349951 ## 2 7.591798e-09 0.8079812 ## 3 6.877492e-04 0.7781361 head(topTFs("Plasma"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 Plasma IRF4 0.8189687 5.261955e-35 Plasma MA1419.1 0.9776046 ## 2 Plasma MEF2C 0.9111213 2.977155e-12 Plasma MA0497.1 0.7596637 ## 3 Plasma TCF4 0.8049409 6.810635e-12 Plasma MA0830.2 0.7840848 ## motif.pval avg_auc ## 1 2.334627e-12 0.8982867 ## 2 1.374353e-04 0.8353925 ## 3 3.028306e-05 0.7945129Session Info sessionInfo()## R version 4.2.0 (2022-04-22) ## Platform: x86_64-pc-linux-gnu (64-bit) ## Running under: Ubuntu 20.04.5 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/liblapack.so.3 ## ## locale: ## [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C ## [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8 ## [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 ## ## attached base packages: ## [1] stats4 stats graphics grDevices utils datasets methods ## [8] base ## ## other attached packages: ## [1] BSgenome.Hsapiens.UCSC.hg38_1.4.5 BSgenome_1.66.3 ## [3] rtracklayer_1.58.0 Biostrings_2.66.0 ## [5] XVector_0.38.0 motifmatchr_1.20.0 ## [7] TFBSTools_1.36.0 JASPAR2020_0.99.10 ## [9] chromVAR_1.20.2 EnsDb.Hsapiens.v86_2.99.0 ## [11] ensembldb_2.22.0 AnnotationFilter_1.22.0 ## [13] GenomicFeatures_1.50.4 AnnotationDbi_1.60.0 ## [15] Biobase_2.58.0 GenomicRanges_1.50.2 ## [17] GenomeInfoDb_1.35.16 IRanges_2.32.0 ## [19] S4Vectors_0.36.2 BiocGenerics_0.44.0 ## [21] Signac_1.9.0 ggplot2_3.4.1 ## [23] dplyr_1.1.1 cowplot_1.1.1 ## [25] thp1.eccite.SeuratData_3.1.5 stxBrain.SeuratData_0.1.1 ## [27] ssHippo.SeuratData_3.1.4 pbmcsca.SeuratData_3.0.0 ## [29] pbmcMultiome.SeuratData_0.1.2 pbmc3k.SeuratData_3.1.4 ## [31] panc8.SeuratData_3.0.2 ifnb.SeuratData_3.1.0 ## [33] hcabm40k.SeuratData_3.0.0 bmcite.SeuratData_0.3.0 ## [35] SeuratData_0.2.2 SeuratObject_4.1.3 ## [37] Seurat_4.2.1.9001 ## ## loaded via a namespace (and not attached): ## [1] rappdirs_0.3.3 scattermore_0.8 ## [3] R.methodsS3_1.8.2 ragg_1.2.5 ## [5] nabor_0.5.0 tidyr_1.3.0 ## [7] bit64_4.0.5 knitr_1.42 ## [9] R.utils_2.12.2 irlba_2.3.5.1 ## [11] DelayedArray_0.24.0 data.table_1.14.8 ## [13] rpart_4.1.16 KEGGREST_1.38.0 ## [15] RCurl_1.98-1.12 generics_0.1.3 ## [17] RSQLite_2.3.0 RANN_2.6.1 ## [19] future_1.32.0 tzdb_0.3.0 ## [21] bit_4.0.5 spatstat.data_3.0-1 ## [23] xml2_1.3.3 httpuv_1.6.9 ## [25] SummarizedExperiment_1.28.0 DirichletMultinomial_1.40.0 ## [27] xfun_0.38 hms_1.1.2 ## [29] jquerylib_0.1.4 evaluate_0.20 ## [31] promises_1.2.0.1 fansi_1.0.4 ## [33] restfulr_0.0.15 progress_1.2.2 ## [35] caTools_1.18.2 dbplyr_2.3.1 ## [37] igraph_1.4.1 DBI_1.1.3 ## [39] htmlwidgets_1.6.2 spatstat.geom_3.1-0 ## [41] purrr_1.0.1 ellipsis_0.3.2 ## [43] backports_1.4.1 annotate_1.76.0 ## [45] biomaRt_2.54.0 deldir_1.0-6 ## [47] MatrixGenerics_1.10.0 vctrs_0.6.1 ## [49] ROCR_1.0-11 abind_1.4-5 ## [51] cachem_1.0.7 withr_2.5.0 ## [53] progressr_0.13.0 presto_1.0.0 ## [55] checkmate_2.1.0 sctransform_0.3.5 ## [57] GenomicAlignments_1.34.0 prettyunits_1.1.1 ## [59] goftest_1.2-3 cluster_2.1.3 ## [61] seqLogo_1.64.0 lazyeval_0.2.2 ## [63] crayon_1.5.2 hdf5r_1.3.8 ## [65] spatstat.explore_3.1-0 pkgconfig_2.0.3 ## [67] labeling_0.4.2 nlme_3.1-157 ## [69] ProtGenerics_1.30.0 nnet_7.3-17 ## [71] rlang_1.1.0 globals_0.16.2 ## [73] lifecycle_1.0.3 miniUI_0.1.1.1 ## [75] filelock_1.0.2 BiocFileCache_2.6.1 ## [77] dichromat_2.0-0.1 rprojroot_2.0.3 ## [79] polyclip_1.10-4 matrixStats_0.63.0 ## [81] lmtest_0.9-40 Matrix_1.5-3 ## [83] zoo_1.8-11 base64enc_0.1-3 ## [85] ggridges_0.5.4 png_0.1-8 ## [87] viridisLite_0.4.1 rjson_0.2.21 ## [89] bitops_1.0-7 R.oo_1.25.0 ## [91] KernSmooth_2.23-20 blob_1.2.3 ## [93] stringr_1.5.0 parallelly_1.35.0 ## [95] spatstat.random_3.1-4 readr_2.1.4 ## [97] jpeg_0.1-10 CNEr_1.34.0 ## [99] scales_1.2.1 memoise_2.0.1 ## [101] magrittr_2.0.3 plyr_1.8.8 ## [103] ica_1.0-3 zlibbioc_1.44.0 ## [105] compiler_4.2.0 BiocIO_1.8.0 ## [107] RColorBrewer_1.1-3 fitdistrplus_1.1-8 ## [109] Rsamtools_2.14.0 cli_3.6.1 ## [111] listenv_0.9.0 patchwork_1.1.2 ## [113] pbapply_1.7-0 htmlTable_2.4.1 ## [115] Formula_1.2-5 MASS_7.3-56 ## [117] tidyselect_1.2.0 stringi_1.7.12 ## [119] textshaping_0.3.6 highr_0.10 ## [121] yaml_2.3.7 latticeExtra_0.6-30 ## [123] ggrepel_0.9.3 grid_4.2.0 ## [125] sass_0.4.5 VariantAnnotation_1.44.1 ## [127] fastmatch_1.1-3 tools_4.2.0 ## [129] future.apply_1.10.0 parallel_4.2.0 ## [131] rstudioapi_0.14 TFMPvalue_0.0.9 ## [133] foreign_0.8-82 gridExtra_2.3 ## [135] farver_2.1.1 Rtsne_0.16 ## [137] digest_0.6.31 pracma_2.4.2 ## [139] shiny_1.7.4 Rcpp_1.0.10 ## [141] later_1.3.0 RcppAnnoy_0.0.20 ## [143] httr_1.4.5 biovizBase_1.46.0 ## [145] colorspace_2.1-0 XML_3.99-0.13 ## [147] fs_1.6.1 tensor_1.5 ## [149] reticulate_1.28 splines_4.2.0 ## [151] uwot_0.1.14 RcppRoll_0.3.0 ## [153] spatstat.utils_3.0-2 pkgdown_2.0.7 ## [155] sp_1.6-0 plotly_4.10.1 ## [157] systemfonts_1.0.4 xtable_1.8-4 ## [159] poweRlaw_0.70.6 jsonlite_1.8.4 ## [161] R6_2.5.1 Hmisc_4.8-0 ## [163] pillar_1.9.0 htmltools_0.5.5 ## [165] mime_0.12 DT_0.27 ## [167] glue_1.6.2 fastmap_1.1.1 ## [169] BiocParallel_1.32.5 codetools_0.2-18 ## [171] utf8_1.2.3 lattice_0.20-45 ## [173] bslib_0.4.2 spatstat.sparse_3.0-1 ## [175] tibble_3.2.1 curl_5.0.0 ## [177] leiden_0.4.3 gtools_3.9.4 ## [179] GO.db_3.16.0 interp_1.1-3 ## [181] survival_3.3-1 rmarkdown_2.21 ## [183] desc_1.4.2 munsell_0.5.0 ## [185] GenomeInfoDbData_1.2.9 reshape2_1.4.4 ## [187] gtable_0.3.3

You can download the dataset from the 10x Genomics website here. Please make sure to download the following files:Filtered feature barcode matrix (HDF5)ATAC Per fragment information file (TSV.GZ)ATAC Per fragment information index (TSV.GZ index)Finally, in order to run the vignette, make sure the following packages are installed:Seurat v4Signac for the analysis of single-cell chromatin datasetsEnsDb.Hsapiens.v86 for a set of annotations for hg38dplyr to help manipulate data tables library(Seurat) library(Signac) library(EnsDb.Hsapiens.v86) library(dplyr) library(ggplot2)We’ll create a Seurat object based on the gene expression data, and then add in the ATAC-seq data as a second assay. You can explore the Signac getting started vignette for more information on the creation and processing of a ChromatinAssay object. # the 10x hdf5 file contains both data types. inputdata.10x <- Read10X_h5("../data/pbmc_granulocyte_sorted_10k_filtered_feature_bc_matrix.h5") # extract RNA and ATAC data rna_counts <- inputdata.10x$`Gene Expression` atac_counts <- inputdata.10x$Peaks # Create Seurat object pbmc <- CreateSeuratObject(counts = rna_counts) pbmc[["percent.mt"]] <- PercentageFeatureSet(pbmc, pattern = "^MT-") # Now add in the ATAC-seq data # we'll only use peaks in standard chromosomes grange.counts <- StringToGRanges(rownames(atac_counts), sep = c(":", "-")) grange.use <- seqnames(grange.counts) %in% standardChromosomes(grange.counts) atac_counts <- atac_counts[as.vector(grange.use), ] annotations <- GetGRangesFromEnsDb(ensdb = EnsDb.Hsapiens.v86) seqlevelsStyle(annotations) <- 'UCSC' genome(annotations) <- "hg38" frag.file <- "../data/pbmc_granulocyte_sorted_10k_atac_fragments.tsv.gz" chrom_assay <- CreateChromatinAssay( counts = atac_counts, sep = c(":", "-"), genome = 'hg38', fragments = frag.file, min.cells = 10, annotation = annotations ) pbmc[["ATAC"]] <- chrom_assayWe perform basic QC based on the number of detected molecules for each modality as well as mitochondrial percentage. VlnPlot(pbmc, features = c("nCount_ATAC", "nCount_RNA","percent.mt"), ncol = 3, log = TRUE, pt.size = 0) + NoLegend() pbmc <- subset( x = pbmc, subset = nCount_ATAC < 7e4 & nCount_ATAC > 5e3 & nCount_RNA < 25000 & nCount_RNA > 1000 & percent.mt < 20 )We next perform pre-processing and dimensional reduction on both assays independently, using standard approaches for RNA and ATAC-seq data. # RNA analysis DefaultAssay(pbmc) <- "RNA" pbmc <- SCTransform(pbmc, verbose = FALSE) %>% RunPCA() %>% RunUMAP(dims = 1:50, reduction.name = 'umap.rna', reduction.key = 'rnaUMAP_') # ATAC analysis # We exclude the first dimension as this is typically correlated with sequencing depth DefaultAssay(pbmc) <- "ATAC" pbmc <- RunTFIDF(pbmc) pbmc <- FindTopFeatures(pbmc, min.cutoff = 'q0') pbmc <- RunSVD(pbmc) pbmc <- RunUMAP(pbmc, reduction = 'lsi', dims = 2:50, reduction.name = "umap.atac", reduction.key = "atacUMAP_")We calculate a WNN graph, representing a weighted combination of RNA and ATAC-seq modalities. We use this graph for UMAP visualization and clustering pbmc <- FindMultiModalNeighbors(pbmc, reduction.list = list("pca", "lsi"), dims.list = list(1:50, 2:50)) pbmc <- RunUMAP(pbmc, nn.name = "weighted.nn", reduction.name = "wnn.umap", reduction.key = "wnnUMAP_") pbmc <- FindClusters(pbmc, graph.name = "wsnn", algorithm = 3, verbose = FALSE)We annotate the clusters below. Note that you could also annotate the dataset using our supervised mapping pipelines, using either our vignette, or automated web tool, Azimuth. # perform sub-clustering on cluster 6 to find additional structure pbmc <- FindSubCluster(pbmc, cluster = 6, graph.name = "wsnn", algorithm = 3) Idents(pbmc) <- "sub.cluster" # add annotations pbmc <- RenameIdents(pbmc, '19' = 'pDC','20' = 'HSPC','15' = 'cDC') pbmc <- RenameIdents(pbmc, '0' = 'CD14 Mono', '9' ='CD14 Mono', '5' = 'CD16 Mono') pbmc <- RenameIdents(pbmc, '10' = 'Naive B', '11' = 'Intermediate B', '17' = 'Memory B', '21' = 'Plasma') pbmc <- RenameIdents(pbmc, '7' = 'NK') pbmc <- RenameIdents(pbmc, '4' = 'CD4 TCM', '13'= "CD4 TEM", '3' = "CD4 TCM", '16' ="Treg", '1' ="CD4 Naive", '14' = "CD4 Naive") pbmc <- RenameIdents(pbmc, '2' = 'CD8 Naive', '8'= "CD8 Naive", '12' = 'CD8 TEM_1', '6_0' = 'CD8 TEM_2', '6_1' ='CD8 TEM_2', '6_4' ='CD8 TEM_2') pbmc <- RenameIdents(pbmc, '18' = 'MAIT') pbmc <- RenameIdents(pbmc, '6_2' ='gdT', '6_3' = 'gdT') pbmc$celltype <- Idents(pbmc)We can visualize clustering based on gene expression, ATAC-seq, or WNN analysis. The differences are more subtle than in the previous analysis (you can explore the weights, which are more evenly split than in our CITE-seq example), but we find that WNN provides the clearest separation of cell states. p1 <- DimPlot(pbmc, reduction = "umap.rna", group.by = "celltype", label = TRUE, label.size = 2.5, repel = TRUE) + ggtitle("RNA") p2 <- DimPlot(pbmc, reduction = "umap.atac", group.by = "celltype", label = TRUE, label.size = 2.5, repel = TRUE) + ggtitle("ATAC") p3 <- DimPlot(pbmc, reduction = "wnn.umap", group.by = "celltype", label = TRUE, label.size = 2.5, repel = TRUE) + ggtitle("WNN") p1 + p2 + p3 & NoLegend() & theme(plot.title = element_text(hjust = 0.5))For example, the ATAC-seq data assists in the separation of CD4 and CD8 T cell states. This is due to the presence of multiple loci that exhibit differential accessibility between different T cell subtypes. For example, we can visualize ‘pseudobulk’ tracks of the CD8A locus alongside violin plots of gene expression levels, using tools in the Signac visualization vignette. ## to make the visualization easier, subset T cell clusters celltype.names <- levels(pbmc) tcell.names <- grep("CD4|CD8|Treg", celltype.names,value = TRUE) tcells <- subset(pbmc, idents = tcell.names) CoveragePlot(tcells, region = 'CD8A', features = 'CD8A', assay = 'ATAC', expression.assay = 'SCT', peaks = FALSE)Next, we will examine the accessible regions of each cell to determine enriched motifs. As described in the Signac motifs vignette, there are a few ways to do this, but we will use the chromVAR package from the Greenleaf lab. This calculates a per-cell accessibility score for known motifs, and adds these scores as a third assay (chromvar) in the Seurat object.To continue, please make sure you have the following packages installed.chromVAR for the analysis of motif accessibility in scATAC-seqpresto for fast differential expression analyses.TFBSTools for TFBS analysisJASPAR2020 for JASPAR motif modelsmotifmatchr for motif matchingBSgenome.Hsapiens.UCSC.hg38 for chromVARInstall command for all dependencies remotes::install_github("immunogenomics/presto") BiocManager::install(c("chromVAR", "TFBSTools", "JASPAR2020", "motifmatchr", "BSgenome.Hsapiens.UCSC.hg38")) library(chromVAR) library(JASPAR2020) library(TFBSTools) library(motifmatchr) library(BSgenome.Hsapiens.UCSC.hg38) # Scan the DNA sequence of each peak for the presence of each motif, and create a Motif object DefaultAssay(pbmc) <- "ATAC" pwm_set <- getMatrixSet(x = JASPAR2020, opts = list(species = 9606, all_versions = FALSE)) motif.matrix <- CreateMotifMatrix(features = granges(pbmc), pwm = pwm_set, genome = 'hg38', use.counts = FALSE) motif.object <- CreateMotifObject(data = motif.matrix, pwm = pwm_set) pbmc <- SetAssayData(pbmc, assay = 'ATAC', slot = 'motifs', new.data = motif.object) # Note that this step can take 30-60 minutes pbmc <- RunChromVAR( object = pbmc, genome = BSgenome.Hsapiens.UCSC.hg38 )Finally, we explore the multimodal dataset to identify key regulators of each cell state. Paired data provides a unique opportunity to identify transcription factors (TFs) that satisfy multiple criteria, helping to narrow down the list of putative regulators to the most likely candidates. We aim to identify TFs whose expression is enriched in multiple cell types in the RNA measurements, but also have enriched accessibility for their motifs in the ATAC measurements.As an example and positive control, the CCAAT Enhancer Binding Protein (CEBP) family of proteins, including the TF CEBPB, have been repeatedly shown to play important roles in the differentiation and function of myeloid cells including monocytes and dendritic cells. We can see that both the expression of the CEBPB, and the accessibility of the MA0466.2.4 motif (which encodes the binding site for CEBPB), are both enriched in monocytes. #returns MA0466.2 motif.name <- ConvertMotifID(pbmc, name = 'CEBPB') gene_plot <- FeaturePlot(pbmc, features = "sct_CEBPB", reduction = 'wnn.umap') motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap') gene_plot | motif_plotWe’d like to quantify this relationship, and search across all cell types to find similar examples. To do so, we will use the presto package to perform fast differential expression. We run two tests: one using gene expression data, and the other using chromVAR motif accessibilities. presto calculates a p-value based on the Wilcox rank sum test, which is also the default test in Seurat, and we restrict our search to TFs that return significant results in both tests.presto also calculates an “AUC” statistic, which reflects the power of each gene (or motif) to serve as a marker of cell type. A maximum AUC value of 1 indicates a perfect marker. Since the AUC statistic is on the same scale for both genes and motifs, we take the average of the AUC values from the two tests, and use this to rank TFs for each cell type: markers_rna <- presto:::wilcoxauc.Seurat(X = pbmc, group_by = 'celltype', assay = 'data', seurat_assay = 'SCT') markers_motifs <- presto:::wilcoxauc.Seurat(X = pbmc, group_by = 'celltype', assay = 'data', seurat_assay = 'chromvar') motif.names <- markers_motifs$feature colnames(markers_rna) <- paste0("RNA.", colnames(markers_rna)) colnames(markers_motifs) <- paste0("motif.", colnames(markers_motifs)) markers_rna$gene <- markers_rna$RNA.feature markers_motifs$gene <- ConvertMotifID(pbmc, id = motif.names) # a simple function to implement the procedure above topTFs <- function(celltype, padj.cutoff = 1e-2) { ctmarkers_rna <- dplyr::filter( markers_rna, RNA.group == celltype, RNA.padj < padj.cutoff, RNA.logFC > 0) %>% arrange(-RNA.auc) ctmarkers_motif <- dplyr::filter( markers_motifs, motif.group == celltype, motif.padj < padj.cutoff, motif.logFC > 0) %>% arrange(-motif.auc) top_tfs <- inner_join( x = ctmarkers_rna[, c(2, 11, 6, 7)], y = ctmarkers_motif[, c(2, 1, 11, 6, 7)], by = "gene" ) top_tfs$avg_auc <- (top_tfs$RNA.auc + top_tfs$motif.auc) / 2 top_tfs <- arrange(top_tfs, -avg_auc) return(top_tfs) }We can now compute, and visualize, putative regulators for any cell type. We recover well-established regulators, including TBX21 for NK cells, IRF4 for plasma cells, SOX4 for hematopoietic progenitors, EBF1 and PAX5 for B cells, IRF8 and TCF4 for pDC. We believe that similar strategies can be used to help focus on a set of putative regulators in diverse systems. # identify top markers in NK and visualize head(topTFs("NK"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 NK TBX21 0.7270859 0.000000e+00 NK MA0690.1 0.9139614 ## 2 NK EOMES 0.5886774 2.411013e-98 NK MA0800.1 0.9214773 ## 3 NK RUNX3 0.7705661 5.977716e-120 NK MA0684.2 0.6769022 ## motif.pval avg_auc ## 1 1.097940e-202 0.8205237 ## 2 4.903866e-210 0.7550774 ## 3 1.560061e-38 0.7237341 motif.name <- ConvertMotifID(pbmc, name = 'TBX21') gene_plot <- FeaturePlot(pbmc, features = "sct_TBX21", reduction = 'wnn.umap') motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap') gene_plot | motif_plot # identify top markers in pDC and visualize head(topTFs("pDC"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 pDC TCF4 0.9998815 1.120711e-162 pDC MA0830.2 0.9965481 ## 2 pDC IRF8 0.9904457 1.308164e-123 pDC MA0652.1 0.8833112 ## 3 pDC SPIB 0.9115207 0.000000e+00 pDC MA0081.2 0.9068540 ## motif.pval avg_auc ## 1 1.785897e-69 0.9982148 ## 2 3.982413e-42 0.9368785 ## 3 3.083509e-47 0.9091874 motif.name <- ConvertMotifID(pbmc, name = 'TCF4') gene_plot <- FeaturePlot(pbmc, features = "sct_TCF4", reduction = 'wnn.umap') motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap') gene_plot | motif_plot # identify top markers in HSPC and visualize head(topTFs("CD16 Mono"),3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 CD16 Mono SPI1 0.8793172 1.666810e-296 CD16 Mono MA0080.5 0.8880908 ## 2 CD16 Mono CEBPB 0.8685933 1.625472e-294 CD16 Mono MA0466.2 0.7840422 ## 3 CD16 Mono MEF2C 0.7129910 2.727252e-79 CD16 Mono MA0497.1 0.8059373 ## motif.pval avg_auc ## 1 4.762491e-194 0.8837040 ## 2 7.049764e-105 0.8263177 ## 3 2.345716e-121 0.7594641 motif.name <- ConvertMotifID(pbmc, name = 'SPI1') gene_plot <- FeaturePlot(pbmc, features = "sct_SPI1", reduction = 'wnn.umap') motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap') gene_plot | motif_plot # identify top markers in other cell types head(topTFs("Naive B"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 Naive B MEF2C 0.8802747 1.890065e-182 Naive B MA0497.1 0.6789079 ## 2 Naive B PAX5 0.9436648 0.000000e+00 Naive B MA0014.3 0.5827061 ## 3 Naive B POU2F2 0.6029377 2.892216e-13 Naive B MA0507.1 0.8912268 ## motif.pval avg_auc ## 1 9.815118e-32 0.7795913 ## 2 5.995185e-08 0.7631854 ## 3 6.471677e-145 0.7470822 head(topTFs("HSPC"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 HSPC SOX4 0.9869406 5.524832e-71 HSPC MA0867.2 0.6830497 ## 2 HSPC GATA2 0.7884615 0.000000e+00 HSPC MA0036.3 0.8275008 ## 3 HSPC MEIS1 0.8638496 0.000000e+00 HSPC MA0498.2 0.6924225 ## motif.pval avg_auc ## 1 1.241915e-03 0.8349951 ## 2 7.591798e-09 0.8079812 ## 3 6.877492e-04 0.7781361 head(topTFs("Plasma"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 Plasma IRF4 0.8189687 5.261955e-35 Plasma MA1419.1 0.9776046 ## 2 Plasma MEF2C 0.9111213 2.977155e-12 Plasma MA0497.1 0.7596637 ## 3 Plasma TCF4 0.8049409 6.810635e-12 Plasma MA0830.2 0.7840848 ## motif.pval avg_auc ## 1 2.334627e-12 0.8982867 ## 2 1.374353e-04 0.8353925 ## 3 3.028306e-05 0.7945129Session Info sessionInfo()## R version 4.2.0 (2022-04-22) ## Platform: x86_64-pc-linux-gnu (64-bit) ## Running under: Ubuntu 20.04.5 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/liblapack.so.3 ## ## locale: ## [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C ## [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8 ## [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 ## ## attached base packages: ## [1] stats4 stats graphics grDevices utils datasets methods ## [8] base ## ## other attached packages: ## [1] BSgenome.Hsapiens.UCSC.hg38_1.4.5 BSgenome_1.66.3 ## [3] rtracklayer_1.58.0 Biostrings_2.66.0 ## [5] XVector_0.38.0 motifmatchr_1.20.0 ## [7] TFBSTools_1.36.0 JASPAR2020_0.99.10 ## [9] chromVAR_1.20.2 EnsDb.Hsapiens.v86_2.99.0 ## [11] ensembldb_2.22.0 AnnotationFilter_1.22.0 ## [13] GenomicFeatures_1.50.4 AnnotationDbi_1.60.0 ## [15] Biobase_2.58.0 GenomicRanges_1.50.2 ## [17] GenomeInfoDb_1.35.16 IRanges_2.32.0 ## [19] S4Vectors_0.36.2 BiocGenerics_0.44.0 ## [21] Signac_1.9.0 ggplot2_3.4.1 ## [23] dplyr_1.1.1 cowplot_1.1.1 ## [25] thp1.eccite.SeuratData_3.1.5 stxBrain.SeuratData_0.1.1 ## [27] ssHippo.SeuratData_3.1.4 pbmcsca.SeuratData_3.0.0 ## [29] pbmcMultiome.SeuratData_0.1.2 pbmc3k.SeuratData_3.1.4 ## [31] panc8.SeuratData_3.0.2 ifnb.SeuratData_3.1.0 ## [33] hcabm40k.SeuratData_3.0.0 bmcite.SeuratData_0.3.0 ## [35] SeuratData_0.2.2 SeuratObject_4.1.3 ## [37] Seurat_4.2.1.9001 ## ## loaded via a namespace (and not attached): ## [1] rappdirs_0.3.3 scattermore_0.8 ## [3] R.methodsS3_1.8.2 ragg_1.2.5 ## [5] nabor_0.5.0 tidyr_1.3.0 ## [7] bit64_4.0.5 knitr_1.42 ## [9] R.utils_2.12.2 irlba_2.3.5.1 ## [11] DelayedArray_0.24.0 data.table_1.14.8 ## [13] rpart_4.1.16 KEGGREST_1.38.0 ## [15] RCurl_1.98-1.12 generics_0.1.3 ## [17] RSQLite_2.3.0 RANN_2.6.1 ## [19] future_1.32.0 tzdb_0.3.0 ## [21] bit_4.0.5 spatstat.data_3.0-1 ## [23] xml2_1.3.3 httpuv_1.6.9 ## [25] SummarizedExperiment_1.28.0 DirichletMultinomial_1.40.0 ## [27] xfun_0.38 hms_1.1.2 ## [29] jquerylib_0.1.4 evaluate_0.20 ## [31] promises_1.2.0.1 fansi_1.0.4 ## [33] restfulr_0.0.15 progress_1.2.2 ## [35] caTools_1.18.2 dbplyr_2.3.1 ## [37] igraph_1.4.1 DBI_1.1.3 ## [39] htmlwidgets_1.6.2 spatstat.geom_3.1-0 ## [41] purrr_1.0.1 ellipsis_0.3.2 ## [43] backports_1.4.1 annotate_1.76.0 ## [45] biomaRt_2.54.0 deldir_1.0-6 ## [47] MatrixGenerics_1.10.0 vctrs_0.6.1 ## [49] ROCR_1.0-11 abind_1.4-5 ## [51] cachem_1.0.7 withr_2.5.0 ## [53] progressr_0.13.0 presto_1.0.0 ## [55] checkmate_2.1.0 sctransform_0.3.5 ## [57] GenomicAlignments_1.34.0 prettyunits_1.1.1 ## [59] goftest_1.2-3 cluster_2.1.3 ## [61] seqLogo_1.64.0 lazyeval_0.2.2 ## [63] crayon_1.5.2 hdf5r_1.3.8 ## [65] spatstat.explore_3.1-0 pkgconfig_2.0.3 ## [67] labeling_0.4.2 nlme_3.1-157 ## [69] ProtGenerics_1.30.0 nnet_7.3-17 ## [71] rlang_1.1.0 globals_0.16.2 ## [73] lifecycle_1.0.3 miniUI_0.1.1.1 ## [75] filelock_1.0.2 BiocFileCache_2.6.1 ## [77] dichromat_2.0-0.1 rprojroot_2.0.3 ## [79] polyclip_1.10-4 matrixStats_0.63.0 ## [81] lmtest_0.9-40 Matrix_1.5-3 ## [83] zoo_1.8-11 base64enc_0.1-3 ## [85] ggridges_0.5.4 png_0.1-8 ## [87] viridisLite_0.4.1 rjson_0.2.21 ## [89] bitops_1.0-7 R.oo_1.25.0 ## [91] KernSmooth_2.23-20 blob_1.2.3 ## [93] stringr_1.5.0 parallelly_1.35.0 ## [95] spatstat.random_3.1-4 readr_2.1.4 ## [97] jpeg_0.1-10 CNEr_1.34.0 ## [99] scales_1.2.1 memoise_2.0.1 ## [101] magrittr_2.0.3 plyr_1.8.8 ## [103] ica_1.0-3 zlibbioc_1.44.0 ## [105] compiler_4.2.0 BiocIO_1.8.0 ## [107] RColorBrewer_1.1-3 fitdistrplus_1.1-8 ## [109] Rsamtools_2.14.0 cli_3.6.1 ## [111] listenv_0.9.0 patchwork_1.1.2 ## [113] pbapply_1.7-0 htmlTable_2.4.1 ## [115] Formula_1.2-5 MASS_7.3-56 ## [117] tidyselect_1.2.0 stringi_1.7.12 ## [119] textshaping_0.3.6 highr_0.10 ## [121] yaml_2.3.7 latticeExtra_0.6-30 ## [123] ggrepel_0.9.3 grid_4.2.0 ## [125] sass_0.4.5 VariantAnnotation_1.44.1 ## [127] fastmatch_1.1-3 tools_4.2.0 ## [129] future.apply_1.10.0 parallel_4.2.0 ## [131] rstudioapi_0.14 TFMPvalue_0.0.9 ## [133] foreign_0.8-82 gridExtra_2.3 ## [135] farver_2.1.1 Rtsne_0.16 ## [137] digest_0.6.31 pracma_2.4.2 ## [139] shiny_1.7.4 Rcpp_1.0.10 ## [141] later_1.3.0 RcppAnnoy_0.0.20 ## [143] httr_1.4.5 biovizBase_1.46.0 ## [145] colorspace_2.1-0 XML_3.99-0.13 ## [147] fs_1.6.1 tensor_1.5 ## [149] reticulate_1.28 splines_4.2.0 ## [151] uwot_0.1.14 RcppRoll_0.3.0 ## [153] spatstat.utils_3.0-2 pkgdown_2.0.7 ## [155] sp_1.6-0 plotly_4.10.1 ## [157] systemfonts_1.0.4 xtable_1.8-4 ## [159] poweRlaw_0.70.6 jsonlite_1.8.4 ## [161] R6_2.5.1 Hmisc_4.8-0 ## [163] pillar_1.9.0 htmltools_0.5.5 ## [165] mime_0.12 DT_0.27 ## [167] glue_1.6.2 fastmap_1.1.1 ## [169] BiocParallel_1.32.5 codetools_0.2-18 ## [171] utf8_1.2.3 lattice_0.20-45 ## [173] bslib_0.4.2 spatstat.sparse_3.0-1 ## [175] tibble_3.2.1 curl_5.0.0 ## [177] leiden_0.4.3 gtools_3.9.4 ## [179] GO.db_3.16.0 interp_1.1-3 ## [181] survival_3.3-1 rmarkdown_2.21 ## [183] desc_1.4.2 munsell_0.5.0 ## [185] GenomeInfoDbData_1.2.9 reshape2_1.4.4 ## [187] gtable_0.3.3

Finally, in order to run the vignette, make sure the following packages are installed:Seurat v4Signac for the analysis of single-cell chromatin datasetsEnsDb.Hsapiens.v86 for a set of annotations for hg38dplyr to help manipulate data tables library(Seurat) library(Signac) library(EnsDb.Hsapiens.v86) library(dplyr) library(ggplot2)We’ll create a Seurat object based on the gene expression data, and then add in the ATAC-seq data as a second assay. You can explore the Signac getting started vignette for more information on the creation and processing of a ChromatinAssay object. # the 10x hdf5 file contains both data types. inputdata.10x <- Read10X_h5("../data/pbmc_granulocyte_sorted_10k_filtered_feature_bc_matrix.h5") # extract RNA and ATAC data rna_counts <- inputdata.10x$`Gene Expression` atac_counts <- inputdata.10x$Peaks # Create Seurat object pbmc <- CreateSeuratObject(counts = rna_counts) pbmc[["percent.mt"]] <- PercentageFeatureSet(pbmc, pattern = "^MT-") # Now add in the ATAC-seq data # we'll only use peaks in standard chromosomes grange.counts <- StringToGRanges(rownames(atac_counts), sep = c(":", "-")) grange.use <- seqnames(grange.counts) %in% standardChromosomes(grange.counts) atac_counts <- atac_counts[as.vector(grange.use), ] annotations <- GetGRangesFromEnsDb(ensdb = EnsDb.Hsapiens.v86) seqlevelsStyle(annotations) <- 'UCSC' genome(annotations) <- "hg38" frag.file <- "../data/pbmc_granulocyte_sorted_10k_atac_fragments.tsv.gz" chrom_assay <- CreateChromatinAssay( counts = atac_counts, sep = c(":", "-"), genome = 'hg38', fragments = frag.file, min.cells = 10, annotation = annotations ) pbmc[["ATAC"]] <- chrom_assayWe perform basic QC based on the number of detected molecules for each modality as well as mitochondrial percentage. VlnPlot(pbmc, features = c("nCount_ATAC", "nCount_RNA","percent.mt"), ncol = 3, log = TRUE, pt.size = 0) + NoLegend() pbmc <- subset( x = pbmc, subset = nCount_ATAC < 7e4 & nCount_ATAC > 5e3 & nCount_RNA < 25000 & nCount_RNA > 1000 & percent.mt < 20 )We next perform pre-processing and dimensional reduction on both assays independently, using standard approaches for RNA and ATAC-seq data. # RNA analysis DefaultAssay(pbmc) <- "RNA" pbmc <- SCTransform(pbmc, verbose = FALSE) %>% RunPCA() %>% RunUMAP(dims = 1:50, reduction.name = 'umap.rna', reduction.key = 'rnaUMAP_') # ATAC analysis # We exclude the first dimension as this is typically correlated with sequencing depth DefaultAssay(pbmc) <- "ATAC" pbmc <- RunTFIDF(pbmc) pbmc <- FindTopFeatures(pbmc, min.cutoff = 'q0') pbmc <- RunSVD(pbmc) pbmc <- RunUMAP(pbmc, reduction = 'lsi', dims = 2:50, reduction.name = "umap.atac", reduction.key = "atacUMAP_")We calculate a WNN graph, representing a weighted combination of RNA and ATAC-seq modalities. We use this graph for UMAP visualization and clustering pbmc <- FindMultiModalNeighbors(pbmc, reduction.list = list("pca", "lsi"), dims.list = list(1:50, 2:50)) pbmc <- RunUMAP(pbmc, nn.name = "weighted.nn", reduction.name = "wnn.umap", reduction.key = "wnnUMAP_") pbmc <- FindClusters(pbmc, graph.name = "wsnn", algorithm = 3, verbose = FALSE)We annotate the clusters below. Note that you could also annotate the dataset using our supervised mapping pipelines, using either our vignette, or automated web tool, Azimuth. # perform sub-clustering on cluster 6 to find additional structure pbmc <- FindSubCluster(pbmc, cluster = 6, graph.name = "wsnn", algorithm = 3) Idents(pbmc) <- "sub.cluster" # add annotations pbmc <- RenameIdents(pbmc, '19' = 'pDC','20' = 'HSPC','15' = 'cDC') pbmc <- RenameIdents(pbmc, '0' = 'CD14 Mono', '9' ='CD14 Mono', '5' = 'CD16 Mono') pbmc <- RenameIdents(pbmc, '10' = 'Naive B', '11' = 'Intermediate B', '17' = 'Memory B', '21' = 'Plasma') pbmc <- RenameIdents(pbmc, '7' = 'NK') pbmc <- RenameIdents(pbmc, '4' = 'CD4 TCM', '13'= "CD4 TEM", '3' = "CD4 TCM", '16' ="Treg", '1' ="CD4 Naive", '14' = "CD4 Naive") pbmc <- RenameIdents(pbmc, '2' = 'CD8 Naive', '8'= "CD8 Naive", '12' = 'CD8 TEM_1', '6_0' = 'CD8 TEM_2', '6_1' ='CD8 TEM_2', '6_4' ='CD8 TEM_2') pbmc <- RenameIdents(pbmc, '18' = 'MAIT') pbmc <- RenameIdents(pbmc, '6_2' ='gdT', '6_3' = 'gdT') pbmc$celltype <- Idents(pbmc)We can visualize clustering based on gene expression, ATAC-seq, or WNN analysis. The differences are more subtle than in the previous analysis (you can explore the weights, which are more evenly split than in our CITE-seq example), but we find that WNN provides the clearest separation of cell states. p1 <- DimPlot(pbmc, reduction = "umap.rna", group.by = "celltype", label = TRUE, label.size = 2.5, repel = TRUE) + ggtitle("RNA") p2 <- DimPlot(pbmc, reduction = "umap.atac", group.by = "celltype", label = TRUE, label.size = 2.5, repel = TRUE) + ggtitle("ATAC") p3 <- DimPlot(pbmc, reduction = "wnn.umap", group.by = "celltype", label = TRUE, label.size = 2.5, repel = TRUE) + ggtitle("WNN") p1 + p2 + p3 & NoLegend() & theme(plot.title = element_text(hjust = 0.5))For example, the ATAC-seq data assists in the separation of CD4 and CD8 T cell states. This is due to the presence of multiple loci that exhibit differential accessibility between different T cell subtypes. For example, we can visualize ‘pseudobulk’ tracks of the CD8A locus alongside violin plots of gene expression levels, using tools in the Signac visualization vignette. ## to make the visualization easier, subset T cell clusters celltype.names <- levels(pbmc) tcell.names <- grep("CD4|CD8|Treg", celltype.names,value = TRUE) tcells <- subset(pbmc, idents = tcell.names) CoveragePlot(tcells, region = 'CD8A', features = 'CD8A', assay = 'ATAC', expression.assay = 'SCT', peaks = FALSE)Next, we will examine the accessible regions of each cell to determine enriched motifs. As described in the Signac motifs vignette, there are a few ways to do this, but we will use the chromVAR package from the Greenleaf lab. This calculates a per-cell accessibility score for known motifs, and adds these scores as a third assay (chromvar) in the Seurat object.To continue, please make sure you have the following packages installed.chromVAR for the analysis of motif accessibility in scATAC-seqpresto for fast differential expression analyses.TFBSTools for TFBS analysisJASPAR2020 for JASPAR motif modelsmotifmatchr for motif matchingBSgenome.Hsapiens.UCSC.hg38 for chromVARInstall command for all dependencies remotes::install_github("immunogenomics/presto") BiocManager::install(c("chromVAR", "TFBSTools", "JASPAR2020", "motifmatchr", "BSgenome.Hsapiens.UCSC.hg38")) library(chromVAR) library(JASPAR2020) library(TFBSTools) library(motifmatchr) library(BSgenome.Hsapiens.UCSC.hg38) # Scan the DNA sequence of each peak for the presence of each motif, and create a Motif object DefaultAssay(pbmc) <- "ATAC" pwm_set <- getMatrixSet(x = JASPAR2020, opts = list(species = 9606, all_versions = FALSE)) motif.matrix <- CreateMotifMatrix(features = granges(pbmc), pwm = pwm_set, genome = 'hg38', use.counts = FALSE) motif.object <- CreateMotifObject(data = motif.matrix, pwm = pwm_set) pbmc <- SetAssayData(pbmc, assay = 'ATAC', slot = 'motifs', new.data = motif.object) # Note that this step can take 30-60 minutes pbmc <- RunChromVAR( object = pbmc, genome = BSgenome.Hsapiens.UCSC.hg38 )Finally, we explore the multimodal dataset to identify key regulators of each cell state. Paired data provides a unique opportunity to identify transcription factors (TFs) that satisfy multiple criteria, helping to narrow down the list of putative regulators to the most likely candidates. We aim to identify TFs whose expression is enriched in multiple cell types in the RNA measurements, but also have enriched accessibility for their motifs in the ATAC measurements.As an example and positive control, the CCAAT Enhancer Binding Protein (CEBP) family of proteins, including the TF CEBPB, have been repeatedly shown to play important roles in the differentiation and function of myeloid cells including monocytes and dendritic cells. We can see that both the expression of the CEBPB, and the accessibility of the MA0466.2.4 motif (which encodes the binding site for CEBPB), are both enriched in monocytes. #returns MA0466.2 motif.name <- ConvertMotifID(pbmc, name = 'CEBPB') gene_plot <- FeaturePlot(pbmc, features = "sct_CEBPB", reduction = 'wnn.umap') motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap') gene_plot | motif_plotWe’d like to quantify this relationship, and search across all cell types to find similar examples. To do so, we will use the presto package to perform fast differential expression. We run two tests: one using gene expression data, and the other using chromVAR motif accessibilities. presto calculates a p-value based on the Wilcox rank sum test, which is also the default test in Seurat, and we restrict our search to TFs that return significant results in both tests.presto also calculates an “AUC” statistic, which reflects the power of each gene (or motif) to serve as a marker of cell type. A maximum AUC value of 1 indicates a perfect marker. Since the AUC statistic is on the same scale for both genes and motifs, we take the average of the AUC values from the two tests, and use this to rank TFs for each cell type: markers_rna <- presto:::wilcoxauc.Seurat(X = pbmc, group_by = 'celltype', assay = 'data', seurat_assay = 'SCT') markers_motifs <- presto:::wilcoxauc.Seurat(X = pbmc, group_by = 'celltype', assay = 'data', seurat_assay = 'chromvar') motif.names <- markers_motifs$feature colnames(markers_rna) <- paste0("RNA.", colnames(markers_rna)) colnames(markers_motifs) <- paste0("motif.", colnames(markers_motifs)) markers_rna$gene <- markers_rna$RNA.feature markers_motifs$gene <- ConvertMotifID(pbmc, id = motif.names) # a simple function to implement the procedure above topTFs <- function(celltype, padj.cutoff = 1e-2) { ctmarkers_rna <- dplyr::filter( markers_rna, RNA.group == celltype, RNA.padj < padj.cutoff, RNA.logFC > 0) %>% arrange(-RNA.auc) ctmarkers_motif <- dplyr::filter( markers_motifs, motif.group == celltype, motif.padj < padj.cutoff, motif.logFC > 0) %>% arrange(-motif.auc) top_tfs <- inner_join( x = ctmarkers_rna[, c(2, 11, 6, 7)], y = ctmarkers_motif[, c(2, 1, 11, 6, 7)], by = "gene" ) top_tfs$avg_auc <- (top_tfs$RNA.auc + top_tfs$motif.auc) / 2 top_tfs <- arrange(top_tfs, -avg_auc) return(top_tfs) }We can now compute, and visualize, putative regulators for any cell type. We recover well-established regulators, including TBX21 for NK cells, IRF4 for plasma cells, SOX4 for hematopoietic progenitors, EBF1 and PAX5 for B cells, IRF8 and TCF4 for pDC. We believe that similar strategies can be used to help focus on a set of putative regulators in diverse systems. # identify top markers in NK and visualize head(topTFs("NK"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 NK TBX21 0.7270859 0.000000e+00 NK MA0690.1 0.9139614 ## 2 NK EOMES 0.5886774 2.411013e-98 NK MA0800.1 0.9214773 ## 3 NK RUNX3 0.7705661 5.977716e-120 NK MA0684.2 0.6769022 ## motif.pval avg_auc ## 1 1.097940e-202 0.8205237 ## 2 4.903866e-210 0.7550774 ## 3 1.560061e-38 0.7237341 motif.name <- ConvertMotifID(pbmc, name = 'TBX21') gene_plot <- FeaturePlot(pbmc, features = "sct_TBX21", reduction = 'wnn.umap') motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap') gene_plot | motif_plot # identify top markers in pDC and visualize head(topTFs("pDC"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 pDC TCF4 0.9998815 1.120711e-162 pDC MA0830.2 0.9965481 ## 2 pDC IRF8 0.9904457 1.308164e-123 pDC MA0652.1 0.8833112 ## 3 pDC SPIB 0.9115207 0.000000e+00 pDC MA0081.2 0.9068540 ## motif.pval avg_auc ## 1 1.785897e-69 0.9982148 ## 2 3.982413e-42 0.9368785 ## 3 3.083509e-47 0.9091874 motif.name <- ConvertMotifID(pbmc, name = 'TCF4') gene_plot <- FeaturePlot(pbmc, features = "sct_TCF4", reduction = 'wnn.umap') motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap') gene_plot | motif_plot # identify top markers in HSPC and visualize head(topTFs("CD16 Mono"),3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 CD16 Mono SPI1 0.8793172 1.666810e-296 CD16 Mono MA0080.5 0.8880908 ## 2 CD16 Mono CEBPB 0.8685933 1.625472e-294 CD16 Mono MA0466.2 0.7840422 ## 3 CD16 Mono MEF2C 0.7129910 2.727252e-79 CD16 Mono MA0497.1 0.8059373 ## motif.pval avg_auc ## 1 4.762491e-194 0.8837040 ## 2 7.049764e-105 0.8263177 ## 3 2.345716e-121 0.7594641 motif.name <- ConvertMotifID(pbmc, name = 'SPI1') gene_plot <- FeaturePlot(pbmc, features = "sct_SPI1", reduction = 'wnn.umap') motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap') gene_plot | motif_plot # identify top markers in other cell types head(topTFs("Naive B"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 Naive B MEF2C 0.8802747 1.890065e-182 Naive B MA0497.1 0.6789079 ## 2 Naive B PAX5 0.9436648 0.000000e+00 Naive B MA0014.3 0.5827061 ## 3 Naive B POU2F2 0.6029377 2.892216e-13 Naive B MA0507.1 0.8912268 ## motif.pval avg_auc ## 1 9.815118e-32 0.7795913 ## 2 5.995185e-08 0.7631854 ## 3 6.471677e-145 0.7470822 head(topTFs("HSPC"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 HSPC SOX4 0.9869406 5.524832e-71 HSPC MA0867.2 0.6830497 ## 2 HSPC GATA2 0.7884615 0.000000e+00 HSPC MA0036.3 0.8275008 ## 3 HSPC MEIS1 0.8638496 0.000000e+00 HSPC MA0498.2 0.6924225 ## motif.pval avg_auc ## 1 1.241915e-03 0.8349951 ## 2 7.591798e-09 0.8079812 ## 3 6.877492e-04 0.7781361 head(topTFs("Plasma"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 Plasma IRF4 0.8189687 5.261955e-35 Plasma MA1419.1 0.9776046 ## 2 Plasma MEF2C 0.9111213 2.977155e-12 Plasma MA0497.1 0.7596637 ## 3 Plasma TCF4 0.8049409 6.810635e-12 Plasma MA0830.2 0.7840848 ## motif.pval avg_auc ## 1 2.334627e-12 0.8982867 ## 2 1.374353e-04 0.8353925 ## 3 3.028306e-05 0.7945129Session Info sessionInfo()## R version 4.2.0 (2022-04-22) ## Platform: x86_64-pc-linux-gnu (64-bit) ## Running under: Ubuntu 20.04.5 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/liblapack.so.3 ## ## locale: ## [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C ## [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8 ## [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 ## ## attached base packages: ## [1] stats4 stats graphics grDevices utils datasets methods ## [8] base ## ## other attached packages: ## [1] BSgenome.Hsapiens.UCSC.hg38_1.4.5 BSgenome_1.66.3 ## [3] rtracklayer_1.58.0 Biostrings_2.66.0 ## [5] XVector_0.38.0 motifmatchr_1.20.0 ## [7] TFBSTools_1.36.0 JASPAR2020_0.99.10 ## [9] chromVAR_1.20.2 EnsDb.Hsapiens.v86_2.99.0 ## [11] ensembldb_2.22.0 AnnotationFilter_1.22.0 ## [13] GenomicFeatures_1.50.4 AnnotationDbi_1.60.0 ## [15] Biobase_2.58.0 GenomicRanges_1.50.2 ## [17] GenomeInfoDb_1.35.16 IRanges_2.32.0 ## [19] S4Vectors_0.36.2 BiocGenerics_0.44.0 ## [21] Signac_1.9.0 ggplot2_3.4.1 ## [23] dplyr_1.1.1 cowplot_1.1.1 ## [25] thp1.eccite.SeuratData_3.1.5 stxBrain.SeuratData_0.1.1 ## [27] ssHippo.SeuratData_3.1.4 pbmcsca.SeuratData_3.0.0 ## [29] pbmcMultiome.SeuratData_0.1.2 pbmc3k.SeuratData_3.1.4 ## [31] panc8.SeuratData_3.0.2 ifnb.SeuratData_3.1.0 ## [33] hcabm40k.SeuratData_3.0.0 bmcite.SeuratData_0.3.0 ## [35] SeuratData_0.2.2 SeuratObject_4.1.3 ## [37] Seurat_4.2.1.9001 ## ## loaded via a namespace (and not attached): ## [1] rappdirs_0.3.3 scattermore_0.8 ## [3] R.methodsS3_1.8.2 ragg_1.2.5 ## [5] nabor_0.5.0 tidyr_1.3.0 ## [7] bit64_4.0.5 knitr_1.42 ## [9] R.utils_2.12.2 irlba_2.3.5.1 ## [11] DelayedArray_0.24.0 data.table_1.14.8 ## [13] rpart_4.1.16 KEGGREST_1.38.0 ## [15] RCurl_1.98-1.12 generics_0.1.3 ## [17] RSQLite_2.3.0 RANN_2.6.1 ## [19] future_1.32.0 tzdb_0.3.0 ## [21] bit_4.0.5 spatstat.data_3.0-1 ## [23] xml2_1.3.3 httpuv_1.6.9 ## [25] SummarizedExperiment_1.28.0 DirichletMultinomial_1.40.0 ## [27] xfun_0.38 hms_1.1.2 ## [29] jquerylib_0.1.4 evaluate_0.20 ## [31] promises_1.2.0.1 fansi_1.0.4 ## [33] restfulr_0.0.15 progress_1.2.2 ## [35] caTools_1.18.2 dbplyr_2.3.1 ## [37] igraph_1.4.1 DBI_1.1.3 ## [39] htmlwidgets_1.6.2 spatstat.geom_3.1-0 ## [41] purrr_1.0.1 ellipsis_0.3.2 ## [43] backports_1.4.1 annotate_1.76.0 ## [45] biomaRt_2.54.0 deldir_1.0-6 ## [47] MatrixGenerics_1.10.0 vctrs_0.6.1 ## [49] ROCR_1.0-11 abind_1.4-5 ## [51] cachem_1.0.7 withr_2.5.0 ## [53] progressr_0.13.0 presto_1.0.0 ## [55] checkmate_2.1.0 sctransform_0.3.5 ## [57] GenomicAlignments_1.34.0 prettyunits_1.1.1 ## [59] goftest_1.2-3 cluster_2.1.3 ## [61] seqLogo_1.64.0 lazyeval_0.2.2 ## [63] crayon_1.5.2 hdf5r_1.3.8 ## [65] spatstat.explore_3.1-0 pkgconfig_2.0.3 ## [67] labeling_0.4.2 nlme_3.1-157 ## [69] ProtGenerics_1.30.0 nnet_7.3-17 ## [71] rlang_1.1.0 globals_0.16.2 ## [73] lifecycle_1.0.3 miniUI_0.1.1.1 ## [75] filelock_1.0.2 BiocFileCache_2.6.1 ## [77] dichromat_2.0-0.1 rprojroot_2.0.3 ## [79] polyclip_1.10-4 matrixStats_0.63.0 ## [81] lmtest_0.9-40 Matrix_1.5-3 ## [83] zoo_1.8-11 base64enc_0.1-3 ## [85] ggridges_0.5.4 png_0.1-8 ## [87] viridisLite_0.4.1 rjson_0.2.21 ## [89] bitops_1.0-7 R.oo_1.25.0 ## [91] KernSmooth_2.23-20 blob_1.2.3 ## [93] stringr_1.5.0 parallelly_1.35.0 ## [95] spatstat.random_3.1-4 readr_2.1.4 ## [97] jpeg_0.1-10 CNEr_1.34.0 ## [99] scales_1.2.1 memoise_2.0.1 ## [101] magrittr_2.0.3 plyr_1.8.8 ## [103] ica_1.0-3 zlibbioc_1.44.0 ## [105] compiler_4.2.0 BiocIO_1.8.0 ## [107] RColorBrewer_1.1-3 fitdistrplus_1.1-8 ## [109] Rsamtools_2.14.0 cli_3.6.1 ## [111] listenv_0.9.0 patchwork_1.1.2 ## [113] pbapply_1.7-0 htmlTable_2.4.1 ## [115] Formula_1.2-5 MASS_7.3-56 ## [117] tidyselect_1.2.0 stringi_1.7.12 ## [119] textshaping_0.3.6 highr_0.10 ## [121] yaml_2.3.7 latticeExtra_0.6-30 ## [123] ggrepel_0.9.3 grid_4.2.0 ## [125] sass_0.4.5 VariantAnnotation_1.44.1 ## [127] fastmatch_1.1-3 tools_4.2.0 ## [129] future.apply_1.10.0 parallel_4.2.0 ## [131] rstudioapi_0.14 TFMPvalue_0.0.9 ## [133] foreign_0.8-82 gridExtra_2.3 ## [135] farver_2.1.1 Rtsne_0.16 ## [137] digest_0.6.31 pracma_2.4.2 ## [139] shiny_1.7.4 Rcpp_1.0.10 ## [141] later_1.3.0 RcppAnnoy_0.0.20 ## [143] httr_1.4.5 biovizBase_1.46.0 ## [145] colorspace_2.1-0 XML_3.99-0.13 ## [147] fs_1.6.1 tensor_1.5 ## [149] reticulate_1.28 splines_4.2.0 ## [151] uwot_0.1.14 RcppRoll_0.3.0 ## [153] spatstat.utils_3.0-2 pkgdown_2.0.7 ## [155] sp_1.6-0 plotly_4.10.1 ## [157] systemfonts_1.0.4 xtable_1.8-4 ## [159] poweRlaw_0.70.6 jsonlite_1.8.4 ## [161] R6_2.5.1 Hmisc_4.8-0 ## [163] pillar_1.9.0 htmltools_0.5.5 ## [165] mime_0.12 DT_0.27 ## [167] glue_1.6.2 fastmap_1.1.1 ## [169] BiocParallel_1.32.5 codetools_0.2-18 ## [171] utf8_1.2.3 lattice_0.20-45 ## [173] bslib_0.4.2 spatstat.sparse_3.0-1 ## [175] tibble_3.2.1 curl_5.0.0 ## [177] leiden_0.4.3 gtools_3.9.4 ## [179] GO.db_3.16.0 interp_1.1-3 ## [181] survival_3.3-1 rmarkdown_2.21 ## [183] desc_1.4.2 munsell_0.5.0 ## [185] GenomeInfoDbData_1.2.9 reshape2_1.4.4 ## [187] gtable_0.3.3

We’ll create a Seurat object based on the gene expression data, and then add in the ATAC-seq data as a second assay. You can explore the Signac getting started vignette for more information on the creation and processing of a ChromatinAssay object. # the 10x hdf5 file contains both data types. inputdata.10x <- Read10X_h5("../data/pbmc_granulocyte_sorted_10k_filtered_feature_bc_matrix.h5") # extract RNA and ATAC data rna_counts <- inputdata.10x$`Gene Expression` atac_counts <- inputdata.10x$Peaks # Create Seurat object pbmc <- CreateSeuratObject(counts = rna_counts) pbmc[["percent.mt"]] <- PercentageFeatureSet(pbmc, pattern = "^MT-") # Now add in the ATAC-seq data # we'll only use peaks in standard chromosomes grange.counts <- StringToGRanges(rownames(atac_counts), sep = c(":", "-")) grange.use <- seqnames(grange.counts) %in% standardChromosomes(grange.counts) atac_counts <- atac_counts[as.vector(grange.use), ] annotations <- GetGRangesFromEnsDb(ensdb = EnsDb.Hsapiens.v86) seqlevelsStyle(annotations) <- 'UCSC' genome(annotations) <- "hg38" frag.file <- "../data/pbmc_granulocyte_sorted_10k_atac_fragments.tsv.gz" chrom_assay <- CreateChromatinAssay( counts = atac_counts, sep = c(":", "-"), genome = 'hg38', fragments = frag.file, min.cells = 10, annotation = annotations ) pbmc[["ATAC"]] <- chrom_assayWe perform basic QC based on the number of detected molecules for each modality as well as mitochondrial percentage. VlnPlot(pbmc, features = c("nCount_ATAC", "nCount_RNA","percent.mt"), ncol = 3, log = TRUE, pt.size = 0) + NoLegend() pbmc <- subset( x = pbmc, subset = nCount_ATAC < 7e4 & nCount_ATAC > 5e3 & nCount_RNA < 25000 & nCount_RNA > 1000 & percent.mt < 20 )We next perform pre-processing and dimensional reduction on both assays independently, using standard approaches for RNA and ATAC-seq data. # RNA analysis DefaultAssay(pbmc) <- "RNA" pbmc <- SCTransform(pbmc, verbose = FALSE) %>% RunPCA() %>% RunUMAP(dims = 1:50, reduction.name = 'umap.rna', reduction.key = 'rnaUMAP_') # ATAC analysis # We exclude the first dimension as this is typically correlated with sequencing depth DefaultAssay(pbmc) <- "ATAC" pbmc <- RunTFIDF(pbmc) pbmc <- FindTopFeatures(pbmc, min.cutoff = 'q0') pbmc <- RunSVD(pbmc) pbmc <- RunUMAP(pbmc, reduction = 'lsi', dims = 2:50, reduction.name = "umap.atac", reduction.key = "atacUMAP_")We calculate a WNN graph, representing a weighted combination of RNA and ATAC-seq modalities. We use this graph for UMAP visualization and clustering pbmc <- FindMultiModalNeighbors(pbmc, reduction.list = list("pca", "lsi"), dims.list = list(1:50, 2:50)) pbmc <- RunUMAP(pbmc, nn.name = "weighted.nn", reduction.name = "wnn.umap", reduction.key = "wnnUMAP_") pbmc <- FindClusters(pbmc, graph.name = "wsnn", algorithm = 3, verbose = FALSE)We annotate the clusters below. Note that you could also annotate the dataset using our supervised mapping pipelines, using either our vignette, or automated web tool, Azimuth. # perform sub-clustering on cluster 6 to find additional structure pbmc <- FindSubCluster(pbmc, cluster = 6, graph.name = "wsnn", algorithm = 3) Idents(pbmc) <- "sub.cluster" # add annotations pbmc <- RenameIdents(pbmc, '19' = 'pDC','20' = 'HSPC','15' = 'cDC') pbmc <- RenameIdents(pbmc, '0' = 'CD14 Mono', '9' ='CD14 Mono', '5' = 'CD16 Mono') pbmc <- RenameIdents(pbmc, '10' = 'Naive B', '11' = 'Intermediate B', '17' = 'Memory B', '21' = 'Plasma') pbmc <- RenameIdents(pbmc, '7' = 'NK') pbmc <- RenameIdents(pbmc, '4' = 'CD4 TCM', '13'= "CD4 TEM", '3' = "CD4 TCM", '16' ="Treg", '1' ="CD4 Naive", '14' = "CD4 Naive") pbmc <- RenameIdents(pbmc, '2' = 'CD8 Naive', '8'= "CD8 Naive", '12' = 'CD8 TEM_1', '6_0' = 'CD8 TEM_2', '6_1' ='CD8 TEM_2', '6_4' ='CD8 TEM_2') pbmc <- RenameIdents(pbmc, '18' = 'MAIT') pbmc <- RenameIdents(pbmc, '6_2' ='gdT', '6_3' = 'gdT') pbmc$celltype <- Idents(pbmc)We can visualize clustering based on gene expression, ATAC-seq, or WNN analysis. The differences are more subtle than in the previous analysis (you can explore the weights, which are more evenly split than in our CITE-seq example), but we find that WNN provides the clearest separation of cell states. p1 <- DimPlot(pbmc, reduction = "umap.rna", group.by = "celltype", label = TRUE, label.size = 2.5, repel = TRUE) + ggtitle("RNA") p2 <- DimPlot(pbmc, reduction = "umap.atac", group.by = "celltype", label = TRUE, label.size = 2.5, repel = TRUE) + ggtitle("ATAC") p3 <- DimPlot(pbmc, reduction = "wnn.umap", group.by = "celltype", label = TRUE, label.size = 2.5, repel = TRUE) + ggtitle("WNN") p1 + p2 + p3 & NoLegend() & theme(plot.title = element_text(hjust = 0.5))For example, the ATAC-seq data assists in the separation of CD4 and CD8 T cell states. This is due to the presence of multiple loci that exhibit differential accessibility between different T cell subtypes. For example, we can visualize ‘pseudobulk’ tracks of the CD8A locus alongside violin plots of gene expression levels, using tools in the Signac visualization vignette. ## to make the visualization easier, subset T cell clusters celltype.names <- levels(pbmc) tcell.names <- grep("CD4|CD8|Treg", celltype.names,value = TRUE) tcells <- subset(pbmc, idents = tcell.names) CoveragePlot(tcells, region = 'CD8A', features = 'CD8A', assay = 'ATAC', expression.assay = 'SCT', peaks = FALSE)Next, we will examine the accessible regions of each cell to determine enriched motifs. As described in the Signac motifs vignette, there are a few ways to do this, but we will use the chromVAR package from the Greenleaf lab. This calculates a per-cell accessibility score for known motifs, and adds these scores as a third assay (chromvar) in the Seurat object.To continue, please make sure you have the following packages installed.chromVAR for the analysis of motif accessibility in scATAC-seqpresto for fast differential expression analyses.TFBSTools for TFBS analysisJASPAR2020 for JASPAR motif modelsmotifmatchr for motif matchingBSgenome.Hsapiens.UCSC.hg38 for chromVARInstall command for all dependencies remotes::install_github("immunogenomics/presto") BiocManager::install(c("chromVAR", "TFBSTools", "JASPAR2020", "motifmatchr", "BSgenome.Hsapiens.UCSC.hg38")) library(chromVAR) library(JASPAR2020) library(TFBSTools) library(motifmatchr) library(BSgenome.Hsapiens.UCSC.hg38) # Scan the DNA sequence of each peak for the presence of each motif, and create a Motif object DefaultAssay(pbmc) <- "ATAC" pwm_set <- getMatrixSet(x = JASPAR2020, opts = list(species = 9606, all_versions = FALSE)) motif.matrix <- CreateMotifMatrix(features = granges(pbmc), pwm = pwm_set, genome = 'hg38', use.counts = FALSE) motif.object <- CreateMotifObject(data = motif.matrix, pwm = pwm_set) pbmc <- SetAssayData(pbmc, assay = 'ATAC', slot = 'motifs', new.data = motif.object) # Note that this step can take 30-60 minutes pbmc <- RunChromVAR( object = pbmc, genome = BSgenome.Hsapiens.UCSC.hg38 )Finally, we explore the multimodal dataset to identify key regulators of each cell state. Paired data provides a unique opportunity to identify transcription factors (TFs) that satisfy multiple criteria, helping to narrow down the list of putative regulators to the most likely candidates. We aim to identify TFs whose expression is enriched in multiple cell types in the RNA measurements, but also have enriched accessibility for their motifs in the ATAC measurements.As an example and positive control, the CCAAT Enhancer Binding Protein (CEBP) family of proteins, including the TF CEBPB, have been repeatedly shown to play important roles in the differentiation and function of myeloid cells including monocytes and dendritic cells. We can see that both the expression of the CEBPB, and the accessibility of the MA0466.2.4 motif (which encodes the binding site for CEBPB), are both enriched in monocytes. #returns MA0466.2 motif.name <- ConvertMotifID(pbmc, name = 'CEBPB') gene_plot <- FeaturePlot(pbmc, features = "sct_CEBPB", reduction = 'wnn.umap') motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap') gene_plot | motif_plotWe’d like to quantify this relationship, and search across all cell types to find similar examples. To do so, we will use the presto package to perform fast differential expression. We run two tests: one using gene expression data, and the other using chromVAR motif accessibilities. presto calculates a p-value based on the Wilcox rank sum test, which is also the default test in Seurat, and we restrict our search to TFs that return significant results in both tests.presto also calculates an “AUC” statistic, which reflects the power of each gene (or motif) to serve as a marker of cell type. A maximum AUC value of 1 indicates a perfect marker. Since the AUC statistic is on the same scale for both genes and motifs, we take the average of the AUC values from the two tests, and use this to rank TFs for each cell type: markers_rna <- presto:::wilcoxauc.Seurat(X = pbmc, group_by = 'celltype', assay = 'data', seurat_assay = 'SCT') markers_motifs <- presto:::wilcoxauc.Seurat(X = pbmc, group_by = 'celltype', assay = 'data', seurat_assay = 'chromvar') motif.names <- markers_motifs$feature colnames(markers_rna) <- paste0("RNA.", colnames(markers_rna)) colnames(markers_motifs) <- paste0("motif.", colnames(markers_motifs)) markers_rna$gene <- markers_rna$RNA.feature markers_motifs$gene <- ConvertMotifID(pbmc, id = motif.names) # a simple function to implement the procedure above topTFs <- function(celltype, padj.cutoff = 1e-2) { ctmarkers_rna <- dplyr::filter( markers_rna, RNA.group == celltype, RNA.padj < padj.cutoff, RNA.logFC > 0) %>% arrange(-RNA.auc) ctmarkers_motif <- dplyr::filter( markers_motifs, motif.group == celltype, motif.padj < padj.cutoff, motif.logFC > 0) %>% arrange(-motif.auc) top_tfs <- inner_join( x = ctmarkers_rna[, c(2, 11, 6, 7)], y = ctmarkers_motif[, c(2, 1, 11, 6, 7)], by = "gene" ) top_tfs$avg_auc <- (top_tfs$RNA.auc + top_tfs$motif.auc) / 2 top_tfs <- arrange(top_tfs, -avg_auc) return(top_tfs) }We can now compute, and visualize, putative regulators for any cell type. We recover well-established regulators, including TBX21 for NK cells, IRF4 for plasma cells, SOX4 for hematopoietic progenitors, EBF1 and PAX5 for B cells, IRF8 and TCF4 for pDC. We believe that similar strategies can be used to help focus on a set of putative regulators in diverse systems. # identify top markers in NK and visualize head(topTFs("NK"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 NK TBX21 0.7270859 0.000000e+00 NK MA0690.1 0.9139614 ## 2 NK EOMES 0.5886774 2.411013e-98 NK MA0800.1 0.9214773 ## 3 NK RUNX3 0.7705661 5.977716e-120 NK MA0684.2 0.6769022 ## motif.pval avg_auc ## 1 1.097940e-202 0.8205237 ## 2 4.903866e-210 0.7550774 ## 3 1.560061e-38 0.7237341 motif.name <- ConvertMotifID(pbmc, name = 'TBX21') gene_plot <- FeaturePlot(pbmc, features = "sct_TBX21", reduction = 'wnn.umap') motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap') gene_plot | motif_plot # identify top markers in pDC and visualize head(topTFs("pDC"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 pDC TCF4 0.9998815 1.120711e-162 pDC MA0830.2 0.9965481 ## 2 pDC IRF8 0.9904457 1.308164e-123 pDC MA0652.1 0.8833112 ## 3 pDC SPIB 0.9115207 0.000000e+00 pDC MA0081.2 0.9068540 ## motif.pval avg_auc ## 1 1.785897e-69 0.9982148 ## 2 3.982413e-42 0.9368785 ## 3 3.083509e-47 0.9091874 motif.name <- ConvertMotifID(pbmc, name = 'TCF4') gene_plot <- FeaturePlot(pbmc, features = "sct_TCF4", reduction = 'wnn.umap') motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap') gene_plot | motif_plot # identify top markers in HSPC and visualize head(topTFs("CD16 Mono"),3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 CD16 Mono SPI1 0.8793172 1.666810e-296 CD16 Mono MA0080.5 0.8880908 ## 2 CD16 Mono CEBPB 0.8685933 1.625472e-294 CD16 Mono MA0466.2 0.7840422 ## 3 CD16 Mono MEF2C 0.7129910 2.727252e-79 CD16 Mono MA0497.1 0.8059373 ## motif.pval avg_auc ## 1 4.762491e-194 0.8837040 ## 2 7.049764e-105 0.8263177 ## 3 2.345716e-121 0.7594641 motif.name <- ConvertMotifID(pbmc, name = 'SPI1') gene_plot <- FeaturePlot(pbmc, features = "sct_SPI1", reduction = 'wnn.umap') motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap') gene_plot | motif_plot # identify top markers in other cell types head(topTFs("Naive B"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 Naive B MEF2C 0.8802747 1.890065e-182 Naive B MA0497.1 0.6789079 ## 2 Naive B PAX5 0.9436648 0.000000e+00 Naive B MA0014.3 0.5827061 ## 3 Naive B POU2F2 0.6029377 2.892216e-13 Naive B MA0507.1 0.8912268 ## motif.pval avg_auc ## 1 9.815118e-32 0.7795913 ## 2 5.995185e-08 0.7631854 ## 3 6.471677e-145 0.7470822 head(topTFs("HSPC"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 HSPC SOX4 0.9869406 5.524832e-71 HSPC MA0867.2 0.6830497 ## 2 HSPC GATA2 0.7884615 0.000000e+00 HSPC MA0036.3 0.8275008 ## 3 HSPC MEIS1 0.8638496 0.000000e+00 HSPC MA0498.2 0.6924225 ## motif.pval avg_auc ## 1 1.241915e-03 0.8349951 ## 2 7.591798e-09 0.8079812 ## 3 6.877492e-04 0.7781361 head(topTFs("Plasma"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 Plasma IRF4 0.8189687 5.261955e-35 Plasma MA1419.1 0.9776046 ## 2 Plasma MEF2C 0.9111213 2.977155e-12 Plasma MA0497.1 0.7596637 ## 3 Plasma TCF4 0.8049409 6.810635e-12 Plasma MA0830.2 0.7840848 ## motif.pval avg_auc ## 1 2.334627e-12 0.8982867 ## 2 1.374353e-04 0.8353925 ## 3 3.028306e-05 0.7945129Session Info sessionInfo()## R version 4.2.0 (2022-04-22) ## Platform: x86_64-pc-linux-gnu (64-bit) ## Running under: Ubuntu 20.04.5 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/liblapack.so.3 ## ## locale: ## [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C ## [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8 ## [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 ## ## attached base packages: ## [1] stats4 stats graphics grDevices utils datasets methods ## [8] base ## ## other attached packages: ## [1] BSgenome.Hsapiens.UCSC.hg38_1.4.5 BSgenome_1.66.3 ## [3] rtracklayer_1.58.0 Biostrings_2.66.0 ## [5] XVector_0.38.0 motifmatchr_1.20.0 ## [7] TFBSTools_1.36.0 JASPAR2020_0.99.10 ## [9] chromVAR_1.20.2 EnsDb.Hsapiens.v86_2.99.0 ## [11] ensembldb_2.22.0 AnnotationFilter_1.22.0 ## [13] GenomicFeatures_1.50.4 AnnotationDbi_1.60.0 ## [15] Biobase_2.58.0 GenomicRanges_1.50.2 ## [17] GenomeInfoDb_1.35.16 IRanges_2.32.0 ## [19] S4Vectors_0.36.2 BiocGenerics_0.44.0 ## [21] Signac_1.9.0 ggplot2_3.4.1 ## [23] dplyr_1.1.1 cowplot_1.1.1 ## [25] thp1.eccite.SeuratData_3.1.5 stxBrain.SeuratData_0.1.1 ## [27] ssHippo.SeuratData_3.1.4 pbmcsca.SeuratData_3.0.0 ## [29] pbmcMultiome.SeuratData_0.1.2 pbmc3k.SeuratData_3.1.4 ## [31] panc8.SeuratData_3.0.2 ifnb.SeuratData_3.1.0 ## [33] hcabm40k.SeuratData_3.0.0 bmcite.SeuratData_0.3.0 ## [35] SeuratData_0.2.2 SeuratObject_4.1.3 ## [37] Seurat_4.2.1.9001 ## ## loaded via a namespace (and not attached): ## [1] rappdirs_0.3.3 scattermore_0.8 ## [3] R.methodsS3_1.8.2 ragg_1.2.5 ## [5] nabor_0.5.0 tidyr_1.3.0 ## [7] bit64_4.0.5 knitr_1.42 ## [9] R.utils_2.12.2 irlba_2.3.5.1 ## [11] DelayedArray_0.24.0 data.table_1.14.8 ## [13] rpart_4.1.16 KEGGREST_1.38.0 ## [15] RCurl_1.98-1.12 generics_0.1.3 ## [17] RSQLite_2.3.0 RANN_2.6.1 ## [19] future_1.32.0 tzdb_0.3.0 ## [21] bit_4.0.5 spatstat.data_3.0-1 ## [23] xml2_1.3.3 httpuv_1.6.9 ## [25] SummarizedExperiment_1.28.0 DirichletMultinomial_1.40.0 ## [27] xfun_0.38 hms_1.1.2 ## [29] jquerylib_0.1.4 evaluate_0.20 ## [31] promises_1.2.0.1 fansi_1.0.4 ## [33] restfulr_0.0.15 progress_1.2.2 ## [35] caTools_1.18.2 dbplyr_2.3.1 ## [37] igraph_1.4.1 DBI_1.1.3 ## [39] htmlwidgets_1.6.2 spatstat.geom_3.1-0 ## [41] purrr_1.0.1 ellipsis_0.3.2 ## [43] backports_1.4.1 annotate_1.76.0 ## [45] biomaRt_2.54.0 deldir_1.0-6 ## [47] MatrixGenerics_1.10.0 vctrs_0.6.1 ## [49] ROCR_1.0-11 abind_1.4-5 ## [51] cachem_1.0.7 withr_2.5.0 ## [53] progressr_0.13.0 presto_1.0.0 ## [55] checkmate_2.1.0 sctransform_0.3.5 ## [57] GenomicAlignments_1.34.0 prettyunits_1.1.1 ## [59] goftest_1.2-3 cluster_2.1.3 ## [61] seqLogo_1.64.0 lazyeval_0.2.2 ## [63] crayon_1.5.2 hdf5r_1.3.8 ## [65] spatstat.explore_3.1-0 pkgconfig_2.0.3 ## [67] labeling_0.4.2 nlme_3.1-157 ## [69] ProtGenerics_1.30.0 nnet_7.3-17 ## [71] rlang_1.1.0 globals_0.16.2 ## [73] lifecycle_1.0.3 miniUI_0.1.1.1 ## [75] filelock_1.0.2 BiocFileCache_2.6.1 ## [77] dichromat_2.0-0.1 rprojroot_2.0.3 ## [79] polyclip_1.10-4 matrixStats_0.63.0 ## [81] lmtest_0.9-40 Matrix_1.5-3 ## [83] zoo_1.8-11 base64enc_0.1-3 ## [85] ggridges_0.5.4 png_0.1-8 ## [87] viridisLite_0.4.1 rjson_0.2.21 ## [89] bitops_1.0-7 R.oo_1.25.0 ## [91] KernSmooth_2.23-20 blob_1.2.3 ## [93] stringr_1.5.0 parallelly_1.35.0 ## [95] spatstat.random_3.1-4 readr_2.1.4 ## [97] jpeg_0.1-10 CNEr_1.34.0 ## [99] scales_1.2.1 memoise_2.0.1 ## [101] magrittr_2.0.3 plyr_1.8.8 ## [103] ica_1.0-3 zlibbioc_1.44.0 ## [105] compiler_4.2.0 BiocIO_1.8.0 ## [107] RColorBrewer_1.1-3 fitdistrplus_1.1-8 ## [109] Rsamtools_2.14.0 cli_3.6.1 ## [111] listenv_0.9.0 patchwork_1.1.2 ## [113] pbapply_1.7-0 htmlTable_2.4.1 ## [115] Formula_1.2-5 MASS_7.3-56 ## [117] tidyselect_1.2.0 stringi_1.7.12 ## [119] textshaping_0.3.6 highr_0.10 ## [121] yaml_2.3.7 latticeExtra_0.6-30 ## [123] ggrepel_0.9.3 grid_4.2.0 ## [125] sass_0.4.5 VariantAnnotation_1.44.1 ## [127] fastmatch_1.1-3 tools_4.2.0 ## [129] future.apply_1.10.0 parallel_4.2.0 ## [131] rstudioapi_0.14 TFMPvalue_0.0.9 ## [133] foreign_0.8-82 gridExtra_2.3 ## [135] farver_2.1.1 Rtsne_0.16 ## [137] digest_0.6.31 pracma_2.4.2 ## [139] shiny_1.7.4 Rcpp_1.0.10 ## [141] later_1.3.0 RcppAnnoy_0.0.20 ## [143] httr_1.4.5 biovizBase_1.46.0 ## [145] colorspace_2.1-0 XML_3.99-0.13 ## [147] fs_1.6.1 tensor_1.5 ## [149] reticulate_1.28 splines_4.2.0 ## [151] uwot_0.1.14 RcppRoll_0.3.0 ## [153] spatstat.utils_3.0-2 pkgdown_2.0.7 ## [155] sp_1.6-0 plotly_4.10.1 ## [157] systemfonts_1.0.4 xtable_1.8-4 ## [159] poweRlaw_0.70.6 jsonlite_1.8.4 ## [161] R6_2.5.1 Hmisc_4.8-0 ## [163] pillar_1.9.0 htmltools_0.5.5 ## [165] mime_0.12 DT_0.27 ## [167] glue_1.6.2 fastmap_1.1.1 ## [169] BiocParallel_1.32.5 codetools_0.2-18 ## [171] utf8_1.2.3 lattice_0.20-45 ## [173] bslib_0.4.2 spatstat.sparse_3.0-1 ## [175] tibble_3.2.1 curl_5.0.0 ## [177] leiden_0.4.3 gtools_3.9.4 ## [179] GO.db_3.16.0 interp_1.1-3 ## [181] survival_3.3-1 rmarkdown_2.21 ## [183] desc_1.4.2 munsell_0.5.0 ## [185] GenomeInfoDbData_1.2.9 reshape2_1.4.4 ## [187] gtable_0.3.3

We perform basic QC based on the number of detected molecules for each modality as well as mitochondrial percentage. VlnPlot(pbmc, features = c("nCount_ATAC", "nCount_RNA","percent.mt"), ncol = 3, log = TRUE, pt.size = 0) + NoLegend() pbmc <- subset( x = pbmc, subset = nCount_ATAC < 7e4 & nCount_ATAC > 5e3 & nCount_RNA < 25000 & nCount_RNA > 1000 & percent.mt < 20 )We next perform pre-processing and dimensional reduction on both assays independently, using standard approaches for RNA and ATAC-seq data. # RNA analysis DefaultAssay(pbmc) <- "RNA" pbmc <- SCTransform(pbmc, verbose = FALSE) %>% RunPCA() %>% RunUMAP(dims = 1:50, reduction.name = 'umap.rna', reduction.key = 'rnaUMAP_') # ATAC analysis # We exclude the first dimension as this is typically correlated with sequencing depth DefaultAssay(pbmc) <- "ATAC" pbmc <- RunTFIDF(pbmc) pbmc <- FindTopFeatures(pbmc, min.cutoff = 'q0') pbmc <- RunSVD(pbmc) pbmc <- RunUMAP(pbmc, reduction = 'lsi', dims = 2:50, reduction.name = "umap.atac", reduction.key = "atacUMAP_")We calculate a WNN graph, representing a weighted combination of RNA and ATAC-seq modalities. We use this graph for UMAP visualization and clustering pbmc <- FindMultiModalNeighbors(pbmc, reduction.list = list("pca", "lsi"), dims.list = list(1:50, 2:50)) pbmc <- RunUMAP(pbmc, nn.name = "weighted.nn", reduction.name = "wnn.umap", reduction.key = "wnnUMAP_") pbmc <- FindClusters(pbmc, graph.name = "wsnn", algorithm = 3, verbose = FALSE)We annotate the clusters below. Note that you could also annotate the dataset using our supervised mapping pipelines, using either our vignette, or automated web tool, Azimuth. # perform sub-clustering on cluster 6 to find additional structure pbmc <- FindSubCluster(pbmc, cluster = 6, graph.name = "wsnn", algorithm = 3) Idents(pbmc) <- "sub.cluster" # add annotations pbmc <- RenameIdents(pbmc, '19' = 'pDC','20' = 'HSPC','15' = 'cDC') pbmc <- RenameIdents(pbmc, '0' = 'CD14 Mono', '9' ='CD14 Mono', '5' = 'CD16 Mono') pbmc <- RenameIdents(pbmc, '10' = 'Naive B', '11' = 'Intermediate B', '17' = 'Memory B', '21' = 'Plasma') pbmc <- RenameIdents(pbmc, '7' = 'NK') pbmc <- RenameIdents(pbmc, '4' = 'CD4 TCM', '13'= "CD4 TEM", '3' = "CD4 TCM", '16' ="Treg", '1' ="CD4 Naive", '14' = "CD4 Naive") pbmc <- RenameIdents(pbmc, '2' = 'CD8 Naive', '8'= "CD8 Naive", '12' = 'CD8 TEM_1', '6_0' = 'CD8 TEM_2', '6_1' ='CD8 TEM_2', '6_4' ='CD8 TEM_2') pbmc <- RenameIdents(pbmc, '18' = 'MAIT') pbmc <- RenameIdents(pbmc, '6_2' ='gdT', '6_3' = 'gdT') pbmc$celltype <- Idents(pbmc)We can visualize clustering based on gene expression, ATAC-seq, or WNN analysis. The differences are more subtle than in the previous analysis (you can explore the weights, which are more evenly split than in our CITE-seq example), but we find that WNN provides the clearest separation of cell states. p1 <- DimPlot(pbmc, reduction = "umap.rna", group.by = "celltype", label = TRUE, label.size = 2.5, repel = TRUE) + ggtitle("RNA") p2 <- DimPlot(pbmc, reduction = "umap.atac", group.by = "celltype", label = TRUE, label.size = 2.5, repel = TRUE) + ggtitle("ATAC") p3 <- DimPlot(pbmc, reduction = "wnn.umap", group.by = "celltype", label = TRUE, label.size = 2.5, repel = TRUE) + ggtitle("WNN") p1 + p2 + p3 & NoLegend() & theme(plot.title = element_text(hjust = 0.5))For example, the ATAC-seq data assists in the separation of CD4 and CD8 T cell states. This is due to the presence of multiple loci that exhibit differential accessibility between different T cell subtypes. For example, we can visualize ‘pseudobulk’ tracks of the CD8A locus alongside violin plots of gene expression levels, using tools in the Signac visualization vignette. ## to make the visualization easier, subset T cell clusters celltype.names <- levels(pbmc) tcell.names <- grep("CD4|CD8|Treg", celltype.names,value = TRUE) tcells <- subset(pbmc, idents = tcell.names) CoveragePlot(tcells, region = 'CD8A', features = 'CD8A', assay = 'ATAC', expression.assay = 'SCT', peaks = FALSE)Next, we will examine the accessible regions of each cell to determine enriched motifs. As described in the Signac motifs vignette, there are a few ways to do this, but we will use the chromVAR package from the Greenleaf lab. This calculates a per-cell accessibility score for known motifs, and adds these scores as a third assay (chromvar) in the Seurat object.To continue, please make sure you have the following packages installed.chromVAR for the analysis of motif accessibility in scATAC-seqpresto for fast differential expression analyses.TFBSTools for TFBS analysisJASPAR2020 for JASPAR motif modelsmotifmatchr for motif matchingBSgenome.Hsapiens.UCSC.hg38 for chromVARInstall command for all dependencies remotes::install_github("immunogenomics/presto") BiocManager::install(c("chromVAR", "TFBSTools", "JASPAR2020", "motifmatchr", "BSgenome.Hsapiens.UCSC.hg38")) library(chromVAR) library(JASPAR2020) library(TFBSTools) library(motifmatchr) library(BSgenome.Hsapiens.UCSC.hg38) # Scan the DNA sequence of each peak for the presence of each motif, and create a Motif object DefaultAssay(pbmc) <- "ATAC" pwm_set <- getMatrixSet(x = JASPAR2020, opts = list(species = 9606, all_versions = FALSE)) motif.matrix <- CreateMotifMatrix(features = granges(pbmc), pwm = pwm_set, genome = 'hg38', use.counts = FALSE) motif.object <- CreateMotifObject(data = motif.matrix, pwm = pwm_set) pbmc <- SetAssayData(pbmc, assay = 'ATAC', slot = 'motifs', new.data = motif.object) # Note that this step can take 30-60 minutes pbmc <- RunChromVAR( object = pbmc, genome = BSgenome.Hsapiens.UCSC.hg38 )Finally, we explore the multimodal dataset to identify key regulators of each cell state. Paired data provides a unique opportunity to identify transcription factors (TFs) that satisfy multiple criteria, helping to narrow down the list of putative regulators to the most likely candidates. We aim to identify TFs whose expression is enriched in multiple cell types in the RNA measurements, but also have enriched accessibility for their motifs in the ATAC measurements.As an example and positive control, the CCAAT Enhancer Binding Protein (CEBP) family of proteins, including the TF CEBPB, have been repeatedly shown to play important roles in the differentiation and function of myeloid cells including monocytes and dendritic cells. We can see that both the expression of the CEBPB, and the accessibility of the MA0466.2.4 motif (which encodes the binding site for CEBPB), are both enriched in monocytes. #returns MA0466.2 motif.name <- ConvertMotifID(pbmc, name = 'CEBPB') gene_plot <- FeaturePlot(pbmc, features = "sct_CEBPB", reduction = 'wnn.umap') motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap') gene_plot | motif_plotWe’d like to quantify this relationship, and search across all cell types to find similar examples. To do so, we will use the presto package to perform fast differential expression. We run two tests: one using gene expression data, and the other using chromVAR motif accessibilities. presto calculates a p-value based on the Wilcox rank sum test, which is also the default test in Seurat, and we restrict our search to TFs that return significant results in both tests.presto also calculates an “AUC” statistic, which reflects the power of each gene (or motif) to serve as a marker of cell type. A maximum AUC value of 1 indicates a perfect marker. Since the AUC statistic is on the same scale for both genes and motifs, we take the average of the AUC values from the two tests, and use this to rank TFs for each cell type: markers_rna <- presto:::wilcoxauc.Seurat(X = pbmc, group_by = 'celltype', assay = 'data', seurat_assay = 'SCT') markers_motifs <- presto:::wilcoxauc.Seurat(X = pbmc, group_by = 'celltype', assay = 'data', seurat_assay = 'chromvar') motif.names <- markers_motifs$feature colnames(markers_rna) <- paste0("RNA.", colnames(markers_rna)) colnames(markers_motifs) <- paste0("motif.", colnames(markers_motifs)) markers_rna$gene <- markers_rna$RNA.feature markers_motifs$gene <- ConvertMotifID(pbmc, id = motif.names) # a simple function to implement the procedure above topTFs <- function(celltype, padj.cutoff = 1e-2) { ctmarkers_rna <- dplyr::filter( markers_rna, RNA.group == celltype, RNA.padj < padj.cutoff, RNA.logFC > 0) %>% arrange(-RNA.auc) ctmarkers_motif <- dplyr::filter( markers_motifs, motif.group == celltype, motif.padj < padj.cutoff, motif.logFC > 0) %>% arrange(-motif.auc) top_tfs <- inner_join( x = ctmarkers_rna[, c(2, 11, 6, 7)], y = ctmarkers_motif[, c(2, 1, 11, 6, 7)], by = "gene" ) top_tfs$avg_auc <- (top_tfs$RNA.auc + top_tfs$motif.auc) / 2 top_tfs <- arrange(top_tfs, -avg_auc) return(top_tfs) }We can now compute, and visualize, putative regulators for any cell type. We recover well-established regulators, including TBX21 for NK cells, IRF4 for plasma cells, SOX4 for hematopoietic progenitors, EBF1 and PAX5 for B cells, IRF8 and TCF4 for pDC. We believe that similar strategies can be used to help focus on a set of putative regulators in diverse systems. # identify top markers in NK and visualize head(topTFs("NK"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 NK TBX21 0.7270859 0.000000e+00 NK MA0690.1 0.9139614 ## 2 NK EOMES 0.5886774 2.411013e-98 NK MA0800.1 0.9214773 ## 3 NK RUNX3 0.7705661 5.977716e-120 NK MA0684.2 0.6769022 ## motif.pval avg_auc ## 1 1.097940e-202 0.8205237 ## 2 4.903866e-210 0.7550774 ## 3 1.560061e-38 0.7237341 motif.name <- ConvertMotifID(pbmc, name = 'TBX21') gene_plot <- FeaturePlot(pbmc, features = "sct_TBX21", reduction = 'wnn.umap') motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap') gene_plot | motif_plot # identify top markers in pDC and visualize head(topTFs("pDC"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 pDC TCF4 0.9998815 1.120711e-162 pDC MA0830.2 0.9965481 ## 2 pDC IRF8 0.9904457 1.308164e-123 pDC MA0652.1 0.8833112 ## 3 pDC SPIB 0.9115207 0.000000e+00 pDC MA0081.2 0.9068540 ## motif.pval avg_auc ## 1 1.785897e-69 0.9982148 ## 2 3.982413e-42 0.9368785 ## 3 3.083509e-47 0.9091874 motif.name <- ConvertMotifID(pbmc, name = 'TCF4') gene_plot <- FeaturePlot(pbmc, features = "sct_TCF4", reduction = 'wnn.umap') motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap') gene_plot | motif_plot # identify top markers in HSPC and visualize head(topTFs("CD16 Mono"),3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 CD16 Mono SPI1 0.8793172 1.666810e-296 CD16 Mono MA0080.5 0.8880908 ## 2 CD16 Mono CEBPB 0.8685933 1.625472e-294 CD16 Mono MA0466.2 0.7840422 ## 3 CD16 Mono MEF2C 0.7129910 2.727252e-79 CD16 Mono MA0497.1 0.8059373 ## motif.pval avg_auc ## 1 4.762491e-194 0.8837040 ## 2 7.049764e-105 0.8263177 ## 3 2.345716e-121 0.7594641 motif.name <- ConvertMotifID(pbmc, name = 'SPI1') gene_plot <- FeaturePlot(pbmc, features = "sct_SPI1", reduction = 'wnn.umap') motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap') gene_plot | motif_plot # identify top markers in other cell types head(topTFs("Naive B"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 Naive B MEF2C 0.8802747 1.890065e-182 Naive B MA0497.1 0.6789079 ## 2 Naive B PAX5 0.9436648 0.000000e+00 Naive B MA0014.3 0.5827061 ## 3 Naive B POU2F2 0.6029377 2.892216e-13 Naive B MA0507.1 0.8912268 ## motif.pval avg_auc ## 1 9.815118e-32 0.7795913 ## 2 5.995185e-08 0.7631854 ## 3 6.471677e-145 0.7470822 head(topTFs("HSPC"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 HSPC SOX4 0.9869406 5.524832e-71 HSPC MA0867.2 0.6830497 ## 2 HSPC GATA2 0.7884615 0.000000e+00 HSPC MA0036.3 0.8275008 ## 3 HSPC MEIS1 0.8638496 0.000000e+00 HSPC MA0498.2 0.6924225 ## motif.pval avg_auc ## 1 1.241915e-03 0.8349951 ## 2 7.591798e-09 0.8079812 ## 3 6.877492e-04 0.7781361 head(topTFs("Plasma"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 Plasma IRF4 0.8189687 5.261955e-35 Plasma MA1419.1 0.9776046 ## 2 Plasma MEF2C 0.9111213 2.977155e-12 Plasma MA0497.1 0.7596637 ## 3 Plasma TCF4 0.8049409 6.810635e-12 Plasma MA0830.2 0.7840848 ## motif.pval avg_auc ## 1 2.334627e-12 0.8982867 ## 2 1.374353e-04 0.8353925 ## 3 3.028306e-05 0.7945129Session Info sessionInfo()## R version 4.2.0 (2022-04-22) ## Platform: x86_64-pc-linux-gnu (64-bit) ## Running under: Ubuntu 20.04.5 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/liblapack.so.3 ## ## locale: ## [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C ## [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8 ## [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 ## ## attached base packages: ## [1] stats4 stats graphics grDevices utils datasets methods ## [8] base ## ## other attached packages: ## [1] BSgenome.Hsapiens.UCSC.hg38_1.4.5 BSgenome_1.66.3 ## [3] rtracklayer_1.58.0 Biostrings_2.66.0 ## [5] XVector_0.38.0 motifmatchr_1.20.0 ## [7] TFBSTools_1.36.0 JASPAR2020_0.99.10 ## [9] chromVAR_1.20.2 EnsDb.Hsapiens.v86_2.99.0 ## [11] ensembldb_2.22.0 AnnotationFilter_1.22.0 ## [13] GenomicFeatures_1.50.4 AnnotationDbi_1.60.0 ## [15] Biobase_2.58.0 GenomicRanges_1.50.2 ## [17] GenomeInfoDb_1.35.16 IRanges_2.32.0 ## [19] S4Vectors_0.36.2 BiocGenerics_0.44.0 ## [21] Signac_1.9.0 ggplot2_3.4.1 ## [23] dplyr_1.1.1 cowplot_1.1.1 ## [25] thp1.eccite.SeuratData_3.1.5 stxBrain.SeuratData_0.1.1 ## [27] ssHippo.SeuratData_3.1.4 pbmcsca.SeuratData_3.0.0 ## [29] pbmcMultiome.SeuratData_0.1.2 pbmc3k.SeuratData_3.1.4 ## [31] panc8.SeuratData_3.0.2 ifnb.SeuratData_3.1.0 ## [33] hcabm40k.SeuratData_3.0.0 bmcite.SeuratData_0.3.0 ## [35] SeuratData_0.2.2 SeuratObject_4.1.3 ## [37] Seurat_4.2.1.9001 ## ## loaded via a namespace (and not attached): ## [1] rappdirs_0.3.3 scattermore_0.8 ## [3] R.methodsS3_1.8.2 ragg_1.2.5 ## [5] nabor_0.5.0 tidyr_1.3.0 ## [7] bit64_4.0.5 knitr_1.42 ## [9] R.utils_2.12.2 irlba_2.3.5.1 ## [11] DelayedArray_0.24.0 data.table_1.14.8 ## [13] rpart_4.1.16 KEGGREST_1.38.0 ## [15] RCurl_1.98-1.12 generics_0.1.3 ## [17] RSQLite_2.3.0 RANN_2.6.1 ## [19] future_1.32.0 tzdb_0.3.0 ## [21] bit_4.0.5 spatstat.data_3.0-1 ## [23] xml2_1.3.3 httpuv_1.6.9 ## [25] SummarizedExperiment_1.28.0 DirichletMultinomial_1.40.0 ## [27] xfun_0.38 hms_1.1.2 ## [29] jquerylib_0.1.4 evaluate_0.20 ## [31] promises_1.2.0.1 fansi_1.0.4 ## [33] restfulr_0.0.15 progress_1.2.2 ## [35] caTools_1.18.2 dbplyr_2.3.1 ## [37] igraph_1.4.1 DBI_1.1.3 ## [39] htmlwidgets_1.6.2 spatstat.geom_3.1-0 ## [41] purrr_1.0.1 ellipsis_0.3.2 ## [43] backports_1.4.1 annotate_1.76.0 ## [45] biomaRt_2.54.0 deldir_1.0-6 ## [47] MatrixGenerics_1.10.0 vctrs_0.6.1 ## [49] ROCR_1.0-11 abind_1.4-5 ## [51] cachem_1.0.7 withr_2.5.0 ## [53] progressr_0.13.0 presto_1.0.0 ## [55] checkmate_2.1.0 sctransform_0.3.5 ## [57] GenomicAlignments_1.34.0 prettyunits_1.1.1 ## [59] goftest_1.2-3 cluster_2.1.3 ## [61] seqLogo_1.64.0 lazyeval_0.2.2 ## [63] crayon_1.5.2 hdf5r_1.3.8 ## [65] spatstat.explore_3.1-0 pkgconfig_2.0.3 ## [67] labeling_0.4.2 nlme_3.1-157 ## [69] ProtGenerics_1.30.0 nnet_7.3-17 ## [71] rlang_1.1.0 globals_0.16.2 ## [73] lifecycle_1.0.3 miniUI_0.1.1.1 ## [75] filelock_1.0.2 BiocFileCache_2.6.1 ## [77] dichromat_2.0-0.1 rprojroot_2.0.3 ## [79] polyclip_1.10-4 matrixStats_0.63.0 ## [81] lmtest_0.9-40 Matrix_1.5-3 ## [83] zoo_1.8-11 base64enc_0.1-3 ## [85] ggridges_0.5.4 png_0.1-8 ## [87] viridisLite_0.4.1 rjson_0.2.21 ## [89] bitops_1.0-7 R.oo_1.25.0 ## [91] KernSmooth_2.23-20 blob_1.2.3 ## [93] stringr_1.5.0 parallelly_1.35.0 ## [95] spatstat.random_3.1-4 readr_2.1.4 ## [97] jpeg_0.1-10 CNEr_1.34.0 ## [99] scales_1.2.1 memoise_2.0.1 ## [101] magrittr_2.0.3 plyr_1.8.8 ## [103] ica_1.0-3 zlibbioc_1.44.0 ## [105] compiler_4.2.0 BiocIO_1.8.0 ## [107] RColorBrewer_1.1-3 fitdistrplus_1.1-8 ## [109] Rsamtools_2.14.0 cli_3.6.1 ## [111] listenv_0.9.0 patchwork_1.1.2 ## [113] pbapply_1.7-0 htmlTable_2.4.1 ## [115] Formula_1.2-5 MASS_7.3-56 ## [117] tidyselect_1.2.0 stringi_1.7.12 ## [119] textshaping_0.3.6 highr_0.10 ## [121] yaml_2.3.7 latticeExtra_0.6-30 ## [123] ggrepel_0.9.3 grid_4.2.0 ## [125] sass_0.4.5 VariantAnnotation_1.44.1 ## [127] fastmatch_1.1-3 tools_4.2.0 ## [129] future.apply_1.10.0 parallel_4.2.0 ## [131] rstudioapi_0.14 TFMPvalue_0.0.9 ## [133] foreign_0.8-82 gridExtra_2.3 ## [135] farver_2.1.1 Rtsne_0.16 ## [137] digest_0.6.31 pracma_2.4.2 ## [139] shiny_1.7.4 Rcpp_1.0.10 ## [141] later_1.3.0 RcppAnnoy_0.0.20 ## [143] httr_1.4.5 biovizBase_1.46.0 ## [145] colorspace_2.1-0 XML_3.99-0.13 ## [147] fs_1.6.1 tensor_1.5 ## [149] reticulate_1.28 splines_4.2.0 ## [151] uwot_0.1.14 RcppRoll_0.3.0 ## [153] spatstat.utils_3.0-2 pkgdown_2.0.7 ## [155] sp_1.6-0 plotly_4.10.1 ## [157] systemfonts_1.0.4 xtable_1.8-4 ## [159] poweRlaw_0.70.6 jsonlite_1.8.4 ## [161] R6_2.5.1 Hmisc_4.8-0 ## [163] pillar_1.9.0 htmltools_0.5.5 ## [165] mime_0.12 DT_0.27 ## [167] glue_1.6.2 fastmap_1.1.1 ## [169] BiocParallel_1.32.5 codetools_0.2-18 ## [171] utf8_1.2.3 lattice_0.20-45 ## [173] bslib_0.4.2 spatstat.sparse_3.0-1 ## [175] tibble_3.2.1 curl_5.0.0 ## [177] leiden_0.4.3 gtools_3.9.4 ## [179] GO.db_3.16.0 interp_1.1-3 ## [181] survival_3.3-1 rmarkdown_2.21 ## [183] desc_1.4.2 munsell_0.5.0 ## [185] GenomeInfoDbData_1.2.9 reshape2_1.4.4 ## [187] gtable_0.3.3

pbmc <- subset( x = pbmc, subset = nCount_ATAC < 7e4 & nCount_ATAC > 5e3 & nCount_RNA < 25000 & nCount_RNA > 1000 & percent.mt < 20 )We next perform pre-processing and dimensional reduction on both assays independently, using standard approaches for RNA and ATAC-seq data. # RNA analysis DefaultAssay(pbmc) <- "RNA" pbmc <- SCTransform(pbmc, verbose = FALSE) %>% RunPCA() %>% RunUMAP(dims = 1:50, reduction.name = 'umap.rna', reduction.key = 'rnaUMAP_') # ATAC analysis # We exclude the first dimension as this is typically correlated with sequencing depth DefaultAssay(pbmc) <- "ATAC" pbmc <- RunTFIDF(pbmc) pbmc <- FindTopFeatures(pbmc, min.cutoff = 'q0') pbmc <- RunSVD(pbmc) pbmc <- RunUMAP(pbmc, reduction = 'lsi', dims = 2:50, reduction.name = "umap.atac", reduction.key = "atacUMAP_")We calculate a WNN graph, representing a weighted combination of RNA and ATAC-seq modalities. We use this graph for UMAP visualization and clustering pbmc <- FindMultiModalNeighbors(pbmc, reduction.list = list("pca", "lsi"), dims.list = list(1:50, 2:50)) pbmc <- RunUMAP(pbmc, nn.name = "weighted.nn", reduction.name = "wnn.umap", reduction.key = "wnnUMAP_") pbmc <- FindClusters(pbmc, graph.name = "wsnn", algorithm = 3, verbose = FALSE)We annotate the clusters below. Note that you could also annotate the dataset using our supervised mapping pipelines, using either our vignette, or automated web tool, Azimuth. # perform sub-clustering on cluster 6 to find additional structure pbmc <- FindSubCluster(pbmc, cluster = 6, graph.name = "wsnn", algorithm = 3) Idents(pbmc) <- "sub.cluster" # add annotations pbmc <- RenameIdents(pbmc, '19' = 'pDC','20' = 'HSPC','15' = 'cDC') pbmc <- RenameIdents(pbmc, '0' = 'CD14 Mono', '9' ='CD14 Mono', '5' = 'CD16 Mono') pbmc <- RenameIdents(pbmc, '10' = 'Naive B', '11' = 'Intermediate B', '17' = 'Memory B', '21' = 'Plasma') pbmc <- RenameIdents(pbmc, '7' = 'NK') pbmc <- RenameIdents(pbmc, '4' = 'CD4 TCM', '13'= "CD4 TEM", '3' = "CD4 TCM", '16' ="Treg", '1' ="CD4 Naive", '14' = "CD4 Naive") pbmc <- RenameIdents(pbmc, '2' = 'CD8 Naive', '8'= "CD8 Naive", '12' = 'CD8 TEM_1', '6_0' = 'CD8 TEM_2', '6_1' ='CD8 TEM_2', '6_4' ='CD8 TEM_2') pbmc <- RenameIdents(pbmc, '18' = 'MAIT') pbmc <- RenameIdents(pbmc, '6_2' ='gdT', '6_3' = 'gdT') pbmc$celltype <- Idents(pbmc)We can visualize clustering based on gene expression, ATAC-seq, or WNN analysis. The differences are more subtle than in the previous analysis (you can explore the weights, which are more evenly split than in our CITE-seq example), but we find that WNN provides the clearest separation of cell states. p1 <- DimPlot(pbmc, reduction = "umap.rna", group.by = "celltype", label = TRUE, label.size = 2.5, repel = TRUE) + ggtitle("RNA") p2 <- DimPlot(pbmc, reduction = "umap.atac", group.by = "celltype", label = TRUE, label.size = 2.5, repel = TRUE) + ggtitle("ATAC") p3 <- DimPlot(pbmc, reduction = "wnn.umap", group.by = "celltype", label = TRUE, label.size = 2.5, repel = TRUE) + ggtitle("WNN") p1 + p2 + p3 & NoLegend() & theme(plot.title = element_text(hjust = 0.5))For example, the ATAC-seq data assists in the separation of CD4 and CD8 T cell states. This is due to the presence of multiple loci that exhibit differential accessibility between different T cell subtypes. For example, we can visualize ‘pseudobulk’ tracks of the CD8A locus alongside violin plots of gene expression levels, using tools in the Signac visualization vignette. ## to make the visualization easier, subset T cell clusters celltype.names <- levels(pbmc) tcell.names <- grep("CD4|CD8|Treg", celltype.names,value = TRUE) tcells <- subset(pbmc, idents = tcell.names) CoveragePlot(tcells, region = 'CD8A', features = 'CD8A', assay = 'ATAC', expression.assay = 'SCT', peaks = FALSE)Next, we will examine the accessible regions of each cell to determine enriched motifs. As described in the Signac motifs vignette, there are a few ways to do this, but we will use the chromVAR package from the Greenleaf lab. This calculates a per-cell accessibility score for known motifs, and adds these scores as a third assay (chromvar) in the Seurat object.To continue, please make sure you have the following packages installed.chromVAR for the analysis of motif accessibility in scATAC-seqpresto for fast differential expression analyses.TFBSTools for TFBS analysisJASPAR2020 for JASPAR motif modelsmotifmatchr for motif matchingBSgenome.Hsapiens.UCSC.hg38 for chromVARInstall command for all dependencies remotes::install_github("immunogenomics/presto") BiocManager::install(c("chromVAR", "TFBSTools", "JASPAR2020", "motifmatchr", "BSgenome.Hsapiens.UCSC.hg38")) library(chromVAR) library(JASPAR2020) library(TFBSTools) library(motifmatchr) library(BSgenome.Hsapiens.UCSC.hg38) # Scan the DNA sequence of each peak for the presence of each motif, and create a Motif object DefaultAssay(pbmc) <- "ATAC" pwm_set <- getMatrixSet(x = JASPAR2020, opts = list(species = 9606, all_versions = FALSE)) motif.matrix <- CreateMotifMatrix(features = granges(pbmc), pwm = pwm_set, genome = 'hg38', use.counts = FALSE) motif.object <- CreateMotifObject(data = motif.matrix, pwm = pwm_set) pbmc <- SetAssayData(pbmc, assay = 'ATAC', slot = 'motifs', new.data = motif.object) # Note that this step can take 30-60 minutes pbmc <- RunChromVAR( object = pbmc, genome = BSgenome.Hsapiens.UCSC.hg38 )Finally, we explore the multimodal dataset to identify key regulators of each cell state. Paired data provides a unique opportunity to identify transcription factors (TFs) that satisfy multiple criteria, helping to narrow down the list of putative regulators to the most likely candidates. We aim to identify TFs whose expression is enriched in multiple cell types in the RNA measurements, but also have enriched accessibility for their motifs in the ATAC measurements.As an example and positive control, the CCAAT Enhancer Binding Protein (CEBP) family of proteins, including the TF CEBPB, have been repeatedly shown to play important roles in the differentiation and function of myeloid cells including monocytes and dendritic cells. We can see that both the expression of the CEBPB, and the accessibility of the MA0466.2.4 motif (which encodes the binding site for CEBPB), are both enriched in monocytes. #returns MA0466.2 motif.name <- ConvertMotifID(pbmc, name = 'CEBPB') gene_plot <- FeaturePlot(pbmc, features = "sct_CEBPB", reduction = 'wnn.umap') motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap') gene_plot | motif_plotWe’d like to quantify this relationship, and search across all cell types to find similar examples. To do so, we will use the presto package to perform fast differential expression. We run two tests: one using gene expression data, and the other using chromVAR motif accessibilities. presto calculates a p-value based on the Wilcox rank sum test, which is also the default test in Seurat, and we restrict our search to TFs that return significant results in both tests.presto also calculates an “AUC” statistic, which reflects the power of each gene (or motif) to serve as a marker of cell type. A maximum AUC value of 1 indicates a perfect marker. Since the AUC statistic is on the same scale for both genes and motifs, we take the average of the AUC values from the two tests, and use this to rank TFs for each cell type: markers_rna <- presto:::wilcoxauc.Seurat(X = pbmc, group_by = 'celltype', assay = 'data', seurat_assay = 'SCT') markers_motifs <- presto:::wilcoxauc.Seurat(X = pbmc, group_by = 'celltype', assay = 'data', seurat_assay = 'chromvar') motif.names <- markers_motifs$feature colnames(markers_rna) <- paste0("RNA.", colnames(markers_rna)) colnames(markers_motifs) <- paste0("motif.", colnames(markers_motifs)) markers_rna$gene <- markers_rna$RNA.feature markers_motifs$gene <- ConvertMotifID(pbmc, id = motif.names) # a simple function to implement the procedure above topTFs <- function(celltype, padj.cutoff = 1e-2) { ctmarkers_rna <- dplyr::filter( markers_rna, RNA.group == celltype, RNA.padj < padj.cutoff, RNA.logFC > 0) %>% arrange(-RNA.auc) ctmarkers_motif <- dplyr::filter( markers_motifs, motif.group == celltype, motif.padj < padj.cutoff, motif.logFC > 0) %>% arrange(-motif.auc) top_tfs <- inner_join( x = ctmarkers_rna[, c(2, 11, 6, 7)], y = ctmarkers_motif[, c(2, 1, 11, 6, 7)], by = "gene" ) top_tfs$avg_auc <- (top_tfs$RNA.auc + top_tfs$motif.auc) / 2 top_tfs <- arrange(top_tfs, -avg_auc) return(top_tfs) }We can now compute, and visualize, putative regulators for any cell type. We recover well-established regulators, including TBX21 for NK cells, IRF4 for plasma cells, SOX4 for hematopoietic progenitors, EBF1 and PAX5 for B cells, IRF8 and TCF4 for pDC. We believe that similar strategies can be used to help focus on a set of putative regulators in diverse systems. # identify top markers in NK and visualize head(topTFs("NK"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 NK TBX21 0.7270859 0.000000e+00 NK MA0690.1 0.9139614 ## 2 NK EOMES 0.5886774 2.411013e-98 NK MA0800.1 0.9214773 ## 3 NK RUNX3 0.7705661 5.977716e-120 NK MA0684.2 0.6769022 ## motif.pval avg_auc ## 1 1.097940e-202 0.8205237 ## 2 4.903866e-210 0.7550774 ## 3 1.560061e-38 0.7237341 motif.name <- ConvertMotifID(pbmc, name = 'TBX21') gene_plot <- FeaturePlot(pbmc, features = "sct_TBX21", reduction = 'wnn.umap') motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap') gene_plot | motif_plot # identify top markers in pDC and visualize head(topTFs("pDC"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 pDC TCF4 0.9998815 1.120711e-162 pDC MA0830.2 0.9965481 ## 2 pDC IRF8 0.9904457 1.308164e-123 pDC MA0652.1 0.8833112 ## 3 pDC SPIB 0.9115207 0.000000e+00 pDC MA0081.2 0.9068540 ## motif.pval avg_auc ## 1 1.785897e-69 0.9982148 ## 2 3.982413e-42 0.9368785 ## 3 3.083509e-47 0.9091874 motif.name <- ConvertMotifID(pbmc, name = 'TCF4') gene_plot <- FeaturePlot(pbmc, features = "sct_TCF4", reduction = 'wnn.umap') motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap') gene_plot | motif_plot # identify top markers in HSPC and visualize head(topTFs("CD16 Mono"),3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 CD16 Mono SPI1 0.8793172 1.666810e-296 CD16 Mono MA0080.5 0.8880908 ## 2 CD16 Mono CEBPB 0.8685933 1.625472e-294 CD16 Mono MA0466.2 0.7840422 ## 3 CD16 Mono MEF2C 0.7129910 2.727252e-79 CD16 Mono MA0497.1 0.8059373 ## motif.pval avg_auc ## 1 4.762491e-194 0.8837040 ## 2 7.049764e-105 0.8263177 ## 3 2.345716e-121 0.7594641 motif.name <- ConvertMotifID(pbmc, name = 'SPI1') gene_plot <- FeaturePlot(pbmc, features = "sct_SPI1", reduction = 'wnn.umap') motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap') gene_plot | motif_plot # identify top markers in other cell types head(topTFs("Naive B"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 Naive B MEF2C 0.8802747 1.890065e-182 Naive B MA0497.1 0.6789079 ## 2 Naive B PAX5 0.9436648 0.000000e+00 Naive B MA0014.3 0.5827061 ## 3 Naive B POU2F2 0.6029377 2.892216e-13 Naive B MA0507.1 0.8912268 ## motif.pval avg_auc ## 1 9.815118e-32 0.7795913 ## 2 5.995185e-08 0.7631854 ## 3 6.471677e-145 0.7470822 head(topTFs("HSPC"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 HSPC SOX4 0.9869406 5.524832e-71 HSPC MA0867.2 0.6830497 ## 2 HSPC GATA2 0.7884615 0.000000e+00 HSPC MA0036.3 0.8275008 ## 3 HSPC MEIS1 0.8638496 0.000000e+00 HSPC MA0498.2 0.6924225 ## motif.pval avg_auc ## 1 1.241915e-03 0.8349951 ## 2 7.591798e-09 0.8079812 ## 3 6.877492e-04 0.7781361 head(topTFs("Plasma"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 Plasma IRF4 0.8189687 5.261955e-35 Plasma MA1419.1 0.9776046 ## 2 Plasma MEF2C 0.9111213 2.977155e-12 Plasma MA0497.1 0.7596637 ## 3 Plasma TCF4 0.8049409 6.810635e-12 Plasma MA0830.2 0.7840848 ## motif.pval avg_auc ## 1 2.334627e-12 0.8982867 ## 2 1.374353e-04 0.8353925 ## 3 3.028306e-05 0.7945129Session Info sessionInfo()## R version 4.2.0 (2022-04-22) ## Platform: x86_64-pc-linux-gnu (64-bit) ## Running under: Ubuntu 20.04.5 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/liblapack.so.3 ## ## locale: ## [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C ## [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8 ## [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 ## ## attached base packages: ## [1] stats4 stats graphics grDevices utils datasets methods ## [8] base ## ## other attached packages: ## [1] BSgenome.Hsapiens.UCSC.hg38_1.4.5 BSgenome_1.66.3 ## [3] rtracklayer_1.58.0 Biostrings_2.66.0 ## [5] XVector_0.38.0 motifmatchr_1.20.0 ## [7] TFBSTools_1.36.0 JASPAR2020_0.99.10 ## [9] chromVAR_1.20.2 EnsDb.Hsapiens.v86_2.99.0 ## [11] ensembldb_2.22.0 AnnotationFilter_1.22.0 ## [13] GenomicFeatures_1.50.4 AnnotationDbi_1.60.0 ## [15] Biobase_2.58.0 GenomicRanges_1.50.2 ## [17] GenomeInfoDb_1.35.16 IRanges_2.32.0 ## [19] S4Vectors_0.36.2 BiocGenerics_0.44.0 ## [21] Signac_1.9.0 ggplot2_3.4.1 ## [23] dplyr_1.1.1 cowplot_1.1.1 ## [25] thp1.eccite.SeuratData_3.1.5 stxBrain.SeuratData_0.1.1 ## [27] ssHippo.SeuratData_3.1.4 pbmcsca.SeuratData_3.0.0 ## [29] pbmcMultiome.SeuratData_0.1.2 pbmc3k.SeuratData_3.1.4 ## [31] panc8.SeuratData_3.0.2 ifnb.SeuratData_3.1.0 ## [33] hcabm40k.SeuratData_3.0.0 bmcite.SeuratData_0.3.0 ## [35] SeuratData_0.2.2 SeuratObject_4.1.3 ## [37] Seurat_4.2.1.9001 ## ## loaded via a namespace (and not attached): ## [1] rappdirs_0.3.3 scattermore_0.8 ## [3] R.methodsS3_1.8.2 ragg_1.2.5 ## [5] nabor_0.5.0 tidyr_1.3.0 ## [7] bit64_4.0.5 knitr_1.42 ## [9] R.utils_2.12.2 irlba_2.3.5.1 ## [11] DelayedArray_0.24.0 data.table_1.14.8 ## [13] rpart_4.1.16 KEGGREST_1.38.0 ## [15] RCurl_1.98-1.12 generics_0.1.3 ## [17] RSQLite_2.3.0 RANN_2.6.1 ## [19] future_1.32.0 tzdb_0.3.0 ## [21] bit_4.0.5 spatstat.data_3.0-1 ## [23] xml2_1.3.3 httpuv_1.6.9 ## [25] SummarizedExperiment_1.28.0 DirichletMultinomial_1.40.0 ## [27] xfun_0.38 hms_1.1.2 ## [29] jquerylib_0.1.4 evaluate_0.20 ## [31] promises_1.2.0.1 fansi_1.0.4 ## [33] restfulr_0.0.15 progress_1.2.2 ## [35] caTools_1.18.2 dbplyr_2.3.1 ## [37] igraph_1.4.1 DBI_1.1.3 ## [39] htmlwidgets_1.6.2 spatstat.geom_3.1-0 ## [41] purrr_1.0.1 ellipsis_0.3.2 ## [43] backports_1.4.1 annotate_1.76.0 ## [45] biomaRt_2.54.0 deldir_1.0-6 ## [47] MatrixGenerics_1.10.0 vctrs_0.6.1 ## [49] ROCR_1.0-11 abind_1.4-5 ## [51] cachem_1.0.7 withr_2.5.0 ## [53] progressr_0.13.0 presto_1.0.0 ## [55] checkmate_2.1.0 sctransform_0.3.5 ## [57] GenomicAlignments_1.34.0 prettyunits_1.1.1 ## [59] goftest_1.2-3 cluster_2.1.3 ## [61] seqLogo_1.64.0 lazyeval_0.2.2 ## [63] crayon_1.5.2 hdf5r_1.3.8 ## [65] spatstat.explore_3.1-0 pkgconfig_2.0.3 ## [67] labeling_0.4.2 nlme_3.1-157 ## [69] ProtGenerics_1.30.0 nnet_7.3-17 ## [71] rlang_1.1.0 globals_0.16.2 ## [73] lifecycle_1.0.3 miniUI_0.1.1.1 ## [75] filelock_1.0.2 BiocFileCache_2.6.1 ## [77] dichromat_2.0-0.1 rprojroot_2.0.3 ## [79] polyclip_1.10-4 matrixStats_0.63.0 ## [81] lmtest_0.9-40 Matrix_1.5-3 ## [83] zoo_1.8-11 base64enc_0.1-3 ## [85] ggridges_0.5.4 png_0.1-8 ## [87] viridisLite_0.4.1 rjson_0.2.21 ## [89] bitops_1.0-7 R.oo_1.25.0 ## [91] KernSmooth_2.23-20 blob_1.2.3 ## [93] stringr_1.5.0 parallelly_1.35.0 ## [95] spatstat.random_3.1-4 readr_2.1.4 ## [97] jpeg_0.1-10 CNEr_1.34.0 ## [99] scales_1.2.1 memoise_2.0.1 ## [101] magrittr_2.0.3 plyr_1.8.8 ## [103] ica_1.0-3 zlibbioc_1.44.0 ## [105] compiler_4.2.0 BiocIO_1.8.0 ## [107] RColorBrewer_1.1-3 fitdistrplus_1.1-8 ## [109] Rsamtools_2.14.0 cli_3.6.1 ## [111] listenv_0.9.0 patchwork_1.1.2 ## [113] pbapply_1.7-0 htmlTable_2.4.1 ## [115] Formula_1.2-5 MASS_7.3-56 ## [117] tidyselect_1.2.0 stringi_1.7.12 ## [119] textshaping_0.3.6 highr_0.10 ## [121] yaml_2.3.7 latticeExtra_0.6-30 ## [123] ggrepel_0.9.3 grid_4.2.0 ## [125] sass_0.4.5 VariantAnnotation_1.44.1 ## [127] fastmatch_1.1-3 tools_4.2.0 ## [129] future.apply_1.10.0 parallel_4.2.0 ## [131] rstudioapi_0.14 TFMPvalue_0.0.9 ## [133] foreign_0.8-82 gridExtra_2.3 ## [135] farver_2.1.1 Rtsne_0.16 ## [137] digest_0.6.31 pracma_2.4.2 ## [139] shiny_1.7.4 Rcpp_1.0.10 ## [141] later_1.3.0 RcppAnnoy_0.0.20 ## [143] httr_1.4.5 biovizBase_1.46.0 ## [145] colorspace_2.1-0 XML_3.99-0.13 ## [147] fs_1.6.1 tensor_1.5 ## [149] reticulate_1.28 splines_4.2.0 ## [151] uwot_0.1.14 RcppRoll_0.3.0 ## [153] spatstat.utils_3.0-2 pkgdown_2.0.7 ## [155] sp_1.6-0 plotly_4.10.1 ## [157] systemfonts_1.0.4 xtable_1.8-4 ## [159] poweRlaw_0.70.6 jsonlite_1.8.4 ## [161] R6_2.5.1 Hmisc_4.8-0 ## [163] pillar_1.9.0 htmltools_0.5.5 ## [165] mime_0.12 DT_0.27 ## [167] glue_1.6.2 fastmap_1.1.1 ## [169] BiocParallel_1.32.5 codetools_0.2-18 ## [171] utf8_1.2.3 lattice_0.20-45 ## [173] bslib_0.4.2 spatstat.sparse_3.0-1 ## [175] tibble_3.2.1 curl_5.0.0 ## [177] leiden_0.4.3 gtools_3.9.4 ## [179] GO.db_3.16.0 interp_1.1-3 ## [181] survival_3.3-1 rmarkdown_2.21 ## [183] desc_1.4.2 munsell_0.5.0 ## [185] GenomeInfoDbData_1.2.9 reshape2_1.4.4 ## [187] gtable_0.3.3

We next perform pre-processing and dimensional reduction on both assays independently, using standard approaches for RNA and ATAC-seq data. # RNA analysis DefaultAssay(pbmc) <- "RNA" pbmc <- SCTransform(pbmc, verbose = FALSE) %>% RunPCA() %>% RunUMAP(dims = 1:50, reduction.name = 'umap.rna', reduction.key = 'rnaUMAP_') # ATAC analysis # We exclude the first dimension as this is typically correlated with sequencing depth DefaultAssay(pbmc) <- "ATAC" pbmc <- RunTFIDF(pbmc) pbmc <- FindTopFeatures(pbmc, min.cutoff = 'q0') pbmc <- RunSVD(pbmc) pbmc <- RunUMAP(pbmc, reduction = 'lsi', dims = 2:50, reduction.name = "umap.atac", reduction.key = "atacUMAP_")We calculate a WNN graph, representing a weighted combination of RNA and ATAC-seq modalities. We use this graph for UMAP visualization and clustering pbmc <- FindMultiModalNeighbors(pbmc, reduction.list = list("pca", "lsi"), dims.list = list(1:50, 2:50)) pbmc <- RunUMAP(pbmc, nn.name = "weighted.nn", reduction.name = "wnn.umap", reduction.key = "wnnUMAP_") pbmc <- FindClusters(pbmc, graph.name = "wsnn", algorithm = 3, verbose = FALSE)We annotate the clusters below. Note that you could also annotate the dataset using our supervised mapping pipelines, using either our vignette, or automated web tool, Azimuth. # perform sub-clustering on cluster 6 to find additional structure pbmc <- FindSubCluster(pbmc, cluster = 6, graph.name = "wsnn", algorithm = 3) Idents(pbmc) <- "sub.cluster" # add annotations pbmc <- RenameIdents(pbmc, '19' = 'pDC','20' = 'HSPC','15' = 'cDC') pbmc <- RenameIdents(pbmc, '0' = 'CD14 Mono', '9' ='CD14 Mono', '5' = 'CD16 Mono') pbmc <- RenameIdents(pbmc, '10' = 'Naive B', '11' = 'Intermediate B', '17' = 'Memory B', '21' = 'Plasma') pbmc <- RenameIdents(pbmc, '7' = 'NK') pbmc <- RenameIdents(pbmc, '4' = 'CD4 TCM', '13'= "CD4 TEM", '3' = "CD4 TCM", '16' ="Treg", '1' ="CD4 Naive", '14' = "CD4 Naive") pbmc <- RenameIdents(pbmc, '2' = 'CD8 Naive', '8'= "CD8 Naive", '12' = 'CD8 TEM_1', '6_0' = 'CD8 TEM_2', '6_1' ='CD8 TEM_2', '6_4' ='CD8 TEM_2') pbmc <- RenameIdents(pbmc, '18' = 'MAIT') pbmc <- RenameIdents(pbmc, '6_2' ='gdT', '6_3' = 'gdT') pbmc$celltype <- Idents(pbmc)We can visualize clustering based on gene expression, ATAC-seq, or WNN analysis. The differences are more subtle than in the previous analysis (you can explore the weights, which are more evenly split than in our CITE-seq example), but we find that WNN provides the clearest separation of cell states. p1 <- DimPlot(pbmc, reduction = "umap.rna", group.by = "celltype", label = TRUE, label.size = 2.5, repel = TRUE) + ggtitle("RNA") p2 <- DimPlot(pbmc, reduction = "umap.atac", group.by = "celltype", label = TRUE, label.size = 2.5, repel = TRUE) + ggtitle("ATAC") p3 <- DimPlot(pbmc, reduction = "wnn.umap", group.by = "celltype", label = TRUE, label.size = 2.5, repel = TRUE) + ggtitle("WNN") p1 + p2 + p3 & NoLegend() & theme(plot.title = element_text(hjust = 0.5))For example, the ATAC-seq data assists in the separation of CD4 and CD8 T cell states. This is due to the presence of multiple loci that exhibit differential accessibility between different T cell subtypes. For example, we can visualize ‘pseudobulk’ tracks of the CD8A locus alongside violin plots of gene expression levels, using tools in the Signac visualization vignette. ## to make the visualization easier, subset T cell clusters celltype.names <- levels(pbmc) tcell.names <- grep("CD4|CD8|Treg", celltype.names,value = TRUE) tcells <- subset(pbmc, idents = tcell.names) CoveragePlot(tcells, region = 'CD8A', features = 'CD8A', assay = 'ATAC', expression.assay = 'SCT', peaks = FALSE)Next, we will examine the accessible regions of each cell to determine enriched motifs. As described in the Signac motifs vignette, there are a few ways to do this, but we will use the chromVAR package from the Greenleaf lab. This calculates a per-cell accessibility score for known motifs, and adds these scores as a third assay (chromvar) in the Seurat object.To continue, please make sure you have the following packages installed.chromVAR for the analysis of motif accessibility in scATAC-seqpresto for fast differential expression analyses.TFBSTools for TFBS analysisJASPAR2020 for JASPAR motif modelsmotifmatchr for motif matchingBSgenome.Hsapiens.UCSC.hg38 for chromVARInstall command for all dependencies remotes::install_github("immunogenomics/presto") BiocManager::install(c("chromVAR", "TFBSTools", "JASPAR2020", "motifmatchr", "BSgenome.Hsapiens.UCSC.hg38")) library(chromVAR) library(JASPAR2020) library(TFBSTools) library(motifmatchr) library(BSgenome.Hsapiens.UCSC.hg38) # Scan the DNA sequence of each peak for the presence of each motif, and create a Motif object DefaultAssay(pbmc) <- "ATAC" pwm_set <- getMatrixSet(x = JASPAR2020, opts = list(species = 9606, all_versions = FALSE)) motif.matrix <- CreateMotifMatrix(features = granges(pbmc), pwm = pwm_set, genome = 'hg38', use.counts = FALSE) motif.object <- CreateMotifObject(data = motif.matrix, pwm = pwm_set) pbmc <- SetAssayData(pbmc, assay = 'ATAC', slot = 'motifs', new.data = motif.object) # Note that this step can take 30-60 minutes pbmc <- RunChromVAR( object = pbmc, genome = BSgenome.Hsapiens.UCSC.hg38 )Finally, we explore the multimodal dataset to identify key regulators of each cell state. Paired data provides a unique opportunity to identify transcription factors (TFs) that satisfy multiple criteria, helping to narrow down the list of putative regulators to the most likely candidates. We aim to identify TFs whose expression is enriched in multiple cell types in the RNA measurements, but also have enriched accessibility for their motifs in the ATAC measurements.As an example and positive control, the CCAAT Enhancer Binding Protein (CEBP) family of proteins, including the TF CEBPB, have been repeatedly shown to play important roles in the differentiation and function of myeloid cells including monocytes and dendritic cells. We can see that both the expression of the CEBPB, and the accessibility of the MA0466.2.4 motif (which encodes the binding site for CEBPB), are both enriched in monocytes. #returns MA0466.2 motif.name <- ConvertMotifID(pbmc, name = 'CEBPB') gene_plot <- FeaturePlot(pbmc, features = "sct_CEBPB", reduction = 'wnn.umap') motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap') gene_plot | motif_plotWe’d like to quantify this relationship, and search across all cell types to find similar examples. To do so, we will use the presto package to perform fast differential expression. We run two tests: one using gene expression data, and the other using chromVAR motif accessibilities. presto calculates a p-value based on the Wilcox rank sum test, which is also the default test in Seurat, and we restrict our search to TFs that return significant results in both tests.presto also calculates an “AUC” statistic, which reflects the power of each gene (or motif) to serve as a marker of cell type. A maximum AUC value of 1 indicates a perfect marker. Since the AUC statistic is on the same scale for both genes and motifs, we take the average of the AUC values from the two tests, and use this to rank TFs for each cell type: markers_rna <- presto:::wilcoxauc.Seurat(X = pbmc, group_by = 'celltype', assay = 'data', seurat_assay = 'SCT') markers_motifs <- presto:::wilcoxauc.Seurat(X = pbmc, group_by = 'celltype', assay = 'data', seurat_assay = 'chromvar') motif.names <- markers_motifs$feature colnames(markers_rna) <- paste0("RNA.", colnames(markers_rna)) colnames(markers_motifs) <- paste0("motif.", colnames(markers_motifs)) markers_rna$gene <- markers_rna$RNA.feature markers_motifs$gene <- ConvertMotifID(pbmc, id = motif.names) # a simple function to implement the procedure above topTFs <- function(celltype, padj.cutoff = 1e-2) { ctmarkers_rna <- dplyr::filter( markers_rna, RNA.group == celltype, RNA.padj < padj.cutoff, RNA.logFC > 0) %>% arrange(-RNA.auc) ctmarkers_motif <- dplyr::filter( markers_motifs, motif.group == celltype, motif.padj < padj.cutoff, motif.logFC > 0) %>% arrange(-motif.auc) top_tfs <- inner_join( x = ctmarkers_rna[, c(2, 11, 6, 7)], y = ctmarkers_motif[, c(2, 1, 11, 6, 7)], by = "gene" ) top_tfs$avg_auc <- (top_tfs$RNA.auc + top_tfs$motif.auc) / 2 top_tfs <- arrange(top_tfs, -avg_auc) return(top_tfs) }We can now compute, and visualize, putative regulators for any cell type. We recover well-established regulators, including TBX21 for NK cells, IRF4 for plasma cells, SOX4 for hematopoietic progenitors, EBF1 and PAX5 for B cells, IRF8 and TCF4 for pDC. We believe that similar strategies can be used to help focus on a set of putative regulators in diverse systems. # identify top markers in NK and visualize head(topTFs("NK"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 NK TBX21 0.7270859 0.000000e+00 NK MA0690.1 0.9139614 ## 2 NK EOMES 0.5886774 2.411013e-98 NK MA0800.1 0.9214773 ## 3 NK RUNX3 0.7705661 5.977716e-120 NK MA0684.2 0.6769022 ## motif.pval avg_auc ## 1 1.097940e-202 0.8205237 ## 2 4.903866e-210 0.7550774 ## 3 1.560061e-38 0.7237341 motif.name <- ConvertMotifID(pbmc, name = 'TBX21') gene_plot <- FeaturePlot(pbmc, features = "sct_TBX21", reduction = 'wnn.umap') motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap') gene_plot | motif_plot # identify top markers in pDC and visualize head(topTFs("pDC"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 pDC TCF4 0.9998815 1.120711e-162 pDC MA0830.2 0.9965481 ## 2 pDC IRF8 0.9904457 1.308164e-123 pDC MA0652.1 0.8833112 ## 3 pDC SPIB 0.9115207 0.000000e+00 pDC MA0081.2 0.9068540 ## motif.pval avg_auc ## 1 1.785897e-69 0.9982148 ## 2 3.982413e-42 0.9368785 ## 3 3.083509e-47 0.9091874 motif.name <- ConvertMotifID(pbmc, name = 'TCF4') gene_plot <- FeaturePlot(pbmc, features = "sct_TCF4", reduction = 'wnn.umap') motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap') gene_plot | motif_plot # identify top markers in HSPC and visualize head(topTFs("CD16 Mono"),3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 CD16 Mono SPI1 0.8793172 1.666810e-296 CD16 Mono MA0080.5 0.8880908 ## 2 CD16 Mono CEBPB 0.8685933 1.625472e-294 CD16 Mono MA0466.2 0.7840422 ## 3 CD16 Mono MEF2C 0.7129910 2.727252e-79 CD16 Mono MA0497.1 0.8059373 ## motif.pval avg_auc ## 1 4.762491e-194 0.8837040 ## 2 7.049764e-105 0.8263177 ## 3 2.345716e-121 0.7594641 motif.name <- ConvertMotifID(pbmc, name = 'SPI1') gene_plot <- FeaturePlot(pbmc, features = "sct_SPI1", reduction = 'wnn.umap') motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap') gene_plot | motif_plot # identify top markers in other cell types head(topTFs("Naive B"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 Naive B MEF2C 0.8802747 1.890065e-182 Naive B MA0497.1 0.6789079 ## 2 Naive B PAX5 0.9436648 0.000000e+00 Naive B MA0014.3 0.5827061 ## 3 Naive B POU2F2 0.6029377 2.892216e-13 Naive B MA0507.1 0.8912268 ## motif.pval avg_auc ## 1 9.815118e-32 0.7795913 ## 2 5.995185e-08 0.7631854 ## 3 6.471677e-145 0.7470822 head(topTFs("HSPC"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 HSPC SOX4 0.9869406 5.524832e-71 HSPC MA0867.2 0.6830497 ## 2 HSPC GATA2 0.7884615 0.000000e+00 HSPC MA0036.3 0.8275008 ## 3 HSPC MEIS1 0.8638496 0.000000e+00 HSPC MA0498.2 0.6924225 ## motif.pval avg_auc ## 1 1.241915e-03 0.8349951 ## 2 7.591798e-09 0.8079812 ## 3 6.877492e-04 0.7781361 head(topTFs("Plasma"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 Plasma IRF4 0.8189687 5.261955e-35 Plasma MA1419.1 0.9776046 ## 2 Plasma MEF2C 0.9111213 2.977155e-12 Plasma MA0497.1 0.7596637 ## 3 Plasma TCF4 0.8049409 6.810635e-12 Plasma MA0830.2 0.7840848 ## motif.pval avg_auc ## 1 2.334627e-12 0.8982867 ## 2 1.374353e-04 0.8353925 ## 3 3.028306e-05 0.7945129Session Info sessionInfo()## R version 4.2.0 (2022-04-22) ## Platform: x86_64-pc-linux-gnu (64-bit) ## Running under: Ubuntu 20.04.5 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/liblapack.so.3 ## ## locale: ## [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C ## [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8 ## [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 ## ## attached base packages: ## [1] stats4 stats graphics grDevices utils datasets methods ## [8] base ## ## other attached packages: ## [1] BSgenome.Hsapiens.UCSC.hg38_1.4.5 BSgenome_1.66.3 ## [3] rtracklayer_1.58.0 Biostrings_2.66.0 ## [5] XVector_0.38.0 motifmatchr_1.20.0 ## [7] TFBSTools_1.36.0 JASPAR2020_0.99.10 ## [9] chromVAR_1.20.2 EnsDb.Hsapiens.v86_2.99.0 ## [11] ensembldb_2.22.0 AnnotationFilter_1.22.0 ## [13] GenomicFeatures_1.50.4 AnnotationDbi_1.60.0 ## [15] Biobase_2.58.0 GenomicRanges_1.50.2 ## [17] GenomeInfoDb_1.35.16 IRanges_2.32.0 ## [19] S4Vectors_0.36.2 BiocGenerics_0.44.0 ## [21] Signac_1.9.0 ggplot2_3.4.1 ## [23] dplyr_1.1.1 cowplot_1.1.1 ## [25] thp1.eccite.SeuratData_3.1.5 stxBrain.SeuratData_0.1.1 ## [27] ssHippo.SeuratData_3.1.4 pbmcsca.SeuratData_3.0.0 ## [29] pbmcMultiome.SeuratData_0.1.2 pbmc3k.SeuratData_3.1.4 ## [31] panc8.SeuratData_3.0.2 ifnb.SeuratData_3.1.0 ## [33] hcabm40k.SeuratData_3.0.0 bmcite.SeuratData_0.3.0 ## [35] SeuratData_0.2.2 SeuratObject_4.1.3 ## [37] Seurat_4.2.1.9001 ## ## loaded via a namespace (and not attached): ## [1] rappdirs_0.3.3 scattermore_0.8 ## [3] R.methodsS3_1.8.2 ragg_1.2.5 ## [5] nabor_0.5.0 tidyr_1.3.0 ## [7] bit64_4.0.5 knitr_1.42 ## [9] R.utils_2.12.2 irlba_2.3.5.1 ## [11] DelayedArray_0.24.0 data.table_1.14.8 ## [13] rpart_4.1.16 KEGGREST_1.38.0 ## [15] RCurl_1.98-1.12 generics_0.1.3 ## [17] RSQLite_2.3.0 RANN_2.6.1 ## [19] future_1.32.0 tzdb_0.3.0 ## [21] bit_4.0.5 spatstat.data_3.0-1 ## [23] xml2_1.3.3 httpuv_1.6.9 ## [25] SummarizedExperiment_1.28.0 DirichletMultinomial_1.40.0 ## [27] xfun_0.38 hms_1.1.2 ## [29] jquerylib_0.1.4 evaluate_0.20 ## [31] promises_1.2.0.1 fansi_1.0.4 ## [33] restfulr_0.0.15 progress_1.2.2 ## [35] caTools_1.18.2 dbplyr_2.3.1 ## [37] igraph_1.4.1 DBI_1.1.3 ## [39] htmlwidgets_1.6.2 spatstat.geom_3.1-0 ## [41] purrr_1.0.1 ellipsis_0.3.2 ## [43] backports_1.4.1 annotate_1.76.0 ## [45] biomaRt_2.54.0 deldir_1.0-6 ## [47] MatrixGenerics_1.10.0 vctrs_0.6.1 ## [49] ROCR_1.0-11 abind_1.4-5 ## [51] cachem_1.0.7 withr_2.5.0 ## [53] progressr_0.13.0 presto_1.0.0 ## [55] checkmate_2.1.0 sctransform_0.3.5 ## [57] GenomicAlignments_1.34.0 prettyunits_1.1.1 ## [59] goftest_1.2-3 cluster_2.1.3 ## [61] seqLogo_1.64.0 lazyeval_0.2.2 ## [63] crayon_1.5.2 hdf5r_1.3.8 ## [65] spatstat.explore_3.1-0 pkgconfig_2.0.3 ## [67] labeling_0.4.2 nlme_3.1-157 ## [69] ProtGenerics_1.30.0 nnet_7.3-17 ## [71] rlang_1.1.0 globals_0.16.2 ## [73] lifecycle_1.0.3 miniUI_0.1.1.1 ## [75] filelock_1.0.2 BiocFileCache_2.6.1 ## [77] dichromat_2.0-0.1 rprojroot_2.0.3 ## [79] polyclip_1.10-4 matrixStats_0.63.0 ## [81] lmtest_0.9-40 Matrix_1.5-3 ## [83] zoo_1.8-11 base64enc_0.1-3 ## [85] ggridges_0.5.4 png_0.1-8 ## [87] viridisLite_0.4.1 rjson_0.2.21 ## [89] bitops_1.0-7 R.oo_1.25.0 ## [91] KernSmooth_2.23-20 blob_1.2.3 ## [93] stringr_1.5.0 parallelly_1.35.0 ## [95] spatstat.random_3.1-4 readr_2.1.4 ## [97] jpeg_0.1-10 CNEr_1.34.0 ## [99] scales_1.2.1 memoise_2.0.1 ## [101] magrittr_2.0.3 plyr_1.8.8 ## [103] ica_1.0-3 zlibbioc_1.44.0 ## [105] compiler_4.2.0 BiocIO_1.8.0 ## [107] RColorBrewer_1.1-3 fitdistrplus_1.1-8 ## [109] Rsamtools_2.14.0 cli_3.6.1 ## [111] listenv_0.9.0 patchwork_1.1.2 ## [113] pbapply_1.7-0 htmlTable_2.4.1 ## [115] Formula_1.2-5 MASS_7.3-56 ## [117] tidyselect_1.2.0 stringi_1.7.12 ## [119] textshaping_0.3.6 highr_0.10 ## [121] yaml_2.3.7 latticeExtra_0.6-30 ## [123] ggrepel_0.9.3 grid_4.2.0 ## [125] sass_0.4.5 VariantAnnotation_1.44.1 ## [127] fastmatch_1.1-3 tools_4.2.0 ## [129] future.apply_1.10.0 parallel_4.2.0 ## [131] rstudioapi_0.14 TFMPvalue_0.0.9 ## [133] foreign_0.8-82 gridExtra_2.3 ## [135] farver_2.1.1 Rtsne_0.16 ## [137] digest_0.6.31 pracma_2.4.2 ## [139] shiny_1.7.4 Rcpp_1.0.10 ## [141] later_1.3.0 RcppAnnoy_0.0.20 ## [143] httr_1.4.5 biovizBase_1.46.0 ## [145] colorspace_2.1-0 XML_3.99-0.13 ## [147] fs_1.6.1 tensor_1.5 ## [149] reticulate_1.28 splines_4.2.0 ## [151] uwot_0.1.14 RcppRoll_0.3.0 ## [153] spatstat.utils_3.0-2 pkgdown_2.0.7 ## [155] sp_1.6-0 plotly_4.10.1 ## [157] systemfonts_1.0.4 xtable_1.8-4 ## [159] poweRlaw_0.70.6 jsonlite_1.8.4 ## [161] R6_2.5.1 Hmisc_4.8-0 ## [163] pillar_1.9.0 htmltools_0.5.5 ## [165] mime_0.12 DT_0.27 ## [167] glue_1.6.2 fastmap_1.1.1 ## [169] BiocParallel_1.32.5 codetools_0.2-18 ## [171] utf8_1.2.3 lattice_0.20-45 ## [173] bslib_0.4.2 spatstat.sparse_3.0-1 ## [175] tibble_3.2.1 curl_5.0.0 ## [177] leiden_0.4.3 gtools_3.9.4 ## [179] GO.db_3.16.0 interp_1.1-3 ## [181] survival_3.3-1 rmarkdown_2.21 ## [183] desc_1.4.2 munsell_0.5.0 ## [185] GenomeInfoDbData_1.2.9 reshape2_1.4.4 ## [187] gtable_0.3.3

We calculate a WNN graph, representing a weighted combination of RNA and ATAC-seq modalities. We use this graph for UMAP visualization and clustering pbmc <- FindMultiModalNeighbors(pbmc, reduction.list = list("pca", "lsi"), dims.list = list(1:50, 2:50)) pbmc <- RunUMAP(pbmc, nn.name = "weighted.nn", reduction.name = "wnn.umap", reduction.key = "wnnUMAP_") pbmc <- FindClusters(pbmc, graph.name = "wsnn", algorithm = 3, verbose = FALSE)We annotate the clusters below. Note that you could also annotate the dataset using our supervised mapping pipelines, using either our vignette, or automated web tool, Azimuth. # perform sub-clustering on cluster 6 to find additional structure pbmc <- FindSubCluster(pbmc, cluster = 6, graph.name = "wsnn", algorithm = 3) Idents(pbmc) <- "sub.cluster" # add annotations pbmc <- RenameIdents(pbmc, '19' = 'pDC','20' = 'HSPC','15' = 'cDC') pbmc <- RenameIdents(pbmc, '0' = 'CD14 Mono', '9' ='CD14 Mono', '5' = 'CD16 Mono') pbmc <- RenameIdents(pbmc, '10' = 'Naive B', '11' = 'Intermediate B', '17' = 'Memory B', '21' = 'Plasma') pbmc <- RenameIdents(pbmc, '7' = 'NK') pbmc <- RenameIdents(pbmc, '4' = 'CD4 TCM', '13'= "CD4 TEM", '3' = "CD4 TCM", '16' ="Treg", '1' ="CD4 Naive", '14' = "CD4 Naive") pbmc <- RenameIdents(pbmc, '2' = 'CD8 Naive', '8'= "CD8 Naive", '12' = 'CD8 TEM_1', '6_0' = 'CD8 TEM_2', '6_1' ='CD8 TEM_2', '6_4' ='CD8 TEM_2') pbmc <- RenameIdents(pbmc, '18' = 'MAIT') pbmc <- RenameIdents(pbmc, '6_2' ='gdT', '6_3' = 'gdT') pbmc$celltype <- Idents(pbmc)We can visualize clustering based on gene expression, ATAC-seq, or WNN analysis. The differences are more subtle than in the previous analysis (you can explore the weights, which are more evenly split than in our CITE-seq example), but we find that WNN provides the clearest separation of cell states. p1 <- DimPlot(pbmc, reduction = "umap.rna", group.by = "celltype", label = TRUE, label.size = 2.5, repel = TRUE) + ggtitle("RNA") p2 <- DimPlot(pbmc, reduction = "umap.atac", group.by = "celltype", label = TRUE, label.size = 2.5, repel = TRUE) + ggtitle("ATAC") p3 <- DimPlot(pbmc, reduction = "wnn.umap", group.by = "celltype", label = TRUE, label.size = 2.5, repel = TRUE) + ggtitle("WNN") p1 + p2 + p3 & NoLegend() & theme(plot.title = element_text(hjust = 0.5))For example, the ATAC-seq data assists in the separation of CD4 and CD8 T cell states. This is due to the presence of multiple loci that exhibit differential accessibility between different T cell subtypes. For example, we can visualize ‘pseudobulk’ tracks of the CD8A locus alongside violin plots of gene expression levels, using tools in the Signac visualization vignette. ## to make the visualization easier, subset T cell clusters celltype.names <- levels(pbmc) tcell.names <- grep("CD4|CD8|Treg", celltype.names,value = TRUE) tcells <- subset(pbmc, idents = tcell.names) CoveragePlot(tcells, region = 'CD8A', features = 'CD8A', assay = 'ATAC', expression.assay = 'SCT', peaks = FALSE)Next, we will examine the accessible regions of each cell to determine enriched motifs. As described in the Signac motifs vignette, there are a few ways to do this, but we will use the chromVAR package from the Greenleaf lab. This calculates a per-cell accessibility score for known motifs, and adds these scores as a third assay (chromvar) in the Seurat object.To continue, please make sure you have the following packages installed.chromVAR for the analysis of motif accessibility in scATAC-seqpresto for fast differential expression analyses.TFBSTools for TFBS analysisJASPAR2020 for JASPAR motif modelsmotifmatchr for motif matchingBSgenome.Hsapiens.UCSC.hg38 for chromVARInstall command for all dependencies remotes::install_github("immunogenomics/presto") BiocManager::install(c("chromVAR", "TFBSTools", "JASPAR2020", "motifmatchr", "BSgenome.Hsapiens.UCSC.hg38")) library(chromVAR) library(JASPAR2020) library(TFBSTools) library(motifmatchr) library(BSgenome.Hsapiens.UCSC.hg38) # Scan the DNA sequence of each peak for the presence of each motif, and create a Motif object DefaultAssay(pbmc) <- "ATAC" pwm_set <- getMatrixSet(x = JASPAR2020, opts = list(species = 9606, all_versions = FALSE)) motif.matrix <- CreateMotifMatrix(features = granges(pbmc), pwm = pwm_set, genome = 'hg38', use.counts = FALSE) motif.object <- CreateMotifObject(data = motif.matrix, pwm = pwm_set) pbmc <- SetAssayData(pbmc, assay = 'ATAC', slot = 'motifs', new.data = motif.object) # Note that this step can take 30-60 minutes pbmc <- RunChromVAR( object = pbmc, genome = BSgenome.Hsapiens.UCSC.hg38 )Finally, we explore the multimodal dataset to identify key regulators of each cell state. Paired data provides a unique opportunity to identify transcription factors (TFs) that satisfy multiple criteria, helping to narrow down the list of putative regulators to the most likely candidates. We aim to identify TFs whose expression is enriched in multiple cell types in the RNA measurements, but also have enriched accessibility for their motifs in the ATAC measurements.As an example and positive control, the CCAAT Enhancer Binding Protein (CEBP) family of proteins, including the TF CEBPB, have been repeatedly shown to play important roles in the differentiation and function of myeloid cells including monocytes and dendritic cells. We can see that both the expression of the CEBPB, and the accessibility of the MA0466.2.4 motif (which encodes the binding site for CEBPB), are both enriched in monocytes. #returns MA0466.2 motif.name <- ConvertMotifID(pbmc, name = 'CEBPB') gene_plot <- FeaturePlot(pbmc, features = "sct_CEBPB", reduction = 'wnn.umap') motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap') gene_plot | motif_plotWe’d like to quantify this relationship, and search across all cell types to find similar examples. To do so, we will use the presto package to perform fast differential expression. We run two tests: one using gene expression data, and the other using chromVAR motif accessibilities. presto calculates a p-value based on the Wilcox rank sum test, which is also the default test in Seurat, and we restrict our search to TFs that return significant results in both tests.presto also calculates an “AUC” statistic, which reflects the power of each gene (or motif) to serve as a marker of cell type. A maximum AUC value of 1 indicates a perfect marker. Since the AUC statistic is on the same scale for both genes and motifs, we take the average of the AUC values from the two tests, and use this to rank TFs for each cell type: markers_rna <- presto:::wilcoxauc.Seurat(X = pbmc, group_by = 'celltype', assay = 'data', seurat_assay = 'SCT') markers_motifs <- presto:::wilcoxauc.Seurat(X = pbmc, group_by = 'celltype', assay = 'data', seurat_assay = 'chromvar') motif.names <- markers_motifs$feature colnames(markers_rna) <- paste0("RNA.", colnames(markers_rna)) colnames(markers_motifs) <- paste0("motif.", colnames(markers_motifs)) markers_rna$gene <- markers_rna$RNA.feature markers_motifs$gene <- ConvertMotifID(pbmc, id = motif.names) # a simple function to implement the procedure above topTFs <- function(celltype, padj.cutoff = 1e-2) { ctmarkers_rna <- dplyr::filter( markers_rna, RNA.group == celltype, RNA.padj < padj.cutoff, RNA.logFC > 0) %>% arrange(-RNA.auc) ctmarkers_motif <- dplyr::filter( markers_motifs, motif.group == celltype, motif.padj < padj.cutoff, motif.logFC > 0) %>% arrange(-motif.auc) top_tfs <- inner_join( x = ctmarkers_rna[, c(2, 11, 6, 7)], y = ctmarkers_motif[, c(2, 1, 11, 6, 7)], by = "gene" ) top_tfs$avg_auc <- (top_tfs$RNA.auc + top_tfs$motif.auc) / 2 top_tfs <- arrange(top_tfs, -avg_auc) return(top_tfs) }We can now compute, and visualize, putative regulators for any cell type. We recover well-established regulators, including TBX21 for NK cells, IRF4 for plasma cells, SOX4 for hematopoietic progenitors, EBF1 and PAX5 for B cells, IRF8 and TCF4 for pDC. We believe that similar strategies can be used to help focus on a set of putative regulators in diverse systems. # identify top markers in NK and visualize head(topTFs("NK"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 NK TBX21 0.7270859 0.000000e+00 NK MA0690.1 0.9139614 ## 2 NK EOMES 0.5886774 2.411013e-98 NK MA0800.1 0.9214773 ## 3 NK RUNX3 0.7705661 5.977716e-120 NK MA0684.2 0.6769022 ## motif.pval avg_auc ## 1 1.097940e-202 0.8205237 ## 2 4.903866e-210 0.7550774 ## 3 1.560061e-38 0.7237341 motif.name <- ConvertMotifID(pbmc, name = 'TBX21') gene_plot <- FeaturePlot(pbmc, features = "sct_TBX21", reduction = 'wnn.umap') motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap') gene_plot | motif_plot # identify top markers in pDC and visualize head(topTFs("pDC"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 pDC TCF4 0.9998815 1.120711e-162 pDC MA0830.2 0.9965481 ## 2 pDC IRF8 0.9904457 1.308164e-123 pDC MA0652.1 0.8833112 ## 3 pDC SPIB 0.9115207 0.000000e+00 pDC MA0081.2 0.9068540 ## motif.pval avg_auc ## 1 1.785897e-69 0.9982148 ## 2 3.982413e-42 0.9368785 ## 3 3.083509e-47 0.9091874 motif.name <- ConvertMotifID(pbmc, name = 'TCF4') gene_plot <- FeaturePlot(pbmc, features = "sct_TCF4", reduction = 'wnn.umap') motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap') gene_plot | motif_plot # identify top markers in HSPC and visualize head(topTFs("CD16 Mono"),3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 CD16 Mono SPI1 0.8793172 1.666810e-296 CD16 Mono MA0080.5 0.8880908 ## 2 CD16 Mono CEBPB 0.8685933 1.625472e-294 CD16 Mono MA0466.2 0.7840422 ## 3 CD16 Mono MEF2C 0.7129910 2.727252e-79 CD16 Mono MA0497.1 0.8059373 ## motif.pval avg_auc ## 1 4.762491e-194 0.8837040 ## 2 7.049764e-105 0.8263177 ## 3 2.345716e-121 0.7594641 motif.name <- ConvertMotifID(pbmc, name = 'SPI1') gene_plot <- FeaturePlot(pbmc, features = "sct_SPI1", reduction = 'wnn.umap') motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap') gene_plot | motif_plot # identify top markers in other cell types head(topTFs("Naive B"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 Naive B MEF2C 0.8802747 1.890065e-182 Naive B MA0497.1 0.6789079 ## 2 Naive B PAX5 0.9436648 0.000000e+00 Naive B MA0014.3 0.5827061 ## 3 Naive B POU2F2 0.6029377 2.892216e-13 Naive B MA0507.1 0.8912268 ## motif.pval avg_auc ## 1 9.815118e-32 0.7795913 ## 2 5.995185e-08 0.7631854 ## 3 6.471677e-145 0.7470822 head(topTFs("HSPC"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 HSPC SOX4 0.9869406 5.524832e-71 HSPC MA0867.2 0.6830497 ## 2 HSPC GATA2 0.7884615 0.000000e+00 HSPC MA0036.3 0.8275008 ## 3 HSPC MEIS1 0.8638496 0.000000e+00 HSPC MA0498.2 0.6924225 ## motif.pval avg_auc ## 1 1.241915e-03 0.8349951 ## 2 7.591798e-09 0.8079812 ## 3 6.877492e-04 0.7781361 head(topTFs("Plasma"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 Plasma IRF4 0.8189687 5.261955e-35 Plasma MA1419.1 0.9776046 ## 2 Plasma MEF2C 0.9111213 2.977155e-12 Plasma MA0497.1 0.7596637 ## 3 Plasma TCF4 0.8049409 6.810635e-12 Plasma MA0830.2 0.7840848 ## motif.pval avg_auc ## 1 2.334627e-12 0.8982867 ## 2 1.374353e-04 0.8353925 ## 3 3.028306e-05 0.7945129Session Info sessionInfo()## R version 4.2.0 (2022-04-22) ## Platform: x86_64-pc-linux-gnu (64-bit) ## Running under: Ubuntu 20.04.5 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/liblapack.so.3 ## ## locale: ## [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C ## [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8 ## [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 ## ## attached base packages: ## [1] stats4 stats graphics grDevices utils datasets methods ## [8] base ## ## other attached packages: ## [1] BSgenome.Hsapiens.UCSC.hg38_1.4.5 BSgenome_1.66.3 ## [3] rtracklayer_1.58.0 Biostrings_2.66.0 ## [5] XVector_0.38.0 motifmatchr_1.20.0 ## [7] TFBSTools_1.36.0 JASPAR2020_0.99.10 ## [9] chromVAR_1.20.2 EnsDb.Hsapiens.v86_2.99.0 ## [11] ensembldb_2.22.0 AnnotationFilter_1.22.0 ## [13] GenomicFeatures_1.50.4 AnnotationDbi_1.60.0 ## [15] Biobase_2.58.0 GenomicRanges_1.50.2 ## [17] GenomeInfoDb_1.35.16 IRanges_2.32.0 ## [19] S4Vectors_0.36.2 BiocGenerics_0.44.0 ## [21] Signac_1.9.0 ggplot2_3.4.1 ## [23] dplyr_1.1.1 cowplot_1.1.1 ## [25] thp1.eccite.SeuratData_3.1.5 stxBrain.SeuratData_0.1.1 ## [27] ssHippo.SeuratData_3.1.4 pbmcsca.SeuratData_3.0.0 ## [29] pbmcMultiome.SeuratData_0.1.2 pbmc3k.SeuratData_3.1.4 ## [31] panc8.SeuratData_3.0.2 ifnb.SeuratData_3.1.0 ## [33] hcabm40k.SeuratData_3.0.0 bmcite.SeuratData_0.3.0 ## [35] SeuratData_0.2.2 SeuratObject_4.1.3 ## [37] Seurat_4.2.1.9001 ## ## loaded via a namespace (and not attached): ## [1] rappdirs_0.3.3 scattermore_0.8 ## [3] R.methodsS3_1.8.2 ragg_1.2.5 ## [5] nabor_0.5.0 tidyr_1.3.0 ## [7] bit64_4.0.5 knitr_1.42 ## [9] R.utils_2.12.2 irlba_2.3.5.1 ## [11] DelayedArray_0.24.0 data.table_1.14.8 ## [13] rpart_4.1.16 KEGGREST_1.38.0 ## [15] RCurl_1.98-1.12 generics_0.1.3 ## [17] RSQLite_2.3.0 RANN_2.6.1 ## [19] future_1.32.0 tzdb_0.3.0 ## [21] bit_4.0.5 spatstat.data_3.0-1 ## [23] xml2_1.3.3 httpuv_1.6.9 ## [25] SummarizedExperiment_1.28.0 DirichletMultinomial_1.40.0 ## [27] xfun_0.38 hms_1.1.2 ## [29] jquerylib_0.1.4 evaluate_0.20 ## [31] promises_1.2.0.1 fansi_1.0.4 ## [33] restfulr_0.0.15 progress_1.2.2 ## [35] caTools_1.18.2 dbplyr_2.3.1 ## [37] igraph_1.4.1 DBI_1.1.3 ## [39] htmlwidgets_1.6.2 spatstat.geom_3.1-0 ## [41] purrr_1.0.1 ellipsis_0.3.2 ## [43] backports_1.4.1 annotate_1.76.0 ## [45] biomaRt_2.54.0 deldir_1.0-6 ## [47] MatrixGenerics_1.10.0 vctrs_0.6.1 ## [49] ROCR_1.0-11 abind_1.4-5 ## [51] cachem_1.0.7 withr_2.5.0 ## [53] progressr_0.13.0 presto_1.0.0 ## [55] checkmate_2.1.0 sctransform_0.3.5 ## [57] GenomicAlignments_1.34.0 prettyunits_1.1.1 ## [59] goftest_1.2-3 cluster_2.1.3 ## [61] seqLogo_1.64.0 lazyeval_0.2.2 ## [63] crayon_1.5.2 hdf5r_1.3.8 ## [65] spatstat.explore_3.1-0 pkgconfig_2.0.3 ## [67] labeling_0.4.2 nlme_3.1-157 ## [69] ProtGenerics_1.30.0 nnet_7.3-17 ## [71] rlang_1.1.0 globals_0.16.2 ## [73] lifecycle_1.0.3 miniUI_0.1.1.1 ## [75] filelock_1.0.2 BiocFileCache_2.6.1 ## [77] dichromat_2.0-0.1 rprojroot_2.0.3 ## [79] polyclip_1.10-4 matrixStats_0.63.0 ## [81] lmtest_0.9-40 Matrix_1.5-3 ## [83] zoo_1.8-11 base64enc_0.1-3 ## [85] ggridges_0.5.4 png_0.1-8 ## [87] viridisLite_0.4.1 rjson_0.2.21 ## [89] bitops_1.0-7 R.oo_1.25.0 ## [91] KernSmooth_2.23-20 blob_1.2.3 ## [93] stringr_1.5.0 parallelly_1.35.0 ## [95] spatstat.random_3.1-4 readr_2.1.4 ## [97] jpeg_0.1-10 CNEr_1.34.0 ## [99] scales_1.2.1 memoise_2.0.1 ## [101] magrittr_2.0.3 plyr_1.8.8 ## [103] ica_1.0-3 zlibbioc_1.44.0 ## [105] compiler_4.2.0 BiocIO_1.8.0 ## [107] RColorBrewer_1.1-3 fitdistrplus_1.1-8 ## [109] Rsamtools_2.14.0 cli_3.6.1 ## [111] listenv_0.9.0 patchwork_1.1.2 ## [113] pbapply_1.7-0 htmlTable_2.4.1 ## [115] Formula_1.2-5 MASS_7.3-56 ## [117] tidyselect_1.2.0 stringi_1.7.12 ## [119] textshaping_0.3.6 highr_0.10 ## [121] yaml_2.3.7 latticeExtra_0.6-30 ## [123] ggrepel_0.9.3 grid_4.2.0 ## [125] sass_0.4.5 VariantAnnotation_1.44.1 ## [127] fastmatch_1.1-3 tools_4.2.0 ## [129] future.apply_1.10.0 parallel_4.2.0 ## [131] rstudioapi_0.14 TFMPvalue_0.0.9 ## [133] foreign_0.8-82 gridExtra_2.3 ## [135] farver_2.1.1 Rtsne_0.16 ## [137] digest_0.6.31 pracma_2.4.2 ## [139] shiny_1.7.4 Rcpp_1.0.10 ## [141] later_1.3.0 RcppAnnoy_0.0.20 ## [143] httr_1.4.5 biovizBase_1.46.0 ## [145] colorspace_2.1-0 XML_3.99-0.13 ## [147] fs_1.6.1 tensor_1.5 ## [149] reticulate_1.28 splines_4.2.0 ## [151] uwot_0.1.14 RcppRoll_0.3.0 ## [153] spatstat.utils_3.0-2 pkgdown_2.0.7 ## [155] sp_1.6-0 plotly_4.10.1 ## [157] systemfonts_1.0.4 xtable_1.8-4 ## [159] poweRlaw_0.70.6 jsonlite_1.8.4 ## [161] R6_2.5.1 Hmisc_4.8-0 ## [163] pillar_1.9.0 htmltools_0.5.5 ## [165] mime_0.12 DT_0.27 ## [167] glue_1.6.2 fastmap_1.1.1 ## [169] BiocParallel_1.32.5 codetools_0.2-18 ## [171] utf8_1.2.3 lattice_0.20-45 ## [173] bslib_0.4.2 spatstat.sparse_3.0-1 ## [175] tibble_3.2.1 curl_5.0.0 ## [177] leiden_0.4.3 gtools_3.9.4 ## [179] GO.db_3.16.0 interp_1.1-3 ## [181] survival_3.3-1 rmarkdown_2.21 ## [183] desc_1.4.2 munsell_0.5.0 ## [185] GenomeInfoDbData_1.2.9 reshape2_1.4.4 ## [187] gtable_0.3.3

We annotate the clusters below. Note that you could also annotate the dataset using our supervised mapping pipelines, using either our vignette, or automated web tool, Azimuth. # perform sub-clustering on cluster 6 to find additional structure pbmc <- FindSubCluster(pbmc, cluster = 6, graph.name = "wsnn", algorithm = 3) Idents(pbmc) <- "sub.cluster" # add annotations pbmc <- RenameIdents(pbmc, '19' = 'pDC','20' = 'HSPC','15' = 'cDC') pbmc <- RenameIdents(pbmc, '0' = 'CD14 Mono', '9' ='CD14 Mono', '5' = 'CD16 Mono') pbmc <- RenameIdents(pbmc, '10' = 'Naive B', '11' = 'Intermediate B', '17' = 'Memory B', '21' = 'Plasma') pbmc <- RenameIdents(pbmc, '7' = 'NK') pbmc <- RenameIdents(pbmc, '4' = 'CD4 TCM', '13'= "CD4 TEM", '3' = "CD4 TCM", '16' ="Treg", '1' ="CD4 Naive", '14' = "CD4 Naive") pbmc <- RenameIdents(pbmc, '2' = 'CD8 Naive', '8'= "CD8 Naive", '12' = 'CD8 TEM_1', '6_0' = 'CD8 TEM_2', '6_1' ='CD8 TEM_2', '6_4' ='CD8 TEM_2') pbmc <- RenameIdents(pbmc, '18' = 'MAIT') pbmc <- RenameIdents(pbmc, '6_2' ='gdT', '6_3' = 'gdT') pbmc$celltype <- Idents(pbmc)We can visualize clustering based on gene expression, ATAC-seq, or WNN analysis. The differences are more subtle than in the previous analysis (you can explore the weights, which are more evenly split than in our CITE-seq example), but we find that WNN provides the clearest separation of cell states. p1 <- DimPlot(pbmc, reduction = "umap.rna", group.by = "celltype", label = TRUE, label.size = 2.5, repel = TRUE) + ggtitle("RNA") p2 <- DimPlot(pbmc, reduction = "umap.atac", group.by = "celltype", label = TRUE, label.size = 2.5, repel = TRUE) + ggtitle("ATAC") p3 <- DimPlot(pbmc, reduction = "wnn.umap", group.by = "celltype", label = TRUE, label.size = 2.5, repel = TRUE) + ggtitle("WNN") p1 + p2 + p3 & NoLegend() & theme(plot.title = element_text(hjust = 0.5))For example, the ATAC-seq data assists in the separation of CD4 and CD8 T cell states. This is due to the presence of multiple loci that exhibit differential accessibility between different T cell subtypes. For example, we can visualize ‘pseudobulk’ tracks of the CD8A locus alongside violin plots of gene expression levels, using tools in the Signac visualization vignette. ## to make the visualization easier, subset T cell clusters celltype.names <- levels(pbmc) tcell.names <- grep("CD4|CD8|Treg", celltype.names,value = TRUE) tcells <- subset(pbmc, idents = tcell.names) CoveragePlot(tcells, region = 'CD8A', features = 'CD8A', assay = 'ATAC', expression.assay = 'SCT', peaks = FALSE)Next, we will examine the accessible regions of each cell to determine enriched motifs. As described in the Signac motifs vignette, there are a few ways to do this, but we will use the chromVAR package from the Greenleaf lab. This calculates a per-cell accessibility score for known motifs, and adds these scores as a third assay (chromvar) in the Seurat object.To continue, please make sure you have the following packages installed.chromVAR for the analysis of motif accessibility in scATAC-seqpresto for fast differential expression analyses.TFBSTools for TFBS analysisJASPAR2020 for JASPAR motif modelsmotifmatchr for motif matchingBSgenome.Hsapiens.UCSC.hg38 for chromVARInstall command for all dependencies remotes::install_github("immunogenomics/presto") BiocManager::install(c("chromVAR", "TFBSTools", "JASPAR2020", "motifmatchr", "BSgenome.Hsapiens.UCSC.hg38")) library(chromVAR) library(JASPAR2020) library(TFBSTools) library(motifmatchr) library(BSgenome.Hsapiens.UCSC.hg38) # Scan the DNA sequence of each peak for the presence of each motif, and create a Motif object DefaultAssay(pbmc) <- "ATAC" pwm_set <- getMatrixSet(x = JASPAR2020, opts = list(species = 9606, all_versions = FALSE)) motif.matrix <- CreateMotifMatrix(features = granges(pbmc), pwm = pwm_set, genome = 'hg38', use.counts = FALSE) motif.object <- CreateMotifObject(data = motif.matrix, pwm = pwm_set) pbmc <- SetAssayData(pbmc, assay = 'ATAC', slot = 'motifs', new.data = motif.object) # Note that this step can take 30-60 minutes pbmc <- RunChromVAR( object = pbmc, genome = BSgenome.Hsapiens.UCSC.hg38 )Finally, we explore the multimodal dataset to identify key regulators of each cell state. Paired data provides a unique opportunity to identify transcription factors (TFs) that satisfy multiple criteria, helping to narrow down the list of putative regulators to the most likely candidates. We aim to identify TFs whose expression is enriched in multiple cell types in the RNA measurements, but also have enriched accessibility for their motifs in the ATAC measurements.As an example and positive control, the CCAAT Enhancer Binding Protein (CEBP) family of proteins, including the TF CEBPB, have been repeatedly shown to play important roles in the differentiation and function of myeloid cells including monocytes and dendritic cells. We can see that both the expression of the CEBPB, and the accessibility of the MA0466.2.4 motif (which encodes the binding site for CEBPB), are both enriched in monocytes. #returns MA0466.2 motif.name <- ConvertMotifID(pbmc, name = 'CEBPB') gene_plot <- FeaturePlot(pbmc, features = "sct_CEBPB", reduction = 'wnn.umap') motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap') gene_plot | motif_plotWe’d like to quantify this relationship, and search across all cell types to find similar examples. To do so, we will use the presto package to perform fast differential expression. We run two tests: one using gene expression data, and the other using chromVAR motif accessibilities. presto calculates a p-value based on the Wilcox rank sum test, which is also the default test in Seurat, and we restrict our search to TFs that return significant results in both tests.presto also calculates an “AUC” statistic, which reflects the power of each gene (or motif) to serve as a marker of cell type. A maximum AUC value of 1 indicates a perfect marker. Since the AUC statistic is on the same scale for both genes and motifs, we take the average of the AUC values from the two tests, and use this to rank TFs for each cell type: markers_rna <- presto:::wilcoxauc.Seurat(X = pbmc, group_by = 'celltype', assay = 'data', seurat_assay = 'SCT') markers_motifs <- presto:::wilcoxauc.Seurat(X = pbmc, group_by = 'celltype', assay = 'data', seurat_assay = 'chromvar') motif.names <- markers_motifs$feature colnames(markers_rna) <- paste0("RNA.", colnames(markers_rna)) colnames(markers_motifs) <- paste0("motif.", colnames(markers_motifs)) markers_rna$gene <- markers_rna$RNA.feature markers_motifs$gene <- ConvertMotifID(pbmc, id = motif.names) # a simple function to implement the procedure above topTFs <- function(celltype, padj.cutoff = 1e-2) { ctmarkers_rna <- dplyr::filter( markers_rna, RNA.group == celltype, RNA.padj < padj.cutoff, RNA.logFC > 0) %>% arrange(-RNA.auc) ctmarkers_motif <- dplyr::filter( markers_motifs, motif.group == celltype, motif.padj < padj.cutoff, motif.logFC > 0) %>% arrange(-motif.auc) top_tfs <- inner_join( x = ctmarkers_rna[, c(2, 11, 6, 7)], y = ctmarkers_motif[, c(2, 1, 11, 6, 7)], by = "gene" ) top_tfs$avg_auc <- (top_tfs$RNA.auc + top_tfs$motif.auc) / 2 top_tfs <- arrange(top_tfs, -avg_auc) return(top_tfs) }We can now compute, and visualize, putative regulators for any cell type. We recover well-established regulators, including TBX21 for NK cells, IRF4 for plasma cells, SOX4 for hematopoietic progenitors, EBF1 and PAX5 for B cells, IRF8 and TCF4 for pDC. We believe that similar strategies can be used to help focus on a set of putative regulators in diverse systems. # identify top markers in NK and visualize head(topTFs("NK"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 NK TBX21 0.7270859 0.000000e+00 NK MA0690.1 0.9139614 ## 2 NK EOMES 0.5886774 2.411013e-98 NK MA0800.1 0.9214773 ## 3 NK RUNX3 0.7705661 5.977716e-120 NK MA0684.2 0.6769022 ## motif.pval avg_auc ## 1 1.097940e-202 0.8205237 ## 2 4.903866e-210 0.7550774 ## 3 1.560061e-38 0.7237341 motif.name <- ConvertMotifID(pbmc, name = 'TBX21') gene_plot <- FeaturePlot(pbmc, features = "sct_TBX21", reduction = 'wnn.umap') motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap') gene_plot | motif_plot # identify top markers in pDC and visualize head(topTFs("pDC"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 pDC TCF4 0.9998815 1.120711e-162 pDC MA0830.2 0.9965481 ## 2 pDC IRF8 0.9904457 1.308164e-123 pDC MA0652.1 0.8833112 ## 3 pDC SPIB 0.9115207 0.000000e+00 pDC MA0081.2 0.9068540 ## motif.pval avg_auc ## 1 1.785897e-69 0.9982148 ## 2 3.982413e-42 0.9368785 ## 3 3.083509e-47 0.9091874 motif.name <- ConvertMotifID(pbmc, name = 'TCF4') gene_plot <- FeaturePlot(pbmc, features = "sct_TCF4", reduction = 'wnn.umap') motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap') gene_plot | motif_plot # identify top markers in HSPC and visualize head(topTFs("CD16 Mono"),3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 CD16 Mono SPI1 0.8793172 1.666810e-296 CD16 Mono MA0080.5 0.8880908 ## 2 CD16 Mono CEBPB 0.8685933 1.625472e-294 CD16 Mono MA0466.2 0.7840422 ## 3 CD16 Mono MEF2C 0.7129910 2.727252e-79 CD16 Mono MA0497.1 0.8059373 ## motif.pval avg_auc ## 1 4.762491e-194 0.8837040 ## 2 7.049764e-105 0.8263177 ## 3 2.345716e-121 0.7594641 motif.name <- ConvertMotifID(pbmc, name = 'SPI1') gene_plot <- FeaturePlot(pbmc, features = "sct_SPI1", reduction = 'wnn.umap') motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap') gene_plot | motif_plot # identify top markers in other cell types head(topTFs("Naive B"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 Naive B MEF2C 0.8802747 1.890065e-182 Naive B MA0497.1 0.6789079 ## 2 Naive B PAX5 0.9436648 0.000000e+00 Naive B MA0014.3 0.5827061 ## 3 Naive B POU2F2 0.6029377 2.892216e-13 Naive B MA0507.1 0.8912268 ## motif.pval avg_auc ## 1 9.815118e-32 0.7795913 ## 2 5.995185e-08 0.7631854 ## 3 6.471677e-145 0.7470822 head(topTFs("HSPC"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 HSPC SOX4 0.9869406 5.524832e-71 HSPC MA0867.2 0.6830497 ## 2 HSPC GATA2 0.7884615 0.000000e+00 HSPC MA0036.3 0.8275008 ## 3 HSPC MEIS1 0.8638496 0.000000e+00 HSPC MA0498.2 0.6924225 ## motif.pval avg_auc ## 1 1.241915e-03 0.8349951 ## 2 7.591798e-09 0.8079812 ## 3 6.877492e-04 0.7781361 head(topTFs("Plasma"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 Plasma IRF4 0.8189687 5.261955e-35 Plasma MA1419.1 0.9776046 ## 2 Plasma MEF2C 0.9111213 2.977155e-12 Plasma MA0497.1 0.7596637 ## 3 Plasma TCF4 0.8049409 6.810635e-12 Plasma MA0830.2 0.7840848 ## motif.pval avg_auc ## 1 2.334627e-12 0.8982867 ## 2 1.374353e-04 0.8353925 ## 3 3.028306e-05 0.7945129Session Info sessionInfo()## R version 4.2.0 (2022-04-22) ## Platform: x86_64-pc-linux-gnu (64-bit) ## Running under: Ubuntu 20.04.5 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/liblapack.so.3 ## ## locale: ## [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C ## [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8 ## [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 ## ## attached base packages: ## [1] stats4 stats graphics grDevices utils datasets methods ## [8] base ## ## other attached packages: ## [1] BSgenome.Hsapiens.UCSC.hg38_1.4.5 BSgenome_1.66.3 ## [3] rtracklayer_1.58.0 Biostrings_2.66.0 ## [5] XVector_0.38.0 motifmatchr_1.20.0 ## [7] TFBSTools_1.36.0 JASPAR2020_0.99.10 ## [9] chromVAR_1.20.2 EnsDb.Hsapiens.v86_2.99.0 ## [11] ensembldb_2.22.0 AnnotationFilter_1.22.0 ## [13] GenomicFeatures_1.50.4 AnnotationDbi_1.60.0 ## [15] Biobase_2.58.0 GenomicRanges_1.50.2 ## [17] GenomeInfoDb_1.35.16 IRanges_2.32.0 ## [19] S4Vectors_0.36.2 BiocGenerics_0.44.0 ## [21] Signac_1.9.0 ggplot2_3.4.1 ## [23] dplyr_1.1.1 cowplot_1.1.1 ## [25] thp1.eccite.SeuratData_3.1.5 stxBrain.SeuratData_0.1.1 ## [27] ssHippo.SeuratData_3.1.4 pbmcsca.SeuratData_3.0.0 ## [29] pbmcMultiome.SeuratData_0.1.2 pbmc3k.SeuratData_3.1.4 ## [31] panc8.SeuratData_3.0.2 ifnb.SeuratData_3.1.0 ## [33] hcabm40k.SeuratData_3.0.0 bmcite.SeuratData_0.3.0 ## [35] SeuratData_0.2.2 SeuratObject_4.1.3 ## [37] Seurat_4.2.1.9001 ## ## loaded via a namespace (and not attached): ## [1] rappdirs_0.3.3 scattermore_0.8 ## [3] R.methodsS3_1.8.2 ragg_1.2.5 ## [5] nabor_0.5.0 tidyr_1.3.0 ## [7] bit64_4.0.5 knitr_1.42 ## [9] R.utils_2.12.2 irlba_2.3.5.1 ## [11] DelayedArray_0.24.0 data.table_1.14.8 ## [13] rpart_4.1.16 KEGGREST_1.38.0 ## [15] RCurl_1.98-1.12 generics_0.1.3 ## [17] RSQLite_2.3.0 RANN_2.6.1 ## [19] future_1.32.0 tzdb_0.3.0 ## [21] bit_4.0.5 spatstat.data_3.0-1 ## [23] xml2_1.3.3 httpuv_1.6.9 ## [25] SummarizedExperiment_1.28.0 DirichletMultinomial_1.40.0 ## [27] xfun_0.38 hms_1.1.2 ## [29] jquerylib_0.1.4 evaluate_0.20 ## [31] promises_1.2.0.1 fansi_1.0.4 ## [33] restfulr_0.0.15 progress_1.2.2 ## [35] caTools_1.18.2 dbplyr_2.3.1 ## [37] igraph_1.4.1 DBI_1.1.3 ## [39] htmlwidgets_1.6.2 spatstat.geom_3.1-0 ## [41] purrr_1.0.1 ellipsis_0.3.2 ## [43] backports_1.4.1 annotate_1.76.0 ## [45] biomaRt_2.54.0 deldir_1.0-6 ## [47] MatrixGenerics_1.10.0 vctrs_0.6.1 ## [49] ROCR_1.0-11 abind_1.4-5 ## [51] cachem_1.0.7 withr_2.5.0 ## [53] progressr_0.13.0 presto_1.0.0 ## [55] checkmate_2.1.0 sctransform_0.3.5 ## [57] GenomicAlignments_1.34.0 prettyunits_1.1.1 ## [59] goftest_1.2-3 cluster_2.1.3 ## [61] seqLogo_1.64.0 lazyeval_0.2.2 ## [63] crayon_1.5.2 hdf5r_1.3.8 ## [65] spatstat.explore_3.1-0 pkgconfig_2.0.3 ## [67] labeling_0.4.2 nlme_3.1-157 ## [69] ProtGenerics_1.30.0 nnet_7.3-17 ## [71] rlang_1.1.0 globals_0.16.2 ## [73] lifecycle_1.0.3 miniUI_0.1.1.1 ## [75] filelock_1.0.2 BiocFileCache_2.6.1 ## [77] dichromat_2.0-0.1 rprojroot_2.0.3 ## [79] polyclip_1.10-4 matrixStats_0.63.0 ## [81] lmtest_0.9-40 Matrix_1.5-3 ## [83] zoo_1.8-11 base64enc_0.1-3 ## [85] ggridges_0.5.4 png_0.1-8 ## [87] viridisLite_0.4.1 rjson_0.2.21 ## [89] bitops_1.0-7 R.oo_1.25.0 ## [91] KernSmooth_2.23-20 blob_1.2.3 ## [93] stringr_1.5.0 parallelly_1.35.0 ## [95] spatstat.random_3.1-4 readr_2.1.4 ## [97] jpeg_0.1-10 CNEr_1.34.0 ## [99] scales_1.2.1 memoise_2.0.1 ## [101] magrittr_2.0.3 plyr_1.8.8 ## [103] ica_1.0-3 zlibbioc_1.44.0 ## [105] compiler_4.2.0 BiocIO_1.8.0 ## [107] RColorBrewer_1.1-3 fitdistrplus_1.1-8 ## [109] Rsamtools_2.14.0 cli_3.6.1 ## [111] listenv_0.9.0 patchwork_1.1.2 ## [113] pbapply_1.7-0 htmlTable_2.4.1 ## [115] Formula_1.2-5 MASS_7.3-56 ## [117] tidyselect_1.2.0 stringi_1.7.12 ## [119] textshaping_0.3.6 highr_0.10 ## [121] yaml_2.3.7 latticeExtra_0.6-30 ## [123] ggrepel_0.9.3 grid_4.2.0 ## [125] sass_0.4.5 VariantAnnotation_1.44.1 ## [127] fastmatch_1.1-3 tools_4.2.0 ## [129] future.apply_1.10.0 parallel_4.2.0 ## [131] rstudioapi_0.14 TFMPvalue_0.0.9 ## [133] foreign_0.8-82 gridExtra_2.3 ## [135] farver_2.1.1 Rtsne_0.16 ## [137] digest_0.6.31 pracma_2.4.2 ## [139] shiny_1.7.4 Rcpp_1.0.10 ## [141] later_1.3.0 RcppAnnoy_0.0.20 ## [143] httr_1.4.5 biovizBase_1.46.0 ## [145] colorspace_2.1-0 XML_3.99-0.13 ## [147] fs_1.6.1 tensor_1.5 ## [149] reticulate_1.28 splines_4.2.0 ## [151] uwot_0.1.14 RcppRoll_0.3.0 ## [153] spatstat.utils_3.0-2 pkgdown_2.0.7 ## [155] sp_1.6-0 plotly_4.10.1 ## [157] systemfonts_1.0.4 xtable_1.8-4 ## [159] poweRlaw_0.70.6 jsonlite_1.8.4 ## [161] R6_2.5.1 Hmisc_4.8-0 ## [163] pillar_1.9.0 htmltools_0.5.5 ## [165] mime_0.12 DT_0.27 ## [167] glue_1.6.2 fastmap_1.1.1 ## [169] BiocParallel_1.32.5 codetools_0.2-18 ## [171] utf8_1.2.3 lattice_0.20-45 ## [173] bslib_0.4.2 spatstat.sparse_3.0-1 ## [175] tibble_3.2.1 curl_5.0.0 ## [177] leiden_0.4.3 gtools_3.9.4 ## [179] GO.db_3.16.0 interp_1.1-3 ## [181] survival_3.3-1 rmarkdown_2.21 ## [183] desc_1.4.2 munsell_0.5.0 ## [185] GenomeInfoDbData_1.2.9 reshape2_1.4.4 ## [187] gtable_0.3.3

We can visualize clustering based on gene expression, ATAC-seq, or WNN analysis. The differences are more subtle than in the previous analysis (you can explore the weights, which are more evenly split than in our CITE-seq example), but we find that WNN provides the clearest separation of cell states. p1 <- DimPlot(pbmc, reduction = "umap.rna", group.by = "celltype", label = TRUE, label.size = 2.5, repel = TRUE) + ggtitle("RNA") p2 <- DimPlot(pbmc, reduction = "umap.atac", group.by = "celltype", label = TRUE, label.size = 2.5, repel = TRUE) + ggtitle("ATAC") p3 <- DimPlot(pbmc, reduction = "wnn.umap", group.by = "celltype", label = TRUE, label.size = 2.5, repel = TRUE) + ggtitle("WNN") p1 + p2 + p3 & NoLegend() & theme(plot.title = element_text(hjust = 0.5))For example, the ATAC-seq data assists in the separation of CD4 and CD8 T cell states. This is due to the presence of multiple loci that exhibit differential accessibility between different T cell subtypes. For example, we can visualize ‘pseudobulk’ tracks of the CD8A locus alongside violin plots of gene expression levels, using tools in the Signac visualization vignette. ## to make the visualization easier, subset T cell clusters celltype.names <- levels(pbmc) tcell.names <- grep("CD4|CD8|Treg", celltype.names,value = TRUE) tcells <- subset(pbmc, idents = tcell.names) CoveragePlot(tcells, region = 'CD8A', features = 'CD8A', assay = 'ATAC', expression.assay = 'SCT', peaks = FALSE)Next, we will examine the accessible regions of each cell to determine enriched motifs. As described in the Signac motifs vignette, there are a few ways to do this, but we will use the chromVAR package from the Greenleaf lab. This calculates a per-cell accessibility score for known motifs, and adds these scores as a third assay (chromvar) in the Seurat object.To continue, please make sure you have the following packages installed.chromVAR for the analysis of motif accessibility in scATAC-seqpresto for fast differential expression analyses.TFBSTools for TFBS analysisJASPAR2020 for JASPAR motif modelsmotifmatchr for motif matchingBSgenome.Hsapiens.UCSC.hg38 for chromVARInstall command for all dependencies remotes::install_github("immunogenomics/presto") BiocManager::install(c("chromVAR", "TFBSTools", "JASPAR2020", "motifmatchr", "BSgenome.Hsapiens.UCSC.hg38")) library(chromVAR) library(JASPAR2020) library(TFBSTools) library(motifmatchr) library(BSgenome.Hsapiens.UCSC.hg38) # Scan the DNA sequence of each peak for the presence of each motif, and create a Motif object DefaultAssay(pbmc) <- "ATAC" pwm_set <- getMatrixSet(x = JASPAR2020, opts = list(species = 9606, all_versions = FALSE)) motif.matrix <- CreateMotifMatrix(features = granges(pbmc), pwm = pwm_set, genome = 'hg38', use.counts = FALSE) motif.object <- CreateMotifObject(data = motif.matrix, pwm = pwm_set) pbmc <- SetAssayData(pbmc, assay = 'ATAC', slot = 'motifs', new.data = motif.object) # Note that this step can take 30-60 minutes pbmc <- RunChromVAR( object = pbmc, genome = BSgenome.Hsapiens.UCSC.hg38 )Finally, we explore the multimodal dataset to identify key regulators of each cell state. Paired data provides a unique opportunity to identify transcription factors (TFs) that satisfy multiple criteria, helping to narrow down the list of putative regulators to the most likely candidates. We aim to identify TFs whose expression is enriched in multiple cell types in the RNA measurements, but also have enriched accessibility for their motifs in the ATAC measurements.As an example and positive control, the CCAAT Enhancer Binding Protein (CEBP) family of proteins, including the TF CEBPB, have been repeatedly shown to play important roles in the differentiation and function of myeloid cells including monocytes and dendritic cells. We can see that both the expression of the CEBPB, and the accessibility of the MA0466.2.4 motif (which encodes the binding site for CEBPB), are both enriched in monocytes. #returns MA0466.2 motif.name <- ConvertMotifID(pbmc, name = 'CEBPB') gene_plot <- FeaturePlot(pbmc, features = "sct_CEBPB", reduction = 'wnn.umap') motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap') gene_plot | motif_plotWe’d like to quantify this relationship, and search across all cell types to find similar examples. To do so, we will use the presto package to perform fast differential expression. We run two tests: one using gene expression data, and the other using chromVAR motif accessibilities. presto calculates a p-value based on the Wilcox rank sum test, which is also the default test in Seurat, and we restrict our search to TFs that return significant results in both tests.presto also calculates an “AUC” statistic, which reflects the power of each gene (or motif) to serve as a marker of cell type. A maximum AUC value of 1 indicates a perfect marker. Since the AUC statistic is on the same scale for both genes and motifs, we take the average of the AUC values from the two tests, and use this to rank TFs for each cell type: markers_rna <- presto:::wilcoxauc.Seurat(X = pbmc, group_by = 'celltype', assay = 'data', seurat_assay = 'SCT') markers_motifs <- presto:::wilcoxauc.Seurat(X = pbmc, group_by = 'celltype', assay = 'data', seurat_assay = 'chromvar') motif.names <- markers_motifs$feature colnames(markers_rna) <- paste0("RNA.", colnames(markers_rna)) colnames(markers_motifs) <- paste0("motif.", colnames(markers_motifs)) markers_rna$gene <- markers_rna$RNA.feature markers_motifs$gene <- ConvertMotifID(pbmc, id = motif.names) # a simple function to implement the procedure above topTFs <- function(celltype, padj.cutoff = 1e-2) { ctmarkers_rna <- dplyr::filter( markers_rna, RNA.group == celltype, RNA.padj < padj.cutoff, RNA.logFC > 0) %>% arrange(-RNA.auc) ctmarkers_motif <- dplyr::filter( markers_motifs, motif.group == celltype, motif.padj < padj.cutoff, motif.logFC > 0) %>% arrange(-motif.auc) top_tfs <- inner_join( x = ctmarkers_rna[, c(2, 11, 6, 7)], y = ctmarkers_motif[, c(2, 1, 11, 6, 7)], by = "gene" ) top_tfs$avg_auc <- (top_tfs$RNA.auc + top_tfs$motif.auc) / 2 top_tfs <- arrange(top_tfs, -avg_auc) return(top_tfs) }We can now compute, and visualize, putative regulators for any cell type. We recover well-established regulators, including TBX21 for NK cells, IRF4 for plasma cells, SOX4 for hematopoietic progenitors, EBF1 and PAX5 for B cells, IRF8 and TCF4 for pDC. We believe that similar strategies can be used to help focus on a set of putative regulators in diverse systems. # identify top markers in NK and visualize head(topTFs("NK"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 NK TBX21 0.7270859 0.000000e+00 NK MA0690.1 0.9139614 ## 2 NK EOMES 0.5886774 2.411013e-98 NK MA0800.1 0.9214773 ## 3 NK RUNX3 0.7705661 5.977716e-120 NK MA0684.2 0.6769022 ## motif.pval avg_auc ## 1 1.097940e-202 0.8205237 ## 2 4.903866e-210 0.7550774 ## 3 1.560061e-38 0.7237341 motif.name <- ConvertMotifID(pbmc, name = 'TBX21') gene_plot <- FeaturePlot(pbmc, features = "sct_TBX21", reduction = 'wnn.umap') motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap') gene_plot | motif_plot # identify top markers in pDC and visualize head(topTFs("pDC"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 pDC TCF4 0.9998815 1.120711e-162 pDC MA0830.2 0.9965481 ## 2 pDC IRF8 0.9904457 1.308164e-123 pDC MA0652.1 0.8833112 ## 3 pDC SPIB 0.9115207 0.000000e+00 pDC MA0081.2 0.9068540 ## motif.pval avg_auc ## 1 1.785897e-69 0.9982148 ## 2 3.982413e-42 0.9368785 ## 3 3.083509e-47 0.9091874 motif.name <- ConvertMotifID(pbmc, name = 'TCF4') gene_plot <- FeaturePlot(pbmc, features = "sct_TCF4", reduction = 'wnn.umap') motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap') gene_plot | motif_plot # identify top markers in HSPC and visualize head(topTFs("CD16 Mono"),3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 CD16 Mono SPI1 0.8793172 1.666810e-296 CD16 Mono MA0080.5 0.8880908 ## 2 CD16 Mono CEBPB 0.8685933 1.625472e-294 CD16 Mono MA0466.2 0.7840422 ## 3 CD16 Mono MEF2C 0.7129910 2.727252e-79 CD16 Mono MA0497.1 0.8059373 ## motif.pval avg_auc ## 1 4.762491e-194 0.8837040 ## 2 7.049764e-105 0.8263177 ## 3 2.345716e-121 0.7594641 motif.name <- ConvertMotifID(pbmc, name = 'SPI1') gene_plot <- FeaturePlot(pbmc, features = "sct_SPI1", reduction = 'wnn.umap') motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap') gene_plot | motif_plot # identify top markers in other cell types head(topTFs("Naive B"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 Naive B MEF2C 0.8802747 1.890065e-182 Naive B MA0497.1 0.6789079 ## 2 Naive B PAX5 0.9436648 0.000000e+00 Naive B MA0014.3 0.5827061 ## 3 Naive B POU2F2 0.6029377 2.892216e-13 Naive B MA0507.1 0.8912268 ## motif.pval avg_auc ## 1 9.815118e-32 0.7795913 ## 2 5.995185e-08 0.7631854 ## 3 6.471677e-145 0.7470822 head(topTFs("HSPC"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 HSPC SOX4 0.9869406 5.524832e-71 HSPC MA0867.2 0.6830497 ## 2 HSPC GATA2 0.7884615 0.000000e+00 HSPC MA0036.3 0.8275008 ## 3 HSPC MEIS1 0.8638496 0.000000e+00 HSPC MA0498.2 0.6924225 ## motif.pval avg_auc ## 1 1.241915e-03 0.8349951 ## 2 7.591798e-09 0.8079812 ## 3 6.877492e-04 0.7781361 head(topTFs("Plasma"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 Plasma IRF4 0.8189687 5.261955e-35 Plasma MA1419.1 0.9776046 ## 2 Plasma MEF2C 0.9111213 2.977155e-12 Plasma MA0497.1 0.7596637 ## 3 Plasma TCF4 0.8049409 6.810635e-12 Plasma MA0830.2 0.7840848 ## motif.pval avg_auc ## 1 2.334627e-12 0.8982867 ## 2 1.374353e-04 0.8353925 ## 3 3.028306e-05 0.7945129Session Info sessionInfo()## R version 4.2.0 (2022-04-22) ## Platform: x86_64-pc-linux-gnu (64-bit) ## Running under: Ubuntu 20.04.5 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/liblapack.so.3 ## ## locale: ## [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C ## [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8 ## [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 ## ## attached base packages: ## [1] stats4 stats graphics grDevices utils datasets methods ## [8] base ## ## other attached packages: ## [1] BSgenome.Hsapiens.UCSC.hg38_1.4.5 BSgenome_1.66.3 ## [3] rtracklayer_1.58.0 Biostrings_2.66.0 ## [5] XVector_0.38.0 motifmatchr_1.20.0 ## [7] TFBSTools_1.36.0 JASPAR2020_0.99.10 ## [9] chromVAR_1.20.2 EnsDb.Hsapiens.v86_2.99.0 ## [11] ensembldb_2.22.0 AnnotationFilter_1.22.0 ## [13] GenomicFeatures_1.50.4 AnnotationDbi_1.60.0 ## [15] Biobase_2.58.0 GenomicRanges_1.50.2 ## [17] GenomeInfoDb_1.35.16 IRanges_2.32.0 ## [19] S4Vectors_0.36.2 BiocGenerics_0.44.0 ## [21] Signac_1.9.0 ggplot2_3.4.1 ## [23] dplyr_1.1.1 cowplot_1.1.1 ## [25] thp1.eccite.SeuratData_3.1.5 stxBrain.SeuratData_0.1.1 ## [27] ssHippo.SeuratData_3.1.4 pbmcsca.SeuratData_3.0.0 ## [29] pbmcMultiome.SeuratData_0.1.2 pbmc3k.SeuratData_3.1.4 ## [31] panc8.SeuratData_3.0.2 ifnb.SeuratData_3.1.0 ## [33] hcabm40k.SeuratData_3.0.0 bmcite.SeuratData_0.3.0 ## [35] SeuratData_0.2.2 SeuratObject_4.1.3 ## [37] Seurat_4.2.1.9001 ## ## loaded via a namespace (and not attached): ## [1] rappdirs_0.3.3 scattermore_0.8 ## [3] R.methodsS3_1.8.2 ragg_1.2.5 ## [5] nabor_0.5.0 tidyr_1.3.0 ## [7] bit64_4.0.5 knitr_1.42 ## [9] R.utils_2.12.2 irlba_2.3.5.1 ## [11] DelayedArray_0.24.0 data.table_1.14.8 ## [13] rpart_4.1.16 KEGGREST_1.38.0 ## [15] RCurl_1.98-1.12 generics_0.1.3 ## [17] RSQLite_2.3.0 RANN_2.6.1 ## [19] future_1.32.0 tzdb_0.3.0 ## [21] bit_4.0.5 spatstat.data_3.0-1 ## [23] xml2_1.3.3 httpuv_1.6.9 ## [25] SummarizedExperiment_1.28.0 DirichletMultinomial_1.40.0 ## [27] xfun_0.38 hms_1.1.2 ## [29] jquerylib_0.1.4 evaluate_0.20 ## [31] promises_1.2.0.1 fansi_1.0.4 ## [33] restfulr_0.0.15 progress_1.2.2 ## [35] caTools_1.18.2 dbplyr_2.3.1 ## [37] igraph_1.4.1 DBI_1.1.3 ## [39] htmlwidgets_1.6.2 spatstat.geom_3.1-0 ## [41] purrr_1.0.1 ellipsis_0.3.2 ## [43] backports_1.4.1 annotate_1.76.0 ## [45] biomaRt_2.54.0 deldir_1.0-6 ## [47] MatrixGenerics_1.10.0 vctrs_0.6.1 ## [49] ROCR_1.0-11 abind_1.4-5 ## [51] cachem_1.0.7 withr_2.5.0 ## [53] progressr_0.13.0 presto_1.0.0 ## [55] checkmate_2.1.0 sctransform_0.3.5 ## [57] GenomicAlignments_1.34.0 prettyunits_1.1.1 ## [59] goftest_1.2-3 cluster_2.1.3 ## [61] seqLogo_1.64.0 lazyeval_0.2.2 ## [63] crayon_1.5.2 hdf5r_1.3.8 ## [65] spatstat.explore_3.1-0 pkgconfig_2.0.3 ## [67] labeling_0.4.2 nlme_3.1-157 ## [69] ProtGenerics_1.30.0 nnet_7.3-17 ## [71] rlang_1.1.0 globals_0.16.2 ## [73] lifecycle_1.0.3 miniUI_0.1.1.1 ## [75] filelock_1.0.2 BiocFileCache_2.6.1 ## [77] dichromat_2.0-0.1 rprojroot_2.0.3 ## [79] polyclip_1.10-4 matrixStats_0.63.0 ## [81] lmtest_0.9-40 Matrix_1.5-3 ## [83] zoo_1.8-11 base64enc_0.1-3 ## [85] ggridges_0.5.4 png_0.1-8 ## [87] viridisLite_0.4.1 rjson_0.2.21 ## [89] bitops_1.0-7 R.oo_1.25.0 ## [91] KernSmooth_2.23-20 blob_1.2.3 ## [93] stringr_1.5.0 parallelly_1.35.0 ## [95] spatstat.random_3.1-4 readr_2.1.4 ## [97] jpeg_0.1-10 CNEr_1.34.0 ## [99] scales_1.2.1 memoise_2.0.1 ## [101] magrittr_2.0.3 plyr_1.8.8 ## [103] ica_1.0-3 zlibbioc_1.44.0 ## [105] compiler_4.2.0 BiocIO_1.8.0 ## [107] RColorBrewer_1.1-3 fitdistrplus_1.1-8 ## [109] Rsamtools_2.14.0 cli_3.6.1 ## [111] listenv_0.9.0 patchwork_1.1.2 ## [113] pbapply_1.7-0 htmlTable_2.4.1 ## [115] Formula_1.2-5 MASS_7.3-56 ## [117] tidyselect_1.2.0 stringi_1.7.12 ## [119] textshaping_0.3.6 highr_0.10 ## [121] yaml_2.3.7 latticeExtra_0.6-30 ## [123] ggrepel_0.9.3 grid_4.2.0 ## [125] sass_0.4.5 VariantAnnotation_1.44.1 ## [127] fastmatch_1.1-3 tools_4.2.0 ## [129] future.apply_1.10.0 parallel_4.2.0 ## [131] rstudioapi_0.14 TFMPvalue_0.0.9 ## [133] foreign_0.8-82 gridExtra_2.3 ## [135] farver_2.1.1 Rtsne_0.16 ## [137] digest_0.6.31 pracma_2.4.2 ## [139] shiny_1.7.4 Rcpp_1.0.10 ## [141] later_1.3.0 RcppAnnoy_0.0.20 ## [143] httr_1.4.5 biovizBase_1.46.0 ## [145] colorspace_2.1-0 XML_3.99-0.13 ## [147] fs_1.6.1 tensor_1.5 ## [149] reticulate_1.28 splines_4.2.0 ## [151] uwot_0.1.14 RcppRoll_0.3.0 ## [153] spatstat.utils_3.0-2 pkgdown_2.0.7 ## [155] sp_1.6-0 plotly_4.10.1 ## [157] systemfonts_1.0.4 xtable_1.8-4 ## [159] poweRlaw_0.70.6 jsonlite_1.8.4 ## [161] R6_2.5.1 Hmisc_4.8-0 ## [163] pillar_1.9.0 htmltools_0.5.5 ## [165] mime_0.12 DT_0.27 ## [167] glue_1.6.2 fastmap_1.1.1 ## [169] BiocParallel_1.32.5 codetools_0.2-18 ## [171] utf8_1.2.3 lattice_0.20-45 ## [173] bslib_0.4.2 spatstat.sparse_3.0-1 ## [175] tibble_3.2.1 curl_5.0.0 ## [177] leiden_0.4.3 gtools_3.9.4 ## [179] GO.db_3.16.0 interp_1.1-3 ## [181] survival_3.3-1 rmarkdown_2.21 ## [183] desc_1.4.2 munsell_0.5.0 ## [185] GenomeInfoDbData_1.2.9 reshape2_1.4.4 ## [187] gtable_0.3.3

For example, the ATAC-seq data assists in the separation of CD4 and CD8 T cell states. This is due to the presence of multiple loci that exhibit differential accessibility between different T cell subtypes. For example, we can visualize ‘pseudobulk’ tracks of the CD8A locus alongside violin plots of gene expression levels, using tools in the Signac visualization vignette. ## to make the visualization easier, subset T cell clusters celltype.names <- levels(pbmc) tcell.names <- grep("CD4|CD8|Treg", celltype.names,value = TRUE) tcells <- subset(pbmc, idents = tcell.names) CoveragePlot(tcells, region = 'CD8A', features = 'CD8A', assay = 'ATAC', expression.assay = 'SCT', peaks = FALSE)Next, we will examine the accessible regions of each cell to determine enriched motifs. As described in the Signac motifs vignette, there are a few ways to do this, but we will use the chromVAR package from the Greenleaf lab. This calculates a per-cell accessibility score for known motifs, and adds these scores as a third assay (chromvar) in the Seurat object.To continue, please make sure you have the following packages installed.chromVAR for the analysis of motif accessibility in scATAC-seqpresto for fast differential expression analyses.TFBSTools for TFBS analysisJASPAR2020 for JASPAR motif modelsmotifmatchr for motif matchingBSgenome.Hsapiens.UCSC.hg38 for chromVARInstall command for all dependencies remotes::install_github("immunogenomics/presto") BiocManager::install(c("chromVAR", "TFBSTools", "JASPAR2020", "motifmatchr", "BSgenome.Hsapiens.UCSC.hg38")) library(chromVAR) library(JASPAR2020) library(TFBSTools) library(motifmatchr) library(BSgenome.Hsapiens.UCSC.hg38) # Scan the DNA sequence of each peak for the presence of each motif, and create a Motif object DefaultAssay(pbmc) <- "ATAC" pwm_set <- getMatrixSet(x = JASPAR2020, opts = list(species = 9606, all_versions = FALSE)) motif.matrix <- CreateMotifMatrix(features = granges(pbmc), pwm = pwm_set, genome = 'hg38', use.counts = FALSE) motif.object <- CreateMotifObject(data = motif.matrix, pwm = pwm_set) pbmc <- SetAssayData(pbmc, assay = 'ATAC', slot = 'motifs', new.data = motif.object) # Note that this step can take 30-60 minutes pbmc <- RunChromVAR( object = pbmc, genome = BSgenome.Hsapiens.UCSC.hg38 )Finally, we explore the multimodal dataset to identify key regulators of each cell state. Paired data provides a unique opportunity to identify transcription factors (TFs) that satisfy multiple criteria, helping to narrow down the list of putative regulators to the most likely candidates. We aim to identify TFs whose expression is enriched in multiple cell types in the RNA measurements, but also have enriched accessibility for their motifs in the ATAC measurements.As an example and positive control, the CCAAT Enhancer Binding Protein (CEBP) family of proteins, including the TF CEBPB, have been repeatedly shown to play important roles in the differentiation and function of myeloid cells including monocytes and dendritic cells. We can see that both the expression of the CEBPB, and the accessibility of the MA0466.2.4 motif (which encodes the binding site for CEBPB), are both enriched in monocytes. #returns MA0466.2 motif.name <- ConvertMotifID(pbmc, name = 'CEBPB') gene_plot <- FeaturePlot(pbmc, features = "sct_CEBPB", reduction = 'wnn.umap') motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap') gene_plot | motif_plotWe’d like to quantify this relationship, and search across all cell types to find similar examples. To do so, we will use the presto package to perform fast differential expression. We run two tests: one using gene expression data, and the other using chromVAR motif accessibilities. presto calculates a p-value based on the Wilcox rank sum test, which is also the default test in Seurat, and we restrict our search to TFs that return significant results in both tests.presto also calculates an “AUC” statistic, which reflects the power of each gene (or motif) to serve as a marker of cell type. A maximum AUC value of 1 indicates a perfect marker. Since the AUC statistic is on the same scale for both genes and motifs, we take the average of the AUC values from the two tests, and use this to rank TFs for each cell type: markers_rna <- presto:::wilcoxauc.Seurat(X = pbmc, group_by = 'celltype', assay = 'data', seurat_assay = 'SCT') markers_motifs <- presto:::wilcoxauc.Seurat(X = pbmc, group_by = 'celltype', assay = 'data', seurat_assay = 'chromvar') motif.names <- markers_motifs$feature colnames(markers_rna) <- paste0("RNA.", colnames(markers_rna)) colnames(markers_motifs) <- paste0("motif.", colnames(markers_motifs)) markers_rna$gene <- markers_rna$RNA.feature markers_motifs$gene <- ConvertMotifID(pbmc, id = motif.names) # a simple function to implement the procedure above topTFs <- function(celltype, padj.cutoff = 1e-2) { ctmarkers_rna <- dplyr::filter( markers_rna, RNA.group == celltype, RNA.padj < padj.cutoff, RNA.logFC > 0) %>% arrange(-RNA.auc) ctmarkers_motif <- dplyr::filter( markers_motifs, motif.group == celltype, motif.padj < padj.cutoff, motif.logFC > 0) %>% arrange(-motif.auc) top_tfs <- inner_join( x = ctmarkers_rna[, c(2, 11, 6, 7)], y = ctmarkers_motif[, c(2, 1, 11, 6, 7)], by = "gene" ) top_tfs$avg_auc <- (top_tfs$RNA.auc + top_tfs$motif.auc) / 2 top_tfs <- arrange(top_tfs, -avg_auc) return(top_tfs) }We can now compute, and visualize, putative regulators for any cell type. We recover well-established regulators, including TBX21 for NK cells, IRF4 for plasma cells, SOX4 for hematopoietic progenitors, EBF1 and PAX5 for B cells, IRF8 and TCF4 for pDC. We believe that similar strategies can be used to help focus on a set of putative regulators in diverse systems. # identify top markers in NK and visualize head(topTFs("NK"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 NK TBX21 0.7270859 0.000000e+00 NK MA0690.1 0.9139614 ## 2 NK EOMES 0.5886774 2.411013e-98 NK MA0800.1 0.9214773 ## 3 NK RUNX3 0.7705661 5.977716e-120 NK MA0684.2 0.6769022 ## motif.pval avg_auc ## 1 1.097940e-202 0.8205237 ## 2 4.903866e-210 0.7550774 ## 3 1.560061e-38 0.7237341 motif.name <- ConvertMotifID(pbmc, name = 'TBX21') gene_plot <- FeaturePlot(pbmc, features = "sct_TBX21", reduction = 'wnn.umap') motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap') gene_plot | motif_plot # identify top markers in pDC and visualize head(topTFs("pDC"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 pDC TCF4 0.9998815 1.120711e-162 pDC MA0830.2 0.9965481 ## 2 pDC IRF8 0.9904457 1.308164e-123 pDC MA0652.1 0.8833112 ## 3 pDC SPIB 0.9115207 0.000000e+00 pDC MA0081.2 0.9068540 ## motif.pval avg_auc ## 1 1.785897e-69 0.9982148 ## 2 3.982413e-42 0.9368785 ## 3 3.083509e-47 0.9091874 motif.name <- ConvertMotifID(pbmc, name = 'TCF4') gene_plot <- FeaturePlot(pbmc, features = "sct_TCF4", reduction = 'wnn.umap') motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap') gene_plot | motif_plot # identify top markers in HSPC and visualize head(topTFs("CD16 Mono"),3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 CD16 Mono SPI1 0.8793172 1.666810e-296 CD16 Mono MA0080.5 0.8880908 ## 2 CD16 Mono CEBPB 0.8685933 1.625472e-294 CD16 Mono MA0466.2 0.7840422 ## 3 CD16 Mono MEF2C 0.7129910 2.727252e-79 CD16 Mono MA0497.1 0.8059373 ## motif.pval avg_auc ## 1 4.762491e-194 0.8837040 ## 2 7.049764e-105 0.8263177 ## 3 2.345716e-121 0.7594641 motif.name <- ConvertMotifID(pbmc, name = 'SPI1') gene_plot <- FeaturePlot(pbmc, features = "sct_SPI1", reduction = 'wnn.umap') motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap') gene_plot | motif_plot # identify top markers in other cell types head(topTFs("Naive B"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 Naive B MEF2C 0.8802747 1.890065e-182 Naive B MA0497.1 0.6789079 ## 2 Naive B PAX5 0.9436648 0.000000e+00 Naive B MA0014.3 0.5827061 ## 3 Naive B POU2F2 0.6029377 2.892216e-13 Naive B MA0507.1 0.8912268 ## motif.pval avg_auc ## 1 9.815118e-32 0.7795913 ## 2 5.995185e-08 0.7631854 ## 3 6.471677e-145 0.7470822 head(topTFs("HSPC"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 HSPC SOX4 0.9869406 5.524832e-71 HSPC MA0867.2 0.6830497 ## 2 HSPC GATA2 0.7884615 0.000000e+00 HSPC MA0036.3 0.8275008 ## 3 HSPC MEIS1 0.8638496 0.000000e+00 HSPC MA0498.2 0.6924225 ## motif.pval avg_auc ## 1 1.241915e-03 0.8349951 ## 2 7.591798e-09 0.8079812 ## 3 6.877492e-04 0.7781361 head(topTFs("Plasma"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 Plasma IRF4 0.8189687 5.261955e-35 Plasma MA1419.1 0.9776046 ## 2 Plasma MEF2C 0.9111213 2.977155e-12 Plasma MA0497.1 0.7596637 ## 3 Plasma TCF4 0.8049409 6.810635e-12 Plasma MA0830.2 0.7840848 ## motif.pval avg_auc ## 1 2.334627e-12 0.8982867 ## 2 1.374353e-04 0.8353925 ## 3 3.028306e-05 0.7945129Session Info sessionInfo()## R version 4.2.0 (2022-04-22) ## Platform: x86_64-pc-linux-gnu (64-bit) ## Running under: Ubuntu 20.04.5 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/liblapack.so.3 ## ## locale: ## [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C ## [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8 ## [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 ## ## attached base packages: ## [1] stats4 stats graphics grDevices utils datasets methods ## [8] base ## ## other attached packages: ## [1] BSgenome.Hsapiens.UCSC.hg38_1.4.5 BSgenome_1.66.3 ## [3] rtracklayer_1.58.0 Biostrings_2.66.0 ## [5] XVector_0.38.0 motifmatchr_1.20.0 ## [7] TFBSTools_1.36.0 JASPAR2020_0.99.10 ## [9] chromVAR_1.20.2 EnsDb.Hsapiens.v86_2.99.0 ## [11] ensembldb_2.22.0 AnnotationFilter_1.22.0 ## [13] GenomicFeatures_1.50.4 AnnotationDbi_1.60.0 ## [15] Biobase_2.58.0 GenomicRanges_1.50.2 ## [17] GenomeInfoDb_1.35.16 IRanges_2.32.0 ## [19] S4Vectors_0.36.2 BiocGenerics_0.44.0 ## [21] Signac_1.9.0 ggplot2_3.4.1 ## [23] dplyr_1.1.1 cowplot_1.1.1 ## [25] thp1.eccite.SeuratData_3.1.5 stxBrain.SeuratData_0.1.1 ## [27] ssHippo.SeuratData_3.1.4 pbmcsca.SeuratData_3.0.0 ## [29] pbmcMultiome.SeuratData_0.1.2 pbmc3k.SeuratData_3.1.4 ## [31] panc8.SeuratData_3.0.2 ifnb.SeuratData_3.1.0 ## [33] hcabm40k.SeuratData_3.0.0 bmcite.SeuratData_0.3.0 ## [35] SeuratData_0.2.2 SeuratObject_4.1.3 ## [37] Seurat_4.2.1.9001 ## ## loaded via a namespace (and not attached): ## [1] rappdirs_0.3.3 scattermore_0.8 ## [3] R.methodsS3_1.8.2 ragg_1.2.5 ## [5] nabor_0.5.0 tidyr_1.3.0 ## [7] bit64_4.0.5 knitr_1.42 ## [9] R.utils_2.12.2 irlba_2.3.5.1 ## [11] DelayedArray_0.24.0 data.table_1.14.8 ## [13] rpart_4.1.16 KEGGREST_1.38.0 ## [15] RCurl_1.98-1.12 generics_0.1.3 ## [17] RSQLite_2.3.0 RANN_2.6.1 ## [19] future_1.32.0 tzdb_0.3.0 ## [21] bit_4.0.5 spatstat.data_3.0-1 ## [23] xml2_1.3.3 httpuv_1.6.9 ## [25] SummarizedExperiment_1.28.0 DirichletMultinomial_1.40.0 ## [27] xfun_0.38 hms_1.1.2 ## [29] jquerylib_0.1.4 evaluate_0.20 ## [31] promises_1.2.0.1 fansi_1.0.4 ## [33] restfulr_0.0.15 progress_1.2.2 ## [35] caTools_1.18.2 dbplyr_2.3.1 ## [37] igraph_1.4.1 DBI_1.1.3 ## [39] htmlwidgets_1.6.2 spatstat.geom_3.1-0 ## [41] purrr_1.0.1 ellipsis_0.3.2 ## [43] backports_1.4.1 annotate_1.76.0 ## [45] biomaRt_2.54.0 deldir_1.0-6 ## [47] MatrixGenerics_1.10.0 vctrs_0.6.1 ## [49] ROCR_1.0-11 abind_1.4-5 ## [51] cachem_1.0.7 withr_2.5.0 ## [53] progressr_0.13.0 presto_1.0.0 ## [55] checkmate_2.1.0 sctransform_0.3.5 ## [57] GenomicAlignments_1.34.0 prettyunits_1.1.1 ## [59] goftest_1.2-3 cluster_2.1.3 ## [61] seqLogo_1.64.0 lazyeval_0.2.2 ## [63] crayon_1.5.2 hdf5r_1.3.8 ## [65] spatstat.explore_3.1-0 pkgconfig_2.0.3 ## [67] labeling_0.4.2 nlme_3.1-157 ## [69] ProtGenerics_1.30.0 nnet_7.3-17 ## [71] rlang_1.1.0 globals_0.16.2 ## [73] lifecycle_1.0.3 miniUI_0.1.1.1 ## [75] filelock_1.0.2 BiocFileCache_2.6.1 ## [77] dichromat_2.0-0.1 rprojroot_2.0.3 ## [79] polyclip_1.10-4 matrixStats_0.63.0 ## [81] lmtest_0.9-40 Matrix_1.5-3 ## [83] zoo_1.8-11 base64enc_0.1-3 ## [85] ggridges_0.5.4 png_0.1-8 ## [87] viridisLite_0.4.1 rjson_0.2.21 ## [89] bitops_1.0-7 R.oo_1.25.0 ## [91] KernSmooth_2.23-20 blob_1.2.3 ## [93] stringr_1.5.0 parallelly_1.35.0 ## [95] spatstat.random_3.1-4 readr_2.1.4 ## [97] jpeg_0.1-10 CNEr_1.34.0 ## [99] scales_1.2.1 memoise_2.0.1 ## [101] magrittr_2.0.3 plyr_1.8.8 ## [103] ica_1.0-3 zlibbioc_1.44.0 ## [105] compiler_4.2.0 BiocIO_1.8.0 ## [107] RColorBrewer_1.1-3 fitdistrplus_1.1-8 ## [109] Rsamtools_2.14.0 cli_3.6.1 ## [111] listenv_0.9.0 patchwork_1.1.2 ## [113] pbapply_1.7-0 htmlTable_2.4.1 ## [115] Formula_1.2-5 MASS_7.3-56 ## [117] tidyselect_1.2.0 stringi_1.7.12 ## [119] textshaping_0.3.6 highr_0.10 ## [121] yaml_2.3.7 latticeExtra_0.6-30 ## [123] ggrepel_0.9.3 grid_4.2.0 ## [125] sass_0.4.5 VariantAnnotation_1.44.1 ## [127] fastmatch_1.1-3 tools_4.2.0 ## [129] future.apply_1.10.0 parallel_4.2.0 ## [131] rstudioapi_0.14 TFMPvalue_0.0.9 ## [133] foreign_0.8-82 gridExtra_2.3 ## [135] farver_2.1.1 Rtsne_0.16 ## [137] digest_0.6.31 pracma_2.4.2 ## [139] shiny_1.7.4 Rcpp_1.0.10 ## [141] later_1.3.0 RcppAnnoy_0.0.20 ## [143] httr_1.4.5 biovizBase_1.46.0 ## [145] colorspace_2.1-0 XML_3.99-0.13 ## [147] fs_1.6.1 tensor_1.5 ## [149] reticulate_1.28 splines_4.2.0 ## [151] uwot_0.1.14 RcppRoll_0.3.0 ## [153] spatstat.utils_3.0-2 pkgdown_2.0.7 ## [155] sp_1.6-0 plotly_4.10.1 ## [157] systemfonts_1.0.4 xtable_1.8-4 ## [159] poweRlaw_0.70.6 jsonlite_1.8.4 ## [161] R6_2.5.1 Hmisc_4.8-0 ## [163] pillar_1.9.0 htmltools_0.5.5 ## [165] mime_0.12 DT_0.27 ## [167] glue_1.6.2 fastmap_1.1.1 ## [169] BiocParallel_1.32.5 codetools_0.2-18 ## [171] utf8_1.2.3 lattice_0.20-45 ## [173] bslib_0.4.2 spatstat.sparse_3.0-1 ## [175] tibble_3.2.1 curl_5.0.0 ## [177] leiden_0.4.3 gtools_3.9.4 ## [179] GO.db_3.16.0 interp_1.1-3 ## [181] survival_3.3-1 rmarkdown_2.21 ## [183] desc_1.4.2 munsell_0.5.0 ## [185] GenomeInfoDbData_1.2.9 reshape2_1.4.4 ## [187] gtable_0.3.3

For example, the ATAC-seq data assists in the separation of CD4 and CD8 T cell states. This is due to the presence of multiple loci that exhibit differential accessibility between different T cell subtypes. For example, we can visualize ‘pseudobulk’ tracks of the CD8A locus alongside violin plots of gene expression levels, using tools in the Signac visualization vignette. ## to make the visualization easier, subset T cell clusters celltype.names <- levels(pbmc) tcell.names <- grep("CD4|CD8|Treg", celltype.names,value = TRUE) tcells <- subset(pbmc, idents = tcell.names) CoveragePlot(tcells, region = 'CD8A', features = 'CD8A', assay = 'ATAC', expression.assay = 'SCT', peaks = FALSE)Next, we will examine the accessible regions of each cell to determine enriched motifs. As described in the Signac motifs vignette, there are a few ways to do this, but we will use the chromVAR package from the Greenleaf lab. This calculates a per-cell accessibility score for known motifs, and adds these scores as a third assay (chromvar) in the Seurat object.To continue, please make sure you have the following packages installed.chromVAR for the analysis of motif accessibility in scATAC-seqpresto for fast differential expression analyses.TFBSTools for TFBS analysisJASPAR2020 for JASPAR motif modelsmotifmatchr for motif matchingBSgenome.Hsapiens.UCSC.hg38 for chromVARInstall command for all dependencies remotes::install_github("immunogenomics/presto") BiocManager::install(c("chromVAR", "TFBSTools", "JASPAR2020", "motifmatchr", "BSgenome.Hsapiens.UCSC.hg38")) library(chromVAR) library(JASPAR2020) library(TFBSTools) library(motifmatchr) library(BSgenome.Hsapiens.UCSC.hg38) # Scan the DNA sequence of each peak for the presence of each motif, and create a Motif object DefaultAssay(pbmc) <- "ATAC" pwm_set <- getMatrixSet(x = JASPAR2020, opts = list(species = 9606, all_versions = FALSE)) motif.matrix <- CreateMotifMatrix(features = granges(pbmc), pwm = pwm_set, genome = 'hg38', use.counts = FALSE) motif.object <- CreateMotifObject(data = motif.matrix, pwm = pwm_set) pbmc <- SetAssayData(pbmc, assay = 'ATAC', slot = 'motifs', new.data = motif.object) # Note that this step can take 30-60 minutes pbmc <- RunChromVAR( object = pbmc, genome = BSgenome.Hsapiens.UCSC.hg38 )Finally, we explore the multimodal dataset to identify key regulators of each cell state. Paired data provides a unique opportunity to identify transcription factors (TFs) that satisfy multiple criteria, helping to narrow down the list of putative regulators to the most likely candidates. We aim to identify TFs whose expression is enriched in multiple cell types in the RNA measurements, but also have enriched accessibility for their motifs in the ATAC measurements.As an example and positive control, the CCAAT Enhancer Binding Protein (CEBP) family of proteins, including the TF CEBPB, have been repeatedly shown to play important roles in the differentiation and function of myeloid cells including monocytes and dendritic cells. We can see that both the expression of the CEBPB, and the accessibility of the MA0466.2.4 motif (which encodes the binding site for CEBPB), are both enriched in monocytes. #returns MA0466.2 motif.name <- ConvertMotifID(pbmc, name = 'CEBPB') gene_plot <- FeaturePlot(pbmc, features = "sct_CEBPB", reduction = 'wnn.umap') motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap') gene_plot | motif_plotWe’d like to quantify this relationship, and search across all cell types to find similar examples. To do so, we will use the presto package to perform fast differential expression. We run two tests: one using gene expression data, and the other using chromVAR motif accessibilities. presto calculates a p-value based on the Wilcox rank sum test, which is also the default test in Seurat, and we restrict our search to TFs that return significant results in both tests.presto also calculates an “AUC” statistic, which reflects the power of each gene (or motif) to serve as a marker of cell type. A maximum AUC value of 1 indicates a perfect marker. Since the AUC statistic is on the same scale for both genes and motifs, we take the average of the AUC values from the two tests, and use this to rank TFs for each cell type: markers_rna <- presto:::wilcoxauc.Seurat(X = pbmc, group_by = 'celltype', assay = 'data', seurat_assay = 'SCT') markers_motifs <- presto:::wilcoxauc.Seurat(X = pbmc, group_by = 'celltype', assay = 'data', seurat_assay = 'chromvar') motif.names <- markers_motifs$feature colnames(markers_rna) <- paste0("RNA.", colnames(markers_rna)) colnames(markers_motifs) <- paste0("motif.", colnames(markers_motifs)) markers_rna$gene <- markers_rna$RNA.feature markers_motifs$gene <- ConvertMotifID(pbmc, id = motif.names) # a simple function to implement the procedure above topTFs <- function(celltype, padj.cutoff = 1e-2) { ctmarkers_rna <- dplyr::filter( markers_rna, RNA.group == celltype, RNA.padj < padj.cutoff, RNA.logFC > 0) %>% arrange(-RNA.auc) ctmarkers_motif <- dplyr::filter( markers_motifs, motif.group == celltype, motif.padj < padj.cutoff, motif.logFC > 0) %>% arrange(-motif.auc) top_tfs <- inner_join( x = ctmarkers_rna[, c(2, 11, 6, 7)], y = ctmarkers_motif[, c(2, 1, 11, 6, 7)], by = "gene" ) top_tfs$avg_auc <- (top_tfs$RNA.auc + top_tfs$motif.auc) / 2 top_tfs <- arrange(top_tfs, -avg_auc) return(top_tfs) }We can now compute, and visualize, putative regulators for any cell type. We recover well-established regulators, including TBX21 for NK cells, IRF4 for plasma cells, SOX4 for hematopoietic progenitors, EBF1 and PAX5 for B cells, IRF8 and TCF4 for pDC. We believe that similar strategies can be used to help focus on a set of putative regulators in diverse systems. # identify top markers in NK and visualize head(topTFs("NK"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 NK TBX21 0.7270859 0.000000e+00 NK MA0690.1 0.9139614 ## 2 NK EOMES 0.5886774 2.411013e-98 NK MA0800.1 0.9214773 ## 3 NK RUNX3 0.7705661 5.977716e-120 NK MA0684.2 0.6769022 ## motif.pval avg_auc ## 1 1.097940e-202 0.8205237 ## 2 4.903866e-210 0.7550774 ## 3 1.560061e-38 0.7237341 motif.name <- ConvertMotifID(pbmc, name = 'TBX21') gene_plot <- FeaturePlot(pbmc, features = "sct_TBX21", reduction = 'wnn.umap') motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap') gene_plot | motif_plot # identify top markers in pDC and visualize head(topTFs("pDC"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 pDC TCF4 0.9998815 1.120711e-162 pDC MA0830.2 0.9965481 ## 2 pDC IRF8 0.9904457 1.308164e-123 pDC MA0652.1 0.8833112 ## 3 pDC SPIB 0.9115207 0.000000e+00 pDC MA0081.2 0.9068540 ## motif.pval avg_auc ## 1 1.785897e-69 0.9982148 ## 2 3.982413e-42 0.9368785 ## 3 3.083509e-47 0.9091874 motif.name <- ConvertMotifID(pbmc, name = 'TCF4') gene_plot <- FeaturePlot(pbmc, features = "sct_TCF4", reduction = 'wnn.umap') motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap') gene_plot | motif_plot # identify top markers in HSPC and visualize head(topTFs("CD16 Mono"),3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 CD16 Mono SPI1 0.8793172 1.666810e-296 CD16 Mono MA0080.5 0.8880908 ## 2 CD16 Mono CEBPB 0.8685933 1.625472e-294 CD16 Mono MA0466.2 0.7840422 ## 3 CD16 Mono MEF2C 0.7129910 2.727252e-79 CD16 Mono MA0497.1 0.8059373 ## motif.pval avg_auc ## 1 4.762491e-194 0.8837040 ## 2 7.049764e-105 0.8263177 ## 3 2.345716e-121 0.7594641 motif.name <- ConvertMotifID(pbmc, name = 'SPI1') gene_plot <- FeaturePlot(pbmc, features = "sct_SPI1", reduction = 'wnn.umap') motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap') gene_plot | motif_plot # identify top markers in other cell types head(topTFs("Naive B"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 Naive B MEF2C 0.8802747 1.890065e-182 Naive B MA0497.1 0.6789079 ## 2 Naive B PAX5 0.9436648 0.000000e+00 Naive B MA0014.3 0.5827061 ## 3 Naive B POU2F2 0.6029377 2.892216e-13 Naive B MA0507.1 0.8912268 ## motif.pval avg_auc ## 1 9.815118e-32 0.7795913 ## 2 5.995185e-08 0.7631854 ## 3 6.471677e-145 0.7470822 head(topTFs("HSPC"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 HSPC SOX4 0.9869406 5.524832e-71 HSPC MA0867.2 0.6830497 ## 2 HSPC GATA2 0.7884615 0.000000e+00 HSPC MA0036.3 0.8275008 ## 3 HSPC MEIS1 0.8638496 0.000000e+00 HSPC MA0498.2 0.6924225 ## motif.pval avg_auc ## 1 1.241915e-03 0.8349951 ## 2 7.591798e-09 0.8079812 ## 3 6.877492e-04 0.7781361 head(topTFs("Plasma"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 Plasma IRF4 0.8189687 5.261955e-35 Plasma MA1419.1 0.9776046 ## 2 Plasma MEF2C 0.9111213 2.977155e-12 Plasma MA0497.1 0.7596637 ## 3 Plasma TCF4 0.8049409 6.810635e-12 Plasma MA0830.2 0.7840848 ## motif.pval avg_auc ## 1 2.334627e-12 0.8982867 ## 2 1.374353e-04 0.8353925 ## 3 3.028306e-05 0.7945129Session Info sessionInfo()## R version 4.2.0 (2022-04-22) ## Platform: x86_64-pc-linux-gnu (64-bit) ## Running under: Ubuntu 20.04.5 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/liblapack.so.3 ## ## locale: ## [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C ## [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8 ## [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 ## ## attached base packages: ## [1] stats4 stats graphics grDevices utils datasets methods ## [8] base ## ## other attached packages: ## [1] BSgenome.Hsapiens.UCSC.hg38_1.4.5 BSgenome_1.66.3 ## [3] rtracklayer_1.58.0 Biostrings_2.66.0 ## [5] XVector_0.38.0 motifmatchr_1.20.0 ## [7] TFBSTools_1.36.0 JASPAR2020_0.99.10 ## [9] chromVAR_1.20.2 EnsDb.Hsapiens.v86_2.99.0 ## [11] ensembldb_2.22.0 AnnotationFilter_1.22.0 ## [13] GenomicFeatures_1.50.4 AnnotationDbi_1.60.0 ## [15] Biobase_2.58.0 GenomicRanges_1.50.2 ## [17] GenomeInfoDb_1.35.16 IRanges_2.32.0 ## [19] S4Vectors_0.36.2 BiocGenerics_0.44.0 ## [21] Signac_1.9.0 ggplot2_3.4.1 ## [23] dplyr_1.1.1 cowplot_1.1.1 ## [25] thp1.eccite.SeuratData_3.1.5 stxBrain.SeuratData_0.1.1 ## [27] ssHippo.SeuratData_3.1.4 pbmcsca.SeuratData_3.0.0 ## [29] pbmcMultiome.SeuratData_0.1.2 pbmc3k.SeuratData_3.1.4 ## [31] panc8.SeuratData_3.0.2 ifnb.SeuratData_3.1.0 ## [33] hcabm40k.SeuratData_3.0.0 bmcite.SeuratData_0.3.0 ## [35] SeuratData_0.2.2 SeuratObject_4.1.3 ## [37] Seurat_4.2.1.9001 ## ## loaded via a namespace (and not attached): ## [1] rappdirs_0.3.3 scattermore_0.8 ## [3] R.methodsS3_1.8.2 ragg_1.2.5 ## [5] nabor_0.5.0 tidyr_1.3.0 ## [7] bit64_4.0.5 knitr_1.42 ## [9] R.utils_2.12.2 irlba_2.3.5.1 ## [11] DelayedArray_0.24.0 data.table_1.14.8 ## [13] rpart_4.1.16 KEGGREST_1.38.0 ## [15] RCurl_1.98-1.12 generics_0.1.3 ## [17] RSQLite_2.3.0 RANN_2.6.1 ## [19] future_1.32.0 tzdb_0.3.0 ## [21] bit_4.0.5 spatstat.data_3.0-1 ## [23] xml2_1.3.3 httpuv_1.6.9 ## [25] SummarizedExperiment_1.28.0 DirichletMultinomial_1.40.0 ## [27] xfun_0.38 hms_1.1.2 ## [29] jquerylib_0.1.4 evaluate_0.20 ## [31] promises_1.2.0.1 fansi_1.0.4 ## [33] restfulr_0.0.15 progress_1.2.2 ## [35] caTools_1.18.2 dbplyr_2.3.1 ## [37] igraph_1.4.1 DBI_1.1.3 ## [39] htmlwidgets_1.6.2 spatstat.geom_3.1-0 ## [41] purrr_1.0.1 ellipsis_0.3.2 ## [43] backports_1.4.1 annotate_1.76.0 ## [45] biomaRt_2.54.0 deldir_1.0-6 ## [47] MatrixGenerics_1.10.0 vctrs_0.6.1 ## [49] ROCR_1.0-11 abind_1.4-5 ## [51] cachem_1.0.7 withr_2.5.0 ## [53] progressr_0.13.0 presto_1.0.0 ## [55] checkmate_2.1.0 sctransform_0.3.5 ## [57] GenomicAlignments_1.34.0 prettyunits_1.1.1 ## [59] goftest_1.2-3 cluster_2.1.3 ## [61] seqLogo_1.64.0 lazyeval_0.2.2 ## [63] crayon_1.5.2 hdf5r_1.3.8 ## [65] spatstat.explore_3.1-0 pkgconfig_2.0.3 ## [67] labeling_0.4.2 nlme_3.1-157 ## [69] ProtGenerics_1.30.0 nnet_7.3-17 ## [71] rlang_1.1.0 globals_0.16.2 ## [73] lifecycle_1.0.3 miniUI_0.1.1.1 ## [75] filelock_1.0.2 BiocFileCache_2.6.1 ## [77] dichromat_2.0-0.1 rprojroot_2.0.3 ## [79] polyclip_1.10-4 matrixStats_0.63.0 ## [81] lmtest_0.9-40 Matrix_1.5-3 ## [83] zoo_1.8-11 base64enc_0.1-3 ## [85] ggridges_0.5.4 png_0.1-8 ## [87] viridisLite_0.4.1 rjson_0.2.21 ## [89] bitops_1.0-7 R.oo_1.25.0 ## [91] KernSmooth_2.23-20 blob_1.2.3 ## [93] stringr_1.5.0 parallelly_1.35.0 ## [95] spatstat.random_3.1-4 readr_2.1.4 ## [97] jpeg_0.1-10 CNEr_1.34.0 ## [99] scales_1.2.1 memoise_2.0.1 ## [101] magrittr_2.0.3 plyr_1.8.8 ## [103] ica_1.0-3 zlibbioc_1.44.0 ## [105] compiler_4.2.0 BiocIO_1.8.0 ## [107] RColorBrewer_1.1-3 fitdistrplus_1.1-8 ## [109] Rsamtools_2.14.0 cli_3.6.1 ## [111] listenv_0.9.0 patchwork_1.1.2 ## [113] pbapply_1.7-0 htmlTable_2.4.1 ## [115] Formula_1.2-5 MASS_7.3-56 ## [117] tidyselect_1.2.0 stringi_1.7.12 ## [119] textshaping_0.3.6 highr_0.10 ## [121] yaml_2.3.7 latticeExtra_0.6-30 ## [123] ggrepel_0.9.3 grid_4.2.0 ## [125] sass_0.4.5 VariantAnnotation_1.44.1 ## [127] fastmatch_1.1-3 tools_4.2.0 ## [129] future.apply_1.10.0 parallel_4.2.0 ## [131] rstudioapi_0.14 TFMPvalue_0.0.9 ## [133] foreign_0.8-82 gridExtra_2.3 ## [135] farver_2.1.1 Rtsne_0.16 ## [137] digest_0.6.31 pracma_2.4.2 ## [139] shiny_1.7.4 Rcpp_1.0.10 ## [141] later_1.3.0 RcppAnnoy_0.0.20 ## [143] httr_1.4.5 biovizBase_1.46.0 ## [145] colorspace_2.1-0 XML_3.99-0.13 ## [147] fs_1.6.1 tensor_1.5 ## [149] reticulate_1.28 splines_4.2.0 ## [151] uwot_0.1.14 RcppRoll_0.3.0 ## [153] spatstat.utils_3.0-2 pkgdown_2.0.7 ## [155] sp_1.6-0 plotly_4.10.1 ## [157] systemfonts_1.0.4 xtable_1.8-4 ## [159] poweRlaw_0.70.6 jsonlite_1.8.4 ## [161] R6_2.5.1 Hmisc_4.8-0 ## [163] pillar_1.9.0 htmltools_0.5.5 ## [165] mime_0.12 DT_0.27 ## [167] glue_1.6.2 fastmap_1.1.1 ## [169] BiocParallel_1.32.5 codetools_0.2-18 ## [171] utf8_1.2.3 lattice_0.20-45 ## [173] bslib_0.4.2 spatstat.sparse_3.0-1 ## [175] tibble_3.2.1 curl_5.0.0 ## [177] leiden_0.4.3 gtools_3.9.4 ## [179] GO.db_3.16.0 interp_1.1-3 ## [181] survival_3.3-1 rmarkdown_2.21 ## [183] desc_1.4.2 munsell_0.5.0 ## [185] GenomeInfoDbData_1.2.9 reshape2_1.4.4 ## [187] gtable_0.3.3

Next, we will examine the accessible regions of each cell to determine enriched motifs. As described in the Signac motifs vignette, there are a few ways to do this, but we will use the chromVAR package from the Greenleaf lab. This calculates a per-cell accessibility score for known motifs, and adds these scores as a third assay (chromvar) in the Seurat object.To continue, please make sure you have the following packages installed.chromVAR for the analysis of motif accessibility in scATAC-seqpresto for fast differential expression analyses.TFBSTools for TFBS analysisJASPAR2020 for JASPAR motif modelsmotifmatchr for motif matchingBSgenome.Hsapiens.UCSC.hg38 for chromVARInstall command for all dependencies remotes::install_github("immunogenomics/presto") BiocManager::install(c("chromVAR", "TFBSTools", "JASPAR2020", "motifmatchr", "BSgenome.Hsapiens.UCSC.hg38")) library(chromVAR) library(JASPAR2020) library(TFBSTools) library(motifmatchr) library(BSgenome.Hsapiens.UCSC.hg38) # Scan the DNA sequence of each peak for the presence of each motif, and create a Motif object DefaultAssay(pbmc) <- "ATAC" pwm_set <- getMatrixSet(x = JASPAR2020, opts = list(species = 9606, all_versions = FALSE)) motif.matrix <- CreateMotifMatrix(features = granges(pbmc), pwm = pwm_set, genome = 'hg38', use.counts = FALSE) motif.object <- CreateMotifObject(data = motif.matrix, pwm = pwm_set) pbmc <- SetAssayData(pbmc, assay = 'ATAC', slot = 'motifs', new.data = motif.object) # Note that this step can take 30-60 minutes pbmc <- RunChromVAR( object = pbmc, genome = BSgenome.Hsapiens.UCSC.hg38 )Finally, we explore the multimodal dataset to identify key regulators of each cell state. Paired data provides a unique opportunity to identify transcription factors (TFs) that satisfy multiple criteria, helping to narrow down the list of putative regulators to the most likely candidates. We aim to identify TFs whose expression is enriched in multiple cell types in the RNA measurements, but also have enriched accessibility for their motifs in the ATAC measurements.As an example and positive control, the CCAAT Enhancer Binding Protein (CEBP) family of proteins, including the TF CEBPB, have been repeatedly shown to play important roles in the differentiation and function of myeloid cells including monocytes and dendritic cells. We can see that both the expression of the CEBPB, and the accessibility of the MA0466.2.4 motif (which encodes the binding site for CEBPB), are both enriched in monocytes. #returns MA0466.2 motif.name <- ConvertMotifID(pbmc, name = 'CEBPB') gene_plot <- FeaturePlot(pbmc, features = "sct_CEBPB", reduction = 'wnn.umap') motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap') gene_plot | motif_plotWe’d like to quantify this relationship, and search across all cell types to find similar examples. To do so, we will use the presto package to perform fast differential expression. We run two tests: one using gene expression data, and the other using chromVAR motif accessibilities. presto calculates a p-value based on the Wilcox rank sum test, which is also the default test in Seurat, and we restrict our search to TFs that return significant results in both tests.presto also calculates an “AUC” statistic, which reflects the power of each gene (or motif) to serve as a marker of cell type. A maximum AUC value of 1 indicates a perfect marker. Since the AUC statistic is on the same scale for both genes and motifs, we take the average of the AUC values from the two tests, and use this to rank TFs for each cell type: markers_rna <- presto:::wilcoxauc.Seurat(X = pbmc, group_by = 'celltype', assay = 'data', seurat_assay = 'SCT') markers_motifs <- presto:::wilcoxauc.Seurat(X = pbmc, group_by = 'celltype', assay = 'data', seurat_assay = 'chromvar') motif.names <- markers_motifs$feature colnames(markers_rna) <- paste0("RNA.", colnames(markers_rna)) colnames(markers_motifs) <- paste0("motif.", colnames(markers_motifs)) markers_rna$gene <- markers_rna$RNA.feature markers_motifs$gene <- ConvertMotifID(pbmc, id = motif.names) # a simple function to implement the procedure above topTFs <- function(celltype, padj.cutoff = 1e-2) { ctmarkers_rna <- dplyr::filter( markers_rna, RNA.group == celltype, RNA.padj < padj.cutoff, RNA.logFC > 0) %>% arrange(-RNA.auc) ctmarkers_motif <- dplyr::filter( markers_motifs, motif.group == celltype, motif.padj < padj.cutoff, motif.logFC > 0) %>% arrange(-motif.auc) top_tfs <- inner_join( x = ctmarkers_rna[, c(2, 11, 6, 7)], y = ctmarkers_motif[, c(2, 1, 11, 6, 7)], by = "gene" ) top_tfs$avg_auc <- (top_tfs$RNA.auc + top_tfs$motif.auc) / 2 top_tfs <- arrange(top_tfs, -avg_auc) return(top_tfs) }We can now compute, and visualize, putative regulators for any cell type. We recover well-established regulators, including TBX21 for NK cells, IRF4 for plasma cells, SOX4 for hematopoietic progenitors, EBF1 and PAX5 for B cells, IRF8 and TCF4 for pDC. We believe that similar strategies can be used to help focus on a set of putative regulators in diverse systems. # identify top markers in NK and visualize head(topTFs("NK"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 NK TBX21 0.7270859 0.000000e+00 NK MA0690.1 0.9139614 ## 2 NK EOMES 0.5886774 2.411013e-98 NK MA0800.1 0.9214773 ## 3 NK RUNX3 0.7705661 5.977716e-120 NK MA0684.2 0.6769022 ## motif.pval avg_auc ## 1 1.097940e-202 0.8205237 ## 2 4.903866e-210 0.7550774 ## 3 1.560061e-38 0.7237341 motif.name <- ConvertMotifID(pbmc, name = 'TBX21') gene_plot <- FeaturePlot(pbmc, features = "sct_TBX21", reduction = 'wnn.umap') motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap') gene_plot | motif_plot # identify top markers in pDC and visualize head(topTFs("pDC"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 pDC TCF4 0.9998815 1.120711e-162 pDC MA0830.2 0.9965481 ## 2 pDC IRF8 0.9904457 1.308164e-123 pDC MA0652.1 0.8833112 ## 3 pDC SPIB 0.9115207 0.000000e+00 pDC MA0081.2 0.9068540 ## motif.pval avg_auc ## 1 1.785897e-69 0.9982148 ## 2 3.982413e-42 0.9368785 ## 3 3.083509e-47 0.9091874 motif.name <- ConvertMotifID(pbmc, name = 'TCF4') gene_plot <- FeaturePlot(pbmc, features = "sct_TCF4", reduction = 'wnn.umap') motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap') gene_plot | motif_plot # identify top markers in HSPC and visualize head(topTFs("CD16 Mono"),3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 CD16 Mono SPI1 0.8793172 1.666810e-296 CD16 Mono MA0080.5 0.8880908 ## 2 CD16 Mono CEBPB 0.8685933 1.625472e-294 CD16 Mono MA0466.2 0.7840422 ## 3 CD16 Mono MEF2C 0.7129910 2.727252e-79 CD16 Mono MA0497.1 0.8059373 ## motif.pval avg_auc ## 1 4.762491e-194 0.8837040 ## 2 7.049764e-105 0.8263177 ## 3 2.345716e-121 0.7594641 motif.name <- ConvertMotifID(pbmc, name = 'SPI1') gene_plot <- FeaturePlot(pbmc, features = "sct_SPI1", reduction = 'wnn.umap') motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap') gene_plot | motif_plot # identify top markers in other cell types head(topTFs("Naive B"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 Naive B MEF2C 0.8802747 1.890065e-182 Naive B MA0497.1 0.6789079 ## 2 Naive B PAX5 0.9436648 0.000000e+00 Naive B MA0014.3 0.5827061 ## 3 Naive B POU2F2 0.6029377 2.892216e-13 Naive B MA0507.1 0.8912268 ## motif.pval avg_auc ## 1 9.815118e-32 0.7795913 ## 2 5.995185e-08 0.7631854 ## 3 6.471677e-145 0.7470822 head(topTFs("HSPC"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 HSPC SOX4 0.9869406 5.524832e-71 HSPC MA0867.2 0.6830497 ## 2 HSPC GATA2 0.7884615 0.000000e+00 HSPC MA0036.3 0.8275008 ## 3 HSPC MEIS1 0.8638496 0.000000e+00 HSPC MA0498.2 0.6924225 ## motif.pval avg_auc ## 1 1.241915e-03 0.8349951 ## 2 7.591798e-09 0.8079812 ## 3 6.877492e-04 0.7781361 head(topTFs("Plasma"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 Plasma IRF4 0.8189687 5.261955e-35 Plasma MA1419.1 0.9776046 ## 2 Plasma MEF2C 0.9111213 2.977155e-12 Plasma MA0497.1 0.7596637 ## 3 Plasma TCF4 0.8049409 6.810635e-12 Plasma MA0830.2 0.7840848 ## motif.pval avg_auc ## 1 2.334627e-12 0.8982867 ## 2 1.374353e-04 0.8353925 ## 3 3.028306e-05 0.7945129Session Info sessionInfo()## R version 4.2.0 (2022-04-22) ## Platform: x86_64-pc-linux-gnu (64-bit) ## Running under: Ubuntu 20.04.5 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/liblapack.so.3 ## ## locale: ## [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C ## [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8 ## [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 ## ## attached base packages: ## [1] stats4 stats graphics grDevices utils datasets methods ## [8] base ## ## other attached packages: ## [1] BSgenome.Hsapiens.UCSC.hg38_1.4.5 BSgenome_1.66.3 ## [3] rtracklayer_1.58.0 Biostrings_2.66.0 ## [5] XVector_0.38.0 motifmatchr_1.20.0 ## [7] TFBSTools_1.36.0 JASPAR2020_0.99.10 ## [9] chromVAR_1.20.2 EnsDb.Hsapiens.v86_2.99.0 ## [11] ensembldb_2.22.0 AnnotationFilter_1.22.0 ## [13] GenomicFeatures_1.50.4 AnnotationDbi_1.60.0 ## [15] Biobase_2.58.0 GenomicRanges_1.50.2 ## [17] GenomeInfoDb_1.35.16 IRanges_2.32.0 ## [19] S4Vectors_0.36.2 BiocGenerics_0.44.0 ## [21] Signac_1.9.0 ggplot2_3.4.1 ## [23] dplyr_1.1.1 cowplot_1.1.1 ## [25] thp1.eccite.SeuratData_3.1.5 stxBrain.SeuratData_0.1.1 ## [27] ssHippo.SeuratData_3.1.4 pbmcsca.SeuratData_3.0.0 ## [29] pbmcMultiome.SeuratData_0.1.2 pbmc3k.SeuratData_3.1.4 ## [31] panc8.SeuratData_3.0.2 ifnb.SeuratData_3.1.0 ## [33] hcabm40k.SeuratData_3.0.0 bmcite.SeuratData_0.3.0 ## [35] SeuratData_0.2.2 SeuratObject_4.1.3 ## [37] Seurat_4.2.1.9001 ## ## loaded via a namespace (and not attached): ## [1] rappdirs_0.3.3 scattermore_0.8 ## [3] R.methodsS3_1.8.2 ragg_1.2.5 ## [5] nabor_0.5.0 tidyr_1.3.0 ## [7] bit64_4.0.5 knitr_1.42 ## [9] R.utils_2.12.2 irlba_2.3.5.1 ## [11] DelayedArray_0.24.0 data.table_1.14.8 ## [13] rpart_4.1.16 KEGGREST_1.38.0 ## [15] RCurl_1.98-1.12 generics_0.1.3 ## [17] RSQLite_2.3.0 RANN_2.6.1 ## [19] future_1.32.0 tzdb_0.3.0 ## [21] bit_4.0.5 spatstat.data_3.0-1 ## [23] xml2_1.3.3 httpuv_1.6.9 ## [25] SummarizedExperiment_1.28.0 DirichletMultinomial_1.40.0 ## [27] xfun_0.38 hms_1.1.2 ## [29] jquerylib_0.1.4 evaluate_0.20 ## [31] promises_1.2.0.1 fansi_1.0.4 ## [33] restfulr_0.0.15 progress_1.2.2 ## [35] caTools_1.18.2 dbplyr_2.3.1 ## [37] igraph_1.4.1 DBI_1.1.3 ## [39] htmlwidgets_1.6.2 spatstat.geom_3.1-0 ## [41] purrr_1.0.1 ellipsis_0.3.2 ## [43] backports_1.4.1 annotate_1.76.0 ## [45] biomaRt_2.54.0 deldir_1.0-6 ## [47] MatrixGenerics_1.10.0 vctrs_0.6.1 ## [49] ROCR_1.0-11 abind_1.4-5 ## [51] cachem_1.0.7 withr_2.5.0 ## [53] progressr_0.13.0 presto_1.0.0 ## [55] checkmate_2.1.0 sctransform_0.3.5 ## [57] GenomicAlignments_1.34.0 prettyunits_1.1.1 ## [59] goftest_1.2-3 cluster_2.1.3 ## [61] seqLogo_1.64.0 lazyeval_0.2.2 ## [63] crayon_1.5.2 hdf5r_1.3.8 ## [65] spatstat.explore_3.1-0 pkgconfig_2.0.3 ## [67] labeling_0.4.2 nlme_3.1-157 ## [69] ProtGenerics_1.30.0 nnet_7.3-17 ## [71] rlang_1.1.0 globals_0.16.2 ## [73] lifecycle_1.0.3 miniUI_0.1.1.1 ## [75] filelock_1.0.2 BiocFileCache_2.6.1 ## [77] dichromat_2.0-0.1 rprojroot_2.0.3 ## [79] polyclip_1.10-4 matrixStats_0.63.0 ## [81] lmtest_0.9-40 Matrix_1.5-3 ## [83] zoo_1.8-11 base64enc_0.1-3 ## [85] ggridges_0.5.4 png_0.1-8 ## [87] viridisLite_0.4.1 rjson_0.2.21 ## [89] bitops_1.0-7 R.oo_1.25.0 ## [91] KernSmooth_2.23-20 blob_1.2.3 ## [93] stringr_1.5.0 parallelly_1.35.0 ## [95] spatstat.random_3.1-4 readr_2.1.4 ## [97] jpeg_0.1-10 CNEr_1.34.0 ## [99] scales_1.2.1 memoise_2.0.1 ## [101] magrittr_2.0.3 plyr_1.8.8 ## [103] ica_1.0-3 zlibbioc_1.44.0 ## [105] compiler_4.2.0 BiocIO_1.8.0 ## [107] RColorBrewer_1.1-3 fitdistrplus_1.1-8 ## [109] Rsamtools_2.14.0 cli_3.6.1 ## [111] listenv_0.9.0 patchwork_1.1.2 ## [113] pbapply_1.7-0 htmlTable_2.4.1 ## [115] Formula_1.2-5 MASS_7.3-56 ## [117] tidyselect_1.2.0 stringi_1.7.12 ## [119] textshaping_0.3.6 highr_0.10 ## [121] yaml_2.3.7 latticeExtra_0.6-30 ## [123] ggrepel_0.9.3 grid_4.2.0 ## [125] sass_0.4.5 VariantAnnotation_1.44.1 ## [127] fastmatch_1.1-3 tools_4.2.0 ## [129] future.apply_1.10.0 parallel_4.2.0 ## [131] rstudioapi_0.14 TFMPvalue_0.0.9 ## [133] foreign_0.8-82 gridExtra_2.3 ## [135] farver_2.1.1 Rtsne_0.16 ## [137] digest_0.6.31 pracma_2.4.2 ## [139] shiny_1.7.4 Rcpp_1.0.10 ## [141] later_1.3.0 RcppAnnoy_0.0.20 ## [143] httr_1.4.5 biovizBase_1.46.0 ## [145] colorspace_2.1-0 XML_3.99-0.13 ## [147] fs_1.6.1 tensor_1.5 ## [149] reticulate_1.28 splines_4.2.0 ## [151] uwot_0.1.14 RcppRoll_0.3.0 ## [153] spatstat.utils_3.0-2 pkgdown_2.0.7 ## [155] sp_1.6-0 plotly_4.10.1 ## [157] systemfonts_1.0.4 xtable_1.8-4 ## [159] poweRlaw_0.70.6 jsonlite_1.8.4 ## [161] R6_2.5.1 Hmisc_4.8-0 ## [163] pillar_1.9.0 htmltools_0.5.5 ## [165] mime_0.12 DT_0.27 ## [167] glue_1.6.2 fastmap_1.1.1 ## [169] BiocParallel_1.32.5 codetools_0.2-18 ## [171] utf8_1.2.3 lattice_0.20-45 ## [173] bslib_0.4.2 spatstat.sparse_3.0-1 ## [175] tibble_3.2.1 curl_5.0.0 ## [177] leiden_0.4.3 gtools_3.9.4 ## [179] GO.db_3.16.0 interp_1.1-3 ## [181] survival_3.3-1 rmarkdown_2.21 ## [183] desc_1.4.2 munsell_0.5.0 ## [185] GenomeInfoDbData_1.2.9 reshape2_1.4.4 ## [187] gtable_0.3.3

Next, we will examine the accessible regions of each cell to determine enriched motifs. As described in the Signac motifs vignette, there are a few ways to do this, but we will use the chromVAR package from the Greenleaf lab. This calculates a per-cell accessibility score for known motifs, and adds these scores as a third assay (chromvar) in the Seurat object.To continue, please make sure you have the following packages installed.chromVAR for the analysis of motif accessibility in scATAC-seqpresto for fast differential expression analyses.TFBSTools for TFBS analysisJASPAR2020 for JASPAR motif modelsmotifmatchr for motif matchingBSgenome.Hsapiens.UCSC.hg38 for chromVARInstall command for all dependencies remotes::install_github("immunogenomics/presto") BiocManager::install(c("chromVAR", "TFBSTools", "JASPAR2020", "motifmatchr", "BSgenome.Hsapiens.UCSC.hg38")) library(chromVAR) library(JASPAR2020) library(TFBSTools) library(motifmatchr) library(BSgenome.Hsapiens.UCSC.hg38) # Scan the DNA sequence of each peak for the presence of each motif, and create a Motif object DefaultAssay(pbmc) <- "ATAC" pwm_set <- getMatrixSet(x = JASPAR2020, opts = list(species = 9606, all_versions = FALSE)) motif.matrix <- CreateMotifMatrix(features = granges(pbmc), pwm = pwm_set, genome = 'hg38', use.counts = FALSE) motif.object <- CreateMotifObject(data = motif.matrix, pwm = pwm_set) pbmc <- SetAssayData(pbmc, assay = 'ATAC', slot = 'motifs', new.data = motif.object) # Note that this step can take 30-60 minutes pbmc <- RunChromVAR( object = pbmc, genome = BSgenome.Hsapiens.UCSC.hg38 )Finally, we explore the multimodal dataset to identify key regulators of each cell state. Paired data provides a unique opportunity to identify transcription factors (TFs) that satisfy multiple criteria, helping to narrow down the list of putative regulators to the most likely candidates. We aim to identify TFs whose expression is enriched in multiple cell types in the RNA measurements, but also have enriched accessibility for their motifs in the ATAC measurements.As an example and positive control, the CCAAT Enhancer Binding Protein (CEBP) family of proteins, including the TF CEBPB, have been repeatedly shown to play important roles in the differentiation and function of myeloid cells including monocytes and dendritic cells. We can see that both the expression of the CEBPB, and the accessibility of the MA0466.2.4 motif (which encodes the binding site for CEBPB), are both enriched in monocytes. #returns MA0466.2 motif.name <- ConvertMotifID(pbmc, name = 'CEBPB') gene_plot <- FeaturePlot(pbmc, features = "sct_CEBPB", reduction = 'wnn.umap') motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap') gene_plot | motif_plotWe’d like to quantify this relationship, and search across all cell types to find similar examples. To do so, we will use the presto package to perform fast differential expression. We run two tests: one using gene expression data, and the other using chromVAR motif accessibilities. presto calculates a p-value based on the Wilcox rank sum test, which is also the default test in Seurat, and we restrict our search to TFs that return significant results in both tests.presto also calculates an “AUC” statistic, which reflects the power of each gene (or motif) to serve as a marker of cell type. A maximum AUC value of 1 indicates a perfect marker. Since the AUC statistic is on the same scale for both genes and motifs, we take the average of the AUC values from the two tests, and use this to rank TFs for each cell type: markers_rna <- presto:::wilcoxauc.Seurat(X = pbmc, group_by = 'celltype', assay = 'data', seurat_assay = 'SCT') markers_motifs <- presto:::wilcoxauc.Seurat(X = pbmc, group_by = 'celltype', assay = 'data', seurat_assay = 'chromvar') motif.names <- markers_motifs$feature colnames(markers_rna) <- paste0("RNA.", colnames(markers_rna)) colnames(markers_motifs) <- paste0("motif.", colnames(markers_motifs)) markers_rna$gene <- markers_rna$RNA.feature markers_motifs$gene <- ConvertMotifID(pbmc, id = motif.names) # a simple function to implement the procedure above topTFs <- function(celltype, padj.cutoff = 1e-2) { ctmarkers_rna <- dplyr::filter( markers_rna, RNA.group == celltype, RNA.padj < padj.cutoff, RNA.logFC > 0) %>% arrange(-RNA.auc) ctmarkers_motif <- dplyr::filter( markers_motifs, motif.group == celltype, motif.padj < padj.cutoff, motif.logFC > 0) %>% arrange(-motif.auc) top_tfs <- inner_join( x = ctmarkers_rna[, c(2, 11, 6, 7)], y = ctmarkers_motif[, c(2, 1, 11, 6, 7)], by = "gene" ) top_tfs$avg_auc <- (top_tfs$RNA.auc + top_tfs$motif.auc) / 2 top_tfs <- arrange(top_tfs, -avg_auc) return(top_tfs) }We can now compute, and visualize, putative regulators for any cell type. We recover well-established regulators, including TBX21 for NK cells, IRF4 for plasma cells, SOX4 for hematopoietic progenitors, EBF1 and PAX5 for B cells, IRF8 and TCF4 for pDC. We believe that similar strategies can be used to help focus on a set of putative regulators in diverse systems. # identify top markers in NK and visualize head(topTFs("NK"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 NK TBX21 0.7270859 0.000000e+00 NK MA0690.1 0.9139614 ## 2 NK EOMES 0.5886774 2.411013e-98 NK MA0800.1 0.9214773 ## 3 NK RUNX3 0.7705661 5.977716e-120 NK MA0684.2 0.6769022 ## motif.pval avg_auc ## 1 1.097940e-202 0.8205237 ## 2 4.903866e-210 0.7550774 ## 3 1.560061e-38 0.7237341 motif.name <- ConvertMotifID(pbmc, name = 'TBX21') gene_plot <- FeaturePlot(pbmc, features = "sct_TBX21", reduction = 'wnn.umap') motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap') gene_plot | motif_plot # identify top markers in pDC and visualize head(topTFs("pDC"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 pDC TCF4 0.9998815 1.120711e-162 pDC MA0830.2 0.9965481 ## 2 pDC IRF8 0.9904457 1.308164e-123 pDC MA0652.1 0.8833112 ## 3 pDC SPIB 0.9115207 0.000000e+00 pDC MA0081.2 0.9068540 ## motif.pval avg_auc ## 1 1.785897e-69 0.9982148 ## 2 3.982413e-42 0.9368785 ## 3 3.083509e-47 0.9091874 motif.name <- ConvertMotifID(pbmc, name = 'TCF4') gene_plot <- FeaturePlot(pbmc, features = "sct_TCF4", reduction = 'wnn.umap') motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap') gene_plot | motif_plot # identify top markers in HSPC and visualize head(topTFs("CD16 Mono"),3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 CD16 Mono SPI1 0.8793172 1.666810e-296 CD16 Mono MA0080.5 0.8880908 ## 2 CD16 Mono CEBPB 0.8685933 1.625472e-294 CD16 Mono MA0466.2 0.7840422 ## 3 CD16 Mono MEF2C 0.7129910 2.727252e-79 CD16 Mono MA0497.1 0.8059373 ## motif.pval avg_auc ## 1 4.762491e-194 0.8837040 ## 2 7.049764e-105 0.8263177 ## 3 2.345716e-121 0.7594641 motif.name <- ConvertMotifID(pbmc, name = 'SPI1') gene_plot <- FeaturePlot(pbmc, features = "sct_SPI1", reduction = 'wnn.umap') motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap') gene_plot | motif_plot # identify top markers in other cell types head(topTFs("Naive B"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 Naive B MEF2C 0.8802747 1.890065e-182 Naive B MA0497.1 0.6789079 ## 2 Naive B PAX5 0.9436648 0.000000e+00 Naive B MA0014.3 0.5827061 ## 3 Naive B POU2F2 0.6029377 2.892216e-13 Naive B MA0507.1 0.8912268 ## motif.pval avg_auc ## 1 9.815118e-32 0.7795913 ## 2 5.995185e-08 0.7631854 ## 3 6.471677e-145 0.7470822 head(topTFs("HSPC"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 HSPC SOX4 0.9869406 5.524832e-71 HSPC MA0867.2 0.6830497 ## 2 HSPC GATA2 0.7884615 0.000000e+00 HSPC MA0036.3 0.8275008 ## 3 HSPC MEIS1 0.8638496 0.000000e+00 HSPC MA0498.2 0.6924225 ## motif.pval avg_auc ## 1 1.241915e-03 0.8349951 ## 2 7.591798e-09 0.8079812 ## 3 6.877492e-04 0.7781361 head(topTFs("Plasma"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 Plasma IRF4 0.8189687 5.261955e-35 Plasma MA1419.1 0.9776046 ## 2 Plasma MEF2C 0.9111213 2.977155e-12 Plasma MA0497.1 0.7596637 ## 3 Plasma TCF4 0.8049409 6.810635e-12 Plasma MA0830.2 0.7840848 ## motif.pval avg_auc ## 1 2.334627e-12 0.8982867 ## 2 1.374353e-04 0.8353925 ## 3 3.028306e-05 0.7945129Session Info sessionInfo()## R version 4.2.0 (2022-04-22) ## Platform: x86_64-pc-linux-gnu (64-bit) ## Running under: Ubuntu 20.04.5 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/liblapack.so.3 ## ## locale: ## [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C ## [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8 ## [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 ## ## attached base packages: ## [1] stats4 stats graphics grDevices utils datasets methods ## [8] base ## ## other attached packages: ## [1] BSgenome.Hsapiens.UCSC.hg38_1.4.5 BSgenome_1.66.3 ## [3] rtracklayer_1.58.0 Biostrings_2.66.0 ## [5] XVector_0.38.0 motifmatchr_1.20.0 ## [7] TFBSTools_1.36.0 JASPAR2020_0.99.10 ## [9] chromVAR_1.20.2 EnsDb.Hsapiens.v86_2.99.0 ## [11] ensembldb_2.22.0 AnnotationFilter_1.22.0 ## [13] GenomicFeatures_1.50.4 AnnotationDbi_1.60.0 ## [15] Biobase_2.58.0 GenomicRanges_1.50.2 ## [17] GenomeInfoDb_1.35.16 IRanges_2.32.0 ## [19] S4Vectors_0.36.2 BiocGenerics_0.44.0 ## [21] Signac_1.9.0 ggplot2_3.4.1 ## [23] dplyr_1.1.1 cowplot_1.1.1 ## [25] thp1.eccite.SeuratData_3.1.5 stxBrain.SeuratData_0.1.1 ## [27] ssHippo.SeuratData_3.1.4 pbmcsca.SeuratData_3.0.0 ## [29] pbmcMultiome.SeuratData_0.1.2 pbmc3k.SeuratData_3.1.4 ## [31] panc8.SeuratData_3.0.2 ifnb.SeuratData_3.1.0 ## [33] hcabm40k.SeuratData_3.0.0 bmcite.SeuratData_0.3.0 ## [35] SeuratData_0.2.2 SeuratObject_4.1.3 ## [37] Seurat_4.2.1.9001 ## ## loaded via a namespace (and not attached): ## [1] rappdirs_0.3.3 scattermore_0.8 ## [3] R.methodsS3_1.8.2 ragg_1.2.5 ## [5] nabor_0.5.0 tidyr_1.3.0 ## [7] bit64_4.0.5 knitr_1.42 ## [9] R.utils_2.12.2 irlba_2.3.5.1 ## [11] DelayedArray_0.24.0 data.table_1.14.8 ## [13] rpart_4.1.16 KEGGREST_1.38.0 ## [15] RCurl_1.98-1.12 generics_0.1.3 ## [17] RSQLite_2.3.0 RANN_2.6.1 ## [19] future_1.32.0 tzdb_0.3.0 ## [21] bit_4.0.5 spatstat.data_3.0-1 ## [23] xml2_1.3.3 httpuv_1.6.9 ## [25] SummarizedExperiment_1.28.0 DirichletMultinomial_1.40.0 ## [27] xfun_0.38 hms_1.1.2 ## [29] jquerylib_0.1.4 evaluate_0.20 ## [31] promises_1.2.0.1 fansi_1.0.4 ## [33] restfulr_0.0.15 progress_1.2.2 ## [35] caTools_1.18.2 dbplyr_2.3.1 ## [37] igraph_1.4.1 DBI_1.1.3 ## [39] htmlwidgets_1.6.2 spatstat.geom_3.1-0 ## [41] purrr_1.0.1 ellipsis_0.3.2 ## [43] backports_1.4.1 annotate_1.76.0 ## [45] biomaRt_2.54.0 deldir_1.0-6 ## [47] MatrixGenerics_1.10.0 vctrs_0.6.1 ## [49] ROCR_1.0-11 abind_1.4-5 ## [51] cachem_1.0.7 withr_2.5.0 ## [53] progressr_0.13.0 presto_1.0.0 ## [55] checkmate_2.1.0 sctransform_0.3.5 ## [57] GenomicAlignments_1.34.0 prettyunits_1.1.1 ## [59] goftest_1.2-3 cluster_2.1.3 ## [61] seqLogo_1.64.0 lazyeval_0.2.2 ## [63] crayon_1.5.2 hdf5r_1.3.8 ## [65] spatstat.explore_3.1-0 pkgconfig_2.0.3 ## [67] labeling_0.4.2 nlme_3.1-157 ## [69] ProtGenerics_1.30.0 nnet_7.3-17 ## [71] rlang_1.1.0 globals_0.16.2 ## [73] lifecycle_1.0.3 miniUI_0.1.1.1 ## [75] filelock_1.0.2 BiocFileCache_2.6.1 ## [77] dichromat_2.0-0.1 rprojroot_2.0.3 ## [79] polyclip_1.10-4 matrixStats_0.63.0 ## [81] lmtest_0.9-40 Matrix_1.5-3 ## [83] zoo_1.8-11 base64enc_0.1-3 ## [85] ggridges_0.5.4 png_0.1-8 ## [87] viridisLite_0.4.1 rjson_0.2.21 ## [89] bitops_1.0-7 R.oo_1.25.0 ## [91] KernSmooth_2.23-20 blob_1.2.3 ## [93] stringr_1.5.0 parallelly_1.35.0 ## [95] spatstat.random_3.1-4 readr_2.1.4 ## [97] jpeg_0.1-10 CNEr_1.34.0 ## [99] scales_1.2.1 memoise_2.0.1 ## [101] magrittr_2.0.3 plyr_1.8.8 ## [103] ica_1.0-3 zlibbioc_1.44.0 ## [105] compiler_4.2.0 BiocIO_1.8.0 ## [107] RColorBrewer_1.1-3 fitdistrplus_1.1-8 ## [109] Rsamtools_2.14.0 cli_3.6.1 ## [111] listenv_0.9.0 patchwork_1.1.2 ## [113] pbapply_1.7-0 htmlTable_2.4.1 ## [115] Formula_1.2-5 MASS_7.3-56 ## [117] tidyselect_1.2.0 stringi_1.7.12 ## [119] textshaping_0.3.6 highr_0.10 ## [121] yaml_2.3.7 latticeExtra_0.6-30 ## [123] ggrepel_0.9.3 grid_4.2.0 ## [125] sass_0.4.5 VariantAnnotation_1.44.1 ## [127] fastmatch_1.1-3 tools_4.2.0 ## [129] future.apply_1.10.0 parallel_4.2.0 ## [131] rstudioapi_0.14 TFMPvalue_0.0.9 ## [133] foreign_0.8-82 gridExtra_2.3 ## [135] farver_2.1.1 Rtsne_0.16 ## [137] digest_0.6.31 pracma_2.4.2 ## [139] shiny_1.7.4 Rcpp_1.0.10 ## [141] later_1.3.0 RcppAnnoy_0.0.20 ## [143] httr_1.4.5 biovizBase_1.46.0 ## [145] colorspace_2.1-0 XML_3.99-0.13 ## [147] fs_1.6.1 tensor_1.5 ## [149] reticulate_1.28 splines_4.2.0 ## [151] uwot_0.1.14 RcppRoll_0.3.0 ## [153] spatstat.utils_3.0-2 pkgdown_2.0.7 ## [155] sp_1.6-0 plotly_4.10.1 ## [157] systemfonts_1.0.4 xtable_1.8-4 ## [159] poweRlaw_0.70.6 jsonlite_1.8.4 ## [161] R6_2.5.1 Hmisc_4.8-0 ## [163] pillar_1.9.0 htmltools_0.5.5 ## [165] mime_0.12 DT_0.27 ## [167] glue_1.6.2 fastmap_1.1.1 ## [169] BiocParallel_1.32.5 codetools_0.2-18 ## [171] utf8_1.2.3 lattice_0.20-45 ## [173] bslib_0.4.2 spatstat.sparse_3.0-1 ## [175] tibble_3.2.1 curl_5.0.0 ## [177] leiden_0.4.3 gtools_3.9.4 ## [179] GO.db_3.16.0 interp_1.1-3 ## [181] survival_3.3-1 rmarkdown_2.21 ## [183] desc_1.4.2 munsell_0.5.0 ## [185] GenomeInfoDbData_1.2.9 reshape2_1.4.4 ## [187] gtable_0.3.3

To continue, please make sure you have the following packages installed.chromVAR for the analysis of motif accessibility in scATAC-seqpresto for fast differential expression analyses.TFBSTools for TFBS analysisJASPAR2020 for JASPAR motif modelsmotifmatchr for motif matchingBSgenome.Hsapiens.UCSC.hg38 for chromVARInstall command for all dependencies remotes::install_github("immunogenomics/presto") BiocManager::install(c("chromVAR", "TFBSTools", "JASPAR2020", "motifmatchr", "BSgenome.Hsapiens.UCSC.hg38")) library(chromVAR) library(JASPAR2020) library(TFBSTools) library(motifmatchr) library(BSgenome.Hsapiens.UCSC.hg38) # Scan the DNA sequence of each peak for the presence of each motif, and create a Motif object DefaultAssay(pbmc) <- "ATAC" pwm_set <- getMatrixSet(x = JASPAR2020, opts = list(species = 9606, all_versions = FALSE)) motif.matrix <- CreateMotifMatrix(features = granges(pbmc), pwm = pwm_set, genome = 'hg38', use.counts = FALSE) motif.object <- CreateMotifObject(data = motif.matrix, pwm = pwm_set) pbmc <- SetAssayData(pbmc, assay = 'ATAC', slot = 'motifs', new.data = motif.object) # Note that this step can take 30-60 minutes pbmc <- RunChromVAR( object = pbmc, genome = BSgenome.Hsapiens.UCSC.hg38 )Finally, we explore the multimodal dataset to identify key regulators of each cell state. Paired data provides a unique opportunity to identify transcription factors (TFs) that satisfy multiple criteria, helping to narrow down the list of putative regulators to the most likely candidates. We aim to identify TFs whose expression is enriched in multiple cell types in the RNA measurements, but also have enriched accessibility for their motifs in the ATAC measurements.As an example and positive control, the CCAAT Enhancer Binding Protein (CEBP) family of proteins, including the TF CEBPB, have been repeatedly shown to play important roles in the differentiation and function of myeloid cells including monocytes and dendritic cells. We can see that both the expression of the CEBPB, and the accessibility of the MA0466.2.4 motif (which encodes the binding site for CEBPB), are both enriched in monocytes. #returns MA0466.2 motif.name <- ConvertMotifID(pbmc, name = 'CEBPB') gene_plot <- FeaturePlot(pbmc, features = "sct_CEBPB", reduction = 'wnn.umap') motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap') gene_plot | motif_plotWe’d like to quantify this relationship, and search across all cell types to find similar examples. To do so, we will use the presto package to perform fast differential expression. We run two tests: one using gene expression data, and the other using chromVAR motif accessibilities. presto calculates a p-value based on the Wilcox rank sum test, which is also the default test in Seurat, and we restrict our search to TFs that return significant results in both tests.presto also calculates an “AUC” statistic, which reflects the power of each gene (or motif) to serve as a marker of cell type. A maximum AUC value of 1 indicates a perfect marker. Since the AUC statistic is on the same scale for both genes and motifs, we take the average of the AUC values from the two tests, and use this to rank TFs for each cell type: markers_rna <- presto:::wilcoxauc.Seurat(X = pbmc, group_by = 'celltype', assay = 'data', seurat_assay = 'SCT') markers_motifs <- presto:::wilcoxauc.Seurat(X = pbmc, group_by = 'celltype', assay = 'data', seurat_assay = 'chromvar') motif.names <- markers_motifs$feature colnames(markers_rna) <- paste0("RNA.", colnames(markers_rna)) colnames(markers_motifs) <- paste0("motif.", colnames(markers_motifs)) markers_rna$gene <- markers_rna$RNA.feature markers_motifs$gene <- ConvertMotifID(pbmc, id = motif.names) # a simple function to implement the procedure above topTFs <- function(celltype, padj.cutoff = 1e-2) { ctmarkers_rna <- dplyr::filter( markers_rna, RNA.group == celltype, RNA.padj < padj.cutoff, RNA.logFC > 0) %>% arrange(-RNA.auc) ctmarkers_motif <- dplyr::filter( markers_motifs, motif.group == celltype, motif.padj < padj.cutoff, motif.logFC > 0) %>% arrange(-motif.auc) top_tfs <- inner_join( x = ctmarkers_rna[, c(2, 11, 6, 7)], y = ctmarkers_motif[, c(2, 1, 11, 6, 7)], by = "gene" ) top_tfs$avg_auc <- (top_tfs$RNA.auc + top_tfs$motif.auc) / 2 top_tfs <- arrange(top_tfs, -avg_auc) return(top_tfs) }We can now compute, and visualize, putative regulators for any cell type. We recover well-established regulators, including TBX21 for NK cells, IRF4 for plasma cells, SOX4 for hematopoietic progenitors, EBF1 and PAX5 for B cells, IRF8 and TCF4 for pDC. We believe that similar strategies can be used to help focus on a set of putative regulators in diverse systems. # identify top markers in NK and visualize head(topTFs("NK"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 NK TBX21 0.7270859 0.000000e+00 NK MA0690.1 0.9139614 ## 2 NK EOMES 0.5886774 2.411013e-98 NK MA0800.1 0.9214773 ## 3 NK RUNX3 0.7705661 5.977716e-120 NK MA0684.2 0.6769022 ## motif.pval avg_auc ## 1 1.097940e-202 0.8205237 ## 2 4.903866e-210 0.7550774 ## 3 1.560061e-38 0.7237341 motif.name <- ConvertMotifID(pbmc, name = 'TBX21') gene_plot <- FeaturePlot(pbmc, features = "sct_TBX21", reduction = 'wnn.umap') motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap') gene_plot | motif_plot # identify top markers in pDC and visualize head(topTFs("pDC"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 pDC TCF4 0.9998815 1.120711e-162 pDC MA0830.2 0.9965481 ## 2 pDC IRF8 0.9904457 1.308164e-123 pDC MA0652.1 0.8833112 ## 3 pDC SPIB 0.9115207 0.000000e+00 pDC MA0081.2 0.9068540 ## motif.pval avg_auc ## 1 1.785897e-69 0.9982148 ## 2 3.982413e-42 0.9368785 ## 3 3.083509e-47 0.9091874 motif.name <- ConvertMotifID(pbmc, name = 'TCF4') gene_plot <- FeaturePlot(pbmc, features = "sct_TCF4", reduction = 'wnn.umap') motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap') gene_plot | motif_plot # identify top markers in HSPC and visualize head(topTFs("CD16 Mono"),3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 CD16 Mono SPI1 0.8793172 1.666810e-296 CD16 Mono MA0080.5 0.8880908 ## 2 CD16 Mono CEBPB 0.8685933 1.625472e-294 CD16 Mono MA0466.2 0.7840422 ## 3 CD16 Mono MEF2C 0.7129910 2.727252e-79 CD16 Mono MA0497.1 0.8059373 ## motif.pval avg_auc ## 1 4.762491e-194 0.8837040 ## 2 7.049764e-105 0.8263177 ## 3 2.345716e-121 0.7594641 motif.name <- ConvertMotifID(pbmc, name = 'SPI1') gene_plot <- FeaturePlot(pbmc, features = "sct_SPI1", reduction = 'wnn.umap') motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap') gene_plot | motif_plot # identify top markers in other cell types head(topTFs("Naive B"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 Naive B MEF2C 0.8802747 1.890065e-182 Naive B MA0497.1 0.6789079 ## 2 Naive B PAX5 0.9436648 0.000000e+00 Naive B MA0014.3 0.5827061 ## 3 Naive B POU2F2 0.6029377 2.892216e-13 Naive B MA0507.1 0.8912268 ## motif.pval avg_auc ## 1 9.815118e-32 0.7795913 ## 2 5.995185e-08 0.7631854 ## 3 6.471677e-145 0.7470822 head(topTFs("HSPC"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 HSPC SOX4 0.9869406 5.524832e-71 HSPC MA0867.2 0.6830497 ## 2 HSPC GATA2 0.7884615 0.000000e+00 HSPC MA0036.3 0.8275008 ## 3 HSPC MEIS1 0.8638496 0.000000e+00 HSPC MA0498.2 0.6924225 ## motif.pval avg_auc ## 1 1.241915e-03 0.8349951 ## 2 7.591798e-09 0.8079812 ## 3 6.877492e-04 0.7781361 head(topTFs("Plasma"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 Plasma IRF4 0.8189687 5.261955e-35 Plasma MA1419.1 0.9776046 ## 2 Plasma MEF2C 0.9111213 2.977155e-12 Plasma MA0497.1 0.7596637 ## 3 Plasma TCF4 0.8049409 6.810635e-12 Plasma MA0830.2 0.7840848 ## motif.pval avg_auc ## 1 2.334627e-12 0.8982867 ## 2 1.374353e-04 0.8353925 ## 3 3.028306e-05 0.7945129Session Info sessionInfo()## R version 4.2.0 (2022-04-22) ## Platform: x86_64-pc-linux-gnu (64-bit) ## Running under: Ubuntu 20.04.5 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/liblapack.so.3 ## ## locale: ## [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C ## [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8 ## [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 ## ## attached base packages: ## [1] stats4 stats graphics grDevices utils datasets methods ## [8] base ## ## other attached packages: ## [1] BSgenome.Hsapiens.UCSC.hg38_1.4.5 BSgenome_1.66.3 ## [3] rtracklayer_1.58.0 Biostrings_2.66.0 ## [5] XVector_0.38.0 motifmatchr_1.20.0 ## [7] TFBSTools_1.36.0 JASPAR2020_0.99.10 ## [9] chromVAR_1.20.2 EnsDb.Hsapiens.v86_2.99.0 ## [11] ensembldb_2.22.0 AnnotationFilter_1.22.0 ## [13] GenomicFeatures_1.50.4 AnnotationDbi_1.60.0 ## [15] Biobase_2.58.0 GenomicRanges_1.50.2 ## [17] GenomeInfoDb_1.35.16 IRanges_2.32.0 ## [19] S4Vectors_0.36.2 BiocGenerics_0.44.0 ## [21] Signac_1.9.0 ggplot2_3.4.1 ## [23] dplyr_1.1.1 cowplot_1.1.1 ## [25] thp1.eccite.SeuratData_3.1.5 stxBrain.SeuratData_0.1.1 ## [27] ssHippo.SeuratData_3.1.4 pbmcsca.SeuratData_3.0.0 ## [29] pbmcMultiome.SeuratData_0.1.2 pbmc3k.SeuratData_3.1.4 ## [31] panc8.SeuratData_3.0.2 ifnb.SeuratData_3.1.0 ## [33] hcabm40k.SeuratData_3.0.0 bmcite.SeuratData_0.3.0 ## [35] SeuratData_0.2.2 SeuratObject_4.1.3 ## [37] Seurat_4.2.1.9001 ## ## loaded via a namespace (and not attached): ## [1] rappdirs_0.3.3 scattermore_0.8 ## [3] R.methodsS3_1.8.2 ragg_1.2.5 ## [5] nabor_0.5.0 tidyr_1.3.0 ## [7] bit64_4.0.5 knitr_1.42 ## [9] R.utils_2.12.2 irlba_2.3.5.1 ## [11] DelayedArray_0.24.0 data.table_1.14.8 ## [13] rpart_4.1.16 KEGGREST_1.38.0 ## [15] RCurl_1.98-1.12 generics_0.1.3 ## [17] RSQLite_2.3.0 RANN_2.6.1 ## [19] future_1.32.0 tzdb_0.3.0 ## [21] bit_4.0.5 spatstat.data_3.0-1 ## [23] xml2_1.3.3 httpuv_1.6.9 ## [25] SummarizedExperiment_1.28.0 DirichletMultinomial_1.40.0 ## [27] xfun_0.38 hms_1.1.2 ## [29] jquerylib_0.1.4 evaluate_0.20 ## [31] promises_1.2.0.1 fansi_1.0.4 ## [33] restfulr_0.0.15 progress_1.2.2 ## [35] caTools_1.18.2 dbplyr_2.3.1 ## [37] igraph_1.4.1 DBI_1.1.3 ## [39] htmlwidgets_1.6.2 spatstat.geom_3.1-0 ## [41] purrr_1.0.1 ellipsis_0.3.2 ## [43] backports_1.4.1 annotate_1.76.0 ## [45] biomaRt_2.54.0 deldir_1.0-6 ## [47] MatrixGenerics_1.10.0 vctrs_0.6.1 ## [49] ROCR_1.0-11 abind_1.4-5 ## [51] cachem_1.0.7 withr_2.5.0 ## [53] progressr_0.13.0 presto_1.0.0 ## [55] checkmate_2.1.0 sctransform_0.3.5 ## [57] GenomicAlignments_1.34.0 prettyunits_1.1.1 ## [59] goftest_1.2-3 cluster_2.1.3 ## [61] seqLogo_1.64.0 lazyeval_0.2.2 ## [63] crayon_1.5.2 hdf5r_1.3.8 ## [65] spatstat.explore_3.1-0 pkgconfig_2.0.3 ## [67] labeling_0.4.2 nlme_3.1-157 ## [69] ProtGenerics_1.30.0 nnet_7.3-17 ## [71] rlang_1.1.0 globals_0.16.2 ## [73] lifecycle_1.0.3 miniUI_0.1.1.1 ## [75] filelock_1.0.2 BiocFileCache_2.6.1 ## [77] dichromat_2.0-0.1 rprojroot_2.0.3 ## [79] polyclip_1.10-4 matrixStats_0.63.0 ## [81] lmtest_0.9-40 Matrix_1.5-3 ## [83] zoo_1.8-11 base64enc_0.1-3 ## [85] ggridges_0.5.4 png_0.1-8 ## [87] viridisLite_0.4.1 rjson_0.2.21 ## [89] bitops_1.0-7 R.oo_1.25.0 ## [91] KernSmooth_2.23-20 blob_1.2.3 ## [93] stringr_1.5.0 parallelly_1.35.0 ## [95] spatstat.random_3.1-4 readr_2.1.4 ## [97] jpeg_0.1-10 CNEr_1.34.0 ## [99] scales_1.2.1 memoise_2.0.1 ## [101] magrittr_2.0.3 plyr_1.8.8 ## [103] ica_1.0-3 zlibbioc_1.44.0 ## [105] compiler_4.2.0 BiocIO_1.8.0 ## [107] RColorBrewer_1.1-3 fitdistrplus_1.1-8 ## [109] Rsamtools_2.14.0 cli_3.6.1 ## [111] listenv_0.9.0 patchwork_1.1.2 ## [113] pbapply_1.7-0 htmlTable_2.4.1 ## [115] Formula_1.2-5 MASS_7.3-56 ## [117] tidyselect_1.2.0 stringi_1.7.12 ## [119] textshaping_0.3.6 highr_0.10 ## [121] yaml_2.3.7 latticeExtra_0.6-30 ## [123] ggrepel_0.9.3 grid_4.2.0 ## [125] sass_0.4.5 VariantAnnotation_1.44.1 ## [127] fastmatch_1.1-3 tools_4.2.0 ## [129] future.apply_1.10.0 parallel_4.2.0 ## [131] rstudioapi_0.14 TFMPvalue_0.0.9 ## [133] foreign_0.8-82 gridExtra_2.3 ## [135] farver_2.1.1 Rtsne_0.16 ## [137] digest_0.6.31 pracma_2.4.2 ## [139] shiny_1.7.4 Rcpp_1.0.10 ## [141] later_1.3.0 RcppAnnoy_0.0.20 ## [143] httr_1.4.5 biovizBase_1.46.0 ## [145] colorspace_2.1-0 XML_3.99-0.13 ## [147] fs_1.6.1 tensor_1.5 ## [149] reticulate_1.28 splines_4.2.0 ## [151] uwot_0.1.14 RcppRoll_0.3.0 ## [153] spatstat.utils_3.0-2 pkgdown_2.0.7 ## [155] sp_1.6-0 plotly_4.10.1 ## [157] systemfonts_1.0.4 xtable_1.8-4 ## [159] poweRlaw_0.70.6 jsonlite_1.8.4 ## [161] R6_2.5.1 Hmisc_4.8-0 ## [163] pillar_1.9.0 htmltools_0.5.5 ## [165] mime_0.12 DT_0.27 ## [167] glue_1.6.2 fastmap_1.1.1 ## [169] BiocParallel_1.32.5 codetools_0.2-18 ## [171] utf8_1.2.3 lattice_0.20-45 ## [173] bslib_0.4.2 spatstat.sparse_3.0-1 ## [175] tibble_3.2.1 curl_5.0.0 ## [177] leiden_0.4.3 gtools_3.9.4 ## [179] GO.db_3.16.0 interp_1.1-3 ## [181] survival_3.3-1 rmarkdown_2.21 ## [183] desc_1.4.2 munsell_0.5.0 ## [185] GenomeInfoDbData_1.2.9 reshape2_1.4.4 ## [187] gtable_0.3.3

remotes::install_github("immunogenomics/presto") BiocManager::install(c("chromVAR", "TFBSTools", "JASPAR2020", "motifmatchr", "BSgenome.Hsapiens.UCSC.hg38"))

Finally, we explore the multimodal dataset to identify key regulators of each cell state. Paired data provides a unique opportunity to identify transcription factors (TFs) that satisfy multiple criteria, helping to narrow down the list of putative regulators to the most likely candidates. We aim to identify TFs whose expression is enriched in multiple cell types in the RNA measurements, but also have enriched accessibility for their motifs in the ATAC measurements.As an example and positive control, the CCAAT Enhancer Binding Protein (CEBP) family of proteins, including the TF CEBPB, have been repeatedly shown to play important roles in the differentiation and function of myeloid cells including monocytes and dendritic cells. We can see that both the expression of the CEBPB, and the accessibility of the MA0466.2.4 motif (which encodes the binding site for CEBPB), are both enriched in monocytes. #returns MA0466.2 motif.name <- ConvertMotifID(pbmc, name = 'CEBPB') gene_plot <- FeaturePlot(pbmc, features = "sct_CEBPB", reduction = 'wnn.umap') motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap') gene_plot | motif_plotWe’d like to quantify this relationship, and search across all cell types to find similar examples. To do so, we will use the presto package to perform fast differential expression. We run two tests: one using gene expression data, and the other using chromVAR motif accessibilities. presto calculates a p-value based on the Wilcox rank sum test, which is also the default test in Seurat, and we restrict our search to TFs that return significant results in both tests.presto also calculates an “AUC” statistic, which reflects the power of each gene (or motif) to serve as a marker of cell type. A maximum AUC value of 1 indicates a perfect marker. Since the AUC statistic is on the same scale for both genes and motifs, we take the average of the AUC values from the two tests, and use this to rank TFs for each cell type: markers_rna <- presto:::wilcoxauc.Seurat(X = pbmc, group_by = 'celltype', assay = 'data', seurat_assay = 'SCT') markers_motifs <- presto:::wilcoxauc.Seurat(X = pbmc, group_by = 'celltype', assay = 'data', seurat_assay = 'chromvar') motif.names <- markers_motifs$feature colnames(markers_rna) <- paste0("RNA.", colnames(markers_rna)) colnames(markers_motifs) <- paste0("motif.", colnames(markers_motifs)) markers_rna$gene <- markers_rna$RNA.feature markers_motifs$gene <- ConvertMotifID(pbmc, id = motif.names) # a simple function to implement the procedure above topTFs <- function(celltype, padj.cutoff = 1e-2) { ctmarkers_rna <- dplyr::filter( markers_rna, RNA.group == celltype, RNA.padj < padj.cutoff, RNA.logFC > 0) %>% arrange(-RNA.auc) ctmarkers_motif <- dplyr::filter( markers_motifs, motif.group == celltype, motif.padj < padj.cutoff, motif.logFC > 0) %>% arrange(-motif.auc) top_tfs <- inner_join( x = ctmarkers_rna[, c(2, 11, 6, 7)], y = ctmarkers_motif[, c(2, 1, 11, 6, 7)], by = "gene" ) top_tfs$avg_auc <- (top_tfs$RNA.auc + top_tfs$motif.auc) / 2 top_tfs <- arrange(top_tfs, -avg_auc) return(top_tfs) }We can now compute, and visualize, putative regulators for any cell type. We recover well-established regulators, including TBX21 for NK cells, IRF4 for plasma cells, SOX4 for hematopoietic progenitors, EBF1 and PAX5 for B cells, IRF8 and TCF4 for pDC. We believe that similar strategies can be used to help focus on a set of putative regulators in diverse systems. # identify top markers in NK and visualize head(topTFs("NK"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 NK TBX21 0.7270859 0.000000e+00 NK MA0690.1 0.9139614 ## 2 NK EOMES 0.5886774 2.411013e-98 NK MA0800.1 0.9214773 ## 3 NK RUNX3 0.7705661 5.977716e-120 NK MA0684.2 0.6769022 ## motif.pval avg_auc ## 1 1.097940e-202 0.8205237 ## 2 4.903866e-210 0.7550774 ## 3 1.560061e-38 0.7237341 motif.name <- ConvertMotifID(pbmc, name = 'TBX21') gene_plot <- FeaturePlot(pbmc, features = "sct_TBX21", reduction = 'wnn.umap') motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap') gene_plot | motif_plot # identify top markers in pDC and visualize head(topTFs("pDC"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 pDC TCF4 0.9998815 1.120711e-162 pDC MA0830.2 0.9965481 ## 2 pDC IRF8 0.9904457 1.308164e-123 pDC MA0652.1 0.8833112 ## 3 pDC SPIB 0.9115207 0.000000e+00 pDC MA0081.2 0.9068540 ## motif.pval avg_auc ## 1 1.785897e-69 0.9982148 ## 2 3.982413e-42 0.9368785 ## 3 3.083509e-47 0.9091874 motif.name <- ConvertMotifID(pbmc, name = 'TCF4') gene_plot <- FeaturePlot(pbmc, features = "sct_TCF4", reduction = 'wnn.umap') motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap') gene_plot | motif_plot # identify top markers in HSPC and visualize head(topTFs("CD16 Mono"),3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 CD16 Mono SPI1 0.8793172 1.666810e-296 CD16 Mono MA0080.5 0.8880908 ## 2 CD16 Mono CEBPB 0.8685933 1.625472e-294 CD16 Mono MA0466.2 0.7840422 ## 3 CD16 Mono MEF2C 0.7129910 2.727252e-79 CD16 Mono MA0497.1 0.8059373 ## motif.pval avg_auc ## 1 4.762491e-194 0.8837040 ## 2 7.049764e-105 0.8263177 ## 3 2.345716e-121 0.7594641 motif.name <- ConvertMotifID(pbmc, name = 'SPI1') gene_plot <- FeaturePlot(pbmc, features = "sct_SPI1", reduction = 'wnn.umap') motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap') gene_plot | motif_plot # identify top markers in other cell types head(topTFs("Naive B"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 Naive B MEF2C 0.8802747 1.890065e-182 Naive B MA0497.1 0.6789079 ## 2 Naive B PAX5 0.9436648 0.000000e+00 Naive B MA0014.3 0.5827061 ## 3 Naive B POU2F2 0.6029377 2.892216e-13 Naive B MA0507.1 0.8912268 ## motif.pval avg_auc ## 1 9.815118e-32 0.7795913 ## 2 5.995185e-08 0.7631854 ## 3 6.471677e-145 0.7470822 head(topTFs("HSPC"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 HSPC SOX4 0.9869406 5.524832e-71 HSPC MA0867.2 0.6830497 ## 2 HSPC GATA2 0.7884615 0.000000e+00 HSPC MA0036.3 0.8275008 ## 3 HSPC MEIS1 0.8638496 0.000000e+00 HSPC MA0498.2 0.6924225 ## motif.pval avg_auc ## 1 1.241915e-03 0.8349951 ## 2 7.591798e-09 0.8079812 ## 3 6.877492e-04 0.7781361 head(topTFs("Plasma"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 Plasma IRF4 0.8189687 5.261955e-35 Plasma MA1419.1 0.9776046 ## 2 Plasma MEF2C 0.9111213 2.977155e-12 Plasma MA0497.1 0.7596637 ## 3 Plasma TCF4 0.8049409 6.810635e-12 Plasma MA0830.2 0.7840848 ## motif.pval avg_auc ## 1 2.334627e-12 0.8982867 ## 2 1.374353e-04 0.8353925 ## 3 3.028306e-05 0.7945129Session Info sessionInfo()## R version 4.2.0 (2022-04-22) ## Platform: x86_64-pc-linux-gnu (64-bit) ## Running under: Ubuntu 20.04.5 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/liblapack.so.3 ## ## locale: ## [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C ## [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8 ## [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 ## ## attached base packages: ## [1] stats4 stats graphics grDevices utils datasets methods ## [8] base ## ## other attached packages: ## [1] BSgenome.Hsapiens.UCSC.hg38_1.4.5 BSgenome_1.66.3 ## [3] rtracklayer_1.58.0 Biostrings_2.66.0 ## [5] XVector_0.38.0 motifmatchr_1.20.0 ## [7] TFBSTools_1.36.0 JASPAR2020_0.99.10 ## [9] chromVAR_1.20.2 EnsDb.Hsapiens.v86_2.99.0 ## [11] ensembldb_2.22.0 AnnotationFilter_1.22.0 ## [13] GenomicFeatures_1.50.4 AnnotationDbi_1.60.0 ## [15] Biobase_2.58.0 GenomicRanges_1.50.2 ## [17] GenomeInfoDb_1.35.16 IRanges_2.32.0 ## [19] S4Vectors_0.36.2 BiocGenerics_0.44.0 ## [21] Signac_1.9.0 ggplot2_3.4.1 ## [23] dplyr_1.1.1 cowplot_1.1.1 ## [25] thp1.eccite.SeuratData_3.1.5 stxBrain.SeuratData_0.1.1 ## [27] ssHippo.SeuratData_3.1.4 pbmcsca.SeuratData_3.0.0 ## [29] pbmcMultiome.SeuratData_0.1.2 pbmc3k.SeuratData_3.1.4 ## [31] panc8.SeuratData_3.0.2 ifnb.SeuratData_3.1.0 ## [33] hcabm40k.SeuratData_3.0.0 bmcite.SeuratData_0.3.0 ## [35] SeuratData_0.2.2 SeuratObject_4.1.3 ## [37] Seurat_4.2.1.9001 ## ## loaded via a namespace (and not attached): ## [1] rappdirs_0.3.3 scattermore_0.8 ## [3] R.methodsS3_1.8.2 ragg_1.2.5 ## [5] nabor_0.5.0 tidyr_1.3.0 ## [7] bit64_4.0.5 knitr_1.42 ## [9] R.utils_2.12.2 irlba_2.3.5.1 ## [11] DelayedArray_0.24.0 data.table_1.14.8 ## [13] rpart_4.1.16 KEGGREST_1.38.0 ## [15] RCurl_1.98-1.12 generics_0.1.3 ## [17] RSQLite_2.3.0 RANN_2.6.1 ## [19] future_1.32.0 tzdb_0.3.0 ## [21] bit_4.0.5 spatstat.data_3.0-1 ## [23] xml2_1.3.3 httpuv_1.6.9 ## [25] SummarizedExperiment_1.28.0 DirichletMultinomial_1.40.0 ## [27] xfun_0.38 hms_1.1.2 ## [29] jquerylib_0.1.4 evaluate_0.20 ## [31] promises_1.2.0.1 fansi_1.0.4 ## [33] restfulr_0.0.15 progress_1.2.2 ## [35] caTools_1.18.2 dbplyr_2.3.1 ## [37] igraph_1.4.1 DBI_1.1.3 ## [39] htmlwidgets_1.6.2 spatstat.geom_3.1-0 ## [41] purrr_1.0.1 ellipsis_0.3.2 ## [43] backports_1.4.1 annotate_1.76.0 ## [45] biomaRt_2.54.0 deldir_1.0-6 ## [47] MatrixGenerics_1.10.0 vctrs_0.6.1 ## [49] ROCR_1.0-11 abind_1.4-5 ## [51] cachem_1.0.7 withr_2.5.0 ## [53] progressr_0.13.0 presto_1.0.0 ## [55] checkmate_2.1.0 sctransform_0.3.5 ## [57] GenomicAlignments_1.34.0 prettyunits_1.1.1 ## [59] goftest_1.2-3 cluster_2.1.3 ## [61] seqLogo_1.64.0 lazyeval_0.2.2 ## [63] crayon_1.5.2 hdf5r_1.3.8 ## [65] spatstat.explore_3.1-0 pkgconfig_2.0.3 ## [67] labeling_0.4.2 nlme_3.1-157 ## [69] ProtGenerics_1.30.0 nnet_7.3-17 ## [71] rlang_1.1.0 globals_0.16.2 ## [73] lifecycle_1.0.3 miniUI_0.1.1.1 ## [75] filelock_1.0.2 BiocFileCache_2.6.1 ## [77] dichromat_2.0-0.1 rprojroot_2.0.3 ## [79] polyclip_1.10-4 matrixStats_0.63.0 ## [81] lmtest_0.9-40 Matrix_1.5-3 ## [83] zoo_1.8-11 base64enc_0.1-3 ## [85] ggridges_0.5.4 png_0.1-8 ## [87] viridisLite_0.4.1 rjson_0.2.21 ## [89] bitops_1.0-7 R.oo_1.25.0 ## [91] KernSmooth_2.23-20 blob_1.2.3 ## [93] stringr_1.5.0 parallelly_1.35.0 ## [95] spatstat.random_3.1-4 readr_2.1.4 ## [97] jpeg_0.1-10 CNEr_1.34.0 ## [99] scales_1.2.1 memoise_2.0.1 ## [101] magrittr_2.0.3 plyr_1.8.8 ## [103] ica_1.0-3 zlibbioc_1.44.0 ## [105] compiler_4.2.0 BiocIO_1.8.0 ## [107] RColorBrewer_1.1-3 fitdistrplus_1.1-8 ## [109] Rsamtools_2.14.0 cli_3.6.1 ## [111] listenv_0.9.0 patchwork_1.1.2 ## [113] pbapply_1.7-0 htmlTable_2.4.1 ## [115] Formula_1.2-5 MASS_7.3-56 ## [117] tidyselect_1.2.0 stringi_1.7.12 ## [119] textshaping_0.3.6 highr_0.10 ## [121] yaml_2.3.7 latticeExtra_0.6-30 ## [123] ggrepel_0.9.3 grid_4.2.0 ## [125] sass_0.4.5 VariantAnnotation_1.44.1 ## [127] fastmatch_1.1-3 tools_4.2.0 ## [129] future.apply_1.10.0 parallel_4.2.0 ## [131] rstudioapi_0.14 TFMPvalue_0.0.9 ## [133] foreign_0.8-82 gridExtra_2.3 ## [135] farver_2.1.1 Rtsne_0.16 ## [137] digest_0.6.31 pracma_2.4.2 ## [139] shiny_1.7.4 Rcpp_1.0.10 ## [141] later_1.3.0 RcppAnnoy_0.0.20 ## [143] httr_1.4.5 biovizBase_1.46.0 ## [145] colorspace_2.1-0 XML_3.99-0.13 ## [147] fs_1.6.1 tensor_1.5 ## [149] reticulate_1.28 splines_4.2.0 ## [151] uwot_0.1.14 RcppRoll_0.3.0 ## [153] spatstat.utils_3.0-2 pkgdown_2.0.7 ## [155] sp_1.6-0 plotly_4.10.1 ## [157] systemfonts_1.0.4 xtable_1.8-4 ## [159] poweRlaw_0.70.6 jsonlite_1.8.4 ## [161] R6_2.5.1 Hmisc_4.8-0 ## [163] pillar_1.9.0 htmltools_0.5.5 ## [165] mime_0.12 DT_0.27 ## [167] glue_1.6.2 fastmap_1.1.1 ## [169] BiocParallel_1.32.5 codetools_0.2-18 ## [171] utf8_1.2.3 lattice_0.20-45 ## [173] bslib_0.4.2 spatstat.sparse_3.0-1 ## [175] tibble_3.2.1 curl_5.0.0 ## [177] leiden_0.4.3 gtools_3.9.4 ## [179] GO.db_3.16.0 interp_1.1-3 ## [181] survival_3.3-1 rmarkdown_2.21 ## [183] desc_1.4.2 munsell_0.5.0 ## [185] GenomeInfoDbData_1.2.9 reshape2_1.4.4 ## [187] gtable_0.3.3

As an example and positive control, the CCAAT Enhancer Binding Protein (CEBP) family of proteins, including the TF CEBPB, have been repeatedly shown to play important roles in the differentiation and function of myeloid cells including monocytes and dendritic cells. We can see that both the expression of the CEBPB, and the accessibility of the MA0466.2.4 motif (which encodes the binding site for CEBPB), are both enriched in monocytes. #returns MA0466.2 motif.name <- ConvertMotifID(pbmc, name = 'CEBPB') gene_plot <- FeaturePlot(pbmc, features = "sct_CEBPB", reduction = 'wnn.umap') motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap') gene_plot | motif_plotWe’d like to quantify this relationship, and search across all cell types to find similar examples. To do so, we will use the presto package to perform fast differential expression. We run two tests: one using gene expression data, and the other using chromVAR motif accessibilities. presto calculates a p-value based on the Wilcox rank sum test, which is also the default test in Seurat, and we restrict our search to TFs that return significant results in both tests.presto also calculates an “AUC” statistic, which reflects the power of each gene (or motif) to serve as a marker of cell type. A maximum AUC value of 1 indicates a perfect marker. Since the AUC statistic is on the same scale for both genes and motifs, we take the average of the AUC values from the two tests, and use this to rank TFs for each cell type: markers_rna <- presto:::wilcoxauc.Seurat(X = pbmc, group_by = 'celltype', assay = 'data', seurat_assay = 'SCT') markers_motifs <- presto:::wilcoxauc.Seurat(X = pbmc, group_by = 'celltype', assay = 'data', seurat_assay = 'chromvar') motif.names <- markers_motifs$feature colnames(markers_rna) <- paste0("RNA.", colnames(markers_rna)) colnames(markers_motifs) <- paste0("motif.", colnames(markers_motifs)) markers_rna$gene <- markers_rna$RNA.feature markers_motifs$gene <- ConvertMotifID(pbmc, id = motif.names) # a simple function to implement the procedure above topTFs <- function(celltype, padj.cutoff = 1e-2) { ctmarkers_rna <- dplyr::filter( markers_rna, RNA.group == celltype, RNA.padj < padj.cutoff, RNA.logFC > 0) %>% arrange(-RNA.auc) ctmarkers_motif <- dplyr::filter( markers_motifs, motif.group == celltype, motif.padj < padj.cutoff, motif.logFC > 0) %>% arrange(-motif.auc) top_tfs <- inner_join( x = ctmarkers_rna[, c(2, 11, 6, 7)], y = ctmarkers_motif[, c(2, 1, 11, 6, 7)], by = "gene" ) top_tfs$avg_auc <- (top_tfs$RNA.auc + top_tfs$motif.auc) / 2 top_tfs <- arrange(top_tfs, -avg_auc) return(top_tfs) }We can now compute, and visualize, putative regulators for any cell type. We recover well-established regulators, including TBX21 for NK cells, IRF4 for plasma cells, SOX4 for hematopoietic progenitors, EBF1 and PAX5 for B cells, IRF8 and TCF4 for pDC. We believe that similar strategies can be used to help focus on a set of putative regulators in diverse systems. # identify top markers in NK and visualize head(topTFs("NK"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 NK TBX21 0.7270859 0.000000e+00 NK MA0690.1 0.9139614 ## 2 NK EOMES 0.5886774 2.411013e-98 NK MA0800.1 0.9214773 ## 3 NK RUNX3 0.7705661 5.977716e-120 NK MA0684.2 0.6769022 ## motif.pval avg_auc ## 1 1.097940e-202 0.8205237 ## 2 4.903866e-210 0.7550774 ## 3 1.560061e-38 0.7237341 motif.name <- ConvertMotifID(pbmc, name = 'TBX21') gene_plot <- FeaturePlot(pbmc, features = "sct_TBX21", reduction = 'wnn.umap') motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap') gene_plot | motif_plot # identify top markers in pDC and visualize head(topTFs("pDC"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 pDC TCF4 0.9998815 1.120711e-162 pDC MA0830.2 0.9965481 ## 2 pDC IRF8 0.9904457 1.308164e-123 pDC MA0652.1 0.8833112 ## 3 pDC SPIB 0.9115207 0.000000e+00 pDC MA0081.2 0.9068540 ## motif.pval avg_auc ## 1 1.785897e-69 0.9982148 ## 2 3.982413e-42 0.9368785 ## 3 3.083509e-47 0.9091874 motif.name <- ConvertMotifID(pbmc, name = 'TCF4') gene_plot <- FeaturePlot(pbmc, features = "sct_TCF4", reduction = 'wnn.umap') motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap') gene_plot | motif_plot # identify top markers in HSPC and visualize head(topTFs("CD16 Mono"),3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 CD16 Mono SPI1 0.8793172 1.666810e-296 CD16 Mono MA0080.5 0.8880908 ## 2 CD16 Mono CEBPB 0.8685933 1.625472e-294 CD16 Mono MA0466.2 0.7840422 ## 3 CD16 Mono MEF2C 0.7129910 2.727252e-79 CD16 Mono MA0497.1 0.8059373 ## motif.pval avg_auc ## 1 4.762491e-194 0.8837040 ## 2 7.049764e-105 0.8263177 ## 3 2.345716e-121 0.7594641 motif.name <- ConvertMotifID(pbmc, name = 'SPI1') gene_plot <- FeaturePlot(pbmc, features = "sct_SPI1", reduction = 'wnn.umap') motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap') gene_plot | motif_plot # identify top markers in other cell types head(topTFs("Naive B"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 Naive B MEF2C 0.8802747 1.890065e-182 Naive B MA0497.1 0.6789079 ## 2 Naive B PAX5 0.9436648 0.000000e+00 Naive B MA0014.3 0.5827061 ## 3 Naive B POU2F2 0.6029377 2.892216e-13 Naive B MA0507.1 0.8912268 ## motif.pval avg_auc ## 1 9.815118e-32 0.7795913 ## 2 5.995185e-08 0.7631854 ## 3 6.471677e-145 0.7470822 head(topTFs("HSPC"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 HSPC SOX4 0.9869406 5.524832e-71 HSPC MA0867.2 0.6830497 ## 2 HSPC GATA2 0.7884615 0.000000e+00 HSPC MA0036.3 0.8275008 ## 3 HSPC MEIS1 0.8638496 0.000000e+00 HSPC MA0498.2 0.6924225 ## motif.pval avg_auc ## 1 1.241915e-03 0.8349951 ## 2 7.591798e-09 0.8079812 ## 3 6.877492e-04 0.7781361 head(topTFs("Plasma"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 Plasma IRF4 0.8189687 5.261955e-35 Plasma MA1419.1 0.9776046 ## 2 Plasma MEF2C 0.9111213 2.977155e-12 Plasma MA0497.1 0.7596637 ## 3 Plasma TCF4 0.8049409 6.810635e-12 Plasma MA0830.2 0.7840848 ## motif.pval avg_auc ## 1 2.334627e-12 0.8982867 ## 2 1.374353e-04 0.8353925 ## 3 3.028306e-05 0.7945129Session Info sessionInfo()## R version 4.2.0 (2022-04-22) ## Platform: x86_64-pc-linux-gnu (64-bit) ## Running under: Ubuntu 20.04.5 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/liblapack.so.3 ## ## locale: ## [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C ## [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8 ## [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 ## ## attached base packages: ## [1] stats4 stats graphics grDevices utils datasets methods ## [8] base ## ## other attached packages: ## [1] BSgenome.Hsapiens.UCSC.hg38_1.4.5 BSgenome_1.66.3 ## [3] rtracklayer_1.58.0 Biostrings_2.66.0 ## [5] XVector_0.38.0 motifmatchr_1.20.0 ## [7] TFBSTools_1.36.0 JASPAR2020_0.99.10 ## [9] chromVAR_1.20.2 EnsDb.Hsapiens.v86_2.99.0 ## [11] ensembldb_2.22.0 AnnotationFilter_1.22.0 ## [13] GenomicFeatures_1.50.4 AnnotationDbi_1.60.0 ## [15] Biobase_2.58.0 GenomicRanges_1.50.2 ## [17] GenomeInfoDb_1.35.16 IRanges_2.32.0 ## [19] S4Vectors_0.36.2 BiocGenerics_0.44.0 ## [21] Signac_1.9.0 ggplot2_3.4.1 ## [23] dplyr_1.1.1 cowplot_1.1.1 ## [25] thp1.eccite.SeuratData_3.1.5 stxBrain.SeuratData_0.1.1 ## [27] ssHippo.SeuratData_3.1.4 pbmcsca.SeuratData_3.0.0 ## [29] pbmcMultiome.SeuratData_0.1.2 pbmc3k.SeuratData_3.1.4 ## [31] panc8.SeuratData_3.0.2 ifnb.SeuratData_3.1.0 ## [33] hcabm40k.SeuratData_3.0.0 bmcite.SeuratData_0.3.0 ## [35] SeuratData_0.2.2 SeuratObject_4.1.3 ## [37] Seurat_4.2.1.9001 ## ## loaded via a namespace (and not attached): ## [1] rappdirs_0.3.3 scattermore_0.8 ## [3] R.methodsS3_1.8.2 ragg_1.2.5 ## [5] nabor_0.5.0 tidyr_1.3.0 ## [7] bit64_4.0.5 knitr_1.42 ## [9] R.utils_2.12.2 irlba_2.3.5.1 ## [11] DelayedArray_0.24.0 data.table_1.14.8 ## [13] rpart_4.1.16 KEGGREST_1.38.0 ## [15] RCurl_1.98-1.12 generics_0.1.3 ## [17] RSQLite_2.3.0 RANN_2.6.1 ## [19] future_1.32.0 tzdb_0.3.0 ## [21] bit_4.0.5 spatstat.data_3.0-1 ## [23] xml2_1.3.3 httpuv_1.6.9 ## [25] SummarizedExperiment_1.28.0 DirichletMultinomial_1.40.0 ## [27] xfun_0.38 hms_1.1.2 ## [29] jquerylib_0.1.4 evaluate_0.20 ## [31] promises_1.2.0.1 fansi_1.0.4 ## [33] restfulr_0.0.15 progress_1.2.2 ## [35] caTools_1.18.2 dbplyr_2.3.1 ## [37] igraph_1.4.1 DBI_1.1.3 ## [39] htmlwidgets_1.6.2 spatstat.geom_3.1-0 ## [41] purrr_1.0.1 ellipsis_0.3.2 ## [43] backports_1.4.1 annotate_1.76.0 ## [45] biomaRt_2.54.0 deldir_1.0-6 ## [47] MatrixGenerics_1.10.0 vctrs_0.6.1 ## [49] ROCR_1.0-11 abind_1.4-5 ## [51] cachem_1.0.7 withr_2.5.0 ## [53] progressr_0.13.0 presto_1.0.0 ## [55] checkmate_2.1.0 sctransform_0.3.5 ## [57] GenomicAlignments_1.34.0 prettyunits_1.1.1 ## [59] goftest_1.2-3 cluster_2.1.3 ## [61] seqLogo_1.64.0 lazyeval_0.2.2 ## [63] crayon_1.5.2 hdf5r_1.3.8 ## [65] spatstat.explore_3.1-0 pkgconfig_2.0.3 ## [67] labeling_0.4.2 nlme_3.1-157 ## [69] ProtGenerics_1.30.0 nnet_7.3-17 ## [71] rlang_1.1.0 globals_0.16.2 ## [73] lifecycle_1.0.3 miniUI_0.1.1.1 ## [75] filelock_1.0.2 BiocFileCache_2.6.1 ## [77] dichromat_2.0-0.1 rprojroot_2.0.3 ## [79] polyclip_1.10-4 matrixStats_0.63.0 ## [81] lmtest_0.9-40 Matrix_1.5-3 ## [83] zoo_1.8-11 base64enc_0.1-3 ## [85] ggridges_0.5.4 png_0.1-8 ## [87] viridisLite_0.4.1 rjson_0.2.21 ## [89] bitops_1.0-7 R.oo_1.25.0 ## [91] KernSmooth_2.23-20 blob_1.2.3 ## [93] stringr_1.5.0 parallelly_1.35.0 ## [95] spatstat.random_3.1-4 readr_2.1.4 ## [97] jpeg_0.1-10 CNEr_1.34.0 ## [99] scales_1.2.1 memoise_2.0.1 ## [101] magrittr_2.0.3 plyr_1.8.8 ## [103] ica_1.0-3 zlibbioc_1.44.0 ## [105] compiler_4.2.0 BiocIO_1.8.0 ## [107] RColorBrewer_1.1-3 fitdistrplus_1.1-8 ## [109] Rsamtools_2.14.0 cli_3.6.1 ## [111] listenv_0.9.0 patchwork_1.1.2 ## [113] pbapply_1.7-0 htmlTable_2.4.1 ## [115] Formula_1.2-5 MASS_7.3-56 ## [117] tidyselect_1.2.0 stringi_1.7.12 ## [119] textshaping_0.3.6 highr_0.10 ## [121] yaml_2.3.7 latticeExtra_0.6-30 ## [123] ggrepel_0.9.3 grid_4.2.0 ## [125] sass_0.4.5 VariantAnnotation_1.44.1 ## [127] fastmatch_1.1-3 tools_4.2.0 ## [129] future.apply_1.10.0 parallel_4.2.0 ## [131] rstudioapi_0.14 TFMPvalue_0.0.9 ## [133] foreign_0.8-82 gridExtra_2.3 ## [135] farver_2.1.1 Rtsne_0.16 ## [137] digest_0.6.31 pracma_2.4.2 ## [139] shiny_1.7.4 Rcpp_1.0.10 ## [141] later_1.3.0 RcppAnnoy_0.0.20 ## [143] httr_1.4.5 biovizBase_1.46.0 ## [145] colorspace_2.1-0 XML_3.99-0.13 ## [147] fs_1.6.1 tensor_1.5 ## [149] reticulate_1.28 splines_4.2.0 ## [151] uwot_0.1.14 RcppRoll_0.3.0 ## [153] spatstat.utils_3.0-2 pkgdown_2.0.7 ## [155] sp_1.6-0 plotly_4.10.1 ## [157] systemfonts_1.0.4 xtable_1.8-4 ## [159] poweRlaw_0.70.6 jsonlite_1.8.4 ## [161] R6_2.5.1 Hmisc_4.8-0 ## [163] pillar_1.9.0 htmltools_0.5.5 ## [165] mime_0.12 DT_0.27 ## [167] glue_1.6.2 fastmap_1.1.1 ## [169] BiocParallel_1.32.5 codetools_0.2-18 ## [171] utf8_1.2.3 lattice_0.20-45 ## [173] bslib_0.4.2 spatstat.sparse_3.0-1 ## [175] tibble_3.2.1 curl_5.0.0 ## [177] leiden_0.4.3 gtools_3.9.4 ## [179] GO.db_3.16.0 interp_1.1-3 ## [181] survival_3.3-1 rmarkdown_2.21 ## [183] desc_1.4.2 munsell_0.5.0 ## [185] GenomeInfoDbData_1.2.9 reshape2_1.4.4 ## [187] gtable_0.3.3

We’d like to quantify this relationship, and search across all cell types to find similar examples. To do so, we will use the presto package to perform fast differential expression. We run two tests: one using gene expression data, and the other using chromVAR motif accessibilities. presto calculates a p-value based on the Wilcox rank sum test, which is also the default test in Seurat, and we restrict our search to TFs that return significant results in both tests.presto also calculates an “AUC” statistic, which reflects the power of each gene (or motif) to serve as a marker of cell type. A maximum AUC value of 1 indicates a perfect marker. Since the AUC statistic is on the same scale for both genes and motifs, we take the average of the AUC values from the two tests, and use this to rank TFs for each cell type: markers_rna <- presto:::wilcoxauc.Seurat(X = pbmc, group_by = 'celltype', assay = 'data', seurat_assay = 'SCT') markers_motifs <- presto:::wilcoxauc.Seurat(X = pbmc, group_by = 'celltype', assay = 'data', seurat_assay = 'chromvar') motif.names <- markers_motifs$feature colnames(markers_rna) <- paste0("RNA.", colnames(markers_rna)) colnames(markers_motifs) <- paste0("motif.", colnames(markers_motifs)) markers_rna$gene <- markers_rna$RNA.feature markers_motifs$gene <- ConvertMotifID(pbmc, id = motif.names) # a simple function to implement the procedure above topTFs <- function(celltype, padj.cutoff = 1e-2) { ctmarkers_rna <- dplyr::filter( markers_rna, RNA.group == celltype, RNA.padj < padj.cutoff, RNA.logFC > 0) %>% arrange(-RNA.auc) ctmarkers_motif <- dplyr::filter( markers_motifs, motif.group == celltype, motif.padj < padj.cutoff, motif.logFC > 0) %>% arrange(-motif.auc) top_tfs <- inner_join( x = ctmarkers_rna[, c(2, 11, 6, 7)], y = ctmarkers_motif[, c(2, 1, 11, 6, 7)], by = "gene" ) top_tfs$avg_auc <- (top_tfs$RNA.auc + top_tfs$motif.auc) / 2 top_tfs <- arrange(top_tfs, -avg_auc) return(top_tfs) }We can now compute, and visualize, putative regulators for any cell type. We recover well-established regulators, including TBX21 for NK cells, IRF4 for plasma cells, SOX4 for hematopoietic progenitors, EBF1 and PAX5 for B cells, IRF8 and TCF4 for pDC. We believe that similar strategies can be used to help focus on a set of putative regulators in diverse systems. # identify top markers in NK and visualize head(topTFs("NK"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 NK TBX21 0.7270859 0.000000e+00 NK MA0690.1 0.9139614 ## 2 NK EOMES 0.5886774 2.411013e-98 NK MA0800.1 0.9214773 ## 3 NK RUNX3 0.7705661 5.977716e-120 NK MA0684.2 0.6769022 ## motif.pval avg_auc ## 1 1.097940e-202 0.8205237 ## 2 4.903866e-210 0.7550774 ## 3 1.560061e-38 0.7237341 motif.name <- ConvertMotifID(pbmc, name = 'TBX21') gene_plot <- FeaturePlot(pbmc, features = "sct_TBX21", reduction = 'wnn.umap') motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap') gene_plot | motif_plot # identify top markers in pDC and visualize head(topTFs("pDC"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 pDC TCF4 0.9998815 1.120711e-162 pDC MA0830.2 0.9965481 ## 2 pDC IRF8 0.9904457 1.308164e-123 pDC MA0652.1 0.8833112 ## 3 pDC SPIB 0.9115207 0.000000e+00 pDC MA0081.2 0.9068540 ## motif.pval avg_auc ## 1 1.785897e-69 0.9982148 ## 2 3.982413e-42 0.9368785 ## 3 3.083509e-47 0.9091874 motif.name <- ConvertMotifID(pbmc, name = 'TCF4') gene_plot <- FeaturePlot(pbmc, features = "sct_TCF4", reduction = 'wnn.umap') motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap') gene_plot | motif_plot # identify top markers in HSPC and visualize head(topTFs("CD16 Mono"),3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 CD16 Mono SPI1 0.8793172 1.666810e-296 CD16 Mono MA0080.5 0.8880908 ## 2 CD16 Mono CEBPB 0.8685933 1.625472e-294 CD16 Mono MA0466.2 0.7840422 ## 3 CD16 Mono MEF2C 0.7129910 2.727252e-79 CD16 Mono MA0497.1 0.8059373 ## motif.pval avg_auc ## 1 4.762491e-194 0.8837040 ## 2 7.049764e-105 0.8263177 ## 3 2.345716e-121 0.7594641 motif.name <- ConvertMotifID(pbmc, name = 'SPI1') gene_plot <- FeaturePlot(pbmc, features = "sct_SPI1", reduction = 'wnn.umap') motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap') gene_plot | motif_plot # identify top markers in other cell types head(topTFs("Naive B"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 Naive B MEF2C 0.8802747 1.890065e-182 Naive B MA0497.1 0.6789079 ## 2 Naive B PAX5 0.9436648 0.000000e+00 Naive B MA0014.3 0.5827061 ## 3 Naive B POU2F2 0.6029377 2.892216e-13 Naive B MA0507.1 0.8912268 ## motif.pval avg_auc ## 1 9.815118e-32 0.7795913 ## 2 5.995185e-08 0.7631854 ## 3 6.471677e-145 0.7470822 head(topTFs("HSPC"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 HSPC SOX4 0.9869406 5.524832e-71 HSPC MA0867.2 0.6830497 ## 2 HSPC GATA2 0.7884615 0.000000e+00 HSPC MA0036.3 0.8275008 ## 3 HSPC MEIS1 0.8638496 0.000000e+00 HSPC MA0498.2 0.6924225 ## motif.pval avg_auc ## 1 1.241915e-03 0.8349951 ## 2 7.591798e-09 0.8079812 ## 3 6.877492e-04 0.7781361 head(topTFs("Plasma"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 Plasma IRF4 0.8189687 5.261955e-35 Plasma MA1419.1 0.9776046 ## 2 Plasma MEF2C 0.9111213 2.977155e-12 Plasma MA0497.1 0.7596637 ## 3 Plasma TCF4 0.8049409 6.810635e-12 Plasma MA0830.2 0.7840848 ## motif.pval avg_auc ## 1 2.334627e-12 0.8982867 ## 2 1.374353e-04 0.8353925 ## 3 3.028306e-05 0.7945129Session Info sessionInfo()## R version 4.2.0 (2022-04-22) ## Platform: x86_64-pc-linux-gnu (64-bit) ## Running under: Ubuntu 20.04.5 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/liblapack.so.3 ## ## locale: ## [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C ## [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8 ## [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 ## ## attached base packages: ## [1] stats4 stats graphics grDevices utils datasets methods ## [8] base ## ## other attached packages: ## [1] BSgenome.Hsapiens.UCSC.hg38_1.4.5 BSgenome_1.66.3 ## [3] rtracklayer_1.58.0 Biostrings_2.66.0 ## [5] XVector_0.38.0 motifmatchr_1.20.0 ## [7] TFBSTools_1.36.0 JASPAR2020_0.99.10 ## [9] chromVAR_1.20.2 EnsDb.Hsapiens.v86_2.99.0 ## [11] ensembldb_2.22.0 AnnotationFilter_1.22.0 ## [13] GenomicFeatures_1.50.4 AnnotationDbi_1.60.0 ## [15] Biobase_2.58.0 GenomicRanges_1.50.2 ## [17] GenomeInfoDb_1.35.16 IRanges_2.32.0 ## [19] S4Vectors_0.36.2 BiocGenerics_0.44.0 ## [21] Signac_1.9.0 ggplot2_3.4.1 ## [23] dplyr_1.1.1 cowplot_1.1.1 ## [25] thp1.eccite.SeuratData_3.1.5 stxBrain.SeuratData_0.1.1 ## [27] ssHippo.SeuratData_3.1.4 pbmcsca.SeuratData_3.0.0 ## [29] pbmcMultiome.SeuratData_0.1.2 pbmc3k.SeuratData_3.1.4 ## [31] panc8.SeuratData_3.0.2 ifnb.SeuratData_3.1.0 ## [33] hcabm40k.SeuratData_3.0.0 bmcite.SeuratData_0.3.0 ## [35] SeuratData_0.2.2 SeuratObject_4.1.3 ## [37] Seurat_4.2.1.9001 ## ## loaded via a namespace (and not attached): ## [1] rappdirs_0.3.3 scattermore_0.8 ## [3] R.methodsS3_1.8.2 ragg_1.2.5 ## [5] nabor_0.5.0 tidyr_1.3.0 ## [7] bit64_4.0.5 knitr_1.42 ## [9] R.utils_2.12.2 irlba_2.3.5.1 ## [11] DelayedArray_0.24.0 data.table_1.14.8 ## [13] rpart_4.1.16 KEGGREST_1.38.0 ## [15] RCurl_1.98-1.12 generics_0.1.3 ## [17] RSQLite_2.3.0 RANN_2.6.1 ## [19] future_1.32.0 tzdb_0.3.0 ## [21] bit_4.0.5 spatstat.data_3.0-1 ## [23] xml2_1.3.3 httpuv_1.6.9 ## [25] SummarizedExperiment_1.28.0 DirichletMultinomial_1.40.0 ## [27] xfun_0.38 hms_1.1.2 ## [29] jquerylib_0.1.4 evaluate_0.20 ## [31] promises_1.2.0.1 fansi_1.0.4 ## [33] restfulr_0.0.15 progress_1.2.2 ## [35] caTools_1.18.2 dbplyr_2.3.1 ## [37] igraph_1.4.1 DBI_1.1.3 ## [39] htmlwidgets_1.6.2 spatstat.geom_3.1-0 ## [41] purrr_1.0.1 ellipsis_0.3.2 ## [43] backports_1.4.1 annotate_1.76.0 ## [45] biomaRt_2.54.0 deldir_1.0-6 ## [47] MatrixGenerics_1.10.0 vctrs_0.6.1 ## [49] ROCR_1.0-11 abind_1.4-5 ## [51] cachem_1.0.7 withr_2.5.0 ## [53] progressr_0.13.0 presto_1.0.0 ## [55] checkmate_2.1.0 sctransform_0.3.5 ## [57] GenomicAlignments_1.34.0 prettyunits_1.1.1 ## [59] goftest_1.2-3 cluster_2.1.3 ## [61] seqLogo_1.64.0 lazyeval_0.2.2 ## [63] crayon_1.5.2 hdf5r_1.3.8 ## [65] spatstat.explore_3.1-0 pkgconfig_2.0.3 ## [67] labeling_0.4.2 nlme_3.1-157 ## [69] ProtGenerics_1.30.0 nnet_7.3-17 ## [71] rlang_1.1.0 globals_0.16.2 ## [73] lifecycle_1.0.3 miniUI_0.1.1.1 ## [75] filelock_1.0.2 BiocFileCache_2.6.1 ## [77] dichromat_2.0-0.1 rprojroot_2.0.3 ## [79] polyclip_1.10-4 matrixStats_0.63.0 ## [81] lmtest_0.9-40 Matrix_1.5-3 ## [83] zoo_1.8-11 base64enc_0.1-3 ## [85] ggridges_0.5.4 png_0.1-8 ## [87] viridisLite_0.4.1 rjson_0.2.21 ## [89] bitops_1.0-7 R.oo_1.25.0 ## [91] KernSmooth_2.23-20 blob_1.2.3 ## [93] stringr_1.5.0 parallelly_1.35.0 ## [95] spatstat.random_3.1-4 readr_2.1.4 ## [97] jpeg_0.1-10 CNEr_1.34.0 ## [99] scales_1.2.1 memoise_2.0.1 ## [101] magrittr_2.0.3 plyr_1.8.8 ## [103] ica_1.0-3 zlibbioc_1.44.0 ## [105] compiler_4.2.0 BiocIO_1.8.0 ## [107] RColorBrewer_1.1-3 fitdistrplus_1.1-8 ## [109] Rsamtools_2.14.0 cli_3.6.1 ## [111] listenv_0.9.0 patchwork_1.1.2 ## [113] pbapply_1.7-0 htmlTable_2.4.1 ## [115] Formula_1.2-5 MASS_7.3-56 ## [117] tidyselect_1.2.0 stringi_1.7.12 ## [119] textshaping_0.3.6 highr_0.10 ## [121] yaml_2.3.7 latticeExtra_0.6-30 ## [123] ggrepel_0.9.3 grid_4.2.0 ## [125] sass_0.4.5 VariantAnnotation_1.44.1 ## [127] fastmatch_1.1-3 tools_4.2.0 ## [129] future.apply_1.10.0 parallel_4.2.0 ## [131] rstudioapi_0.14 TFMPvalue_0.0.9 ## [133] foreign_0.8-82 gridExtra_2.3 ## [135] farver_2.1.1 Rtsne_0.16 ## [137] digest_0.6.31 pracma_2.4.2 ## [139] shiny_1.7.4 Rcpp_1.0.10 ## [141] later_1.3.0 RcppAnnoy_0.0.20 ## [143] httr_1.4.5 biovizBase_1.46.0 ## [145] colorspace_2.1-0 XML_3.99-0.13 ## [147] fs_1.6.1 tensor_1.5 ## [149] reticulate_1.28 splines_4.2.0 ## [151] uwot_0.1.14 RcppRoll_0.3.0 ## [153] spatstat.utils_3.0-2 pkgdown_2.0.7 ## [155] sp_1.6-0 plotly_4.10.1 ## [157] systemfonts_1.0.4 xtable_1.8-4 ## [159] poweRlaw_0.70.6 jsonlite_1.8.4 ## [161] R6_2.5.1 Hmisc_4.8-0 ## [163] pillar_1.9.0 htmltools_0.5.5 ## [165] mime_0.12 DT_0.27 ## [167] glue_1.6.2 fastmap_1.1.1 ## [169] BiocParallel_1.32.5 codetools_0.2-18 ## [171] utf8_1.2.3 lattice_0.20-45 ## [173] bslib_0.4.2 spatstat.sparse_3.0-1 ## [175] tibble_3.2.1 curl_5.0.0 ## [177] leiden_0.4.3 gtools_3.9.4 ## [179] GO.db_3.16.0 interp_1.1-3 ## [181] survival_3.3-1 rmarkdown_2.21 ## [183] desc_1.4.2 munsell_0.5.0 ## [185] GenomeInfoDbData_1.2.9 reshape2_1.4.4 ## [187] gtable_0.3.3

We’d like to quantify this relationship, and search across all cell types to find similar examples. To do so, we will use the presto package to perform fast differential expression. We run two tests: one using gene expression data, and the other using chromVAR motif accessibilities. presto calculates a p-value based on the Wilcox rank sum test, which is also the default test in Seurat, and we restrict our search to TFs that return significant results in both tests.presto also calculates an “AUC” statistic, which reflects the power of each gene (or motif) to serve as a marker of cell type. A maximum AUC value of 1 indicates a perfect marker. Since the AUC statistic is on the same scale for both genes and motifs, we take the average of the AUC values from the two tests, and use this to rank TFs for each cell type: markers_rna <- presto:::wilcoxauc.Seurat(X = pbmc, group_by = 'celltype', assay = 'data', seurat_assay = 'SCT') markers_motifs <- presto:::wilcoxauc.Seurat(X = pbmc, group_by = 'celltype', assay = 'data', seurat_assay = 'chromvar') motif.names <- markers_motifs$feature colnames(markers_rna) <- paste0("RNA.", colnames(markers_rna)) colnames(markers_motifs) <- paste0("motif.", colnames(markers_motifs)) markers_rna$gene <- markers_rna$RNA.feature markers_motifs$gene <- ConvertMotifID(pbmc, id = motif.names) # a simple function to implement the procedure above topTFs <- function(celltype, padj.cutoff = 1e-2) { ctmarkers_rna <- dplyr::filter( markers_rna, RNA.group == celltype, RNA.padj < padj.cutoff, RNA.logFC > 0) %>% arrange(-RNA.auc) ctmarkers_motif <- dplyr::filter( markers_motifs, motif.group == celltype, motif.padj < padj.cutoff, motif.logFC > 0) %>% arrange(-motif.auc) top_tfs <- inner_join( x = ctmarkers_rna[, c(2, 11, 6, 7)], y = ctmarkers_motif[, c(2, 1, 11, 6, 7)], by = "gene" ) top_tfs$avg_auc <- (top_tfs$RNA.auc + top_tfs$motif.auc) / 2 top_tfs <- arrange(top_tfs, -avg_auc) return(top_tfs) }We can now compute, and visualize, putative regulators for any cell type. We recover well-established regulators, including TBX21 for NK cells, IRF4 for plasma cells, SOX4 for hematopoietic progenitors, EBF1 and PAX5 for B cells, IRF8 and TCF4 for pDC. We believe that similar strategies can be used to help focus on a set of putative regulators in diverse systems. # identify top markers in NK and visualize head(topTFs("NK"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 NK TBX21 0.7270859 0.000000e+00 NK MA0690.1 0.9139614 ## 2 NK EOMES 0.5886774 2.411013e-98 NK MA0800.1 0.9214773 ## 3 NK RUNX3 0.7705661 5.977716e-120 NK MA0684.2 0.6769022 ## motif.pval avg_auc ## 1 1.097940e-202 0.8205237 ## 2 4.903866e-210 0.7550774 ## 3 1.560061e-38 0.7237341 motif.name <- ConvertMotifID(pbmc, name = 'TBX21') gene_plot <- FeaturePlot(pbmc, features = "sct_TBX21", reduction = 'wnn.umap') motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap') gene_plot | motif_plot # identify top markers in pDC and visualize head(topTFs("pDC"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 pDC TCF4 0.9998815 1.120711e-162 pDC MA0830.2 0.9965481 ## 2 pDC IRF8 0.9904457 1.308164e-123 pDC MA0652.1 0.8833112 ## 3 pDC SPIB 0.9115207 0.000000e+00 pDC MA0081.2 0.9068540 ## motif.pval avg_auc ## 1 1.785897e-69 0.9982148 ## 2 3.982413e-42 0.9368785 ## 3 3.083509e-47 0.9091874 motif.name <- ConvertMotifID(pbmc, name = 'TCF4') gene_plot <- FeaturePlot(pbmc, features = "sct_TCF4", reduction = 'wnn.umap') motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap') gene_plot | motif_plot # identify top markers in HSPC and visualize head(topTFs("CD16 Mono"),3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 CD16 Mono SPI1 0.8793172 1.666810e-296 CD16 Mono MA0080.5 0.8880908 ## 2 CD16 Mono CEBPB 0.8685933 1.625472e-294 CD16 Mono MA0466.2 0.7840422 ## 3 CD16 Mono MEF2C 0.7129910 2.727252e-79 CD16 Mono MA0497.1 0.8059373 ## motif.pval avg_auc ## 1 4.762491e-194 0.8837040 ## 2 7.049764e-105 0.8263177 ## 3 2.345716e-121 0.7594641 motif.name <- ConvertMotifID(pbmc, name = 'SPI1') gene_plot <- FeaturePlot(pbmc, features = "sct_SPI1", reduction = 'wnn.umap') motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap') gene_plot | motif_plot # identify top markers in other cell types head(topTFs("Naive B"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 Naive B MEF2C 0.8802747 1.890065e-182 Naive B MA0497.1 0.6789079 ## 2 Naive B PAX5 0.9436648 0.000000e+00 Naive B MA0014.3 0.5827061 ## 3 Naive B POU2F2 0.6029377 2.892216e-13 Naive B MA0507.1 0.8912268 ## motif.pval avg_auc ## 1 9.815118e-32 0.7795913 ## 2 5.995185e-08 0.7631854 ## 3 6.471677e-145 0.7470822 head(topTFs("HSPC"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 HSPC SOX4 0.9869406 5.524832e-71 HSPC MA0867.2 0.6830497 ## 2 HSPC GATA2 0.7884615 0.000000e+00 HSPC MA0036.3 0.8275008 ## 3 HSPC MEIS1 0.8638496 0.000000e+00 HSPC MA0498.2 0.6924225 ## motif.pval avg_auc ## 1 1.241915e-03 0.8349951 ## 2 7.591798e-09 0.8079812 ## 3 6.877492e-04 0.7781361 head(topTFs("Plasma"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 Plasma IRF4 0.8189687 5.261955e-35 Plasma MA1419.1 0.9776046 ## 2 Plasma MEF2C 0.9111213 2.977155e-12 Plasma MA0497.1 0.7596637 ## 3 Plasma TCF4 0.8049409 6.810635e-12 Plasma MA0830.2 0.7840848 ## motif.pval avg_auc ## 1 2.334627e-12 0.8982867 ## 2 1.374353e-04 0.8353925 ## 3 3.028306e-05 0.7945129Session Info sessionInfo()## R version 4.2.0 (2022-04-22) ## Platform: x86_64-pc-linux-gnu (64-bit) ## Running under: Ubuntu 20.04.5 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/liblapack.so.3 ## ## locale: ## [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C ## [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8 ## [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 ## ## attached base packages: ## [1] stats4 stats graphics grDevices utils datasets methods ## [8] base ## ## other attached packages: ## [1] BSgenome.Hsapiens.UCSC.hg38_1.4.5 BSgenome_1.66.3 ## [3] rtracklayer_1.58.0 Biostrings_2.66.0 ## [5] XVector_0.38.0 motifmatchr_1.20.0 ## [7] TFBSTools_1.36.0 JASPAR2020_0.99.10 ## [9] chromVAR_1.20.2 EnsDb.Hsapiens.v86_2.99.0 ## [11] ensembldb_2.22.0 AnnotationFilter_1.22.0 ## [13] GenomicFeatures_1.50.4 AnnotationDbi_1.60.0 ## [15] Biobase_2.58.0 GenomicRanges_1.50.2 ## [17] GenomeInfoDb_1.35.16 IRanges_2.32.0 ## [19] S4Vectors_0.36.2 BiocGenerics_0.44.0 ## [21] Signac_1.9.0 ggplot2_3.4.1 ## [23] dplyr_1.1.1 cowplot_1.1.1 ## [25] thp1.eccite.SeuratData_3.1.5 stxBrain.SeuratData_0.1.1 ## [27] ssHippo.SeuratData_3.1.4 pbmcsca.SeuratData_3.0.0 ## [29] pbmcMultiome.SeuratData_0.1.2 pbmc3k.SeuratData_3.1.4 ## [31] panc8.SeuratData_3.0.2 ifnb.SeuratData_3.1.0 ## [33] hcabm40k.SeuratData_3.0.0 bmcite.SeuratData_0.3.0 ## [35] SeuratData_0.2.2 SeuratObject_4.1.3 ## [37] Seurat_4.2.1.9001 ## ## loaded via a namespace (and not attached): ## [1] rappdirs_0.3.3 scattermore_0.8 ## [3] R.methodsS3_1.8.2 ragg_1.2.5 ## [5] nabor_0.5.0 tidyr_1.3.0 ## [7] bit64_4.0.5 knitr_1.42 ## [9] R.utils_2.12.2 irlba_2.3.5.1 ## [11] DelayedArray_0.24.0 data.table_1.14.8 ## [13] rpart_4.1.16 KEGGREST_1.38.0 ## [15] RCurl_1.98-1.12 generics_0.1.3 ## [17] RSQLite_2.3.0 RANN_2.6.1 ## [19] future_1.32.0 tzdb_0.3.0 ## [21] bit_4.0.5 spatstat.data_3.0-1 ## [23] xml2_1.3.3 httpuv_1.6.9 ## [25] SummarizedExperiment_1.28.0 DirichletMultinomial_1.40.0 ## [27] xfun_0.38 hms_1.1.2 ## [29] jquerylib_0.1.4 evaluate_0.20 ## [31] promises_1.2.0.1 fansi_1.0.4 ## [33] restfulr_0.0.15 progress_1.2.2 ## [35] caTools_1.18.2 dbplyr_2.3.1 ## [37] igraph_1.4.1 DBI_1.1.3 ## [39] htmlwidgets_1.6.2 spatstat.geom_3.1-0 ## [41] purrr_1.0.1 ellipsis_0.3.2 ## [43] backports_1.4.1 annotate_1.76.0 ## [45] biomaRt_2.54.0 deldir_1.0-6 ## [47] MatrixGenerics_1.10.0 vctrs_0.6.1 ## [49] ROCR_1.0-11 abind_1.4-5 ## [51] cachem_1.0.7 withr_2.5.0 ## [53] progressr_0.13.0 presto_1.0.0 ## [55] checkmate_2.1.0 sctransform_0.3.5 ## [57] GenomicAlignments_1.34.0 prettyunits_1.1.1 ## [59] goftest_1.2-3 cluster_2.1.3 ## [61] seqLogo_1.64.0 lazyeval_0.2.2 ## [63] crayon_1.5.2 hdf5r_1.3.8 ## [65] spatstat.explore_3.1-0 pkgconfig_2.0.3 ## [67] labeling_0.4.2 nlme_3.1-157 ## [69] ProtGenerics_1.30.0 nnet_7.3-17 ## [71] rlang_1.1.0 globals_0.16.2 ## [73] lifecycle_1.0.3 miniUI_0.1.1.1 ## [75] filelock_1.0.2 BiocFileCache_2.6.1 ## [77] dichromat_2.0-0.1 rprojroot_2.0.3 ## [79] polyclip_1.10-4 matrixStats_0.63.0 ## [81] lmtest_0.9-40 Matrix_1.5-3 ## [83] zoo_1.8-11 base64enc_0.1-3 ## [85] ggridges_0.5.4 png_0.1-8 ## [87] viridisLite_0.4.1 rjson_0.2.21 ## [89] bitops_1.0-7 R.oo_1.25.0 ## [91] KernSmooth_2.23-20 blob_1.2.3 ## [93] stringr_1.5.0 parallelly_1.35.0 ## [95] spatstat.random_3.1-4 readr_2.1.4 ## [97] jpeg_0.1-10 CNEr_1.34.0 ## [99] scales_1.2.1 memoise_2.0.1 ## [101] magrittr_2.0.3 plyr_1.8.8 ## [103] ica_1.0-3 zlibbioc_1.44.0 ## [105] compiler_4.2.0 BiocIO_1.8.0 ## [107] RColorBrewer_1.1-3 fitdistrplus_1.1-8 ## [109] Rsamtools_2.14.0 cli_3.6.1 ## [111] listenv_0.9.0 patchwork_1.1.2 ## [113] pbapply_1.7-0 htmlTable_2.4.1 ## [115] Formula_1.2-5 MASS_7.3-56 ## [117] tidyselect_1.2.0 stringi_1.7.12 ## [119] textshaping_0.3.6 highr_0.10 ## [121] yaml_2.3.7 latticeExtra_0.6-30 ## [123] ggrepel_0.9.3 grid_4.2.0 ## [125] sass_0.4.5 VariantAnnotation_1.44.1 ## [127] fastmatch_1.1-3 tools_4.2.0 ## [129] future.apply_1.10.0 parallel_4.2.0 ## [131] rstudioapi_0.14 TFMPvalue_0.0.9 ## [133] foreign_0.8-82 gridExtra_2.3 ## [135] farver_2.1.1 Rtsne_0.16 ## [137] digest_0.6.31 pracma_2.4.2 ## [139] shiny_1.7.4 Rcpp_1.0.10 ## [141] later_1.3.0 RcppAnnoy_0.0.20 ## [143] httr_1.4.5 biovizBase_1.46.0 ## [145] colorspace_2.1-0 XML_3.99-0.13 ## [147] fs_1.6.1 tensor_1.5 ## [149] reticulate_1.28 splines_4.2.0 ## [151] uwot_0.1.14 RcppRoll_0.3.0 ## [153] spatstat.utils_3.0-2 pkgdown_2.0.7 ## [155] sp_1.6-0 plotly_4.10.1 ## [157] systemfonts_1.0.4 xtable_1.8-4 ## [159] poweRlaw_0.70.6 jsonlite_1.8.4 ## [161] R6_2.5.1 Hmisc_4.8-0 ## [163] pillar_1.9.0 htmltools_0.5.5 ## [165] mime_0.12 DT_0.27 ## [167] glue_1.6.2 fastmap_1.1.1 ## [169] BiocParallel_1.32.5 codetools_0.2-18 ## [171] utf8_1.2.3 lattice_0.20-45 ## [173] bslib_0.4.2 spatstat.sparse_3.0-1 ## [175] tibble_3.2.1 curl_5.0.0 ## [177] leiden_0.4.3 gtools_3.9.4 ## [179] GO.db_3.16.0 interp_1.1-3 ## [181] survival_3.3-1 rmarkdown_2.21 ## [183] desc_1.4.2 munsell_0.5.0 ## [185] GenomeInfoDbData_1.2.9 reshape2_1.4.4 ## [187] gtable_0.3.3

presto also calculates an “AUC” statistic, which reflects the power of each gene (or motif) to serve as a marker of cell type. A maximum AUC value of 1 indicates a perfect marker. Since the AUC statistic is on the same scale for both genes and motifs, we take the average of the AUC values from the two tests, and use this to rank TFs for each cell type: markers_rna <- presto:::wilcoxauc.Seurat(X = pbmc, group_by = 'celltype', assay = 'data', seurat_assay = 'SCT') markers_motifs <- presto:::wilcoxauc.Seurat(X = pbmc, group_by = 'celltype', assay = 'data', seurat_assay = 'chromvar') motif.names <- markers_motifs$feature colnames(markers_rna) <- paste0("RNA.", colnames(markers_rna)) colnames(markers_motifs) <- paste0("motif.", colnames(markers_motifs)) markers_rna$gene <- markers_rna$RNA.feature markers_motifs$gene <- ConvertMotifID(pbmc, id = motif.names) # a simple function to implement the procedure above topTFs <- function(celltype, padj.cutoff = 1e-2) { ctmarkers_rna <- dplyr::filter( markers_rna, RNA.group == celltype, RNA.padj < padj.cutoff, RNA.logFC > 0) %>% arrange(-RNA.auc) ctmarkers_motif <- dplyr::filter( markers_motifs, motif.group == celltype, motif.padj < padj.cutoff, motif.logFC > 0) %>% arrange(-motif.auc) top_tfs <- inner_join( x = ctmarkers_rna[, c(2, 11, 6, 7)], y = ctmarkers_motif[, c(2, 1, 11, 6, 7)], by = "gene" ) top_tfs$avg_auc <- (top_tfs$RNA.auc + top_tfs$motif.auc) / 2 top_tfs <- arrange(top_tfs, -avg_auc) return(top_tfs) }We can now compute, and visualize, putative regulators for any cell type. We recover well-established regulators, including TBX21 for NK cells, IRF4 for plasma cells, SOX4 for hematopoietic progenitors, EBF1 and PAX5 for B cells, IRF8 and TCF4 for pDC. We believe that similar strategies can be used to help focus on a set of putative regulators in diverse systems. # identify top markers in NK and visualize head(topTFs("NK"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 NK TBX21 0.7270859 0.000000e+00 NK MA0690.1 0.9139614 ## 2 NK EOMES 0.5886774 2.411013e-98 NK MA0800.1 0.9214773 ## 3 NK RUNX3 0.7705661 5.977716e-120 NK MA0684.2 0.6769022 ## motif.pval avg_auc ## 1 1.097940e-202 0.8205237 ## 2 4.903866e-210 0.7550774 ## 3 1.560061e-38 0.7237341 motif.name <- ConvertMotifID(pbmc, name = 'TBX21') gene_plot <- FeaturePlot(pbmc, features = "sct_TBX21", reduction = 'wnn.umap') motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap') gene_plot | motif_plot # identify top markers in pDC and visualize head(topTFs("pDC"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 pDC TCF4 0.9998815 1.120711e-162 pDC MA0830.2 0.9965481 ## 2 pDC IRF8 0.9904457 1.308164e-123 pDC MA0652.1 0.8833112 ## 3 pDC SPIB 0.9115207 0.000000e+00 pDC MA0081.2 0.9068540 ## motif.pval avg_auc ## 1 1.785897e-69 0.9982148 ## 2 3.982413e-42 0.9368785 ## 3 3.083509e-47 0.9091874 motif.name <- ConvertMotifID(pbmc, name = 'TCF4') gene_plot <- FeaturePlot(pbmc, features = "sct_TCF4", reduction = 'wnn.umap') motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap') gene_plot | motif_plot # identify top markers in HSPC and visualize head(topTFs("CD16 Mono"),3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 CD16 Mono SPI1 0.8793172 1.666810e-296 CD16 Mono MA0080.5 0.8880908 ## 2 CD16 Mono CEBPB 0.8685933 1.625472e-294 CD16 Mono MA0466.2 0.7840422 ## 3 CD16 Mono MEF2C 0.7129910 2.727252e-79 CD16 Mono MA0497.1 0.8059373 ## motif.pval avg_auc ## 1 4.762491e-194 0.8837040 ## 2 7.049764e-105 0.8263177 ## 3 2.345716e-121 0.7594641 motif.name <- ConvertMotifID(pbmc, name = 'SPI1') gene_plot <- FeaturePlot(pbmc, features = "sct_SPI1", reduction = 'wnn.umap') motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap') gene_plot | motif_plot # identify top markers in other cell types head(topTFs("Naive B"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 Naive B MEF2C 0.8802747 1.890065e-182 Naive B MA0497.1 0.6789079 ## 2 Naive B PAX5 0.9436648 0.000000e+00 Naive B MA0014.3 0.5827061 ## 3 Naive B POU2F2 0.6029377 2.892216e-13 Naive B MA0507.1 0.8912268 ## motif.pval avg_auc ## 1 9.815118e-32 0.7795913 ## 2 5.995185e-08 0.7631854 ## 3 6.471677e-145 0.7470822 head(topTFs("HSPC"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 HSPC SOX4 0.9869406 5.524832e-71 HSPC MA0867.2 0.6830497 ## 2 HSPC GATA2 0.7884615 0.000000e+00 HSPC MA0036.3 0.8275008 ## 3 HSPC MEIS1 0.8638496 0.000000e+00 HSPC MA0498.2 0.6924225 ## motif.pval avg_auc ## 1 1.241915e-03 0.8349951 ## 2 7.591798e-09 0.8079812 ## 3 6.877492e-04 0.7781361 head(topTFs("Plasma"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 Plasma IRF4 0.8189687 5.261955e-35 Plasma MA1419.1 0.9776046 ## 2 Plasma MEF2C 0.9111213 2.977155e-12 Plasma MA0497.1 0.7596637 ## 3 Plasma TCF4 0.8049409 6.810635e-12 Plasma MA0830.2 0.7840848 ## motif.pval avg_auc ## 1 2.334627e-12 0.8982867 ## 2 1.374353e-04 0.8353925 ## 3 3.028306e-05 0.7945129Session Info sessionInfo()## R version 4.2.0 (2022-04-22) ## Platform: x86_64-pc-linux-gnu (64-bit) ## Running under: Ubuntu 20.04.5 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/liblapack.so.3 ## ## locale: ## [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C ## [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8 ## [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 ## ## attached base packages: ## [1] stats4 stats graphics grDevices utils datasets methods ## [8] base ## ## other attached packages: ## [1] BSgenome.Hsapiens.UCSC.hg38_1.4.5 BSgenome_1.66.3 ## [3] rtracklayer_1.58.0 Biostrings_2.66.0 ## [5] XVector_0.38.0 motifmatchr_1.20.0 ## [7] TFBSTools_1.36.0 JASPAR2020_0.99.10 ## [9] chromVAR_1.20.2 EnsDb.Hsapiens.v86_2.99.0 ## [11] ensembldb_2.22.0 AnnotationFilter_1.22.0 ## [13] GenomicFeatures_1.50.4 AnnotationDbi_1.60.0 ## [15] Biobase_2.58.0 GenomicRanges_1.50.2 ## [17] GenomeInfoDb_1.35.16 IRanges_2.32.0 ## [19] S4Vectors_0.36.2 BiocGenerics_0.44.0 ## [21] Signac_1.9.0 ggplot2_3.4.1 ## [23] dplyr_1.1.1 cowplot_1.1.1 ## [25] thp1.eccite.SeuratData_3.1.5 stxBrain.SeuratData_0.1.1 ## [27] ssHippo.SeuratData_3.1.4 pbmcsca.SeuratData_3.0.0 ## [29] pbmcMultiome.SeuratData_0.1.2 pbmc3k.SeuratData_3.1.4 ## [31] panc8.SeuratData_3.0.2 ifnb.SeuratData_3.1.0 ## [33] hcabm40k.SeuratData_3.0.0 bmcite.SeuratData_0.3.0 ## [35] SeuratData_0.2.2 SeuratObject_4.1.3 ## [37] Seurat_4.2.1.9001 ## ## loaded via a namespace (and not attached): ## [1] rappdirs_0.3.3 scattermore_0.8 ## [3] R.methodsS3_1.8.2 ragg_1.2.5 ## [5] nabor_0.5.0 tidyr_1.3.0 ## [7] bit64_4.0.5 knitr_1.42 ## [9] R.utils_2.12.2 irlba_2.3.5.1 ## [11] DelayedArray_0.24.0 data.table_1.14.8 ## [13] rpart_4.1.16 KEGGREST_1.38.0 ## [15] RCurl_1.98-1.12 generics_0.1.3 ## [17] RSQLite_2.3.0 RANN_2.6.1 ## [19] future_1.32.0 tzdb_0.3.0 ## [21] bit_4.0.5 spatstat.data_3.0-1 ## [23] xml2_1.3.3 httpuv_1.6.9 ## [25] SummarizedExperiment_1.28.0 DirichletMultinomial_1.40.0 ## [27] xfun_0.38 hms_1.1.2 ## [29] jquerylib_0.1.4 evaluate_0.20 ## [31] promises_1.2.0.1 fansi_1.0.4 ## [33] restfulr_0.0.15 progress_1.2.2 ## [35] caTools_1.18.2 dbplyr_2.3.1 ## [37] igraph_1.4.1 DBI_1.1.3 ## [39] htmlwidgets_1.6.2 spatstat.geom_3.1-0 ## [41] purrr_1.0.1 ellipsis_0.3.2 ## [43] backports_1.4.1 annotate_1.76.0 ## [45] biomaRt_2.54.0 deldir_1.0-6 ## [47] MatrixGenerics_1.10.0 vctrs_0.6.1 ## [49] ROCR_1.0-11 abind_1.4-5 ## [51] cachem_1.0.7 withr_2.5.0 ## [53] progressr_0.13.0 presto_1.0.0 ## [55] checkmate_2.1.0 sctransform_0.3.5 ## [57] GenomicAlignments_1.34.0 prettyunits_1.1.1 ## [59] goftest_1.2-3 cluster_2.1.3 ## [61] seqLogo_1.64.0 lazyeval_0.2.2 ## [63] crayon_1.5.2 hdf5r_1.3.8 ## [65] spatstat.explore_3.1-0 pkgconfig_2.0.3 ## [67] labeling_0.4.2 nlme_3.1-157 ## [69] ProtGenerics_1.30.0 nnet_7.3-17 ## [71] rlang_1.1.0 globals_0.16.2 ## [73] lifecycle_1.0.3 miniUI_0.1.1.1 ## [75] filelock_1.0.2 BiocFileCache_2.6.1 ## [77] dichromat_2.0-0.1 rprojroot_2.0.3 ## [79] polyclip_1.10-4 matrixStats_0.63.0 ## [81] lmtest_0.9-40 Matrix_1.5-3 ## [83] zoo_1.8-11 base64enc_0.1-3 ## [85] ggridges_0.5.4 png_0.1-8 ## [87] viridisLite_0.4.1 rjson_0.2.21 ## [89] bitops_1.0-7 R.oo_1.25.0 ## [91] KernSmooth_2.23-20 blob_1.2.3 ## [93] stringr_1.5.0 parallelly_1.35.0 ## [95] spatstat.random_3.1-4 readr_2.1.4 ## [97] jpeg_0.1-10 CNEr_1.34.0 ## [99] scales_1.2.1 memoise_2.0.1 ## [101] magrittr_2.0.3 plyr_1.8.8 ## [103] ica_1.0-3 zlibbioc_1.44.0 ## [105] compiler_4.2.0 BiocIO_1.8.0 ## [107] RColorBrewer_1.1-3 fitdistrplus_1.1-8 ## [109] Rsamtools_2.14.0 cli_3.6.1 ## [111] listenv_0.9.0 patchwork_1.1.2 ## [113] pbapply_1.7-0 htmlTable_2.4.1 ## [115] Formula_1.2-5 MASS_7.3-56 ## [117] tidyselect_1.2.0 stringi_1.7.12 ## [119] textshaping_0.3.6 highr_0.10 ## [121] yaml_2.3.7 latticeExtra_0.6-30 ## [123] ggrepel_0.9.3 grid_4.2.0 ## [125] sass_0.4.5 VariantAnnotation_1.44.1 ## [127] fastmatch_1.1-3 tools_4.2.0 ## [129] future.apply_1.10.0 parallel_4.2.0 ## [131] rstudioapi_0.14 TFMPvalue_0.0.9 ## [133] foreign_0.8-82 gridExtra_2.3 ## [135] farver_2.1.1 Rtsne_0.16 ## [137] digest_0.6.31 pracma_2.4.2 ## [139] shiny_1.7.4 Rcpp_1.0.10 ## [141] later_1.3.0 RcppAnnoy_0.0.20 ## [143] httr_1.4.5 biovizBase_1.46.0 ## [145] colorspace_2.1-0 XML_3.99-0.13 ## [147] fs_1.6.1 tensor_1.5 ## [149] reticulate_1.28 splines_4.2.0 ## [151] uwot_0.1.14 RcppRoll_0.3.0 ## [153] spatstat.utils_3.0-2 pkgdown_2.0.7 ## [155] sp_1.6-0 plotly_4.10.1 ## [157] systemfonts_1.0.4 xtable_1.8-4 ## [159] poweRlaw_0.70.6 jsonlite_1.8.4 ## [161] R6_2.5.1 Hmisc_4.8-0 ## [163] pillar_1.9.0 htmltools_0.5.5 ## [165] mime_0.12 DT_0.27 ## [167] glue_1.6.2 fastmap_1.1.1 ## [169] BiocParallel_1.32.5 codetools_0.2-18 ## [171] utf8_1.2.3 lattice_0.20-45 ## [173] bslib_0.4.2 spatstat.sparse_3.0-1 ## [175] tibble_3.2.1 curl_5.0.0 ## [177] leiden_0.4.3 gtools_3.9.4 ## [179] GO.db_3.16.0 interp_1.1-3 ## [181] survival_3.3-1 rmarkdown_2.21 ## [183] desc_1.4.2 munsell_0.5.0 ## [185] GenomeInfoDbData_1.2.9 reshape2_1.4.4 ## [187] gtable_0.3.3

We can now compute, and visualize, putative regulators for any cell type. We recover well-established regulators, including TBX21 for NK cells, IRF4 for plasma cells, SOX4 for hematopoietic progenitors, EBF1 and PAX5 for B cells, IRF8 and TCF4 for pDC. We believe that similar strategies can be used to help focus on a set of putative regulators in diverse systems. # identify top markers in NK and visualize head(topTFs("NK"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 NK TBX21 0.7270859 0.000000e+00 NK MA0690.1 0.9139614 ## 2 NK EOMES 0.5886774 2.411013e-98 NK MA0800.1 0.9214773 ## 3 NK RUNX3 0.7705661 5.977716e-120 NK MA0684.2 0.6769022 ## motif.pval avg_auc ## 1 1.097940e-202 0.8205237 ## 2 4.903866e-210 0.7550774 ## 3 1.560061e-38 0.7237341 motif.name <- ConvertMotifID(pbmc, name = 'TBX21') gene_plot <- FeaturePlot(pbmc, features = "sct_TBX21", reduction = 'wnn.umap') motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap') gene_plot | motif_plot # identify top markers in pDC and visualize head(topTFs("pDC"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 pDC TCF4 0.9998815 1.120711e-162 pDC MA0830.2 0.9965481 ## 2 pDC IRF8 0.9904457 1.308164e-123 pDC MA0652.1 0.8833112 ## 3 pDC SPIB 0.9115207 0.000000e+00 pDC MA0081.2 0.9068540 ## motif.pval avg_auc ## 1 1.785897e-69 0.9982148 ## 2 3.982413e-42 0.9368785 ## 3 3.083509e-47 0.9091874 motif.name <- ConvertMotifID(pbmc, name = 'TCF4') gene_plot <- FeaturePlot(pbmc, features = "sct_TCF4", reduction = 'wnn.umap') motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap') gene_plot | motif_plot # identify top markers in HSPC and visualize head(topTFs("CD16 Mono"),3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 CD16 Mono SPI1 0.8793172 1.666810e-296 CD16 Mono MA0080.5 0.8880908 ## 2 CD16 Mono CEBPB 0.8685933 1.625472e-294 CD16 Mono MA0466.2 0.7840422 ## 3 CD16 Mono MEF2C 0.7129910 2.727252e-79 CD16 Mono MA0497.1 0.8059373 ## motif.pval avg_auc ## 1 4.762491e-194 0.8837040 ## 2 7.049764e-105 0.8263177 ## 3 2.345716e-121 0.7594641 motif.name <- ConvertMotifID(pbmc, name = 'SPI1') gene_plot <- FeaturePlot(pbmc, features = "sct_SPI1", reduction = 'wnn.umap') motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap') gene_plot | motif_plot # identify top markers in other cell types head(topTFs("Naive B"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 Naive B MEF2C 0.8802747 1.890065e-182 Naive B MA0497.1 0.6789079 ## 2 Naive B PAX5 0.9436648 0.000000e+00 Naive B MA0014.3 0.5827061 ## 3 Naive B POU2F2 0.6029377 2.892216e-13 Naive B MA0507.1 0.8912268 ## motif.pval avg_auc ## 1 9.815118e-32 0.7795913 ## 2 5.995185e-08 0.7631854 ## 3 6.471677e-145 0.7470822 head(topTFs("HSPC"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 HSPC SOX4 0.9869406 5.524832e-71 HSPC MA0867.2 0.6830497 ## 2 HSPC GATA2 0.7884615 0.000000e+00 HSPC MA0036.3 0.8275008 ## 3 HSPC MEIS1 0.8638496 0.000000e+00 HSPC MA0498.2 0.6924225 ## motif.pval avg_auc ## 1 1.241915e-03 0.8349951 ## 2 7.591798e-09 0.8079812 ## 3 6.877492e-04 0.7781361 head(topTFs("Plasma"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 Plasma IRF4 0.8189687 5.261955e-35 Plasma MA1419.1 0.9776046 ## 2 Plasma MEF2C 0.9111213 2.977155e-12 Plasma MA0497.1 0.7596637 ## 3 Plasma TCF4 0.8049409 6.810635e-12 Plasma MA0830.2 0.7840848 ## motif.pval avg_auc ## 1 2.334627e-12 0.8982867 ## 2 1.374353e-04 0.8353925 ## 3 3.028306e-05 0.7945129Session Info sessionInfo()## R version 4.2.0 (2022-04-22) ## Platform: x86_64-pc-linux-gnu (64-bit) ## Running under: Ubuntu 20.04.5 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/liblapack.so.3 ## ## locale: ## [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C ## [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8 ## [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 ## ## attached base packages: ## [1] stats4 stats graphics grDevices utils datasets methods ## [8] base ## ## other attached packages: ## [1] BSgenome.Hsapiens.UCSC.hg38_1.4.5 BSgenome_1.66.3 ## [3] rtracklayer_1.58.0 Biostrings_2.66.0 ## [5] XVector_0.38.0 motifmatchr_1.20.0 ## [7] TFBSTools_1.36.0 JASPAR2020_0.99.10 ## [9] chromVAR_1.20.2 EnsDb.Hsapiens.v86_2.99.0 ## [11] ensembldb_2.22.0 AnnotationFilter_1.22.0 ## [13] GenomicFeatures_1.50.4 AnnotationDbi_1.60.0 ## [15] Biobase_2.58.0 GenomicRanges_1.50.2 ## [17] GenomeInfoDb_1.35.16 IRanges_2.32.0 ## [19] S4Vectors_0.36.2 BiocGenerics_0.44.0 ## [21] Signac_1.9.0 ggplot2_3.4.1 ## [23] dplyr_1.1.1 cowplot_1.1.1 ## [25] thp1.eccite.SeuratData_3.1.5 stxBrain.SeuratData_0.1.1 ## [27] ssHippo.SeuratData_3.1.4 pbmcsca.SeuratData_3.0.0 ## [29] pbmcMultiome.SeuratData_0.1.2 pbmc3k.SeuratData_3.1.4 ## [31] panc8.SeuratData_3.0.2 ifnb.SeuratData_3.1.0 ## [33] hcabm40k.SeuratData_3.0.0 bmcite.SeuratData_0.3.0 ## [35] SeuratData_0.2.2 SeuratObject_4.1.3 ## [37] Seurat_4.2.1.9001 ## ## loaded via a namespace (and not attached): ## [1] rappdirs_0.3.3 scattermore_0.8 ## [3] R.methodsS3_1.8.2 ragg_1.2.5 ## [5] nabor_0.5.0 tidyr_1.3.0 ## [7] bit64_4.0.5 knitr_1.42 ## [9] R.utils_2.12.2 irlba_2.3.5.1 ## [11] DelayedArray_0.24.0 data.table_1.14.8 ## [13] rpart_4.1.16 KEGGREST_1.38.0 ## [15] RCurl_1.98-1.12 generics_0.1.3 ## [17] RSQLite_2.3.0 RANN_2.6.1 ## [19] future_1.32.0 tzdb_0.3.0 ## [21] bit_4.0.5 spatstat.data_3.0-1 ## [23] xml2_1.3.3 httpuv_1.6.9 ## [25] SummarizedExperiment_1.28.0 DirichletMultinomial_1.40.0 ## [27] xfun_0.38 hms_1.1.2 ## [29] jquerylib_0.1.4 evaluate_0.20 ## [31] promises_1.2.0.1 fansi_1.0.4 ## [33] restfulr_0.0.15 progress_1.2.2 ## [35] caTools_1.18.2 dbplyr_2.3.1 ## [37] igraph_1.4.1 DBI_1.1.3 ## [39] htmlwidgets_1.6.2 spatstat.geom_3.1-0 ## [41] purrr_1.0.1 ellipsis_0.3.2 ## [43] backports_1.4.1 annotate_1.76.0 ## [45] biomaRt_2.54.0 deldir_1.0-6 ## [47] MatrixGenerics_1.10.0 vctrs_0.6.1 ## [49] ROCR_1.0-11 abind_1.4-5 ## [51] cachem_1.0.7 withr_2.5.0 ## [53] progressr_0.13.0 presto_1.0.0 ## [55] checkmate_2.1.0 sctransform_0.3.5 ## [57] GenomicAlignments_1.34.0 prettyunits_1.1.1 ## [59] goftest_1.2-3 cluster_2.1.3 ## [61] seqLogo_1.64.0 lazyeval_0.2.2 ## [63] crayon_1.5.2 hdf5r_1.3.8 ## [65] spatstat.explore_3.1-0 pkgconfig_2.0.3 ## [67] labeling_0.4.2 nlme_3.1-157 ## [69] ProtGenerics_1.30.0 nnet_7.3-17 ## [71] rlang_1.1.0 globals_0.16.2 ## [73] lifecycle_1.0.3 miniUI_0.1.1.1 ## [75] filelock_1.0.2 BiocFileCache_2.6.1 ## [77] dichromat_2.0-0.1 rprojroot_2.0.3 ## [79] polyclip_1.10-4 matrixStats_0.63.0 ## [81] lmtest_0.9-40 Matrix_1.5-3 ## [83] zoo_1.8-11 base64enc_0.1-3 ## [85] ggridges_0.5.4 png_0.1-8 ## [87] viridisLite_0.4.1 rjson_0.2.21 ## [89] bitops_1.0-7 R.oo_1.25.0 ## [91] KernSmooth_2.23-20 blob_1.2.3 ## [93] stringr_1.5.0 parallelly_1.35.0 ## [95] spatstat.random_3.1-4 readr_2.1.4 ## [97] jpeg_0.1-10 CNEr_1.34.0 ## [99] scales_1.2.1 memoise_2.0.1 ## [101] magrittr_2.0.3 plyr_1.8.8 ## [103] ica_1.0-3 zlibbioc_1.44.0 ## [105] compiler_4.2.0 BiocIO_1.8.0 ## [107] RColorBrewer_1.1-3 fitdistrplus_1.1-8 ## [109] Rsamtools_2.14.0 cli_3.6.1 ## [111] listenv_0.9.0 patchwork_1.1.2 ## [113] pbapply_1.7-0 htmlTable_2.4.1 ## [115] Formula_1.2-5 MASS_7.3-56 ## [117] tidyselect_1.2.0 stringi_1.7.12 ## [119] textshaping_0.3.6 highr_0.10 ## [121] yaml_2.3.7 latticeExtra_0.6-30 ## [123] ggrepel_0.9.3 grid_4.2.0 ## [125] sass_0.4.5 VariantAnnotation_1.44.1 ## [127] fastmatch_1.1-3 tools_4.2.0 ## [129] future.apply_1.10.0 parallel_4.2.0 ## [131] rstudioapi_0.14 TFMPvalue_0.0.9 ## [133] foreign_0.8-82 gridExtra_2.3 ## [135] farver_2.1.1 Rtsne_0.16 ## [137] digest_0.6.31 pracma_2.4.2 ## [139] shiny_1.7.4 Rcpp_1.0.10 ## [141] later_1.3.0 RcppAnnoy_0.0.20 ## [143] httr_1.4.5 biovizBase_1.46.0 ## [145] colorspace_2.1-0 XML_3.99-0.13 ## [147] fs_1.6.1 tensor_1.5 ## [149] reticulate_1.28 splines_4.2.0 ## [151] uwot_0.1.14 RcppRoll_0.3.0 ## [153] spatstat.utils_3.0-2 pkgdown_2.0.7 ## [155] sp_1.6-0 plotly_4.10.1 ## [157] systemfonts_1.0.4 xtable_1.8-4 ## [159] poweRlaw_0.70.6 jsonlite_1.8.4 ## [161] R6_2.5.1 Hmisc_4.8-0 ## [163] pillar_1.9.0 htmltools_0.5.5 ## [165] mime_0.12 DT_0.27 ## [167] glue_1.6.2 fastmap_1.1.1 ## [169] BiocParallel_1.32.5 codetools_0.2-18 ## [171] utf8_1.2.3 lattice_0.20-45 ## [173] bslib_0.4.2 spatstat.sparse_3.0-1 ## [175] tibble_3.2.1 curl_5.0.0 ## [177] leiden_0.4.3 gtools_3.9.4 ## [179] GO.db_3.16.0 interp_1.1-3 ## [181] survival_3.3-1 rmarkdown_2.21 ## [183] desc_1.4.2 munsell_0.5.0 ## [185] GenomeInfoDbData_1.2.9 reshape2_1.4.4 ## [187] gtable_0.3.3

# identify top markers in pDC and visualize head(topTFs("pDC"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 pDC TCF4 0.9998815 1.120711e-162 pDC MA0830.2 0.9965481 ## 2 pDC IRF8 0.9904457 1.308164e-123 pDC MA0652.1 0.8833112 ## 3 pDC SPIB 0.9115207 0.000000e+00 pDC MA0081.2 0.9068540 ## motif.pval avg_auc ## 1 1.785897e-69 0.9982148 ## 2 3.982413e-42 0.9368785 ## 3 3.083509e-47 0.9091874 motif.name <- ConvertMotifID(pbmc, name = 'TCF4') gene_plot <- FeaturePlot(pbmc, features = "sct_TCF4", reduction = 'wnn.umap') motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap') gene_plot | motif_plot # identify top markers in HSPC and visualize head(topTFs("CD16 Mono"),3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 CD16 Mono SPI1 0.8793172 1.666810e-296 CD16 Mono MA0080.5 0.8880908 ## 2 CD16 Mono CEBPB 0.8685933 1.625472e-294 CD16 Mono MA0466.2 0.7840422 ## 3 CD16 Mono MEF2C 0.7129910 2.727252e-79 CD16 Mono MA0497.1 0.8059373 ## motif.pval avg_auc ## 1 4.762491e-194 0.8837040 ## 2 7.049764e-105 0.8263177 ## 3 2.345716e-121 0.7594641 motif.name <- ConvertMotifID(pbmc, name = 'SPI1') gene_plot <- FeaturePlot(pbmc, features = "sct_SPI1", reduction = 'wnn.umap') motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap') gene_plot | motif_plot # identify top markers in other cell types head(topTFs("Naive B"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 Naive B MEF2C 0.8802747 1.890065e-182 Naive B MA0497.1 0.6789079 ## 2 Naive B PAX5 0.9436648 0.000000e+00 Naive B MA0014.3 0.5827061 ## 3 Naive B POU2F2 0.6029377 2.892216e-13 Naive B MA0507.1 0.8912268 ## motif.pval avg_auc ## 1 9.815118e-32 0.7795913 ## 2 5.995185e-08 0.7631854 ## 3 6.471677e-145 0.7470822 head(topTFs("HSPC"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 HSPC SOX4 0.9869406 5.524832e-71 HSPC MA0867.2 0.6830497 ## 2 HSPC GATA2 0.7884615 0.000000e+00 HSPC MA0036.3 0.8275008 ## 3 HSPC MEIS1 0.8638496 0.000000e+00 HSPC MA0498.2 0.6924225 ## motif.pval avg_auc ## 1 1.241915e-03 0.8349951 ## 2 7.591798e-09 0.8079812 ## 3 6.877492e-04 0.7781361 head(topTFs("Plasma"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 Plasma IRF4 0.8189687 5.261955e-35 Plasma MA1419.1 0.9776046 ## 2 Plasma MEF2C 0.9111213 2.977155e-12 Plasma MA0497.1 0.7596637 ## 3 Plasma TCF4 0.8049409 6.810635e-12 Plasma MA0830.2 0.7840848 ## motif.pval avg_auc ## 1 2.334627e-12 0.8982867 ## 2 1.374353e-04 0.8353925 ## 3 3.028306e-05 0.7945129Session Info sessionInfo()## R version 4.2.0 (2022-04-22) ## Platform: x86_64-pc-linux-gnu (64-bit) ## Running under: Ubuntu 20.04.5 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/liblapack.so.3 ## ## locale: ## [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C ## [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8 ## [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 ## ## attached base packages: ## [1] stats4 stats graphics grDevices utils datasets methods ## [8] base ## ## other attached packages: ## [1] BSgenome.Hsapiens.UCSC.hg38_1.4.5 BSgenome_1.66.3 ## [3] rtracklayer_1.58.0 Biostrings_2.66.0 ## [5] XVector_0.38.0 motifmatchr_1.20.0 ## [7] TFBSTools_1.36.0 JASPAR2020_0.99.10 ## [9] chromVAR_1.20.2 EnsDb.Hsapiens.v86_2.99.0 ## [11] ensembldb_2.22.0 AnnotationFilter_1.22.0 ## [13] GenomicFeatures_1.50.4 AnnotationDbi_1.60.0 ## [15] Biobase_2.58.0 GenomicRanges_1.50.2 ## [17] GenomeInfoDb_1.35.16 IRanges_2.32.0 ## [19] S4Vectors_0.36.2 BiocGenerics_0.44.0 ## [21] Signac_1.9.0 ggplot2_3.4.1 ## [23] dplyr_1.1.1 cowplot_1.1.1 ## [25] thp1.eccite.SeuratData_3.1.5 stxBrain.SeuratData_0.1.1 ## [27] ssHippo.SeuratData_3.1.4 pbmcsca.SeuratData_3.0.0 ## [29] pbmcMultiome.SeuratData_0.1.2 pbmc3k.SeuratData_3.1.4 ## [31] panc8.SeuratData_3.0.2 ifnb.SeuratData_3.1.0 ## [33] hcabm40k.SeuratData_3.0.0 bmcite.SeuratData_0.3.0 ## [35] SeuratData_0.2.2 SeuratObject_4.1.3 ## [37] Seurat_4.2.1.9001 ## ## loaded via a namespace (and not attached): ## [1] rappdirs_0.3.3 scattermore_0.8 ## [3] R.methodsS3_1.8.2 ragg_1.2.5 ## [5] nabor_0.5.0 tidyr_1.3.0 ## [7] bit64_4.0.5 knitr_1.42 ## [9] R.utils_2.12.2 irlba_2.3.5.1 ## [11] DelayedArray_0.24.0 data.table_1.14.8 ## [13] rpart_4.1.16 KEGGREST_1.38.0 ## [15] RCurl_1.98-1.12 generics_0.1.3 ## [17] RSQLite_2.3.0 RANN_2.6.1 ## [19] future_1.32.0 tzdb_0.3.0 ## [21] bit_4.0.5 spatstat.data_3.0-1 ## [23] xml2_1.3.3 httpuv_1.6.9 ## [25] SummarizedExperiment_1.28.0 DirichletMultinomial_1.40.0 ## [27] xfun_0.38 hms_1.1.2 ## [29] jquerylib_0.1.4 evaluate_0.20 ## [31] promises_1.2.0.1 fansi_1.0.4 ## [33] restfulr_0.0.15 progress_1.2.2 ## [35] caTools_1.18.2 dbplyr_2.3.1 ## [37] igraph_1.4.1 DBI_1.1.3 ## [39] htmlwidgets_1.6.2 spatstat.geom_3.1-0 ## [41] purrr_1.0.1 ellipsis_0.3.2 ## [43] backports_1.4.1 annotate_1.76.0 ## [45] biomaRt_2.54.0 deldir_1.0-6 ## [47] MatrixGenerics_1.10.0 vctrs_0.6.1 ## [49] ROCR_1.0-11 abind_1.4-5 ## [51] cachem_1.0.7 withr_2.5.0 ## [53] progressr_0.13.0 presto_1.0.0 ## [55] checkmate_2.1.0 sctransform_0.3.5 ## [57] GenomicAlignments_1.34.0 prettyunits_1.1.1 ## [59] goftest_1.2-3 cluster_2.1.3 ## [61] seqLogo_1.64.0 lazyeval_0.2.2 ## [63] crayon_1.5.2 hdf5r_1.3.8 ## [65] spatstat.explore_3.1-0 pkgconfig_2.0.3 ## [67] labeling_0.4.2 nlme_3.1-157 ## [69] ProtGenerics_1.30.0 nnet_7.3-17 ## [71] rlang_1.1.0 globals_0.16.2 ## [73] lifecycle_1.0.3 miniUI_0.1.1.1 ## [75] filelock_1.0.2 BiocFileCache_2.6.1 ## [77] dichromat_2.0-0.1 rprojroot_2.0.3 ## [79] polyclip_1.10-4 matrixStats_0.63.0 ## [81] lmtest_0.9-40 Matrix_1.5-3 ## [83] zoo_1.8-11 base64enc_0.1-3 ## [85] ggridges_0.5.4 png_0.1-8 ## [87] viridisLite_0.4.1 rjson_0.2.21 ## [89] bitops_1.0-7 R.oo_1.25.0 ## [91] KernSmooth_2.23-20 blob_1.2.3 ## [93] stringr_1.5.0 parallelly_1.35.0 ## [95] spatstat.random_3.1-4 readr_2.1.4 ## [97] jpeg_0.1-10 CNEr_1.34.0 ## [99] scales_1.2.1 memoise_2.0.1 ## [101] magrittr_2.0.3 plyr_1.8.8 ## [103] ica_1.0-3 zlibbioc_1.44.0 ## [105] compiler_4.2.0 BiocIO_1.8.0 ## [107] RColorBrewer_1.1-3 fitdistrplus_1.1-8 ## [109] Rsamtools_2.14.0 cli_3.6.1 ## [111] listenv_0.9.0 patchwork_1.1.2 ## [113] pbapply_1.7-0 htmlTable_2.4.1 ## [115] Formula_1.2-5 MASS_7.3-56 ## [117] tidyselect_1.2.0 stringi_1.7.12 ## [119] textshaping_0.3.6 highr_0.10 ## [121] yaml_2.3.7 latticeExtra_0.6-30 ## [123] ggrepel_0.9.3 grid_4.2.0 ## [125] sass_0.4.5 VariantAnnotation_1.44.1 ## [127] fastmatch_1.1-3 tools_4.2.0 ## [129] future.apply_1.10.0 parallel_4.2.0 ## [131] rstudioapi_0.14 TFMPvalue_0.0.9 ## [133] foreign_0.8-82 gridExtra_2.3 ## [135] farver_2.1.1 Rtsne_0.16 ## [137] digest_0.6.31 pracma_2.4.2 ## [139] shiny_1.7.4 Rcpp_1.0.10 ## [141] later_1.3.0 RcppAnnoy_0.0.20 ## [143] httr_1.4.5 biovizBase_1.46.0 ## [145] colorspace_2.1-0 XML_3.99-0.13 ## [147] fs_1.6.1 tensor_1.5 ## [149] reticulate_1.28 splines_4.2.0 ## [151] uwot_0.1.14 RcppRoll_0.3.0 ## [153] spatstat.utils_3.0-2 pkgdown_2.0.7 ## [155] sp_1.6-0 plotly_4.10.1 ## [157] systemfonts_1.0.4 xtable_1.8-4 ## [159] poweRlaw_0.70.6 jsonlite_1.8.4 ## [161] R6_2.5.1 Hmisc_4.8-0 ## [163] pillar_1.9.0 htmltools_0.5.5 ## [165] mime_0.12 DT_0.27 ## [167] glue_1.6.2 fastmap_1.1.1 ## [169] BiocParallel_1.32.5 codetools_0.2-18 ## [171] utf8_1.2.3 lattice_0.20-45 ## [173] bslib_0.4.2 spatstat.sparse_3.0-1 ## [175] tibble_3.2.1 curl_5.0.0 ## [177] leiden_0.4.3 gtools_3.9.4 ## [179] GO.db_3.16.0 interp_1.1-3 ## [181] survival_3.3-1 rmarkdown_2.21 ## [183] desc_1.4.2 munsell_0.5.0 ## [185] GenomeInfoDbData_1.2.9 reshape2_1.4.4 ## [187] gtable_0.3.3

# identify top markers in HSPC and visualize head(topTFs("CD16 Mono"),3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 CD16 Mono SPI1 0.8793172 1.666810e-296 CD16 Mono MA0080.5 0.8880908 ## 2 CD16 Mono CEBPB 0.8685933 1.625472e-294 CD16 Mono MA0466.2 0.7840422 ## 3 CD16 Mono MEF2C 0.7129910 2.727252e-79 CD16 Mono MA0497.1 0.8059373 ## motif.pval avg_auc ## 1 4.762491e-194 0.8837040 ## 2 7.049764e-105 0.8263177 ## 3 2.345716e-121 0.7594641 motif.name <- ConvertMotifID(pbmc, name = 'SPI1') gene_plot <- FeaturePlot(pbmc, features = "sct_SPI1", reduction = 'wnn.umap') motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap') gene_plot | motif_plot # identify top markers in other cell types head(topTFs("Naive B"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 Naive B MEF2C 0.8802747 1.890065e-182 Naive B MA0497.1 0.6789079 ## 2 Naive B PAX5 0.9436648 0.000000e+00 Naive B MA0014.3 0.5827061 ## 3 Naive B POU2F2 0.6029377 2.892216e-13 Naive B MA0507.1 0.8912268 ## motif.pval avg_auc ## 1 9.815118e-32 0.7795913 ## 2 5.995185e-08 0.7631854 ## 3 6.471677e-145 0.7470822 head(topTFs("HSPC"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 HSPC SOX4 0.9869406 5.524832e-71 HSPC MA0867.2 0.6830497 ## 2 HSPC GATA2 0.7884615 0.000000e+00 HSPC MA0036.3 0.8275008 ## 3 HSPC MEIS1 0.8638496 0.000000e+00 HSPC MA0498.2 0.6924225 ## motif.pval avg_auc ## 1 1.241915e-03 0.8349951 ## 2 7.591798e-09 0.8079812 ## 3 6.877492e-04 0.7781361 head(topTFs("Plasma"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 Plasma IRF4 0.8189687 5.261955e-35 Plasma MA1419.1 0.9776046 ## 2 Plasma MEF2C 0.9111213 2.977155e-12 Plasma MA0497.1 0.7596637 ## 3 Plasma TCF4 0.8049409 6.810635e-12 Plasma MA0830.2 0.7840848 ## motif.pval avg_auc ## 1 2.334627e-12 0.8982867 ## 2 1.374353e-04 0.8353925 ## 3 3.028306e-05 0.7945129Session Info sessionInfo()## R version 4.2.0 (2022-04-22) ## Platform: x86_64-pc-linux-gnu (64-bit) ## Running under: Ubuntu 20.04.5 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/liblapack.so.3 ## ## locale: ## [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C ## [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8 ## [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 ## ## attached base packages: ## [1] stats4 stats graphics grDevices utils datasets methods ## [8] base ## ## other attached packages: ## [1] BSgenome.Hsapiens.UCSC.hg38_1.4.5 BSgenome_1.66.3 ## [3] rtracklayer_1.58.0 Biostrings_2.66.0 ## [5] XVector_0.38.0 motifmatchr_1.20.0 ## [7] TFBSTools_1.36.0 JASPAR2020_0.99.10 ## [9] chromVAR_1.20.2 EnsDb.Hsapiens.v86_2.99.0 ## [11] ensembldb_2.22.0 AnnotationFilter_1.22.0 ## [13] GenomicFeatures_1.50.4 AnnotationDbi_1.60.0 ## [15] Biobase_2.58.0 GenomicRanges_1.50.2 ## [17] GenomeInfoDb_1.35.16 IRanges_2.32.0 ## [19] S4Vectors_0.36.2 BiocGenerics_0.44.0 ## [21] Signac_1.9.0 ggplot2_3.4.1 ## [23] dplyr_1.1.1 cowplot_1.1.1 ## [25] thp1.eccite.SeuratData_3.1.5 stxBrain.SeuratData_0.1.1 ## [27] ssHippo.SeuratData_3.1.4 pbmcsca.SeuratData_3.0.0 ## [29] pbmcMultiome.SeuratData_0.1.2 pbmc3k.SeuratData_3.1.4 ## [31] panc8.SeuratData_3.0.2 ifnb.SeuratData_3.1.0 ## [33] hcabm40k.SeuratData_3.0.0 bmcite.SeuratData_0.3.0 ## [35] SeuratData_0.2.2 SeuratObject_4.1.3 ## [37] Seurat_4.2.1.9001 ## ## loaded via a namespace (and not attached): ## [1] rappdirs_0.3.3 scattermore_0.8 ## [3] R.methodsS3_1.8.2 ragg_1.2.5 ## [5] nabor_0.5.0 tidyr_1.3.0 ## [7] bit64_4.0.5 knitr_1.42 ## [9] R.utils_2.12.2 irlba_2.3.5.1 ## [11] DelayedArray_0.24.0 data.table_1.14.8 ## [13] rpart_4.1.16 KEGGREST_1.38.0 ## [15] RCurl_1.98-1.12 generics_0.1.3 ## [17] RSQLite_2.3.0 RANN_2.6.1 ## [19] future_1.32.0 tzdb_0.3.0 ## [21] bit_4.0.5 spatstat.data_3.0-1 ## [23] xml2_1.3.3 httpuv_1.6.9 ## [25] SummarizedExperiment_1.28.0 DirichletMultinomial_1.40.0 ## [27] xfun_0.38 hms_1.1.2 ## [29] jquerylib_0.1.4 evaluate_0.20 ## [31] promises_1.2.0.1 fansi_1.0.4 ## [33] restfulr_0.0.15 progress_1.2.2 ## [35] caTools_1.18.2 dbplyr_2.3.1 ## [37] igraph_1.4.1 DBI_1.1.3 ## [39] htmlwidgets_1.6.2 spatstat.geom_3.1-0 ## [41] purrr_1.0.1 ellipsis_0.3.2 ## [43] backports_1.4.1 annotate_1.76.0 ## [45] biomaRt_2.54.0 deldir_1.0-6 ## [47] MatrixGenerics_1.10.0 vctrs_0.6.1 ## [49] ROCR_1.0-11 abind_1.4-5 ## [51] cachem_1.0.7 withr_2.5.0 ## [53] progressr_0.13.0 presto_1.0.0 ## [55] checkmate_2.1.0 sctransform_0.3.5 ## [57] GenomicAlignments_1.34.0 prettyunits_1.1.1 ## [59] goftest_1.2-3 cluster_2.1.3 ## [61] seqLogo_1.64.0 lazyeval_0.2.2 ## [63] crayon_1.5.2 hdf5r_1.3.8 ## [65] spatstat.explore_3.1-0 pkgconfig_2.0.3 ## [67] labeling_0.4.2 nlme_3.1-157 ## [69] ProtGenerics_1.30.0 nnet_7.3-17 ## [71] rlang_1.1.0 globals_0.16.2 ## [73] lifecycle_1.0.3 miniUI_0.1.1.1 ## [75] filelock_1.0.2 BiocFileCache_2.6.1 ## [77] dichromat_2.0-0.1 rprojroot_2.0.3 ## [79] polyclip_1.10-4 matrixStats_0.63.0 ## [81] lmtest_0.9-40 Matrix_1.5-3 ## [83] zoo_1.8-11 base64enc_0.1-3 ## [85] ggridges_0.5.4 png_0.1-8 ## [87] viridisLite_0.4.1 rjson_0.2.21 ## [89] bitops_1.0-7 R.oo_1.25.0 ## [91] KernSmooth_2.23-20 blob_1.2.3 ## [93] stringr_1.5.0 parallelly_1.35.0 ## [95] spatstat.random_3.1-4 readr_2.1.4 ## [97] jpeg_0.1-10 CNEr_1.34.0 ## [99] scales_1.2.1 memoise_2.0.1 ## [101] magrittr_2.0.3 plyr_1.8.8 ## [103] ica_1.0-3 zlibbioc_1.44.0 ## [105] compiler_4.2.0 BiocIO_1.8.0 ## [107] RColorBrewer_1.1-3 fitdistrplus_1.1-8 ## [109] Rsamtools_2.14.0 cli_3.6.1 ## [111] listenv_0.9.0 patchwork_1.1.2 ## [113] pbapply_1.7-0 htmlTable_2.4.1 ## [115] Formula_1.2-5 MASS_7.3-56 ## [117] tidyselect_1.2.0 stringi_1.7.12 ## [119] textshaping_0.3.6 highr_0.10 ## [121] yaml_2.3.7 latticeExtra_0.6-30 ## [123] ggrepel_0.9.3 grid_4.2.0 ## [125] sass_0.4.5 VariantAnnotation_1.44.1 ## [127] fastmatch_1.1-3 tools_4.2.0 ## [129] future.apply_1.10.0 parallel_4.2.0 ## [131] rstudioapi_0.14 TFMPvalue_0.0.9 ## [133] foreign_0.8-82 gridExtra_2.3 ## [135] farver_2.1.1 Rtsne_0.16 ## [137] digest_0.6.31 pracma_2.4.2 ## [139] shiny_1.7.4 Rcpp_1.0.10 ## [141] later_1.3.0 RcppAnnoy_0.0.20 ## [143] httr_1.4.5 biovizBase_1.46.0 ## [145] colorspace_2.1-0 XML_3.99-0.13 ## [147] fs_1.6.1 tensor_1.5 ## [149] reticulate_1.28 splines_4.2.0 ## [151] uwot_0.1.14 RcppRoll_0.3.0 ## [153] spatstat.utils_3.0-2 pkgdown_2.0.7 ## [155] sp_1.6-0 plotly_4.10.1 ## [157] systemfonts_1.0.4 xtable_1.8-4 ## [159] poweRlaw_0.70.6 jsonlite_1.8.4 ## [161] R6_2.5.1 Hmisc_4.8-0 ## [163] pillar_1.9.0 htmltools_0.5.5 ## [165] mime_0.12 DT_0.27 ## [167] glue_1.6.2 fastmap_1.1.1 ## [169] BiocParallel_1.32.5 codetools_0.2-18 ## [171] utf8_1.2.3 lattice_0.20-45 ## [173] bslib_0.4.2 spatstat.sparse_3.0-1 ## [175] tibble_3.2.1 curl_5.0.0 ## [177] leiden_0.4.3 gtools_3.9.4 ## [179] GO.db_3.16.0 interp_1.1-3 ## [181] survival_3.3-1 rmarkdown_2.21 ## [183] desc_1.4.2 munsell_0.5.0 ## [185] GenomeInfoDbData_1.2.9 reshape2_1.4.4 ## [187] gtable_0.3.3

# identify top markers in other cell types head(topTFs("Naive B"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 Naive B MEF2C 0.8802747 1.890065e-182 Naive B MA0497.1 0.6789079 ## 2 Naive B PAX5 0.9436648 0.000000e+00 Naive B MA0014.3 0.5827061 ## 3 Naive B POU2F2 0.6029377 2.892216e-13 Naive B MA0507.1 0.8912268 ## motif.pval avg_auc ## 1 9.815118e-32 0.7795913 ## 2 5.995185e-08 0.7631854 ## 3 6.471677e-145 0.7470822 head(topTFs("HSPC"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 HSPC SOX4 0.9869406 5.524832e-71 HSPC MA0867.2 0.6830497 ## 2 HSPC GATA2 0.7884615 0.000000e+00 HSPC MA0036.3 0.8275008 ## 3 HSPC MEIS1 0.8638496 0.000000e+00 HSPC MA0498.2 0.6924225 ## motif.pval avg_auc ## 1 1.241915e-03 0.8349951 ## 2 7.591798e-09 0.8079812 ## 3 6.877492e-04 0.7781361 head(topTFs("Plasma"), 3)## RNA.group gene RNA.auc RNA.pval motif.group motif.feature motif.auc ## 1 Plasma IRF4 0.8189687 5.261955e-35 Plasma MA1419.1 0.9776046 ## 2 Plasma MEF2C 0.9111213 2.977155e-12 Plasma MA0497.1 0.7596637 ## 3 Plasma TCF4 0.8049409 6.810635e-12 Plasma MA0830.2 0.7840848 ## motif.pval avg_auc ## 1 2.334627e-12 0.8982867 ## 2 1.374353e-04 0.8353925 ## 3 3.028306e-05 0.7945129Session Info sessionInfo()## R version 4.2.0 (2022-04-22) ## Platform: x86_64-pc-linux-gnu (64-bit) ## Running under: Ubuntu 20.04.5 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/liblapack.so.3 ## ## locale: ## [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C ## [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8 ## [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 ## ## attached base packages: ## [1] stats4 stats graphics grDevices utils datasets methods ## [8] base ## ## other attached packages: ## [1] BSgenome.Hsapiens.UCSC.hg38_1.4.5 BSgenome_1.66.3 ## [3] rtracklayer_1.58.0 Biostrings_2.66.0 ## [5] XVector_0.38.0 motifmatchr_1.20.0 ## [7] TFBSTools_1.36.0 JASPAR2020_0.99.10 ## [9] chromVAR_1.20.2 EnsDb.Hsapiens.v86_2.99.0 ## [11] ensembldb_2.22.0 AnnotationFilter_1.22.0 ## [13] GenomicFeatures_1.50.4 AnnotationDbi_1.60.0 ## [15] Biobase_2.58.0 GenomicRanges_1.50.2 ## [17] GenomeInfoDb_1.35.16 IRanges_2.32.0 ## [19] S4Vectors_0.36.2 BiocGenerics_0.44.0 ## [21] Signac_1.9.0 ggplot2_3.4.1 ## [23] dplyr_1.1.1 cowplot_1.1.1 ## [25] thp1.eccite.SeuratData_3.1.5 stxBrain.SeuratData_0.1.1 ## [27] ssHippo.SeuratData_3.1.4 pbmcsca.SeuratData_3.0.0 ## [29] pbmcMultiome.SeuratData_0.1.2 pbmc3k.SeuratData_3.1.4 ## [31] panc8.SeuratData_3.0.2 ifnb.SeuratData_3.1.0 ## [33] hcabm40k.SeuratData_3.0.0 bmcite.SeuratData_0.3.0 ## [35] SeuratData_0.2.2 SeuratObject_4.1.3 ## [37] Seurat_4.2.1.9001 ## ## loaded via a namespace (and not attached): ## [1] rappdirs_0.3.3 scattermore_0.8 ## [3] R.methodsS3_1.8.2 ragg_1.2.5 ## [5] nabor_0.5.0 tidyr_1.3.0 ## [7] bit64_4.0.5 knitr_1.42 ## [9] R.utils_2.12.2 irlba_2.3.5.1 ## [11] DelayedArray_0.24.0 data.table_1.14.8 ## [13] rpart_4.1.16 KEGGREST_1.38.0 ## [15] RCurl_1.98-1.12 generics_0.1.3 ## [17] RSQLite_2.3.0 RANN_2.6.1 ## [19] future_1.32.0 tzdb_0.3.0 ## [21] bit_4.0.5 spatstat.data_3.0-1 ## [23] xml2_1.3.3 httpuv_1.6.9 ## [25] SummarizedExperiment_1.28.0 DirichletMultinomial_1.40.0 ## [27] xfun_0.38 hms_1.1.2 ## [29] jquerylib_0.1.4 evaluate_0.20 ## [31] promises_1.2.0.1 fansi_1.0.4 ## [33] restfulr_0.0.15 progress_1.2.2 ## [35] caTools_1.18.2 dbplyr_2.3.1 ## [37] igraph_1.4.1 DBI_1.1.3 ## [39] htmlwidgets_1.6.2 spatstat.geom_3.1-0 ## [41] purrr_1.0.1 ellipsis_0.3.2 ## [43] backports_1.4.1 annotate_1.76.0 ## [45] biomaRt_2.54.0 deldir_1.0-6 ## [47] MatrixGenerics_1.10.0 vctrs_0.6.1 ## [49] ROCR_1.0-11 abind_1.4-5 ## [51] cachem_1.0.7 withr_2.5.0 ## [53] progressr_0.13.0 presto_1.0.0 ## [55] checkmate_2.1.0 sctransform_0.3.5 ## [57] GenomicAlignments_1.34.0 prettyunits_1.1.1 ## [59] goftest_1.2-3 cluster_2.1.3 ## [61] seqLogo_1.64.0 lazyeval_0.2.2 ## [63] crayon_1.5.2 hdf5r_1.3.8 ## [65] spatstat.explore_3.1-0 pkgconfig_2.0.3 ## [67] labeling_0.4.2 nlme_3.1-157 ## [69] ProtGenerics_1.30.0 nnet_7.3-17 ## [71] rlang_1.1.0 globals_0.16.2 ## [73] lifecycle_1.0.3 miniUI_0.1.1.1 ## [75] filelock_1.0.2 BiocFileCache_2.6.1 ## [77] dichromat_2.0-0.1 rprojroot_2.0.3 ## [79] polyclip_1.10-4 matrixStats_0.63.0 ## [81] lmtest_0.9-40 Matrix_1.5-3 ## [83] zoo_1.8-11 base64enc_0.1-3 ## [85] ggridges_0.5.4 png_0.1-8 ## [87] viridisLite_0.4.1 rjson_0.2.21 ## [89] bitops_1.0-7 R.oo_1.25.0 ## [91] KernSmooth_2.23-20 blob_1.2.3 ## [93] stringr_1.5.0 parallelly_1.35.0 ## [95] spatstat.random_3.1-4 readr_2.1.4 ## [97] jpeg_0.1-10 CNEr_1.34.0 ## [99] scales_1.2.1 memoise_2.0.1 ## [101] magrittr_2.0.3 plyr_1.8.8 ## [103] ica_1.0-3 zlibbioc_1.44.0 ## [105] compiler_4.2.0 BiocIO_1.8.0 ## [107] RColorBrewer_1.1-3 fitdistrplus_1.1-8 ## [109] Rsamtools_2.14.0 cli_3.6.1 ## [111] listenv_0.9.0 patchwork_1.1.2 ## [113] pbapply_1.7-0 htmlTable_2.4.1 ## [115] Formula_1.2-5 MASS_7.3-56 ## [117] tidyselect_1.2.0 stringi_1.7.12 ## [119] textshaping_0.3.6 highr_0.10 ## [121] yaml_2.3.7 latticeExtra_0.6-30 ## [123] ggrepel_0.9.3 grid_4.2.0 ## [125] sass_0.4.5 VariantAnnotation_1.44.1 ## [127] fastmatch_1.1-3 tools_4.2.0 ## [129] future.apply_1.10.0 parallel_4.2.0 ## [131] rstudioapi_0.14 TFMPvalue_0.0.9 ## [133] foreign_0.8-82 gridExtra_2.3 ## [135] farver_2.1.1 Rtsne_0.16 ## [137] digest_0.6.31 pracma_2.4.2 ## [139] shiny_1.7.4 Rcpp_1.0.10 ## [141] later_1.3.0 RcppAnnoy_0.0.20 ## [143] httr_1.4.5 biovizBase_1.46.0 ## [145] colorspace_2.1-0 XML_3.99-0.13 ## [147] fs_1.6.1 tensor_1.5 ## [149] reticulate_1.28 splines_4.2.0 ## [151] uwot_0.1.14 RcppRoll_0.3.0 ## [153] spatstat.utils_3.0-2 pkgdown_2.0.7 ## [155] sp_1.6-0 plotly_4.10.1 ## [157] systemfonts_1.0.4 xtable_1.8-4 ## [159] poweRlaw_0.70.6 jsonlite_1.8.4 ## [161] R6_2.5.1 Hmisc_4.8-0 ## [163] pillar_1.9.0 htmltools_0.5.5 ## [165] mime_0.12 DT_0.27 ## [167] glue_1.6.2 fastmap_1.1.1 ## [169] BiocParallel_1.32.5 codetools_0.2-18 ## [171] utf8_1.2.3 lattice_0.20-45 ## [173] bslib_0.4.2 spatstat.sparse_3.0-1 ## [175] tibble_3.2.1 curl_5.0.0 ## [177] leiden_0.4.3 gtools_3.9.4 ## [179] GO.db_3.16.0 interp_1.1-3 ## [181] survival_3.3-1 rmarkdown_2.21 ## [183] desc_1.4.2 munsell_0.5.0 ## [185] GenomeInfoDbData_1.2.9 reshape2_1.4.4 ## [187] gtable_0.3.3

sessionInfo()## R version 4.2.0 (2022-04-22) ## Platform: x86_64-pc-linux-gnu (64-bit) ## Running under: Ubuntu 20.04.5 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/liblapack.so.3 ## ## locale: ## [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C ## [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8 ## [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 ## ## attached base packages: ## [1] stats4 stats graphics grDevices utils datasets methods ## [8] base ## ## other attached packages: ## [1] BSgenome.Hsapiens.UCSC.hg38_1.4.5 BSgenome_1.66.3 ## [3] rtracklayer_1.58.0 Biostrings_2.66.0 ## [5] XVector_0.38.0 motifmatchr_1.20.0 ## [7] TFBSTools_1.36.0 JASPAR2020_0.99.10 ## [9] chromVAR_1.20.2 EnsDb.Hsapiens.v86_2.99.0 ## [11] ensembldb_2.22.0 AnnotationFilter_1.22.0 ## [13] GenomicFeatures_1.50.4 AnnotationDbi_1.60.0 ## [15] Biobase_2.58.0 GenomicRanges_1.50.2 ## [17] GenomeInfoDb_1.35.16 IRanges_2.32.0 ## [19] S4Vectors_0.36.2 BiocGenerics_0.44.0 ## [21] Signac_1.9.0 ggplot2_3.4.1 ## [23] dplyr_1.1.1 cowplot_1.1.1 ## [25] thp1.eccite.SeuratData_3.1.5 stxBrain.SeuratData_0.1.1 ## [27] ssHippo.SeuratData_3.1.4 pbmcsca.SeuratData_3.0.0 ## [29] pbmcMultiome.SeuratData_0.1.2 pbmc3k.SeuratData_3.1.4 ## [31] panc8.SeuratData_3.0.2 ifnb.SeuratData_3.1.0 ## [33] hcabm40k.SeuratData_3.0.0 bmcite.SeuratData_0.3.0 ## [35] SeuratData_0.2.2 SeuratObject_4.1.3 ## [37] Seurat_4.2.1.9001 ## ## loaded via a namespace (and not attached): ## [1] rappdirs_0.3.3 scattermore_0.8 ## [3] R.methodsS3_1.8.2 ragg_1.2.5 ## [5] nabor_0.5.0 tidyr_1.3.0 ## [7] bit64_4.0.5 knitr_1.42 ## [9] R.utils_2.12.2 irlba_2.3.5.1 ## [11] DelayedArray_0.24.0 data.table_1.14.8 ## [13] rpart_4.1.16 KEGGREST_1.38.0 ## [15] RCurl_1.98-1.12 generics_0.1.3 ## [17] RSQLite_2.3.0 RANN_2.6.1 ## [19] future_1.32.0 tzdb_0.3.0 ## [21] bit_4.0.5 spatstat.data_3.0-1 ## [23] xml2_1.3.3 httpuv_1.6.9 ## [25] SummarizedExperiment_1.28.0 DirichletMultinomial_1.40.0 ## [27] xfun_0.38 hms_1.1.2 ## [29] jquerylib_0.1.4 evaluate_0.20 ## [31] promises_1.2.0.1 fansi_1.0.4 ## [33] restfulr_0.0.15 progress_1.2.2 ## [35] caTools_1.18.2 dbplyr_2.3.1 ## [37] igraph_1.4.1 DBI_1.1.3 ## [39] htmlwidgets_1.6.2 spatstat.geom_3.1-0 ## [41] purrr_1.0.1 ellipsis_0.3.2 ## [43] backports_1.4.1 annotate_1.76.0 ## [45] biomaRt_2.54.0 deldir_1.0-6 ## [47] MatrixGenerics_1.10.0 vctrs_0.6.1 ## [49] ROCR_1.0-11 abind_1.4-5 ## [51] cachem_1.0.7 withr_2.5.0 ## [53] progressr_0.13.0 presto_1.0.0 ## [55] checkmate_2.1.0 sctransform_0.3.5 ## [57] GenomicAlignments_1.34.0 prettyunits_1.1.1 ## [59] goftest_1.2-3 cluster_2.1.3 ## [61] seqLogo_1.64.0 lazyeval_0.2.2 ## [63] crayon_1.5.2 hdf5r_1.3.8 ## [65] spatstat.explore_3.1-0 pkgconfig_2.0.3 ## [67] labeling_0.4.2 nlme_3.1-157 ## [69] ProtGenerics_1.30.0 nnet_7.3-17 ## [71] rlang_1.1.0 globals_0.16.2 ## [73] lifecycle_1.0.3 miniUI_0.1.1.1 ## [75] filelock_1.0.2 BiocFileCache_2.6.1 ## [77] dichromat_2.0-0.1 rprojroot_2.0.3 ## [79] polyclip_1.10-4 matrixStats_0.63.0 ## [81] lmtest_0.9-40 Matrix_1.5-3 ## [83] zoo_1.8-11 base64enc_0.1-3 ## [85] ggridges_0.5.4 png_0.1-8 ## [87] viridisLite_0.4.1 rjson_0.2.21 ## [89] bitops_1.0-7 R.oo_1.25.0 ## [91] KernSmooth_2.23-20 blob_1.2.3 ## [93] stringr_1.5.0 parallelly_1.35.0 ## [95] spatstat.random_3.1-4 readr_2.1.4 ## [97] jpeg_0.1-10 CNEr_1.34.0 ## [99] scales_1.2.1 memoise_2.0.1 ## [101] magrittr_2.0.3 plyr_1.8.8 ## [103] ica_1.0-3 zlibbioc_1.44.0 ## [105] compiler_4.2.0 BiocIO_1.8.0 ## [107] RColorBrewer_1.1-3 fitdistrplus_1.1-8 ## [109] Rsamtools_2.14.0 cli_3.6.1 ## [111] listenv_0.9.0 patchwork_1.1.2 ## [113] pbapply_1.7-0 htmlTable_2.4.1 ## [115] Formula_1.2-5 MASS_7.3-56 ## [117] tidyselect_1.2.0 stringi_1.7.12 ## [119] textshaping_0.3.6 highr_0.10 ## [121] yaml_2.3.7 latticeExtra_0.6-30 ## [123] ggrepel_0.9.3 grid_4.2.0 ## [125] sass_0.4.5 VariantAnnotation_1.44.1 ## [127] fastmatch_1.1-3 tools_4.2.0 ## [129] future.apply_1.10.0 parallel_4.2.0 ## [131] rstudioapi_0.14 TFMPvalue_0.0.9 ## [133] foreign_0.8-82 gridExtra_2.3 ## [135] farver_2.1.1 Rtsne_0.16 ## [137] digest_0.6.31 pracma_2.4.2 ## [139] shiny_1.7.4 Rcpp_1.0.10 ## [141] later_1.3.0 RcppAnnoy_0.0.20 ## [143] httr_1.4.5 biovizBase_1.46.0 ## [145] colorspace_2.1-0 XML_3.99-0.13 ## [147] fs_1.6.1 tensor_1.5 ## [149] reticulate_1.28 splines_4.2.0 ## [151] uwot_0.1.14 RcppRoll_0.3.0 ## [153] spatstat.utils_3.0-2 pkgdown_2.0.7 ## [155] sp_1.6-0 plotly_4.10.1 ## [157] systemfonts_1.0.4 xtable_1.8-4 ## [159] poweRlaw_0.70.6 jsonlite_1.8.4 ## [161] R6_2.5.1 Hmisc_4.8-0 ## [163] pillar_1.9.0 htmltools_0.5.5 ## [165] mime_0.12 DT_0.27 ## [167] glue_1.6.2 fastmap_1.1.1 ## [169] BiocParallel_1.32.5 codetools_0.2-18 ## [171] utf8_1.2.3 lattice_0.20-45 ## [173] bslib_0.4.2 spatstat.sparse_3.0-1 ## [175] tibble_3.2.1 curl_5.0.0 ## [177] leiden_0.4.3 gtools_3.9.4 ## [179] GO.db_3.16.0 interp_1.1-3 ## [181] survival_3.3-1 rmarkdown_2.21 ## [183] desc_1.4.2 munsell_0.5.0 ## [185] GenomeInfoDbData_1.2.9 reshape2_1.4.4 ## [187] gtable_0.3.3

Developed by Paul Hoffman, Satija Lab and Collaborators.

Developed by Paul Hoffman, Satija Lab and Collaborators.

Site built with pkgdown 2.0.7.

Site built with pkgdown 2.0.7.

**Examples:**

Example 1 (unknown):
```unknown
vignettes/weighted_nearest_neighbor_analysis.Rmd
```

Example 2 (unknown):
```unknown
weighted_nearest_neighbor_analysis.Rmd
```

Example 3 (unknown):
```unknown
install.packages("Seurat")
```

Example 4 (r):
```r
install.packages("Seurat")
```

Example 5 (r):
```r
install.packages("Seurat")
```

Example 6 (unknown):
```unknown
library(Seurat)
library(SeuratData)
library(cowplot)
library(dplyr)
```

Example 7 (r):
```r
library(Seurat)
library(SeuratData)
library(cowplot)
library(dplyr)
```

Example 8 (r):
```r
library(Seurat)
library(SeuratData)
library(cowplot)
library(dplyr)
```

Example 9 (unknown):
```unknown
InstallData("bmcite")
bm <- LoadData(ds = "bmcite")
```

Example 10 (r):
```r
InstallData("bmcite")
bm <- LoadData(ds = "bmcite")
```

Example 11 (r):
```r
InstallData("bmcite")
bm <- LoadData(ds = "bmcite")
```

Example 12 (unknown):
```unknown
DefaultAssay(bm) <- 'RNA'
bm <- NormalizeData(bm) %>% FindVariableFeatures() %>% ScaleData() %>% RunPCA()

DefaultAssay(bm) <- 'ADT'
# we will use all ADT features for dimensional reduction
# we set a dimensional reduction name to avoid overwriting the 
VariableFeatures(bm) <- rownames(bm[["ADT"]])
bm <- NormalizeData(bm, normalization.method = 'CLR', margin = 2) %>% 
  ScaleData() %>% RunPCA(reduction.name = 'apca')
```

Example 13 (r):
```r
DefaultAssay(bm) <- 'RNA'
bm <- NormalizeData(bm) %>% FindVariableFeatures() %>% ScaleData() %>% RunPCA()

DefaultAssay(bm) <- 'ADT'
# we will use all ADT features for dimensional reduction
# we set a dimensional reduction name to avoid overwriting the 
VariableFeatures(bm) <- rownames(bm[["ADT"]])
bm <- NormalizeData(bm, normalization.method = 'CLR', margin = 2) %>% 
  ScaleData() %>% RunPCA(reduction.name = 'apca')
```

Example 14 (r):
```r
DefaultAssay(bm) <- 'RNA'
bm <- NormalizeData(bm) %>% FindVariableFeatures() %>% ScaleData() %>% RunPCA()

DefaultAssay(bm) <- 'ADT'
# we will use all ADT features for dimensional reduction
# we set a dimensional reduction name to avoid overwriting the 
VariableFeatures(bm) <- rownames(bm[["ADT"]])
bm <- NormalizeData(bm, normalization.method = 'CLR', margin = 2) %>% 
  ScaleData() %>% RunPCA(reduction.name = 'apca')
```

Example 15 (unknown):
```unknown
# Identify multimodal neighbors. These will be stored in the neighbors slot, 
# and can be accessed using bm[['weighted.nn']]
# The WNN graph can be accessed at bm[["wknn"]], 
# and the SNN graph used for clustering at bm[["wsnn"]]
# Cell-specific modality weights can be accessed at bm$RNA.weight
bm <- FindMultiModalNeighbors(
  bm, reduction.list = list("pca", "apca"), 
  dims.list = list(1:30, 1:18), modality.weight.name = "RNA.weight"
)
```

Example 16 (r):
```r
# Identify multimodal neighbors. These will be stored in the neighbors slot, 
# and can be accessed using bm[['weighted.nn']]
# The WNN graph can be accessed at bm[["wknn"]], 
# and the SNN graph used for clustering at bm[["wsnn"]]
# Cell-specific modality weights can be accessed at bm$RNA.weight
bm <- FindMultiModalNeighbors(
  bm, reduction.list = list("pca", "apca"), 
  dims.list = list(1:30, 1:18), modality.weight.name = "RNA.weight"
)
```

Example 17 (r):
```r
# Identify multimodal neighbors. These will be stored in the neighbors slot, 
# and can be accessed using bm[['weighted.nn']]
# The WNN graph can be accessed at bm[["wknn"]], 
# and the SNN graph used for clustering at bm[["wsnn"]]
# Cell-specific modality weights can be accessed at bm$RNA.weight
bm <- FindMultiModalNeighbors(
  bm, reduction.list = list("pca", "apca"), 
  dims.list = list(1:30, 1:18), modality.weight.name = "RNA.weight"
)
```

Example 18 (unknown):
```unknown
bm <- RunUMAP(bm, nn.name = "weighted.nn", reduction.name = "wnn.umap", reduction.key = "wnnUMAP_")
bm <- FindClusters(bm, graph.name = "wsnn", algorithm = 3, resolution = 2, verbose = FALSE)
```

Example 19 (r):
```r
bm <- RunUMAP(bm, nn.name = "weighted.nn", reduction.name = "wnn.umap", reduction.key = "wnnUMAP_")
bm <- FindClusters(bm, graph.name = "wsnn", algorithm = 3, resolution = 2, verbose = FALSE)
```

Example 20 (r):
```r
bm <- RunUMAP(bm, nn.name = "weighted.nn", reduction.name = "wnn.umap", reduction.key = "wnnUMAP_")
bm <- FindClusters(bm, graph.name = "wsnn", algorithm = 3, resolution = 2, verbose = FALSE)
```

Example 21 (unknown):
```unknown
p1 <- DimPlot(bm, reduction = 'wnn.umap', label = TRUE, repel = TRUE, label.size = 2.5) + NoLegend()
p2 <- DimPlot(bm, reduction = 'wnn.umap', group.by = 'celltype.l2', label = TRUE, repel = TRUE, label.size = 2.5) + NoLegend()
p1 + p2
```

Example 22 (r):
```r
p1 <- DimPlot(bm, reduction = 'wnn.umap', label = TRUE, repel = TRUE, label.size = 2.5) + NoLegend()
p2 <- DimPlot(bm, reduction = 'wnn.umap', group.by = 'celltype.l2', label = TRUE, repel = TRUE, label.size = 2.5) + NoLegend()
p1 + p2
```

Example 23 (r):
```r
p1 <- DimPlot(bm, reduction = 'wnn.umap', label = TRUE, repel = TRUE, label.size = 2.5) + NoLegend()
p2 <- DimPlot(bm, reduction = 'wnn.umap', group.by = 'celltype.l2', label = TRUE, repel = TRUE, label.size = 2.5) + NoLegend()
p1 + p2
```

Example 24 (unknown):
```unknown
bm <- RunUMAP(bm, reduction = 'pca', dims = 1:30, assay = 'RNA', 
              reduction.name = 'rna.umap', reduction.key = 'rnaUMAP_')
bm <- RunUMAP(bm, reduction = 'apca', dims = 1:18, assay = 'ADT', 
              reduction.name = 'adt.umap', reduction.key = 'adtUMAP_')
```

Example 25 (r):
```r
bm <- RunUMAP(bm, reduction = 'pca', dims = 1:30, assay = 'RNA', 
              reduction.name = 'rna.umap', reduction.key = 'rnaUMAP_')
bm <- RunUMAP(bm, reduction = 'apca', dims = 1:18, assay = 'ADT', 
              reduction.name = 'adt.umap', reduction.key = 'adtUMAP_')
```

Example 26 (r):
```r
bm <- RunUMAP(bm, reduction = 'pca', dims = 1:30, assay = 'RNA', 
              reduction.name = 'rna.umap', reduction.key = 'rnaUMAP_')
bm <- RunUMAP(bm, reduction = 'apca', dims = 1:18, assay = 'ADT', 
              reduction.name = 'adt.umap', reduction.key = 'adtUMAP_')
```

Example 27 (unknown):
```unknown
p3 <- DimPlot(bm, reduction = 'rna.umap', group.by = 'celltype.l2', label = TRUE, 
              repel = TRUE, label.size = 2.5) + NoLegend()
p4 <- DimPlot(bm, reduction = 'adt.umap', group.by = 'celltype.l2', label = TRUE, 
              repel = TRUE, label.size = 2.5) + NoLegend()
p3 + p4
```

Example 28 (r):
```r
p3 <- DimPlot(bm, reduction = 'rna.umap', group.by = 'celltype.l2', label = TRUE, 
              repel = TRUE, label.size = 2.5) + NoLegend()
p4 <- DimPlot(bm, reduction = 'adt.umap', group.by = 'celltype.l2', label = TRUE, 
              repel = TRUE, label.size = 2.5) + NoLegend()
p3 + p4
```

Example 29 (r):
```r
p3 <- DimPlot(bm, reduction = 'rna.umap', group.by = 'celltype.l2', label = TRUE, 
              repel = TRUE, label.size = 2.5) + NoLegend()
p4 <- DimPlot(bm, reduction = 'adt.umap', group.by = 'celltype.l2', label = TRUE, 
              repel = TRUE, label.size = 2.5) + NoLegend()
p3 + p4
```

Example 30 (unknown):
```unknown
p5 <- FeaturePlot(bm, features = c("adt_CD45RA","adt_CD16","adt_CD161"),
                  reduction = 'wnn.umap', max.cutoff = 2, 
                  cols = c("lightgrey","darkgreen"), ncol = 3)
p6 <- FeaturePlot(bm, features = c("rna_TRDC","rna_MPO","rna_AVP"), 
                  reduction = 'wnn.umap', max.cutoff = 3, ncol = 3)
p5 / p6
```

Example 31 (r):
```r
p5 <- FeaturePlot(bm, features = c("adt_CD45RA","adt_CD16","adt_CD161"),
                  reduction = 'wnn.umap', max.cutoff = 2, 
                  cols = c("lightgrey","darkgreen"), ncol = 3)
p6 <- FeaturePlot(bm, features = c("rna_TRDC","rna_MPO","rna_AVP"), 
                  reduction = 'wnn.umap', max.cutoff = 3, ncol = 3)
p5 / p6
```

Example 32 (r):
```r
p5 <- FeaturePlot(bm, features = c("adt_CD45RA","adt_CD16","adt_CD161"),
                  reduction = 'wnn.umap', max.cutoff = 2, 
                  cols = c("lightgrey","darkgreen"), ncol = 3)
p6 <- FeaturePlot(bm, features = c("rna_TRDC","rna_MPO","rna_AVP"), 
                  reduction = 'wnn.umap', max.cutoff = 3, ncol = 3)
p5 / p6
```

Example 33 (unknown):
```unknown
VlnPlot(bm, features = "RNA.weight", group.by = 'celltype.l2', sort = TRUE, pt.size = 0.1) +
  NoLegend()
```

Example 34 (r):
```r
VlnPlot(bm, features = "RNA.weight", group.by = 'celltype.l2', sort = TRUE, pt.size = 0.1) +
  NoLegend()
```

Example 35 (r):
```r
VlnPlot(bm, features = "RNA.weight", group.by = 'celltype.l2', sort = TRUE, pt.size = 0.1) +
  NoLegend()
```

Example 36 (unknown):
```unknown
library(Seurat)
library(Signac)
library(EnsDb.Hsapiens.v86)
library(dplyr)
library(ggplot2)
```

Example 37 (r):
```r
library(Seurat)
library(Signac)
library(EnsDb.Hsapiens.v86)
library(dplyr)
library(ggplot2)
```

Example 38 (r):
```r
library(Seurat)
library(Signac)
library(EnsDb.Hsapiens.v86)
library(dplyr)
library(ggplot2)
```

Example 39 (unknown):
```unknown
# the 10x hdf5 file contains both data types. 
inputdata.10x <- Read10X_h5("../data/pbmc_granulocyte_sorted_10k_filtered_feature_bc_matrix.h5")

# extract RNA and ATAC data
rna_counts <- inputdata.10x$`Gene Expression`
atac_counts <- inputdata.10x$Peaks

# Create Seurat object
pbmc <- CreateSeuratObject(counts = rna_counts)
pbmc[["percent.mt"]] <- PercentageFeatureSet(pbmc, pattern = "^MT-")

# Now add in the ATAC-seq data
# we'll only use peaks in standard chromosomes
grange.counts <- StringToGRanges(rownames(atac_counts), sep = c(":", "-"))
grange.use <- seqnames(grange.counts) %in% standardChromosomes(grange.counts)
atac_counts <- atac_counts[as.vector(grange.use), ]
annotations <- GetGRangesFromEnsDb(ensdb = EnsDb.Hsapiens.v86)
seqlevelsStyle(annotations) <- 'UCSC'
genome(annotations) <- "hg38"

frag.file <- "../data/pbmc_granulocyte_sorted_10k_atac_fragments.tsv.gz"
chrom_assay <- CreateChromatinAssay(
   counts = atac_counts,
   sep = c(":", "-"),
   genome = 'hg38',
   fragments = frag.file,
   min.cells = 10,
   annotation = annotations
 )
pbmc[["ATAC"]] <- chrom_assay
```

Example 40 (r):
```r
# the 10x hdf5 file contains both data types. 
inputdata.10x <- Read10X_h5("../data/pbmc_granulocyte_sorted_10k_filtered_feature_bc_matrix.h5")

# extract RNA and ATAC data
rna_counts <- inputdata.10x$`Gene Expression`
atac_counts <- inputdata.10x$Peaks

# Create Seurat object
pbmc <- CreateSeuratObject(counts = rna_counts)
pbmc[["percent.mt"]] <- PercentageFeatureSet(pbmc, pattern = "^MT-")

# Now add in the ATAC-seq data
# we'll only use peaks in standard chromosomes
grange.counts <- StringToGRanges(rownames(atac_counts), sep = c(":", "-"))
grange.use <- seqnames(grange.counts) %in% standardChromosomes(grange.counts)
atac_counts <- atac_counts[as.vector(grange.use), ]
annotations <- GetGRangesFromEnsDb(ensdb = EnsDb.Hsapiens.v86)
seqlevelsStyle(annotations) <- 'UCSC'
genome(annotations) <- "hg38"

frag.file <- "../data/pbmc_granulocyte_sorted_10k_atac_fragments.tsv.gz"
chrom_assay <- CreateChromatinAssay(
   counts = atac_counts,
   sep = c(":", "-"),
   genome = 'hg38',
   fragments = frag.file,
   min.cells = 10,
   annotation = annotations
 )
pbmc[["ATAC"]] <- chrom_assay
```

Example 41 (r):
```r
# the 10x hdf5 file contains both data types. 
inputdata.10x <- Read10X_h5("../data/pbmc_granulocyte_sorted_10k_filtered_feature_bc_matrix.h5")

# extract RNA and ATAC data
rna_counts <- inputdata.10x$`Gene Expression`
atac_counts <- inputdata.10x$Peaks

# Create Seurat object
pbmc <- CreateSeuratObject(counts = rna_counts)
pbmc[["percent.mt"]] <- PercentageFeatureSet(pbmc, pattern = "^MT-")

# Now add in the ATAC-seq data
# we'll only use peaks in standard chromosomes
grange.counts <- StringToGRanges(rownames(atac_counts), sep = c(":", "-"))
grange.use <- seqnames(grange.counts) %in% standardChromosomes(grange.counts)
atac_counts <- atac_counts[as.vector(grange.use), ]
annotations <- GetGRangesFromEnsDb(ensdb = EnsDb.Hsapiens.v86)
seqlevelsStyle(annotations) <- 'UCSC'
genome(annotations) <- "hg38"

frag.file <- "../data/pbmc_granulocyte_sorted_10k_atac_fragments.tsv.gz"
chrom_assay <- CreateChromatinAssay(
   counts = atac_counts,
   sep = c(":", "-"),
   genome = 'hg38',
   fragments = frag.file,
   min.cells = 10,
   annotation = annotations
 )
pbmc[["ATAC"]] <- chrom_assay
```

Example 42 (unknown):
```unknown
VlnPlot(pbmc, features = c("nCount_ATAC", "nCount_RNA","percent.mt"), ncol = 3,
  log = TRUE, pt.size = 0) + NoLegend()
```

Example 43 (r):
```r
VlnPlot(pbmc, features = c("nCount_ATAC", "nCount_RNA","percent.mt"), ncol = 3,
  log = TRUE, pt.size = 0) + NoLegend()
```

Example 44 (r):
```r
VlnPlot(pbmc, features = c("nCount_ATAC", "nCount_RNA","percent.mt"), ncol = 3,
  log = TRUE, pt.size = 0) + NoLegend()
```

Example 45 (unknown):
```unknown
pbmc <- subset(
  x = pbmc,
  subset = nCount_ATAC < 7e4 &
    nCount_ATAC > 5e3 &
    nCount_RNA < 25000 &
    nCount_RNA > 1000 &
    percent.mt < 20
)
```

Example 46 (r):
```r
pbmc <- subset(
  x = pbmc,
  subset = nCount_ATAC < 7e4 &
    nCount_ATAC > 5e3 &
    nCount_RNA < 25000 &
    nCount_RNA > 1000 &
    percent.mt < 20
)
```

Example 47 (r):
```r
pbmc <- subset(
  x = pbmc,
  subset = nCount_ATAC < 7e4 &
    nCount_ATAC > 5e3 &
    nCount_RNA < 25000 &
    nCount_RNA > 1000 &
    percent.mt < 20
)
```

Example 48 (unknown):
```unknown
# RNA analysis
DefaultAssay(pbmc) <- "RNA"
pbmc <- SCTransform(pbmc, verbose = FALSE) %>% RunPCA() %>% RunUMAP(dims = 1:50, reduction.name = 'umap.rna', reduction.key = 'rnaUMAP_')

# ATAC analysis
# We exclude the first dimension as this is typically correlated with sequencing depth
DefaultAssay(pbmc) <- "ATAC"
pbmc <- RunTFIDF(pbmc)
pbmc <- FindTopFeatures(pbmc, min.cutoff = 'q0')
pbmc <- RunSVD(pbmc)
pbmc <- RunUMAP(pbmc, reduction = 'lsi', dims = 2:50, reduction.name = "umap.atac", reduction.key = "atacUMAP_")
```

Example 49 (r):
```r
# RNA analysis
DefaultAssay(pbmc) <- "RNA"
pbmc <- SCTransform(pbmc, verbose = FALSE) %>% RunPCA() %>% RunUMAP(dims = 1:50, reduction.name = 'umap.rna', reduction.key = 'rnaUMAP_')

# ATAC analysis
# We exclude the first dimension as this is typically correlated with sequencing depth
DefaultAssay(pbmc) <- "ATAC"
pbmc <- RunTFIDF(pbmc)
pbmc <- FindTopFeatures(pbmc, min.cutoff = 'q0')
pbmc <- RunSVD(pbmc)
pbmc <- RunUMAP(pbmc, reduction = 'lsi', dims = 2:50, reduction.name = "umap.atac", reduction.key = "atacUMAP_")
```

Example 50 (r):
```r
# RNA analysis
DefaultAssay(pbmc) <- "RNA"
pbmc <- SCTransform(pbmc, verbose = FALSE) %>% RunPCA() %>% RunUMAP(dims = 1:50, reduction.name = 'umap.rna', reduction.key = 'rnaUMAP_')

# ATAC analysis
# We exclude the first dimension as this is typically correlated with sequencing depth
DefaultAssay(pbmc) <- "ATAC"
pbmc <- RunTFIDF(pbmc)
pbmc <- FindTopFeatures(pbmc, min.cutoff = 'q0')
pbmc <- RunSVD(pbmc)
pbmc <- RunUMAP(pbmc, reduction = 'lsi', dims = 2:50, reduction.name = "umap.atac", reduction.key = "atacUMAP_")
```

Example 51 (unknown):
```unknown
pbmc <- FindMultiModalNeighbors(pbmc, reduction.list = list("pca", "lsi"), dims.list = list(1:50, 2:50))
pbmc <- RunUMAP(pbmc, nn.name = "weighted.nn", reduction.name = "wnn.umap", reduction.key = "wnnUMAP_")
pbmc <- FindClusters(pbmc, graph.name = "wsnn", algorithm = 3, verbose = FALSE)
```

Example 52 (r):
```r
pbmc <- FindMultiModalNeighbors(pbmc, reduction.list = list("pca", "lsi"), dims.list = list(1:50, 2:50))
pbmc <- RunUMAP(pbmc, nn.name = "weighted.nn", reduction.name = "wnn.umap", reduction.key = "wnnUMAP_")
pbmc <- FindClusters(pbmc, graph.name = "wsnn", algorithm = 3, verbose = FALSE)
```

Example 53 (r):
```r
pbmc <- FindMultiModalNeighbors(pbmc, reduction.list = list("pca", "lsi"), dims.list = list(1:50, 2:50))
pbmc <- RunUMAP(pbmc, nn.name = "weighted.nn", reduction.name = "wnn.umap", reduction.key = "wnnUMAP_")
pbmc <- FindClusters(pbmc, graph.name = "wsnn", algorithm = 3, verbose = FALSE)
```

Example 54 (unknown):
```unknown
# perform sub-clustering on cluster 6 to find additional structure
pbmc <- FindSubCluster(pbmc, cluster = 6, graph.name = "wsnn", algorithm = 3)
Idents(pbmc) <- "sub.cluster"
```

Example 55 (r):
```r
# perform sub-clustering on cluster 6 to find additional structure
pbmc <- FindSubCluster(pbmc, cluster = 6, graph.name = "wsnn", algorithm = 3)
Idents(pbmc) <- "sub.cluster"
```

Example 56 (r):
```r
# perform sub-clustering on cluster 6 to find additional structure
pbmc <- FindSubCluster(pbmc, cluster = 6, graph.name = "wsnn", algorithm = 3)
Idents(pbmc) <- "sub.cluster"
```

Example 57 (unknown):
```unknown
# add annotations
pbmc <- RenameIdents(pbmc, '19' = 'pDC','20' = 'HSPC','15' = 'cDC')
pbmc <- RenameIdents(pbmc, '0' = 'CD14 Mono', '9' ='CD14 Mono', '5' = 'CD16 Mono')
pbmc <- RenameIdents(pbmc, '10' = 'Naive B', '11' = 'Intermediate B', '17' = 'Memory B', '21' = 'Plasma')
pbmc <- RenameIdents(pbmc, '7' = 'NK')
pbmc <- RenameIdents(pbmc, '4' = 'CD4 TCM', '13'= "CD4 TEM", '3' = "CD4 TCM", '16' ="Treg", '1' ="CD4 Naive", '14' = "CD4 Naive")
pbmc <- RenameIdents(pbmc, '2' = 'CD8 Naive', '8'= "CD8 Naive", '12' = 'CD8 TEM_1', '6_0' = 'CD8 TEM_2', '6_1' ='CD8 TEM_2', '6_4' ='CD8 TEM_2')
pbmc <- RenameIdents(pbmc, '18' = 'MAIT')
pbmc <- RenameIdents(pbmc, '6_2' ='gdT', '6_3' = 'gdT')
pbmc$celltype <- Idents(pbmc)
```

Example 58 (r):
```r
# add annotations
pbmc <- RenameIdents(pbmc, '19' = 'pDC','20' = 'HSPC','15' = 'cDC')
pbmc <- RenameIdents(pbmc, '0' = 'CD14 Mono', '9' ='CD14 Mono', '5' = 'CD16 Mono')
pbmc <- RenameIdents(pbmc, '10' = 'Naive B', '11' = 'Intermediate B', '17' = 'Memory B', '21' = 'Plasma')
pbmc <- RenameIdents(pbmc, '7' = 'NK')
pbmc <- RenameIdents(pbmc, '4' = 'CD4 TCM', '13'= "CD4 TEM", '3' = "CD4 TCM", '16' ="Treg", '1' ="CD4 Naive", '14' = "CD4 Naive")
pbmc <- RenameIdents(pbmc, '2' = 'CD8 Naive', '8'= "CD8 Naive", '12' = 'CD8 TEM_1', '6_0' = 'CD8 TEM_2', '6_1' ='CD8 TEM_2', '6_4' ='CD8 TEM_2')
pbmc <- RenameIdents(pbmc, '18' = 'MAIT')
pbmc <- RenameIdents(pbmc, '6_2' ='gdT', '6_3' = 'gdT')
pbmc$celltype <- Idents(pbmc)
```

Example 59 (r):
```r
# add annotations
pbmc <- RenameIdents(pbmc, '19' = 'pDC','20' = 'HSPC','15' = 'cDC')
pbmc <- RenameIdents(pbmc, '0' = 'CD14 Mono', '9' ='CD14 Mono', '5' = 'CD16 Mono')
pbmc <- RenameIdents(pbmc, '10' = 'Naive B', '11' = 'Intermediate B', '17' = 'Memory B', '21' = 'Plasma')
pbmc <- RenameIdents(pbmc, '7' = 'NK')
pbmc <- RenameIdents(pbmc, '4' = 'CD4 TCM', '13'= "CD4 TEM", '3' = "CD4 TCM", '16' ="Treg", '1' ="CD4 Naive", '14' = "CD4 Naive")
pbmc <- RenameIdents(pbmc, '2' = 'CD8 Naive', '8'= "CD8 Naive", '12' = 'CD8 TEM_1', '6_0' = 'CD8 TEM_2', '6_1' ='CD8 TEM_2', '6_4' ='CD8 TEM_2')
pbmc <- RenameIdents(pbmc, '18' = 'MAIT')
pbmc <- RenameIdents(pbmc, '6_2' ='gdT', '6_3' = 'gdT')
pbmc$celltype <- Idents(pbmc)
```

Example 60 (unknown):
```unknown
p1 <- DimPlot(pbmc, reduction = "umap.rna", group.by = "celltype", label = TRUE, label.size = 2.5, repel = TRUE) + ggtitle("RNA")
p2 <- DimPlot(pbmc, reduction = "umap.atac", group.by = "celltype", label = TRUE, label.size = 2.5, repel = TRUE) + ggtitle("ATAC")
p3 <- DimPlot(pbmc, reduction = "wnn.umap", group.by = "celltype", label = TRUE, label.size = 2.5, repel = TRUE) + ggtitle("WNN")
p1 + p2 + p3 & NoLegend() & theme(plot.title = element_text(hjust = 0.5))
```

Example 61 (r):
```r
p1 <- DimPlot(pbmc, reduction = "umap.rna", group.by = "celltype", label = TRUE, label.size = 2.5, repel = TRUE) + ggtitle("RNA")
p2 <- DimPlot(pbmc, reduction = "umap.atac", group.by = "celltype", label = TRUE, label.size = 2.5, repel = TRUE) + ggtitle("ATAC")
p3 <- DimPlot(pbmc, reduction = "wnn.umap", group.by = "celltype", label = TRUE, label.size = 2.5, repel = TRUE) + ggtitle("WNN")
p1 + p2 + p3 & NoLegend() & theme(plot.title = element_text(hjust = 0.5))
```

Example 62 (r):
```r
p1 <- DimPlot(pbmc, reduction = "umap.rna", group.by = "celltype", label = TRUE, label.size = 2.5, repel = TRUE) + ggtitle("RNA")
p2 <- DimPlot(pbmc, reduction = "umap.atac", group.by = "celltype", label = TRUE, label.size = 2.5, repel = TRUE) + ggtitle("ATAC")
p3 <- DimPlot(pbmc, reduction = "wnn.umap", group.by = "celltype", label = TRUE, label.size = 2.5, repel = TRUE) + ggtitle("WNN")
p1 + p2 + p3 & NoLegend() & theme(plot.title = element_text(hjust = 0.5))
```

Example 63 (unknown):
```unknown
## to make the visualization easier, subset T cell clusters
celltype.names <- levels(pbmc)
tcell.names <- grep("CD4|CD8|Treg", celltype.names,value = TRUE)
tcells <- subset(pbmc, idents = tcell.names)
CoveragePlot(tcells, region = 'CD8A', features = 'CD8A', assay = 'ATAC', expression.assay = 'SCT', peaks = FALSE)
```

Example 64 (r):
```r
## to make the visualization easier, subset T cell clusters
celltype.names <- levels(pbmc)
tcell.names <- grep("CD4|CD8|Treg", celltype.names,value = TRUE)
tcells <- subset(pbmc, idents = tcell.names)
CoveragePlot(tcells, region = 'CD8A', features = 'CD8A', assay = 'ATAC', expression.assay = 'SCT', peaks = FALSE)
```

Example 65 (r):
```r
## to make the visualization easier, subset T cell clusters
celltype.names <- levels(pbmc)
tcell.names <- grep("CD4|CD8|Treg", celltype.names,value = TRUE)
tcells <- subset(pbmc, idents = tcell.names)
CoveragePlot(tcells, region = 'CD8A', features = 'CD8A', assay = 'ATAC', expression.assay = 'SCT', peaks = FALSE)
```

Example 66 (unknown):
```unknown
remotes::install_github("immunogenomics/presto")
BiocManager::install(c("chromVAR", "TFBSTools", "JASPAR2020", "motifmatchr", "BSgenome.Hsapiens.UCSC.hg38"))
```

Example 67 (r):
```r
remotes::install_github("immunogenomics/presto")
BiocManager::install(c("chromVAR", "TFBSTools", "JASPAR2020", "motifmatchr", "BSgenome.Hsapiens.UCSC.hg38"))
```

Example 68 (r):
```r
remotes::install_github("immunogenomics/presto")
BiocManager::install(c("chromVAR", "TFBSTools", "JASPAR2020", "motifmatchr", "BSgenome.Hsapiens.UCSC.hg38"))
```

Example 69 (unknown):
```unknown
library(chromVAR)
library(JASPAR2020)
library(TFBSTools)
library(motifmatchr)
library(BSgenome.Hsapiens.UCSC.hg38)

# Scan the DNA sequence of each peak for the presence of each motif, and create a Motif object
DefaultAssay(pbmc) <- "ATAC"
pwm_set <- getMatrixSet(x = JASPAR2020, opts = list(species = 9606, all_versions = FALSE))
motif.matrix <- CreateMotifMatrix(features = granges(pbmc), pwm = pwm_set, genome = 'hg38', use.counts = FALSE)
motif.object <- CreateMotifObject(data = motif.matrix, pwm = pwm_set)
pbmc <- SetAssayData(pbmc, assay = 'ATAC', slot = 'motifs', new.data = motif.object)

# Note that this step can take 30-60 minutes 
pbmc <- RunChromVAR(
  object = pbmc,
  genome = BSgenome.Hsapiens.UCSC.hg38
)
```

Example 70 (r):
```r
library(chromVAR)
library(JASPAR2020)
library(TFBSTools)
library(motifmatchr)
library(BSgenome.Hsapiens.UCSC.hg38)

# Scan the DNA sequence of each peak for the presence of each motif, and create a Motif object
DefaultAssay(pbmc) <- "ATAC"
pwm_set <- getMatrixSet(x = JASPAR2020, opts = list(species = 9606, all_versions = FALSE))
motif.matrix <- CreateMotifMatrix(features = granges(pbmc), pwm = pwm_set, genome = 'hg38', use.counts = FALSE)
motif.object <- CreateMotifObject(data = motif.matrix, pwm = pwm_set)
pbmc <- SetAssayData(pbmc, assay = 'ATAC', slot = 'motifs', new.data = motif.object)

# Note that this step can take 30-60 minutes 
pbmc <- RunChromVAR(
  object = pbmc,
  genome = BSgenome.Hsapiens.UCSC.hg38
)
```

Example 71 (r):
```r
library(chromVAR)
library(JASPAR2020)
library(TFBSTools)
library(motifmatchr)
library(BSgenome.Hsapiens.UCSC.hg38)

# Scan the DNA sequence of each peak for the presence of each motif, and create a Motif object
DefaultAssay(pbmc) <- "ATAC"
pwm_set <- getMatrixSet(x = JASPAR2020, opts = list(species = 9606, all_versions = FALSE))
motif.matrix <- CreateMotifMatrix(features = granges(pbmc), pwm = pwm_set, genome = 'hg38', use.counts = FALSE)
motif.object <- CreateMotifObject(data = motif.matrix, pwm = pwm_set)
pbmc <- SetAssayData(pbmc, assay = 'ATAC', slot = 'motifs', new.data = motif.object)

# Note that this step can take 30-60 minutes 
pbmc <- RunChromVAR(
  object = pbmc,
  genome = BSgenome.Hsapiens.UCSC.hg38
)
```

Example 72 (unknown):
```unknown
#returns MA0466.2
motif.name <- ConvertMotifID(pbmc, name = 'CEBPB')
gene_plot <- FeaturePlot(pbmc, features = "sct_CEBPB", reduction = 'wnn.umap')
motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap')
gene_plot | motif_plot
```

Example 73 (r):
```r
#returns MA0466.2
motif.name <- ConvertMotifID(pbmc, name = 'CEBPB')
gene_plot <- FeaturePlot(pbmc, features = "sct_CEBPB", reduction = 'wnn.umap')
motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap')
gene_plot | motif_plot
```

Example 74 (r):
```r
#returns MA0466.2
motif.name <- ConvertMotifID(pbmc, name = 'CEBPB')
gene_plot <- FeaturePlot(pbmc, features = "sct_CEBPB", reduction = 'wnn.umap')
motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap')
gene_plot | motif_plot
```

Example 75 (unknown):
```unknown
markers_rna <- presto:::wilcoxauc.Seurat(X = pbmc, group_by = 'celltype', assay = 'data', seurat_assay = 'SCT')
markers_motifs <- presto:::wilcoxauc.Seurat(X = pbmc, group_by = 'celltype', assay = 'data', seurat_assay = 'chromvar')
motif.names <- markers_motifs$feature
colnames(markers_rna) <- paste0("RNA.", colnames(markers_rna))
colnames(markers_motifs) <- paste0("motif.", colnames(markers_motifs))
markers_rna$gene <- markers_rna$RNA.feature
markers_motifs$gene <- ConvertMotifID(pbmc, id = motif.names)
```

Example 76 (r):
```r
markers_rna <- presto:::wilcoxauc.Seurat(X = pbmc, group_by = 'celltype', assay = 'data', seurat_assay = 'SCT')
markers_motifs <- presto:::wilcoxauc.Seurat(X = pbmc, group_by = 'celltype', assay = 'data', seurat_assay = 'chromvar')
motif.names <- markers_motifs$feature
colnames(markers_rna) <- paste0("RNA.", colnames(markers_rna))
colnames(markers_motifs) <- paste0("motif.", colnames(markers_motifs))
markers_rna$gene <- markers_rna$RNA.feature
markers_motifs$gene <- ConvertMotifID(pbmc, id = motif.names)
```

Example 77 (r):
```r
markers_rna <- presto:::wilcoxauc.Seurat(X = pbmc, group_by = 'celltype', assay = 'data', seurat_assay = 'SCT')
markers_motifs <- presto:::wilcoxauc.Seurat(X = pbmc, group_by = 'celltype', assay = 'data', seurat_assay = 'chromvar')
motif.names <- markers_motifs$feature
colnames(markers_rna) <- paste0("RNA.", colnames(markers_rna))
colnames(markers_motifs) <- paste0("motif.", colnames(markers_motifs))
markers_rna$gene <- markers_rna$RNA.feature
markers_motifs$gene <- ConvertMotifID(pbmc, id = motif.names)
```

Example 78 (javascript):
```javascript
# a simple function to implement the procedure above
topTFs <- function(celltype, padj.cutoff = 1e-2) {
  ctmarkers_rna <- dplyr::filter(
    markers_rna, RNA.group == celltype, RNA.padj < padj.cutoff, RNA.logFC > 0) %>% 
    arrange(-RNA.auc)
  ctmarkers_motif <- dplyr::filter(
    markers_motifs, motif.group == celltype, motif.padj < padj.cutoff, motif.logFC > 0) %>% 
    arrange(-motif.auc)
  top_tfs <- inner_join(
    x = ctmarkers_rna[, c(2, 11, 6, 7)], 
    y = ctmarkers_motif[, c(2, 1, 11, 6, 7)], by = "gene"
  )
  top_tfs$avg_auc <- (top_tfs$RNA.auc + top_tfs$motif.auc) / 2
  top_tfs <- arrange(top_tfs, -avg_auc)
  return(top_tfs)
}
```

Example 79 (r):
```r
# a simple function to implement the procedure above
topTFs <- function(celltype, padj.cutoff = 1e-2) {
  ctmarkers_rna <- dplyr::filter(
    markers_rna, RNA.group == celltype, RNA.padj < padj.cutoff, RNA.logFC > 0) %>% 
    arrange(-RNA.auc)
  ctmarkers_motif <- dplyr::filter(
    markers_motifs, motif.group == celltype, motif.padj < padj.cutoff, motif.logFC > 0) %>% 
    arrange(-motif.auc)
  top_tfs <- inner_join(
    x = ctmarkers_rna[, c(2, 11, 6, 7)], 
    y = ctmarkers_motif[, c(2, 1, 11, 6, 7)], by = "gene"
  )
  top_tfs$avg_auc <- (top_tfs$RNA.auc + top_tfs$motif.auc) / 2
  top_tfs <- arrange(top_tfs, -avg_auc)
  return(top_tfs)
}
```

Example 80 (r):
```r
# a simple function to implement the procedure above
topTFs <- function(celltype, padj.cutoff = 1e-2) {
  ctmarkers_rna <- dplyr::filter(
    markers_rna, RNA.group == celltype, RNA.padj < padj.cutoff, RNA.logFC > 0) %>% 
    arrange(-RNA.auc)
  ctmarkers_motif <- dplyr::filter(
    markers_motifs, motif.group == celltype, motif.padj < padj.cutoff, motif.logFC > 0) %>% 
    arrange(-motif.auc)
  top_tfs <- inner_join(
    x = ctmarkers_rna[, c(2, 11, 6, 7)], 
    y = ctmarkers_motif[, c(2, 1, 11, 6, 7)], by = "gene"
  )
  top_tfs$avg_auc <- (top_tfs$RNA.auc + top_tfs$motif.auc) / 2
  top_tfs <- arrange(top_tfs, -avg_auc)
  return(top_tfs)
}
```

Example 81 (unknown):
```unknown
# identify top markers in NK and visualize
head(topTFs("NK"), 3)
```

Example 82 (r):
```r
# identify top markers in NK and visualize
head(topTFs("NK"), 3)
```

Example 83 (r):
```r
# identify top markers in NK and visualize
head(topTFs("NK"), 3)
```

Example 84 (unknown):
```unknown
##   RNA.group  gene   RNA.auc      RNA.pval motif.group motif.feature motif.auc
## 1        NK TBX21 0.7270859  0.000000e+00          NK      MA0690.1 0.9139614
## 2        NK EOMES 0.5886774  2.411013e-98          NK      MA0800.1 0.9214773
## 3        NK RUNX3 0.7705661 5.977716e-120          NK      MA0684.2 0.6769022
##      motif.pval   avg_auc
## 1 1.097940e-202 0.8205237
## 2 4.903866e-210 0.7550774
## 3  1.560061e-38 0.7237341
```

Example 85 (unknown):
```unknown
##   RNA.group  gene   RNA.auc      RNA.pval motif.group motif.feature motif.auc
## 1        NK TBX21 0.7270859  0.000000e+00          NK      MA0690.1 0.9139614
## 2        NK EOMES 0.5886774  2.411013e-98          NK      MA0800.1 0.9214773
## 3        NK RUNX3 0.7705661 5.977716e-120          NK      MA0684.2 0.6769022
##      motif.pval   avg_auc
## 1 1.097940e-202 0.8205237
## 2 4.903866e-210 0.7550774
## 3  1.560061e-38 0.7237341
```

Example 86 (unknown):
```unknown
motif.name <- ConvertMotifID(pbmc, name = 'TBX21')
gene_plot <- FeaturePlot(pbmc, features = "sct_TBX21", reduction = 'wnn.umap')
motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap')
gene_plot | motif_plot
```

Example 87 (r):
```r
motif.name <- ConvertMotifID(pbmc, name = 'TBX21')
gene_plot <- FeaturePlot(pbmc, features = "sct_TBX21", reduction = 'wnn.umap')
motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap')
gene_plot | motif_plot
```

Example 88 (r):
```r
motif.name <- ConvertMotifID(pbmc, name = 'TBX21')
gene_plot <- FeaturePlot(pbmc, features = "sct_TBX21", reduction = 'wnn.umap')
motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap')
gene_plot | motif_plot
```

Example 89 (unknown):
```unknown
# identify top markers in pDC and visualize
head(topTFs("pDC"), 3)
```

Example 90 (r):
```r
# identify top markers in pDC and visualize
head(topTFs("pDC"), 3)
```

Example 91 (r):
```r
# identify top markers in pDC and visualize
head(topTFs("pDC"), 3)
```

Example 92 (unknown):
```unknown
##   RNA.group gene   RNA.auc      RNA.pval motif.group motif.feature motif.auc
## 1       pDC TCF4 0.9998815 1.120711e-162         pDC      MA0830.2 0.9965481
## 2       pDC IRF8 0.9904457 1.308164e-123         pDC      MA0652.1 0.8833112
## 3       pDC SPIB 0.9115207  0.000000e+00         pDC      MA0081.2 0.9068540
##     motif.pval   avg_auc
## 1 1.785897e-69 0.9982148
## 2 3.982413e-42 0.9368785
## 3 3.083509e-47 0.9091874
```

Example 93 (unknown):
```unknown
##   RNA.group gene   RNA.auc      RNA.pval motif.group motif.feature motif.auc
## 1       pDC TCF4 0.9998815 1.120711e-162         pDC      MA0830.2 0.9965481
## 2       pDC IRF8 0.9904457 1.308164e-123         pDC      MA0652.1 0.8833112
## 3       pDC SPIB 0.9115207  0.000000e+00         pDC      MA0081.2 0.9068540
##     motif.pval   avg_auc
## 1 1.785897e-69 0.9982148
## 2 3.982413e-42 0.9368785
## 3 3.083509e-47 0.9091874
```

Example 94 (unknown):
```unknown
motif.name <- ConvertMotifID(pbmc, name = 'TCF4')
gene_plot <- FeaturePlot(pbmc, features = "sct_TCF4", reduction = 'wnn.umap')
motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap')
gene_plot | motif_plot
```

Example 95 (r):
```r
motif.name <- ConvertMotifID(pbmc, name = 'TCF4')
gene_plot <- FeaturePlot(pbmc, features = "sct_TCF4", reduction = 'wnn.umap')
motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap')
gene_plot | motif_plot
```

Example 96 (r):
```r
motif.name <- ConvertMotifID(pbmc, name = 'TCF4')
gene_plot <- FeaturePlot(pbmc, features = "sct_TCF4", reduction = 'wnn.umap')
motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap')
gene_plot | motif_plot
```

Example 97 (unknown):
```unknown
# identify top markers in HSPC and visualize
head(topTFs("CD16 Mono"),3)
```

Example 98 (r):
```r
# identify top markers in HSPC and visualize
head(topTFs("CD16 Mono"),3)
```

Example 99 (r):
```r
# identify top markers in HSPC and visualize
head(topTFs("CD16 Mono"),3)
```

Example 100 (unknown):
```unknown
##   RNA.group  gene   RNA.auc      RNA.pval motif.group motif.feature motif.auc
## 1 CD16 Mono  SPI1 0.8793172 1.666810e-296   CD16 Mono      MA0080.5 0.8880908
## 2 CD16 Mono CEBPB 0.8685933 1.625472e-294   CD16 Mono      MA0466.2 0.7840422
## 3 CD16 Mono MEF2C 0.7129910  2.727252e-79   CD16 Mono      MA0497.1 0.8059373
##      motif.pval   avg_auc
## 1 4.762491e-194 0.8837040
## 2 7.049764e-105 0.8263177
## 3 2.345716e-121 0.7594641
```

Example 101 (unknown):
```unknown
##   RNA.group  gene   RNA.auc      RNA.pval motif.group motif.feature motif.auc
## 1 CD16 Mono  SPI1 0.8793172 1.666810e-296   CD16 Mono      MA0080.5 0.8880908
## 2 CD16 Mono CEBPB 0.8685933 1.625472e-294   CD16 Mono      MA0466.2 0.7840422
## 3 CD16 Mono MEF2C 0.7129910  2.727252e-79   CD16 Mono      MA0497.1 0.8059373
##      motif.pval   avg_auc
## 1 4.762491e-194 0.8837040
## 2 7.049764e-105 0.8263177
## 3 2.345716e-121 0.7594641
```

Example 102 (unknown):
```unknown
motif.name <- ConvertMotifID(pbmc, name = 'SPI1')
gene_plot <- FeaturePlot(pbmc, features = "sct_SPI1", reduction = 'wnn.umap')
motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap')
gene_plot | motif_plot
```

Example 103 (r):
```r
motif.name <- ConvertMotifID(pbmc, name = 'SPI1')
gene_plot <- FeaturePlot(pbmc, features = "sct_SPI1", reduction = 'wnn.umap')
motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap')
gene_plot | motif_plot
```

Example 104 (r):
```r
motif.name <- ConvertMotifID(pbmc, name = 'SPI1')
gene_plot <- FeaturePlot(pbmc, features = "sct_SPI1", reduction = 'wnn.umap')
motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap')
gene_plot | motif_plot
```

Example 105 (unknown):
```unknown
# identify top markers in other cell types
head(topTFs("Naive B"), 3)
```

Example 106 (r):
```r
# identify top markers in other cell types
head(topTFs("Naive B"), 3)
```

Example 107 (r):
```r
# identify top markers in other cell types
head(topTFs("Naive B"), 3)
```

Example 108 (unknown):
```unknown
##   RNA.group   gene   RNA.auc      RNA.pval motif.group motif.feature motif.auc
## 1   Naive B  MEF2C 0.8802747 1.890065e-182     Naive B      MA0497.1 0.6789079
## 2   Naive B   PAX5 0.9436648  0.000000e+00     Naive B      MA0014.3 0.5827061
## 3   Naive B POU2F2 0.6029377  2.892216e-13     Naive B      MA0507.1 0.8912268
##      motif.pval   avg_auc
## 1  9.815118e-32 0.7795913
## 2  5.995185e-08 0.7631854
## 3 6.471677e-145 0.7470822
```

Example 109 (unknown):
```unknown
##   RNA.group   gene   RNA.auc      RNA.pval motif.group motif.feature motif.auc
## 1   Naive B  MEF2C 0.8802747 1.890065e-182     Naive B      MA0497.1 0.6789079
## 2   Naive B   PAX5 0.9436648  0.000000e+00     Naive B      MA0014.3 0.5827061
## 3   Naive B POU2F2 0.6029377  2.892216e-13     Naive B      MA0507.1 0.8912268
##      motif.pval   avg_auc
## 1  9.815118e-32 0.7795913
## 2  5.995185e-08 0.7631854
## 3 6.471677e-145 0.7470822
```

Example 110 (unknown):
```unknown
head(topTFs("HSPC"), 3)
```

Example 111 (r):
```r
head(topTFs("HSPC"), 3)
```

Example 112 (r):
```r
head(topTFs("HSPC"), 3)
```

Example 113 (unknown):
```unknown
##   RNA.group  gene   RNA.auc     RNA.pval motif.group motif.feature motif.auc
## 1      HSPC  SOX4 0.9869406 5.524832e-71        HSPC      MA0867.2 0.6830497
## 2      HSPC GATA2 0.7884615 0.000000e+00        HSPC      MA0036.3 0.8275008
## 3      HSPC MEIS1 0.8638496 0.000000e+00        HSPC      MA0498.2 0.6924225
##     motif.pval   avg_auc
## 1 1.241915e-03 0.8349951
## 2 7.591798e-09 0.8079812
## 3 6.877492e-04 0.7781361
```

Example 114 (unknown):
```unknown
##   RNA.group  gene   RNA.auc     RNA.pval motif.group motif.feature motif.auc
## 1      HSPC  SOX4 0.9869406 5.524832e-71        HSPC      MA0867.2 0.6830497
## 2      HSPC GATA2 0.7884615 0.000000e+00        HSPC      MA0036.3 0.8275008
## 3      HSPC MEIS1 0.8638496 0.000000e+00        HSPC      MA0498.2 0.6924225
##     motif.pval   avg_auc
## 1 1.241915e-03 0.8349951
## 2 7.591798e-09 0.8079812
## 3 6.877492e-04 0.7781361
```

Example 115 (unknown):
```unknown
head(topTFs("Plasma"), 3)
```

Example 116 (r):
```r
head(topTFs("Plasma"), 3)
```

Example 117 (r):
```r
head(topTFs("Plasma"), 3)
```

Example 118 (unknown):
```unknown
##   RNA.group  gene   RNA.auc     RNA.pval motif.group motif.feature motif.auc
## 1    Plasma  IRF4 0.8189687 5.261955e-35      Plasma      MA1419.1 0.9776046
## 2    Plasma MEF2C 0.9111213 2.977155e-12      Plasma      MA0497.1 0.7596637
## 3    Plasma  TCF4 0.8049409 6.810635e-12      Plasma      MA0830.2 0.7840848
##     motif.pval   avg_auc
## 1 2.334627e-12 0.8982867
## 2 1.374353e-04 0.8353925
## 3 3.028306e-05 0.7945129
```

Example 119 (unknown):
```unknown
##   RNA.group  gene   RNA.auc     RNA.pval motif.group motif.feature motif.auc
## 1    Plasma  IRF4 0.8189687 5.261955e-35      Plasma      MA1419.1 0.9776046
## 2    Plasma MEF2C 0.9111213 2.977155e-12      Plasma      MA0497.1 0.7596637
## 3    Plasma  TCF4 0.8049409 6.810635e-12      Plasma      MA0830.2 0.7840848
##     motif.pval   avg_auc
## 1 2.334627e-12 0.8982867
## 2 1.374353e-04 0.8353925
## 3 3.028306e-05 0.7945129
```

Example 120 (unknown):
```unknown
sessionInfo()
```

Example 121 (r):
```r
sessionInfo()
```

Example 122 (r):
```r
sessionInfo()
```

Example 123 (unknown):
```unknown
## R version 4.2.0 (2022-04-22)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.5 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/liblapack.so.3
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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       
## 
## attached base packages:
## [1] stats4    stats     graphics  grDevices utils     datasets  methods  
## [8] base     
## 
## other attached packages:
##  [1] BSgenome.Hsapiens.UCSC.hg38_1.4.5 BSgenome_1.66.3                  
##  [3] rtracklayer_1.58.0                Biostrings_2.66.0                
##  [5] XVector_0.38.0                    motifmatchr_1.20.0               
##  [7] TFBSTools_1.36.0                  JASPAR2020_0.99.10               
##  [9] chromVAR_1.20.2                   EnsDb.Hsapiens.v86_2.99.0        
## [11] ensembldb_2.22.0                  AnnotationFilter_1.22.0          
## [13] GenomicFeatures_1.50.4            AnnotationDbi_1.60.0             
## [15] Biobase_2.58.0                    GenomicRanges_1.50.2             
## [17] GenomeInfoDb_1.35.16              IRanges_2.32.0                   
## [19] S4Vectors_0.36.2                  BiocGenerics_0.44.0              
## [21] Signac_1.9.0                      ggplot2_3.4.1                    
## [23] dplyr_1.1.1                       cowplot_1.1.1                    
## [25] thp1.eccite.SeuratData_3.1.5      stxBrain.SeuratData_0.1.1        
## [27] ssHippo.SeuratData_3.1.4          pbmcsca.SeuratData_3.0.0         
## [29] pbmcMultiome.SeuratData_0.1.2     pbmc3k.SeuratData_3.1.4          
## [31] panc8.SeuratData_3.0.2            ifnb.SeuratData_3.1.0            
## [33] hcabm40k.SeuratData_3.0.0         bmcite.SeuratData_0.3.0          
## [35] SeuratData_0.2.2                  SeuratObject_4.1.3               
## [37] Seurat_4.2.1.9001                
## 
## loaded via a namespace (and not attached):
##   [1] rappdirs_0.3.3              scattermore_0.8            
##   [3] R.methodsS3_1.8.2           ragg_1.2.5                 
##   [5] nabor_0.5.0                 tidyr_1.3.0                
##   [7] bit64_4.0.5                 knitr_1.42                 
##   [9] R.utils_2.12.2              irlba_2.3.5.1              
##  [11] DelayedArray_0.24.0         data.table_1.14.8          
##  [13] rpart_4.1.16                KEGGREST_1.38.0            
##  [15] RCurl_1.98-1.12             generics_0.1.3             
##  [17] RSQLite_2.3.0               RANN_2.6.1                 
##  [19] future_1.32.0               tzdb_0.3.0                 
##  [21] bit_4.0.5                   spatstat.data_3.0-1        
##  [23] xml2_1.3.3                  httpuv_1.6.9               
##  [25] SummarizedExperiment_1.28.0 DirichletMultinomial_1.40.0
##  [27] xfun_0.38                   hms_1.1.2                  
##  [29] jquerylib_0.1.4             evaluate_0.20              
##  [31] promises_1.2.0.1            fansi_1.0.4                
##  [33] restfulr_0.0.15             progress_1.2.2             
##  [35] caTools_1.18.2              dbplyr_2.3.1               
##  [37] igraph_1.4.1                DBI_1.1.3                  
##  [39] htmlwidgets_1.6.2           spatstat.geom_3.1-0        
##  [41] purrr_1.0.1                 ellipsis_0.3.2             
##  [43] backports_1.4.1             annotate_1.76.0            
##  [45] biomaRt_2.54.0              deldir_1.0-6               
##  [47] MatrixGenerics_1.10.0       vctrs_0.6.1                
##  [49] ROCR_1.0-11                 abind_1.4-5                
##  [51] cachem_1.0.7                withr_2.5.0                
##  [53] progressr_0.13.0            presto_1.0.0               
##  [55] checkmate_2.1.0             sctransform_0.3.5          
##  [57] GenomicAlignments_1.34.0    prettyunits_1.1.1          
##  [59] goftest_1.2-3               cluster_2.1.3              
##  [61] seqLogo_1.64.0              lazyeval_0.2.2             
##  [63] crayon_1.5.2                hdf5r_1.3.8                
##  [65] spatstat.explore_3.1-0      pkgconfig_2.0.3            
##  [67] labeling_0.4.2              nlme_3.1-157               
##  [69] ProtGenerics_1.30.0         nnet_7.3-17                
##  [71] rlang_1.1.0                 globals_0.16.2             
##  [73] lifecycle_1.0.3             miniUI_0.1.1.1             
##  [75] filelock_1.0.2              BiocFileCache_2.6.1        
##  [77] dichromat_2.0-0.1           rprojroot_2.0.3            
##  [79] polyclip_1.10-4             matrixStats_0.63.0         
##  [81] lmtest_0.9-40               Matrix_1.5-3               
##  [83] zoo_1.8-11                  base64enc_0.1-3            
##  [85] ggridges_0.5.4              png_0.1-8                  
##  [87] viridisLite_0.4.1           rjson_0.2.21               
##  [89] bitops_1.0-7                R.oo_1.25.0                
##  [91] KernSmooth_2.23-20          blob_1.2.3                 
##  [93] stringr_1.5.0               parallelly_1.35.0          
##  [95] spatstat.random_3.1-4       readr_2.1.4                
##  [97] jpeg_0.1-10                 CNEr_1.34.0                
##  [99] scales_1.2.1                memoise_2.0.1              
## [101] magrittr_2.0.3              plyr_1.8.8                 
## [103] ica_1.0-3                   zlibbioc_1.44.0            
## [105] compiler_4.2.0              BiocIO_1.8.0               
## [107] RColorBrewer_1.1-3          fitdistrplus_1.1-8         
## [109] Rsamtools_2.14.0            cli_3.6.1                  
## [111] listenv_0.9.0               patchwork_1.1.2            
## [113] pbapply_1.7-0               htmlTable_2.4.1            
## [115] Formula_1.2-5               MASS_7.3-56                
## [117] tidyselect_1.2.0            stringi_1.7.12             
## [119] textshaping_0.3.6           highr_0.10                 
## [121] yaml_2.3.7                  latticeExtra_0.6-30        
## [123] ggrepel_0.9.3               grid_4.2.0                 
## [125] sass_0.4.5                  VariantAnnotation_1.44.1   
## [127] fastmatch_1.1-3             tools_4.2.0                
## [129] future.apply_1.10.0         parallel_4.2.0             
## [131] rstudioapi_0.14             TFMPvalue_0.0.9            
## [133] foreign_0.8-82              gridExtra_2.3              
## [135] farver_2.1.1                Rtsne_0.16                 
## [137] digest_0.6.31               pracma_2.4.2               
## [139] shiny_1.7.4                 Rcpp_1.0.10                
## [141] later_1.3.0                 RcppAnnoy_0.0.20           
## [143] httr_1.4.5                  biovizBase_1.46.0          
## [145] colorspace_2.1-0            XML_3.99-0.13              
## [147] fs_1.6.1                    tensor_1.5                 
## [149] reticulate_1.28             splines_4.2.0              
## [151] uwot_0.1.14                 RcppRoll_0.3.0             
## [153] spatstat.utils_3.0-2        pkgdown_2.0.7              
## [155] sp_1.6-0                    plotly_4.10.1              
## [157] systemfonts_1.0.4           xtable_1.8-4               
## [159] poweRlaw_0.70.6             jsonlite_1.8.4             
## [161] R6_2.5.1                    Hmisc_4.8-0                
## [163] pillar_1.9.0                htmltools_0.5.5            
## [165] mime_0.12                   DT_0.27                    
## [167] glue_1.6.2                  fastmap_1.1.1              
## [169] BiocParallel_1.32.5         codetools_0.2-18           
## [171] utf8_1.2.3                  lattice_0.20-45            
## [173] bslib_0.4.2                 spatstat.sparse_3.0-1      
## [175] tibble_3.2.1                curl_5.0.0                 
## [177] leiden_0.4.3                gtools_3.9.4               
## [179] GO.db_3.16.0                interp_1.1-3               
## [181] survival_3.3-1              rmarkdown_2.21             
## [183] desc_1.4.2                  munsell_0.5.0              
## [185] GenomeInfoDbData_1.2.9      reshape2_1.4.4             
## [187] gtable_0.3.3
```

Example 124 (unknown):
```unknown
## R version 4.2.0 (2022-04-22)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.5 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/liblapack.so.3
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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       
## 
## attached base packages:
## [1] stats4    stats     graphics  grDevices utils     datasets  methods  
## [8] base     
## 
## other attached packages:
##  [1] BSgenome.Hsapiens.UCSC.hg38_1.4.5 BSgenome_1.66.3                  
##  [3] rtracklayer_1.58.0                Biostrings_2.66.0                
##  [5] XVector_0.38.0                    motifmatchr_1.20.0               
##  [7] TFBSTools_1.36.0                  JASPAR2020_0.99.10               
##  [9] chromVAR_1.20.2                   EnsDb.Hsapiens.v86_2.99.0        
## [11] ensembldb_2.22.0                  AnnotationFilter_1.22.0          
## [13] GenomicFeatures_1.50.4            AnnotationDbi_1.60.0             
## [15] Biobase_2.58.0                    GenomicRanges_1.50.2             
## [17] GenomeInfoDb_1.35.16              IRanges_2.32.0                   
## [19] S4Vectors_0.36.2                  BiocGenerics_0.44.0              
## [21] Signac_1.9.0                      ggplot2_3.4.1                    
## [23] dplyr_1.1.1                       cowplot_1.1.1                    
## [25] thp1.eccite.SeuratData_3.1.5      stxBrain.SeuratData_0.1.1        
## [27] ssHippo.SeuratData_3.1.4          pbmcsca.SeuratData_3.0.0         
## [29] pbmcMultiome.SeuratData_0.1.2     pbmc3k.SeuratData_3.1.4          
## [31] panc8.SeuratData_3.0.2            ifnb.SeuratData_3.1.0            
## [33] hcabm40k.SeuratData_3.0.0         bmcite.SeuratData_0.3.0          
## [35] SeuratData_0.2.2                  SeuratObject_4.1.3               
## [37] Seurat_4.2.1.9001                
## 
## loaded via a namespace (and not attached):
##   [1] rappdirs_0.3.3              scattermore_0.8            
##   [3] R.methodsS3_1.8.2           ragg_1.2.5                 
##   [5] nabor_0.5.0                 tidyr_1.3.0                
##   [7] bit64_4.0.5                 knitr_1.42                 
##   [9] R.utils_2.12.2              irlba_2.3.5.1              
##  [11] DelayedArray_0.24.0         data.table_1.14.8          
##  [13] rpart_4.1.16                KEGGREST_1.38.0            
##  [15] RCurl_1.98-1.12             generics_0.1.3             
##  [17] RSQLite_2.3.0               RANN_2.6.1                 
##  [19] future_1.32.0               tzdb_0.3.0                 
##  [21] bit_4.0.5                   spatstat.data_3.0-1        
##  [23] xml2_1.3.3                  httpuv_1.6.9               
##  [25] SummarizedExperiment_1.28.0 DirichletMultinomial_1.40.0
##  [27] xfun_0.38                   hms_1.1.2                  
##  [29] jquerylib_0.1.4             evaluate_0.20              
##  [31] promises_1.2.0.1            fansi_1.0.4                
##  [33] restfulr_0.0.15             progress_1.2.2             
##  [35] caTools_1.18.2              dbplyr_2.3.1               
##  [37] igraph_1.4.1                DBI_1.1.3                  
##  [39] htmlwidgets_1.6.2           spatstat.geom_3.1-0        
##  [41] purrr_1.0.1                 ellipsis_0.3.2             
##  [43] backports_1.4.1             annotate_1.76.0            
##  [45] biomaRt_2.54.0              deldir_1.0-6               
##  [47] MatrixGenerics_1.10.0       vctrs_0.6.1                
##  [49] ROCR_1.0-11                 abind_1.4-5                
##  [51] cachem_1.0.7                withr_2.5.0                
##  [53] progressr_0.13.0            presto_1.0.0               
##  [55] checkmate_2.1.0             sctransform_0.3.5          
##  [57] GenomicAlignments_1.34.0    prettyunits_1.1.1          
##  [59] goftest_1.2-3               cluster_2.1.3              
##  [61] seqLogo_1.64.0              lazyeval_0.2.2             
##  [63] crayon_1.5.2                hdf5r_1.3.8                
##  [65] spatstat.explore_3.1-0      pkgconfig_2.0.3            
##  [67] labeling_0.4.2              nlme_3.1-157               
##  [69] ProtGenerics_1.30.0         nnet_7.3-17                
##  [71] rlang_1.1.0                 globals_0.16.2             
##  [73] lifecycle_1.0.3             miniUI_0.1.1.1             
##  [75] filelock_1.0.2              BiocFileCache_2.6.1        
##  [77] dichromat_2.0-0.1           rprojroot_2.0.3            
##  [79] polyclip_1.10-4             matrixStats_0.63.0         
##  [81] lmtest_0.9-40               Matrix_1.5-3               
##  [83] zoo_1.8-11                  base64enc_0.1-3            
##  [85] ggridges_0.5.4              png_0.1-8                  
##  [87] viridisLite_0.4.1           rjson_0.2.21               
##  [89] bitops_1.0-7                R.oo_1.25.0                
##  [91] KernSmooth_2.23-20          blob_1.2.3                 
##  [93] stringr_1.5.0               parallelly_1.35.0          
##  [95] spatstat.random_3.1-4       readr_2.1.4                
##  [97] jpeg_0.1-10                 CNEr_1.34.0                
##  [99] scales_1.2.1                memoise_2.0.1              
## [101] magrittr_2.0.3              plyr_1.8.8                 
## [103] ica_1.0-3                   zlibbioc_1.44.0            
## [105] compiler_4.2.0              BiocIO_1.8.0               
## [107] RColorBrewer_1.1-3          fitdistrplus_1.1-8         
## [109] Rsamtools_2.14.0            cli_3.6.1                  
## [111] listenv_0.9.0               patchwork_1.1.2            
## [113] pbapply_1.7-0               htmlTable_2.4.1            
## [115] Formula_1.2-5               MASS_7.3-56                
## [117] tidyselect_1.2.0            stringi_1.7.12             
## [119] textshaping_0.3.6           highr_0.10                 
## [121] yaml_2.3.7                  latticeExtra_0.6-30        
## [123] ggrepel_0.9.3               grid_4.2.0                 
## [125] sass_0.4.5                  VariantAnnotation_1.44.1   
## [127] fastmatch_1.1-3             tools_4.2.0                
## [129] future.apply_1.10.0         parallel_4.2.0             
## [131] rstudioapi_0.14             TFMPvalue_0.0.9            
## [133] foreign_0.8-82              gridExtra_2.3              
## [135] farver_2.1.1                Rtsne_0.16                 
## [137] digest_0.6.31               pracma_2.4.2               
## [139] shiny_1.7.4                 Rcpp_1.0.10                
## [141] later_1.3.0                 RcppAnnoy_0.0.20           
## [143] httr_1.4.5                  biovizBase_1.46.0          
## [145] colorspace_2.1-0            XML_3.99-0.13              
## [147] fs_1.6.1                    tensor_1.5                 
## [149] reticulate_1.28             splines_4.2.0              
## [151] uwot_0.1.14                 RcppRoll_0.3.0             
## [153] spatstat.utils_3.0-2        pkgdown_2.0.7              
## [155] sp_1.6-0                    plotly_4.10.1              
## [157] systemfonts_1.0.4           xtable_1.8-4               
## [159] poweRlaw_0.70.6             jsonlite_1.8.4             
## [161] R6_2.5.1                    Hmisc_4.8-0                
## [163] pillar_1.9.0                htmltools_0.5.5            
## [165] mime_0.12                   DT_0.27                    
## [167] glue_1.6.2                  fastmap_1.1.1              
## [169] BiocParallel_1.32.5         codetools_0.2-18           
## [171] utf8_1.2.3                  lattice_0.20-45            
## [173] bslib_0.4.2                 spatstat.sparse_3.0-1      
## [175] tibble_3.2.1                curl_5.0.0                 
## [177] leiden_0.4.3                gtools_3.9.4               
## [179] GO.db_3.16.0                interp_1.1-3               
## [181] survival_3.3-1              rmarkdown_2.21             
## [183] desc_1.4.2                  munsell_0.5.0              
## [185] GenomeInfoDbData_1.2.9      reshape2_1.4.4             
## [187] gtable_0.3.3
```

---

## Analysis of Image-based Spatial Data in Seurat • Seurat

**URL:** http://127.0.0.1:9173/articles_seurat5_spatial_vignette_2.html

**Contents:**
- Analysis of Image-based Spatial Data in Seurat
    - Compiled: August 20, 2025
- Overview
- Mouse Brain: Vizgen MERSCOPE
  - Preprocessing and unsupervised analysis
- Mouse Brain: 10x Genomics Xenium In Situ
- Human Lung: Nanostring CosMx Spatial Molecular Imager
  - Visualization of cell type and expression localization patterns
- Human Lymph Node: Akoya CODEX system

In this vignette, we introduce a Seurat extension to analyze new types of spatially-resolved data. We have previously introduced a spatial framework which is compatible with sequencing-based technologies, like the 10x Genomics Visium system, or SLIDE-seq. Here, we extend this framework to analyze new data types that are captured via highly multiplexed imaging. In contrast to sequencing-based technologies, these datasets are often targeted (i.e. they profile a pre-selected set of genes). However they can resolve individual molecules - retaining single-cell (and subcellular) resolution. These approaches also often capture cellular boundaries (segmentations).

We update the Seurat infrastructure to enable the analysis, visualization, and exploration of these exciting datasets. In this vignette, we focus on three datasets produced by different multiplexed imaging technologies, each of which is publicly available. We will be adding support for additional imaging-based technologies in the coming months.

First, we load the packages necessary for this vignette.

This dataset was produced using the Vizgen MERSCOPE system, which utilizes the MERFISH technology. The total dataset is available for public download, and contains nine samples (three full coronal slices of the mouse brain, with three biological replicates per slice). The gene panel consists of 483 gene targets, representing known anonical cell type markers, nonsensory G-Protein coupled receptors (GPCRs), and Receptor Tyrosine Kinases (RTKs). In this vignette, we analyze one of the samples - slice 2, replicate 1. The median number of transcripts detected in each cell is 206.

First, we read in the dataset and create a Seurat object.

We use the LoadVizgen() function, which we have written to read in the output of the Vizgen analysis pipeline. The resulting Seurat object contains the following information:

The next pieces of information are specific to imaging assays, and is stored in the images slot of the resulting Seurat object:

We start by performing a standard unsupervised clustering analysis, essentially first treating the dataset as an scRNA-seq experiment. We use SCTransform-based normalization, though we slightly modify the default clipping parameters to mitigate the effect of outliers that we occasionally observe in smFISH experiments. After normalization, we can run dimensional reduction and clustering.

We can then visualize the results of the clustering either in UMAP space (with DimPlot()) or overlaid on the image with ImageDimPlot().

You can also customize multiple aspect of the plot, including the color scheme, cell border widths, and size (see below).

The ImageDimPlot() and ImageFeaturePlot() functions have a few parameters which you can customize individual visualizations. These include:

Since it can be difficult to visualize the spatial localization patterns of an individual cluster when viewing them all together, we can highlight all cells that belong to a particular cluster:

We can find markers of individual clusters and visualize their spatial expression pattern. We can color cells based on their quantified expression of an individual gene, using ImageFeaturePlot(), which is analagous to the FeaturePlot() function for visualizing expression on a 2D embedding. Since MERFISH images individual molecules, we can also visualize the location of individual molecules.

Note that the nmols parameter can be used to reduce the total number of molecules shown to reduce overplotting. You can also use the mols.size, mols.cols, and mols.alpha parameter to further optimize.

Plotting molecules is especially useful for visualizing co-expression of multiple genes on the same plot.

The updated Seurat spatial framework has the option to treat cells as individual points, or also to visualize cell boundaries (segmentations). By default, Seurat ignores cell segmentations and treats each cell as a point (‘centroids’). This speeds up plotting, especially when looking at large areas, where cell boundaries are too small to visualize.

We can zoom into a region of tissue, creating a new field of view. For example, we can zoom into a region that contains the hippocampus. Once zoomed-in, we can set DefaultBoundary() to show cell segmentations. You can also ‘simplify’ the cell segmentations, reducing the number of edges in each polygon to speed up plotting.

The tol parameter determines how simplified the resulting segmentations are. A higher value of tol will reduce the number of vertices more drastically which will speed up plotting, but some segmentation detail will be lost. See https://rgeos.r-forge.r-project.org/reference/topo-unary-gSimplify.html for examples using different values for tol.

We can visualize individual molecules plotted at higher resolution after zooming-in

In this section we’ll analyze data produced by the Xenium platform. The vignette demonstrates how to load the per-transcript location data, cell x gene matrix, cell segmentation, and cell centroid information available in the Xenium outputs. The resulting Seurat object will contain the gene expression profile of each cell, the centroid and boundary of each cell, and the location of each individual detected transcript. The per-cell gene expression profiles are similar to standard single-cell RNA-seq and can be analyzed using the same tools.

This uses the Tiny subset dataset from 10x Genomics provided in the Fresh Frozen Mouse Brain for Xenium Explorer Demo which can be downloaded as described below. These analysis steps are also compatible with the larger Full coronal section, but will take longer to execute.

First we read in the dataset and create a Seurat object. Provide the path to the data folder for a Xenium run as the input path. The RNA data is stored in the Xenium assay of the Seurat object. This step should take about a minute (you can improve this by installing arrow and hdf5r).

Spatial information is loaded into slots of the Seurat object, labelled by the name of “field of view” (FOV) being loaded. Initially all the data is loaded into the FOV named fov. Later, we will make a cropped FOV that zooms into a region of interest.

Standard QC plots provided by Seurat are available via the Xenium assay. Here are violin plots of genes per cell (nFeature_Xenium) and transcript counts per cell (nCount_Xenium)

Next, we plot the positions of the pan-inhibitory neuron marker Gad1, inhibitory neuron sub-type markers Pvalb, and Sst, and astrocyte marker Gfap on the tissue using ImageDimPlot().

Here we visualize the expression level of some key layer marker genes at the per-cell level using ImageFeaturePlot() which is analogous to the FeaturePlot() function for visualizing expression on a 2D embedding. We manually adjust the max.cutoff for each gene to roughly the 90th percentile (which can be specified with max.cutoff='q90') of it’s count distribution to improve contrast.

We can zoom in on a chosen area with the Crop() function. Once zoomed-in, we can visualize cell segmentation boundaries along with individual molecules.

Next, we use SCTransform for normalization followed by standard dimensionality reduction and clustering. This step takes about 5 minutes from start to finish.

We can then visualize the results of the clustering by coloring each cell according to its cluster either in UMAP space with DimPlot() or overlaid on the image with ImageDimPlot().

We can visualize the expression level of the markers we looked at earlier on the UMAP coordinates.

We can now use ImageDimPlot() to color the cell positions colored by the cluster labels determined in the previous step.

Using the positional information of each cell, we compute spatial niches. We use a cortex reference from the the Allen Brain Institute to annotate cells, so we first crop the dataset to the cortex. The Allen Brain reference can be installed here.

Below, we use Slc17a7 expression to help determine the cortical region.

While FindTransferAnchors can be used to integrate spot-level data from spatial transcriptomic datasets, Seurat v5 also includes support for the Robust Cell Type Decomposition, a computational approach to deconvolve spot-level data from spatial datasets, when provided with an scRNA-seq reference. RCTD has been shown to accurately annotate spatial data from a variety of technologies, including SLIDE-seq, Visium, and the 10x Xenium in-situ spatial platform.

To run RCTD, we first install the spacexr package from GitHub which implements RCTD.

Counts, cluster, and spot information is extracted from the Seurat query and reference objects to construct Reference and SpatialRNA objects used by RCTD for annotation. The output of the annotation is then added to the Seurat object.

While the previous analyses consider each cell independently, spatial data enables cells to be defined not just by their neighborhood, but also by their broader spatial context. In Seurat v5, we introduce support for ‘niche’ analysis of spatial data, which demarcates regions of tissue (‘niches’), each of which is defined by a different composition of spatially adjacent cell types. Inspired by methods in Goltsev et al, Cell 2018 and He et al, NBT 2022, we consider the ‘local neighborhood’ for each cell - consisting of its k.neighbor spatially closest neighbors, and count the occurrences of each cell type present in this neighborhood. We then use k-means clustering to group cells that have similar neighborhoods together, into spatial niches.

We call the BuildNicheAssay function from within Seurat to construct a new assay called niche containing the cell type composition spatially neighboring each cell. A metadata column called niches is also returned, which contains cluster assignments based on the niche assay.

We can then group cells either by their cell type identity, or their niche identity. The niches identified clearly demarcate the neuronal layers in the cortex.

Further, we observe that the composition of each niche is enriched for distinct cell types.

This dataset was produced using Nanostring CosMx Spatial Molecular Imager (SMI). The CosMX SMI performs multiplexed single molecule profiling, can profile both RNA and protein targets, and can be applied directly to FFPE tissues. The dataset represents 8 FFPE samples taken from 5 non-small-cell lung cancer (NSCLC) tissues, and is available for public download. The gene panel consists of 960 transcripts.

In this vignette, we load one of 8 samples (lung 5, replicate 1). We use the LoadNanostring() function, which parses the outputs available on the public download site. Note that the coordinates for the cell boundaries were provided by Nanostring by request, and are available for download here.

For this dataset, instead of performing unsupervised analysis, we map the Nanostring profiles to our Azimuth Healthy Human Lung reference, which was defined by scRNA-seq. We used Azimuth version 0.4.3 with the human lung reference version 1.0.0. You can download the precomputed results here, which include annotations, prediction scores, and a UMAP visualization. The median number of detected transcripts/cell is 249, which does create uncertainty for the annotation process.

We can visualize the Nanostring cells and annotations, projected onto the reference-defined UMAP. Note that for this NSCLC sample, tumor samples are annotated as ‘basal’, which is the closest cell type match in the healthy reference.

As in the previous example, ImageDimPlot() plots c ells based on their spatial locations, and colors them based on their assigned cell type. Notice that the basal cell population (tumor cells) is tightly spatially organized, as expected.

Since there are many cell types present, we can highlight the localization of a few select groups.

We can also visualize gene expression markers a few different ways:

We can plot molecules in order to co-visualize the expression of multiple markers, including KRT17 (basal cells), C1QA (macrophages), IL7R (T cells), and TAGLN (Smooth muscle cells).

We zoom in on one basal-rich region using the Crop() function. Once zoomed-in, we can visualize individual cell boundaries as well in all visualizations.

This dataset was produced using Akoya CODEX system. The CODEX system performs multiplexed spatially-resolved protein profiling, iteratively visualizing antibody-binding events. The dataset here represents a tissue section from a human lymph node, and was generated by the University of Florida as part of the Human Biomolecular Atlas Program (HuBMAP). More information about the sample and experiment is available here. The protein panel in this dataset consists of 28 markers, and protein intensities were quantified as part of the Akoya processor pipeline, which outputs a CSV file providing the intensity of each marker in each cell, as well as the cell coordinates. The file is available for public download via Globus here.

First, we load in the data of a HuBMAP dataset using the LoadAkoya() function in Seurat:

We can now run unsupervised analysis to identify cell clusters. To normalize the protein data, we use centered log-ratio based normalization, as we typically apply to the protein modality of CITE-seq data. We then run dimensional reduction and graph-based clustering.

We can visualize the cell clusters based on a protein intensity-based UMAP embedding, or also based on their spatial location.

The expression patters of individual markers clearly denote different cell types and spatial structures, including Lyve1 (lymphatic endothelial cells), CD34 (blood endothelial cells), and CD21 (B cells). As expected, endothelial cells group together into vessels, and B cells are key components of specialized microstructures known as germinal zones. You can read more about protein markers in this dataset, as well as cellular networks in human lynmphatic tissues, in this preprint.

Each of these datasets represents an opportunity to learn organizing principles that govern the spatial localization of different cell types. Stay tuned for future updates to Seurat enabling further exploration and characterization of the relationship between spatial position and molecular state.

Developed by Rahul Satija, Satija Lab and Collaborators.

Site built with pkgdown 2.1.3.

**Examples:**

Example 1 (unknown):
```unknown
vignettes/seurat5_spatial_vignette_2.Rmd
```

Example 2 (unknown):
```unknown
seurat5_spatial_vignette_2.Rmd
```

Example 3 (unknown):
```unknown
library(Seurat)
library(future)
plan("multisession", workers = 10)
library(ggplot2)

options(future.globals.maxSize = 10 * 1024^3)
```

Example 4 (r):
```r
library(Seurat)
library(future)
plan("multisession", workers = 10)
library(ggplot2)

options(future.globals.maxSize = 10 * 1024^3)
```

Example 5 (r):
```r
library(Seurat)
library(future)
plan("multisession", workers = 10)
library(ggplot2)

options(future.globals.maxSize = 10 * 1024^3)
```

Example 6 (unknown):
```unknown
LoadVizgen()
```

Example 7 (unknown):
```unknown
# Loading segmentations is a slow process and multi processing with the future pacakge is
# recommended
vizgen.obj <- LoadVizgen(data.dir = "/brahms/hartmana/vignette_data/vizgen/s2r1/", fov = "s2r1")
```

Example 8 (r):
```r
# Loading segmentations is a slow process and multi processing with the future pacakge is
# recommended
vizgen.obj <- LoadVizgen(data.dir = "/brahms/hartmana/vignette_data/vizgen/s2r1/", fov = "s2r1")
```

Example 9 (r):
```r
# Loading segmentations is a slow process and multi processing with the future pacakge is
# recommended
vizgen.obj <- LoadVizgen(data.dir = "/brahms/hartmana/vignette_data/vizgen/s2r1/", fov = "s2r1")
```

Example 10 (unknown):
```unknown
# Get the center position of each centroid. There is one row per cell in this dataframe.
head(GetTissueCoordinates(vizgen.obj[["s2r1"]][["centroids"]]))
```

Example 11 (r):
```r
# Get the center position of each centroid. There is one row per cell in this dataframe.
head(GetTissueCoordinates(vizgen.obj[["s2r1"]][["centroids"]]))
```

Example 12 (r):
```r
# Get the center position of each centroid. There is one row per cell in this dataframe.
head(GetTissueCoordinates(vizgen.obj[["s2r1"]][["centroids"]]))
```

Example 13 (unknown):
```unknown
##          x        y                                    cell
## 1 638.5640 4594.216 149164679103246548309819743981609972453
## 2 593.8034 4516.240 215843146921706462965382248182021894607
## 3 597.3134 4566.676 230248905804673613678286091156141465134
## 4 613.2434 4609.498 237155298815097057940587033798543926454
## 5 609.1934 4603.180 256099454901769634241742157204636917386
## 6 623.8814 4642.708  52442222147121971758529793775250916001
```

Example 14 (unknown):
```unknown
##          x        y                                    cell
## 1 638.5640 4594.216 149164679103246548309819743981609972453
## 2 593.8034 4516.240 215843146921706462965382248182021894607
## 3 597.3134 4566.676 230248905804673613678286091156141465134
## 4 613.2434 4609.498 237155298815097057940587033798543926454
## 5 609.1934 4603.180 256099454901769634241742157204636917386
## 6 623.8814 4642.708  52442222147121971758529793775250916001
```

Example 15 (unknown):
```unknown
# Get the coordinates for each segmentation vertice. Each cell will have a variable number of
# vertices describing its shape.
head(GetTissueCoordinates(vizgen.obj[["s2r1"]][["segmentation"]]))
```

Example 16 (r):
```r
# Get the coordinates for each segmentation vertice. Each cell will have a variable number of
# vertices describing its shape.
head(GetTissueCoordinates(vizgen.obj[["s2r1"]][["segmentation"]]))
```

Example 17 (r):
```r
# Get the coordinates for each segmentation vertice. Each cell will have a variable number of
# vertices describing its shape.
head(GetTissueCoordinates(vizgen.obj[["s2r1"]][["segmentation"]]))
```

Example 18 (unknown):
```unknown
##          x        y                                    cell
## 1 644.0774 4589.022 149164679103246548309819743981609972453
## 2 643.9694 4589.022 149164679103246548309819743981609972453
## 3 643.8614 4589.022 149164679103246548309819743981609972453
## 4 643.7642 4588.924 149164679103246548309819743981609972453
## 5 643.7534 4588.914 149164679103246548309819743981609972453
## 6 643.6454 4588.914 149164679103246548309819743981609972453
```

Example 19 (unknown):
```unknown
##          x        y                                    cell
## 1 644.0774 4589.022 149164679103246548309819743981609972453
## 2 643.9694 4589.022 149164679103246548309819743981609972453
## 3 643.8614 4589.022 149164679103246548309819743981609972453
## 4 643.7642 4588.924 149164679103246548309819743981609972453
## 5 643.7534 4588.914 149164679103246548309819743981609972453
## 6 643.6454 4588.914 149164679103246548309819743981609972453
```

Example 20 (unknown):
```unknown
# Fetch molecules positions for Chrm1
head(FetchData(vizgen.obj[["s2r1"]][["molecules"]], vars = "Chrm1"))
```

Example 21 (r):
```r
# Fetch molecules positions for Chrm1
head(FetchData(vizgen.obj[["s2r1"]][["molecules"]], vars = "Chrm1"))
```

Example 22 (r):
```r
# Fetch molecules positions for Chrm1
head(FetchData(vizgen.obj[["s2r1"]][["molecules"]], vars = "Chrm1"))
```

Example 23 (unknown):
```unknown
##          x        y molecule
## 1 577.3373 4205.977    Chrm1
## 2 600.0218 3917.781    Chrm1
## 3 508.2736 3934.063    Chrm1
## 4 630.7590 3948.586    Chrm1
## 5 635.1143 3969.567    Chrm1
## 6 582.7043 4021.577    Chrm1
```

Example 24 (unknown):
```unknown
##          x        y molecule
## 1 577.3373 4205.977    Chrm1
## 2 600.0218 3917.781    Chrm1
## 3 508.2736 3934.063    Chrm1
## 4 630.7590 3948.586    Chrm1
## 5 635.1143 3969.567    Chrm1
## 6 582.7043 4021.577    Chrm1
```

Example 25 (unknown):
```unknown
vizgen.obj <- SCTransform(vizgen.obj, assay = "Vizgen", clip.range = c(-10, 10))
vizgen.obj <- RunPCA(vizgen.obj, npcs = 30, features = rownames(vizgen.obj))
vizgen.obj <- RunUMAP(vizgen.obj, dims = 1:30)
vizgen.obj <- FindNeighbors(vizgen.obj, reduction = "pca", dims = 1:30)
vizgen.obj <- FindClusters(vizgen.obj, resolution = 0.3)
```

Example 26 (r):
```r
vizgen.obj <- SCTransform(vizgen.obj, assay = "Vizgen", clip.range = c(-10, 10))
vizgen.obj <- RunPCA(vizgen.obj, npcs = 30, features = rownames(vizgen.obj))
vizgen.obj <- RunUMAP(vizgen.obj, dims = 1:30)
vizgen.obj <- FindNeighbors(vizgen.obj, reduction = "pca", dims = 1:30)
vizgen.obj <- FindClusters(vizgen.obj, resolution = 0.3)
```

Example 27 (r):
```r
vizgen.obj <- SCTransform(vizgen.obj, assay = "Vizgen", clip.range = c(-10, 10))
vizgen.obj <- RunPCA(vizgen.obj, npcs = 30, features = rownames(vizgen.obj))
vizgen.obj <- RunUMAP(vizgen.obj, dims = 1:30)
vizgen.obj <- FindNeighbors(vizgen.obj, reduction = "pca", dims = 1:30)
vizgen.obj <- FindClusters(vizgen.obj, resolution = 0.3)
```

Example 28 (unknown):
```unknown
ImageDimPlot()
```

Example 29 (unknown):
```unknown
DimPlot(vizgen.obj, reduction = "umap")
```

Example 30 (r):
```r
DimPlot(vizgen.obj, reduction = "umap")
```

Example 31 (r):
```r
DimPlot(vizgen.obj, reduction = "umap")
```

Example 32 (unknown):
```unknown
ImageDimPlot(vizgen.obj, fov = "s2r1", cols = "polychrome", axes = TRUE)
```

Example 33 (r):
```r
ImageDimPlot(vizgen.obj, fov = "s2r1", cols = "polychrome", axes = TRUE)
```

Example 34 (r):
```r
ImageDimPlot(vizgen.obj, fov = "s2r1", cols = "polychrome", axes = TRUE)
```

Example 35 (unknown):
```unknown
ImageDimPlot()
```

Example 36 (unknown):
```unknown
ImageFeaturePlot()
```

Example 37 (unknown):
```unknown
shuffle.cols = TRUE
```

Example 38 (unknown):
```unknown
p1 <- ImageDimPlot(vizgen.obj, fov = "s2r1", cols = "red", cells = WhichCells(vizgen.obj, idents = 1))
p2 <- ImageDimPlot(vizgen.obj, fov = "s2r1", cols = "red", cells = WhichCells(vizgen.obj, idents = 15))
p1 + p2
```

Example 39 (r):
```r
p1 <- ImageDimPlot(vizgen.obj, fov = "s2r1", cols = "red", cells = WhichCells(vizgen.obj, idents = 1))
p2 <- ImageDimPlot(vizgen.obj, fov = "s2r1", cols = "red", cells = WhichCells(vizgen.obj, idents = 15))
p1 + p2
```

Example 40 (r):
```r
p1 <- ImageDimPlot(vizgen.obj, fov = "s2r1", cols = "red", cells = WhichCells(vizgen.obj, idents = 1))
p2 <- ImageDimPlot(vizgen.obj, fov = "s2r1", cols = "red", cells = WhichCells(vizgen.obj, idents = 15))
p1 + p2
```

Example 41 (unknown):
```unknown
ImageFeaturePlot()
```

Example 42 (unknown):
```unknown
FeaturePlot()
```

Example 43 (unknown):
```unknown
p1 <- ImageFeaturePlot(vizgen.obj, features = "Slc17a7")
p2 <- ImageDimPlot(vizgen.obj, molecules = "Slc17a7", nmols = 10000, alpha = 0.3, mols.cols = "red")
p1 + p2
```

Example 44 (r):
```r
p1 <- ImageFeaturePlot(vizgen.obj, features = "Slc17a7")
p2 <- ImageDimPlot(vizgen.obj, molecules = "Slc17a7", nmols = 10000, alpha = 0.3, mols.cols = "red")
p1 + p2
```

Example 45 (r):
```r
p1 <- ImageFeaturePlot(vizgen.obj, features = "Slc17a7")
p2 <- ImageDimPlot(vizgen.obj, molecules = "Slc17a7", nmols = 10000, alpha = 0.3, mols.cols = "red")
p1 + p2
```

Example 46 (unknown):
```unknown
p1 <- ImageDimPlot(vizgen.obj, fov = "s2r1", alpha = 0.3, molecules = c("Slc17a7", "Olig1"), nmols = 10000)
markers.14 <- FindMarkers(vizgen.obj, ident.1 = "14")
p2 <- ImageDimPlot(vizgen.obj, fov = "s2r1", alpha = 0.3, molecules = rownames(markers.14)[1:4],
    nmols = 10000)
p1 + p2
```

Example 47 (r):
```r
p1 <- ImageDimPlot(vizgen.obj, fov = "s2r1", alpha = 0.3, molecules = c("Slc17a7", "Olig1"), nmols = 10000)
markers.14 <- FindMarkers(vizgen.obj, ident.1 = "14")
p2 <- ImageDimPlot(vizgen.obj, fov = "s2r1", alpha = 0.3, molecules = rownames(markers.14)[1:4],
    nmols = 10000)
p1 + p2
```

Example 48 (r):
```r
p1 <- ImageDimPlot(vizgen.obj, fov = "s2r1", alpha = 0.3, molecules = c("Slc17a7", "Olig1"), nmols = 10000)
markers.14 <- FindMarkers(vizgen.obj, ident.1 = "14")
p2 <- ImageDimPlot(vizgen.obj, fov = "s2r1", alpha = 0.3, molecules = rownames(markers.14)[1:4],
    nmols = 10000)
p1 + p2
```

Example 49 (unknown):
```unknown
DefaultBoundary()
```

Example 50 (unknown):
```unknown
# create a Crop
cropped.coords <- Crop(vizgen.obj[["s2r1"]], x = c(1750, 3000), y = c(3750, 5250), coords = "plot")
# set a new field of view (fov)
vizgen.obj[["hippo"]] <- cropped.coords

# visualize FOV using default settings (no cell boundaries)
p1 <- ImageDimPlot(vizgen.obj, fov = "hippo", axes = TRUE, size = 0.7, border.color = "white", cols = "polychrome",
    coord.fixed = FALSE)

# visualize FOV with full cell segmentations
DefaultBoundary(vizgen.obj[["hippo"]]) <- "segmentation"
p2 <- ImageDimPlot(vizgen.obj, fov = "hippo", axes = TRUE, border.color = "white", border.size = 0.1,
    cols = "polychrome", coord.fixed = FALSE)

# simplify cell segmentations
vizgen.obj[["hippo"]][["simplified.segmentations"]] <- Simplify(coords = vizgen.obj[["hippo"]][["segmentation"]],
    tol = 3)
DefaultBoundary(vizgen.obj[["hippo"]]) <- "simplified.segmentations"

# visualize FOV with simplified cell segmentations
DefaultBoundary(vizgen.obj[["hippo"]]) <- "simplified.segmentations"
p3 <- ImageDimPlot(vizgen.obj, fov = "hippo", axes = TRUE, border.color = "white", border.size = 0.1,
    cols = "polychrome", coord.fixed = FALSE)

p1 + p2 + p3
```

Example 51 (r):
```r
# create a Crop
cropped.coords <- Crop(vizgen.obj[["s2r1"]], x = c(1750, 3000), y = c(3750, 5250), coords = "plot")
# set a new field of view (fov)
vizgen.obj[["hippo"]] <- cropped.coords

# visualize FOV using default settings (no cell boundaries)
p1 <- ImageDimPlot(vizgen.obj, fov = "hippo", axes = TRUE, size = 0.7, border.color = "white", cols = "polychrome",
    coord.fixed = FALSE)

# visualize FOV with full cell segmentations
DefaultBoundary(vizgen.obj[["hippo"]]) <- "segmentation"
p2 <- ImageDimPlot(vizgen.obj, fov = "hippo", axes = TRUE, border.color = "white", border.size = 0.1,
    cols = "polychrome", coord.fixed = FALSE)

# simplify cell segmentations
vizgen.obj[["hippo"]][["simplified.segmentations"]] <- Simplify(coords = vizgen.obj[["hippo"]][["segmentation"]],
    tol = 3)
DefaultBoundary(vizgen.obj[["hippo"]]) <- "simplified.segmentations"

# visualize FOV with simplified cell segmentations
DefaultBoundary(vizgen.obj[["hippo"]]) <- "simplified.segmentations"
p3 <- ImageDimPlot(vizgen.obj, fov = "hippo", axes = TRUE, border.color = "white", border.size = 0.1,
    cols = "polychrome", coord.fixed = FALSE)

p1 + p2 + p3
```

Example 52 (r):
```r
# create a Crop
cropped.coords <- Crop(vizgen.obj[["s2r1"]], x = c(1750, 3000), y = c(3750, 5250), coords = "plot")
# set a new field of view (fov)
vizgen.obj[["hippo"]] <- cropped.coords

# visualize FOV using default settings (no cell boundaries)
p1 <- ImageDimPlot(vizgen.obj, fov = "hippo", axes = TRUE, size = 0.7, border.color = "white", cols = "polychrome",
    coord.fixed = FALSE)

# visualize FOV with full cell segmentations
DefaultBoundary(vizgen.obj[["hippo"]]) <- "segmentation"
p2 <- ImageDimPlot(vizgen.obj, fov = "hippo", axes = TRUE, border.color = "white", border.size = 0.1,
    cols = "polychrome", coord.fixed = FALSE)

# simplify cell segmentations
vizgen.obj[["hippo"]][["simplified.segmentations"]] <- Simplify(coords = vizgen.obj[["hippo"]][["segmentation"]],
    tol = 3)
DefaultBoundary(vizgen.obj[["hippo"]]) <- "simplified.segmentations"

# visualize FOV with simplified cell segmentations
DefaultBoundary(vizgen.obj[["hippo"]]) <- "simplified.segmentations"
p3 <- ImageDimPlot(vizgen.obj, fov = "hippo", axes = TRUE, border.color = "white", border.size = 0.1,
    cols = "polychrome", coord.fixed = FALSE)

p1 + p2 + p3
```

Example 53 (unknown):
```unknown
# Since there is nothing behind the segmentations, alpha will slightly mute colors
ImageDimPlot(vizgen.obj, fov = "hippo", molecules = rownames(markers.14)[1:4], cols = "polychrome",
    mols.size = 1, alpha = 0.5, mols.cols = c("red", "blue", "yellow", "green"))
```

Example 54 (r):
```r
# Since there is nothing behind the segmentations, alpha will slightly mute colors
ImageDimPlot(vizgen.obj, fov = "hippo", molecules = rownames(markers.14)[1:4], cols = "polychrome",
    mols.size = 1, alpha = 0.5, mols.cols = c("red", "blue", "yellow", "green"))
```

Example 55 (r):
```r
# Since there is nothing behind the segmentations, alpha will slightly mute colors
ImageDimPlot(vizgen.obj, fov = "hippo", molecules = rownames(markers.14)[1:4], cols = "polychrome",
    mols.size = 1, alpha = 0.5, mols.cols = c("red", "blue", "yellow", "green"))
```

Example 56 (unknown):
```unknown
Tiny subset
```

Example 57 (unknown):
```unknown
Full coronal section
```

Example 58 (unknown):
```unknown
wget https://cf.10xgenomics.com/samples/xenium/1.0.2/Xenium_V1_FF_Mouse_Brain_Coronal_Subset_CTX_HP/Xenium_V1_FF_Mouse_Brain_Coronal_Subset_CTX_HP_outs.zip
unzip Xenium_V1_FF_Mouse_Brain_Coronal_Subset_CTX_HP_outs.zip
```

Example 59 (bash):
```bash
wget https://cf.10xgenomics.com/samples/xenium/1.0.2/Xenium_V1_FF_Mouse_Brain_Coronal_Subset_CTX_HP/Xenium_V1_FF_Mouse_Brain_Coronal_Subset_CTX_HP_outs.zip
unzip Xenium_V1_FF_Mouse_Brain_Coronal_Subset_CTX_HP_outs.zip
```

Example 60 (bash):
```bash
wget https://cf.10xgenomics.com/samples/xenium/1.0.2/Xenium_V1_FF_Mouse_Brain_Coronal_Subset_CTX_HP/Xenium_V1_FF_Mouse_Brain_Coronal_Subset_CTX_HP_outs.zip
unzip Xenium_V1_FF_Mouse_Brain_Coronal_Subset_CTX_HP_outs.zip
```

Example 61 (unknown):
```unknown
path <- "/brahms/hartmana/vignette_data/xenium_tiny_subset"
# Load the Xenium data
xenium.obj <- LoadXenium(path, fov = "fov", segmentations = "cell")
# remove cells with 0 counts
xenium.obj <- subset(xenium.obj, subset = nCount_Xenium > 0)
```

Example 62 (r):
```r
path <- "/brahms/hartmana/vignette_data/xenium_tiny_subset"
# Load the Xenium data
xenium.obj <- LoadXenium(path, fov = "fov", segmentations = "cell")
# remove cells with 0 counts
xenium.obj <- subset(xenium.obj, subset = nCount_Xenium > 0)
```

Example 63 (r):
```r
path <- "/brahms/hartmana/vignette_data/xenium_tiny_subset"
# Load the Xenium data
xenium.obj <- LoadXenium(path, fov = "fov", segmentations = "cell")
# remove cells with 0 counts
xenium.obj <- subset(xenium.obj, subset = nCount_Xenium > 0)
```

Example 64 (unknown):
```unknown
nFeature_Xenium
```

Example 65 (unknown):
```unknown
nCount_Xenium
```

Example 66 (unknown):
```unknown
VlnPlot(xenium.obj, features = c("nFeature_Xenium", "nCount_Xenium"), ncol = 2, pt.size = 0)
```

Example 67 (r):
```r
VlnPlot(xenium.obj, features = c("nFeature_Xenium", "nCount_Xenium"), ncol = 2, pt.size = 0)
```

Example 68 (r):
```r
VlnPlot(xenium.obj, features = c("nFeature_Xenium", "nCount_Xenium"), ncol = 2, pt.size = 0)
```

Example 69 (unknown):
```unknown
ImageDimPlot()
```

Example 70 (unknown):
```unknown
ImageDimPlot(xenium.obj, fov = "fov", molecules = c("Gad1", "Sst", "Pvalb", "Gfap"), nmols = 20000)
```

Example 71 (r):
```r
ImageDimPlot(xenium.obj, fov = "fov", molecules = c("Gad1", "Sst", "Pvalb", "Gfap"), nmols = 20000)
```

Example 72 (r):
```r
ImageDimPlot(xenium.obj, fov = "fov", molecules = c("Gad1", "Sst", "Pvalb", "Gfap"), nmols = 20000)
```

Example 73 (unknown):
```unknown
ImageFeaturePlot()
```

Example 74 (unknown):
```unknown
FeaturePlot()
```

Example 75 (unknown):
```unknown
max.cutoff='q90'
```

Example 76 (unknown):
```unknown
ImageFeaturePlot(xenium.obj, features = c("Cux2", "Rorb", "Bcl11b", "Foxp2"), max.cutoff = c(25,
    35, 12, 10), size = 0.75, cols = c("white", "red"))
```

Example 77 (r):
```r
ImageFeaturePlot(xenium.obj, features = c("Cux2", "Rorb", "Bcl11b", "Foxp2"), max.cutoff = c(25,
    35, 12, 10), size = 0.75, cols = c("white", "red"))
```

Example 78 (r):
```r
ImageFeaturePlot(xenium.obj, features = c("Cux2", "Rorb", "Bcl11b", "Foxp2"), max.cutoff = c(25,
    35, 12, 10), size = 0.75, cols = c("white", "red"))
```

Example 79 (unknown):
```unknown
cropped.coords <- Crop(xenium.obj[["fov"]], x = c(1200, 2900), y = c(3750, 4550), coords = "plot")
xenium.obj[["zoom"]] <- cropped.coords
# visualize cropped area with cell segmentations & selected molecules
DefaultBoundary(xenium.obj[["zoom"]]) <- "segmentation"
ImageDimPlot(xenium.obj, fov = "zoom", axes = TRUE, border.color = "white", border.size = 0.1, cols = "polychrome",
    coord.fixed = FALSE, molecules = c("Gad1", "Sst", "Npy2r", "Pvalb", "Nrn1"), nmols = 10000)
```

Example 80 (r):
```r
cropped.coords <- Crop(xenium.obj[["fov"]], x = c(1200, 2900), y = c(3750, 4550), coords = "plot")
xenium.obj[["zoom"]] <- cropped.coords
# visualize cropped area with cell segmentations & selected molecules
DefaultBoundary(xenium.obj[["zoom"]]) <- "segmentation"
ImageDimPlot(xenium.obj, fov = "zoom", axes = TRUE, border.color = "white", border.size = 0.1, cols = "polychrome",
    coord.fixed = FALSE, molecules = c("Gad1", "Sst", "Npy2r", "Pvalb", "Nrn1"), nmols = 10000)
```

Example 81 (r):
```r
cropped.coords <- Crop(xenium.obj[["fov"]], x = c(1200, 2900), y = c(3750, 4550), coords = "plot")
xenium.obj[["zoom"]] <- cropped.coords
# visualize cropped area with cell segmentations & selected molecules
DefaultBoundary(xenium.obj[["zoom"]]) <- "segmentation"
ImageDimPlot(xenium.obj, fov = "zoom", axes = TRUE, border.color = "white", border.size = 0.1, cols = "polychrome",
    coord.fixed = FALSE, molecules = c("Gad1", "Sst", "Npy2r", "Pvalb", "Nrn1"), nmols = 10000)
```

Example 82 (unknown):
```unknown
xenium.obj <- SCTransform(xenium.obj, assay = "Xenium")
xenium.obj <- RunPCA(xenium.obj, npcs = 30, features = rownames(xenium.obj))
xenium.obj <- RunUMAP(xenium.obj, dims = 1:30)
xenium.obj <- FindNeighbors(xenium.obj, reduction = "pca", dims = 1:30)
xenium.obj <- FindClusters(xenium.obj, resolution = 0.3)
```

Example 83 (r):
```r
xenium.obj <- SCTransform(xenium.obj, assay = "Xenium")
xenium.obj <- RunPCA(xenium.obj, npcs = 30, features = rownames(xenium.obj))
xenium.obj <- RunUMAP(xenium.obj, dims = 1:30)
xenium.obj <- FindNeighbors(xenium.obj, reduction = "pca", dims = 1:30)
xenium.obj <- FindClusters(xenium.obj, resolution = 0.3)
```

Example 84 (r):
```r
xenium.obj <- SCTransform(xenium.obj, assay = "Xenium")
xenium.obj <- RunPCA(xenium.obj, npcs = 30, features = rownames(xenium.obj))
xenium.obj <- RunUMAP(xenium.obj, dims = 1:30)
xenium.obj <- FindNeighbors(xenium.obj, reduction = "pca", dims = 1:30)
xenium.obj <- FindClusters(xenium.obj, resolution = 0.3)
```

Example 85 (unknown):
```unknown
ImageDimPlot()
```

Example 86 (unknown):
```unknown
DimPlot(xenium.obj)
```

Example 87 (r):
```r
DimPlot(xenium.obj)
```

Example 88 (r):
```r
DimPlot(xenium.obj)
```

Example 89 (unknown):
```unknown
FeaturePlot(xenium.obj, features = c("Cux2", "Bcl11b", "Foxp2", "Gad1", "Sst", "Gfap"))
```

Example 90 (r):
```r
FeaturePlot(xenium.obj, features = c("Cux2", "Bcl11b", "Foxp2", "Gad1", "Sst", "Gfap"))
```

Example 91 (r):
```r
FeaturePlot(xenium.obj, features = c("Cux2", "Bcl11b", "Foxp2", "Gad1", "Sst", "Gfap"))
```

Example 92 (unknown):
```unknown
ImageDimPlot()
```

Example 93 (unknown):
```unknown
ImageDimPlot(xenium.obj, cols = "polychrome", size = 0.75)
```

Example 94 (r):
```r
ImageDimPlot(xenium.obj, cols = "polychrome", size = 0.75)
```

Example 95 (r):
```r
ImageDimPlot(xenium.obj, cols = "polychrome", size = 0.75)
```

Example 96 (unknown):
```unknown
xenium.obj <- LoadXenium("/brahms/hartmana/vignette_data/xenium_tiny_subset")
p1 <- ImageFeaturePlot(xenium.obj, features = "Slc17a7", axes = TRUE, max.cutoff = "q90")
p1
```

Example 97 (r):
```r
xenium.obj <- LoadXenium("/brahms/hartmana/vignette_data/xenium_tiny_subset")
p1 <- ImageFeaturePlot(xenium.obj, features = "Slc17a7", axes = TRUE, max.cutoff = "q90")
p1
```

Example 98 (r):
```r
xenium.obj <- LoadXenium("/brahms/hartmana/vignette_data/xenium_tiny_subset")
p1 <- ImageFeaturePlot(xenium.obj, features = "Slc17a7", axes = TRUE, max.cutoff = "q90")
p1
```

Example 99 (unknown):
```unknown
crop <- Crop(xenium.obj[["fov"]], x = c(600, 2100), y = c(900, 4700))
xenium.obj[["crop"]] <- crop
p2 <- ImageFeaturePlot(xenium.obj, fov = "crop", features = "Slc17a7", size = 1, axes = TRUE, max.cutoff = "q90")
p2
```

Example 100 (r):
```r
crop <- Crop(xenium.obj[["fov"]], x = c(600, 2100), y = c(900, 4700))
xenium.obj[["crop"]] <- crop
p2 <- ImageFeaturePlot(xenium.obj, fov = "crop", features = "Slc17a7", size = 1, axes = TRUE, max.cutoff = "q90")
p2
```

Example 101 (r):
```r
crop <- Crop(xenium.obj[["fov"]], x = c(600, 2100), y = c(900, 4700))
xenium.obj[["crop"]] <- crop
p2 <- ImageFeaturePlot(xenium.obj, fov = "crop", features = "Slc17a7", size = 1, axes = TRUE, max.cutoff = "q90")
p2
```

Example 102 (unknown):
```unknown
FindTransferAnchors
```

Example 103 (unknown):
```unknown
devtools::install_github("dmcable/spacexr", build_vignettes = FALSE)
```

Example 104 (r):
```r
devtools::install_github("dmcable/spacexr", build_vignettes = FALSE)
```

Example 105 (r):
```r
devtools::install_github("dmcable/spacexr", build_vignettes = FALSE)
```

Example 106 (unknown):
```unknown
library(spacexr)

query.counts <- GetAssayData(xenium.obj, assay = "Xenium", slot = "counts")[, Cells(xenium.obj[["crop"]])]
coords <- GetTissueCoordinates(xenium.obj[["crop"]], which = "centroids")
rownames(coords) <- coords$cell
coords$cell <- NULL
query <- SpatialRNA(coords, query.counts, colSums(query.counts))
```

Example 107 (r):
```r
library(spacexr)

query.counts <- GetAssayData(xenium.obj, assay = "Xenium", slot = "counts")[, Cells(xenium.obj[["crop"]])]
coords <- GetTissueCoordinates(xenium.obj[["crop"]], which = "centroids")
rownames(coords) <- coords$cell
coords$cell <- NULL
query <- SpatialRNA(coords, query.counts, colSums(query.counts))
```

Example 108 (r):
```r
library(spacexr)

query.counts <- GetAssayData(xenium.obj, assay = "Xenium", slot = "counts")[, Cells(xenium.obj[["crop"]])]
coords <- GetTissueCoordinates(xenium.obj[["crop"]], which = "centroids")
rownames(coords) <- coords$cell
coords$cell <- NULL
query <- SpatialRNA(coords, query.counts, colSums(query.counts))
```

Example 109 (python):
```python
# allen.corted.ref can be downloaded here:
# https://www.dropbox.com/s/cuowvm4vrf65pvq/allen_cortex.rds?dl=1
allen.cortex.ref <- readRDS("/brahms/shared/vignette-data/allen_cortex.rds")
allen.cortex.ref <- UpdateSeuratObject(allen.cortex.ref)

Idents(allen.cortex.ref) <- "subclass"
# remove CR cells because there aren't enough of them for annotation
allen.cortex.ref <- subset(allen.cortex.ref, subset = subclass != "CR")
counts <- GetAssayData(allen.cortex.ref, assay = "RNA", slot = "counts")
cluster <- as.factor(allen.cortex.ref$subclass)
names(cluster) <- colnames(allen.cortex.ref)
nUMI <- allen.cortex.ref$nCount_RNA
names(nUMI) <- colnames(allen.cortex.ref)
nUMI <- colSums(counts)
levels(cluster) <- gsub("/", "-", levels(cluster))
reference <- Reference(counts, cluster, nUMI)
```

Example 110 (r):
```r
# allen.corted.ref can be downloaded here:
# https://www.dropbox.com/s/cuowvm4vrf65pvq/allen_cortex.rds?dl=1
allen.cortex.ref <- readRDS("/brahms/shared/vignette-data/allen_cortex.rds")
allen.cortex.ref <- UpdateSeuratObject(allen.cortex.ref)

Idents(allen.cortex.ref) <- "subclass"
# remove CR cells because there aren't enough of them for annotation
allen.cortex.ref <- subset(allen.cortex.ref, subset = subclass != "CR")
counts <- GetAssayData(allen.cortex.ref, assay = "RNA", slot = "counts")
cluster <- as.factor(allen.cortex.ref$subclass)
names(cluster) <- colnames(allen.cortex.ref)
nUMI <- allen.cortex.ref$nCount_RNA
names(nUMI) <- colnames(allen.cortex.ref)
nUMI <- colSums(counts)
levels(cluster) <- gsub("/", "-", levels(cluster))
reference <- Reference(counts, cluster, nUMI)
```

Example 111 (r):
```r
# allen.corted.ref can be downloaded here:
# https://www.dropbox.com/s/cuowvm4vrf65pvq/allen_cortex.rds?dl=1
allen.cortex.ref <- readRDS("/brahms/shared/vignette-data/allen_cortex.rds")
allen.cortex.ref <- UpdateSeuratObject(allen.cortex.ref)

Idents(allen.cortex.ref) <- "subclass"
# remove CR cells because there aren't enough of them for annotation
allen.cortex.ref <- subset(allen.cortex.ref, subset = subclass != "CR")
counts <- GetAssayData(allen.cortex.ref, assay = "RNA", slot = "counts")
cluster <- as.factor(allen.cortex.ref$subclass)
names(cluster) <- colnames(allen.cortex.ref)
nUMI <- allen.cortex.ref$nCount_RNA
names(nUMI) <- colnames(allen.cortex.ref)
nUMI <- colSums(counts)
levels(cluster) <- gsub("/", "-", levels(cluster))
reference <- Reference(counts, cluster, nUMI)
```

Example 112 (unknown):
```unknown
# run RCTD with many cores
RCTD <- create.RCTD(query, reference, max_cores = 8)
RCTD <- run.RCTD(RCTD, doublet_mode = "doublet")
```

Example 113 (r):
```r
# run RCTD with many cores
RCTD <- create.RCTD(query, reference, max_cores = 8)
RCTD <- run.RCTD(RCTD, doublet_mode = "doublet")
```

Example 114 (r):
```r
# run RCTD with many cores
RCTD <- create.RCTD(query, reference, max_cores = 8)
RCTD <- run.RCTD(RCTD, doublet_mode = "doublet")
```

Example 115 (unknown):
```unknown
annotations.df <- RCTD@results$results_df
annotations <- annotations.df$first_type
names(annotations) <- rownames(annotations.df)
xenium.obj$predicted.celltype <- annotations
keep.cells <- Cells(xenium.obj)[!is.na(xenium.obj$predicted.celltype)]
xenium.obj <- subset(xenium.obj, cells = keep.cells)
```

Example 116 (r):
```r
annotations.df <- RCTD@results$results_df
annotations <- annotations.df$first_type
names(annotations) <- rownames(annotations.df)
xenium.obj$predicted.celltype <- annotations
keep.cells <- Cells(xenium.obj)[!is.na(xenium.obj$predicted.celltype)]
xenium.obj <- subset(xenium.obj, cells = keep.cells)
```

Example 117 (r):
```r
annotations.df <- RCTD@results$results_df
annotations <- annotations.df$first_type
names(annotations) <- rownames(annotations.df)
xenium.obj$predicted.celltype <- annotations
keep.cells <- Cells(xenium.obj)[!is.na(xenium.obj$predicted.celltype)]
xenium.obj <- subset(xenium.obj, cells = keep.cells)
```

Example 118 (unknown):
```unknown
BuildNicheAssay
```

Example 119 (unknown):
```unknown
xenium.obj <- BuildNicheAssay(object = xenium.obj, fov = "crop", group.by = "predicted.celltype",
    niches.k = 5, neighbors.k = 30)
```

Example 120 (r):
```r
xenium.obj <- BuildNicheAssay(object = xenium.obj, fov = "crop", group.by = "predicted.celltype",
    niches.k = 5, neighbors.k = 30)
```

Example 121 (r):
```r
xenium.obj <- BuildNicheAssay(object = xenium.obj, fov = "crop", group.by = "predicted.celltype",
    niches.k = 5, neighbors.k = 30)
```

Example 122 (unknown):
```unknown
celltype.plot <- ImageDimPlot(xenium.obj, group.by = "predicted.celltype", size = 1.5, cols = "polychrome",
    dark.background = F) + ggtitle("Cell type")
niche.plot <- ImageDimPlot(xenium.obj, group.by = "niches", size = 1.5, dark.background = F) + ggtitle("Niches") +
    scale_fill_manual(values = c("#442288", "#6CA2EA", "#B5D33D", "#FED23F", "#EB7D5B"))
celltype.plot | niche.plot
```

Example 123 (r):
```r
celltype.plot <- ImageDimPlot(xenium.obj, group.by = "predicted.celltype", size = 1.5, cols = "polychrome",
    dark.background = F) + ggtitle("Cell type")
niche.plot <- ImageDimPlot(xenium.obj, group.by = "niches", size = 1.5, dark.background = F) + ggtitle("Niches") +
    scale_fill_manual(values = c("#442288", "#6CA2EA", "#B5D33D", "#FED23F", "#EB7D5B"))
celltype.plot | niche.plot
```

Example 124 (r):
```r
celltype.plot <- ImageDimPlot(xenium.obj, group.by = "predicted.celltype", size = 1.5, cols = "polychrome",
    dark.background = F) + ggtitle("Cell type")
niche.plot <- ImageDimPlot(xenium.obj, group.by = "niches", size = 1.5, dark.background = F) + ggtitle("Niches") +
    scale_fill_manual(values = c("#442288", "#6CA2EA", "#B5D33D", "#FED23F", "#EB7D5B"))
celltype.plot | niche.plot
```

Example 125 (unknown):
```unknown
table(xenium.obj$predicted.celltype, xenium.obj$niches)
```

Example 126 (r):
```r
table(xenium.obj$predicted.celltype, xenium.obj$niches)
```

Example 127 (r):
```r
table(xenium.obj$predicted.celltype, xenium.obj$niches)
```

Example 128 (unknown):
```unknown
##             
##                 1    2    3    4    5
##   Astro       115  484  241  146   89
##   Endo         27  250   66   62   45
##   L2-3 IT       0 1749   14    5    6
##   L4            2 2163    3   94   14
##   L5 IT         2   66    2  627   84
##   L5 PT         2   92    4  711   21
##   L6 CT        82    2    0   34  857
##   L6 IT         4   22    1   56  275
##   L6b          95    0    0    2    2
##   Lamp5         4   77   61    8    7
##   Macrophage    7   48   15   16   10
##   Meis2         0    0    0    0    0
##   NP            0    1    0   78    9
##   Oligo       305  130   42   76   70
##   Peri          6   40    4   10   12
##   Pvalb         5  155    0   75   54
##   Serpinf1      0    5    0    1    1
##   SMC           2   34    2   12    2
##   Sncg          3   15    1    0    5
##   Sst           0   53    0   55   26
##   Vip           3   85    5   14    4
##   VLMC          2   31  257    7    2
```

Example 129 (unknown):
```unknown
##             
##                 1    2    3    4    5
##   Astro       115  484  241  146   89
##   Endo         27  250   66   62   45
##   L2-3 IT       0 1749   14    5    6
##   L4            2 2163    3   94   14
##   L5 IT         2   66    2  627   84
##   L5 PT         2   92    4  711   21
##   L6 CT        82    2    0   34  857
##   L6 IT         4   22    1   56  275
##   L6b          95    0    0    2    2
##   Lamp5         4   77   61    8    7
##   Macrophage    7   48   15   16   10
##   Meis2         0    0    0    0    0
##   NP            0    1    0   78    9
##   Oligo       305  130   42   76   70
##   Peri          6   40    4   10   12
##   Pvalb         5  155    0   75   54
##   Serpinf1      0    5    0    1    1
##   SMC           2   34    2   12    2
##   Sncg          3   15    1    0    5
##   Sst           0   53    0   55   26
##   Vip           3   85    5   14    4
##   VLMC          2   31  257    7    2
```

Example 130 (unknown):
```unknown
LoadNanostring()
```

Example 131 (unknown):
```unknown
nano.obj <- LoadNanostring(data.dir = "/brahms/hartmana/vignette_data/nanostring/lung5_rep1", fov = "lung5.rep1")
```

Example 132 (r):
```r
nano.obj <- LoadNanostring(data.dir = "/brahms/hartmana/vignette_data/nanostring/lung5_rep1", fov = "lung5.rep1")
```

Example 133 (r):
```r
nano.obj <- LoadNanostring(data.dir = "/brahms/hartmana/vignette_data/nanostring/lung5_rep1", fov = "lung5.rep1")
```

Example 134 (python):
```python
# add in precomputed Azimuth annotations
azimuth.data <- readRDS("/brahms/hartmana/vignette_data/nanostring_data.Rds")
nano.obj <- AddMetaData(nano.obj, metadata = azimuth.data$annotations)
nano.obj[["proj.umap"]] <- azimuth.data$umap
Idents(nano.obj) <- nano.obj$predicted.annotation.l1

nano.obj <- SCTransform(nano.obj, assay = "Nanostring", clip.range = c(-10, 10), verbose = FALSE)

# text display of annotations and prediction scores
head(slot(object = nano.obj, name = "meta.data")[2:5])
```

Example 135 (r):
```r
# add in precomputed Azimuth annotations
azimuth.data <- readRDS("/brahms/hartmana/vignette_data/nanostring_data.Rds")
nano.obj <- AddMetaData(nano.obj, metadata = azimuth.data$annotations)
nano.obj[["proj.umap"]] <- azimuth.data$umap
Idents(nano.obj) <- nano.obj$predicted.annotation.l1

nano.obj <- SCTransform(nano.obj, assay = "Nanostring", clip.range = c(-10, 10), verbose = FALSE)

# text display of annotations and prediction scores
head(slot(object = nano.obj, name = "meta.data")[2:5])
```

Example 136 (r):
```r
# add in precomputed Azimuth annotations
azimuth.data <- readRDS("/brahms/hartmana/vignette_data/nanostring_data.Rds")
nano.obj <- AddMetaData(nano.obj, metadata = azimuth.data$annotations)
nano.obj[["proj.umap"]] <- azimuth.data$umap
Idents(nano.obj) <- nano.obj$predicted.annotation.l1

nano.obj <- SCTransform(nano.obj, assay = "Nanostring", clip.range = c(-10, 10), verbose = FALSE)

# text display of annotations and prediction scores
head(slot(object = nano.obj, name = "meta.data")[2:5])
```

Example 137 (unknown):
```unknown
##     nCount_Nanostring nFeature_Nanostring predicted.annotation.l1
## 1_1                23                  19               Dendritic
## 2_1                26                  23              Macrophage
## 3_1                74                  51          Neuroendocrine
## 4_1                60                  48              Macrophage
## 5_1                52                  39              Macrophage
## 6_1                 5                   5                   CD4 T
##     predicted.annotation.l1.score
## 1_1                     0.5884506
## 2_1                     0.5707920
## 3_1                     0.5449661
## 4_1                     0.6951970
## 5_1                     0.8155319
## 6_1                     0.5677324
```

Example 138 (unknown):
```unknown
##     nCount_Nanostring nFeature_Nanostring predicted.annotation.l1
## 1_1                23                  19               Dendritic
## 2_1                26                  23              Macrophage
## 3_1                74                  51          Neuroendocrine
## 4_1                60                  48              Macrophage
## 5_1                52                  39              Macrophage
## 6_1                 5                   5                   CD4 T
##     predicted.annotation.l1.score
## 1_1                     0.5884506
## 2_1                     0.5707920
## 3_1                     0.5449661
## 4_1                     0.6951970
## 5_1                     0.8155319
## 6_1                     0.5677324
```

Example 139 (unknown):
```unknown
DimPlot(nano.obj)
```

Example 140 (r):
```r
DimPlot(nano.obj)
```

Example 141 (r):
```r
DimPlot(nano.obj)
```

Example 142 (unknown):
```unknown
ImageDimPlot()
```

Example 143 (unknown):
```unknown
ImageDimPlot(nano.obj, fov = "lung5.rep1", axes = TRUE, cols = "glasbey")
```

Example 144 (r):
```r
ImageDimPlot(nano.obj, fov = "lung5.rep1", axes = TRUE, cols = "glasbey")
```

Example 145 (r):
```r
ImageDimPlot(nano.obj, fov = "lung5.rep1", axes = TRUE, cols = "glasbey")
```

Example 146 (unknown):
```unknown
ImageDimPlot(nano.obj, fov = "lung5.rep1", cells = WhichCells(nano.obj, idents = c("Basal", "Macrophage",
    "Smooth Muscle", "CD4 T")), cols = c("red", "green", "blue", "orange"), size = 0.6)
```

Example 147 (r):
```r
ImageDimPlot(nano.obj, fov = "lung5.rep1", cells = WhichCells(nano.obj, idents = c("Basal", "Macrophage",
    "Smooth Muscle", "CD4 T")), cols = c("red", "green", "blue", "orange"), size = 0.6)
```

Example 148 (r):
```r
ImageDimPlot(nano.obj, fov = "lung5.rep1", cells = WhichCells(nano.obj, idents = c("Basal", "Macrophage",
    "Smooth Muscle", "CD4 T")), cols = c("red", "green", "blue", "orange"), size = 0.6)
```

Example 149 (unknown):
```unknown
VlnPlot(nano.obj, features = "KRT17", assay = "Nanostring", layer = "counts", pt.size = 0.1, y.max = 30) +
    NoLegend()
```

Example 150 (r):
```r
VlnPlot(nano.obj, features = "KRT17", assay = "Nanostring", layer = "counts", pt.size = 0.1, y.max = 30) +
    NoLegend()
```

Example 151 (r):
```r
VlnPlot(nano.obj, features = "KRT17", assay = "Nanostring", layer = "counts", pt.size = 0.1, y.max = 30) +
    NoLegend()
```

Example 152 (unknown):
```unknown
FeaturePlot(nano.obj, features = "KRT17", max.cutoff = "q95")
```

Example 153 (r):
```r
FeaturePlot(nano.obj, features = "KRT17", max.cutoff = "q95")
```

Example 154 (r):
```r
FeaturePlot(nano.obj, features = "KRT17", max.cutoff = "q95")
```

Example 155 (unknown):
```unknown
p1 <- ImageFeaturePlot(nano.obj, fov = "lung5.rep1", features = "KRT17", max.cutoff = "q95")
p2 <- ImageDimPlot(nano.obj, fov = "lung5.rep1", alpha = 0.3, molecules = "KRT17", nmols = 10000) +
    NoLegend()
p1 + p2
```

Example 156 (r):
```r
p1 <- ImageFeaturePlot(nano.obj, fov = "lung5.rep1", features = "KRT17", max.cutoff = "q95")
p2 <- ImageDimPlot(nano.obj, fov = "lung5.rep1", alpha = 0.3, molecules = "KRT17", nmols = 10000) +
    NoLegend()
p1 + p2
```

Example 157 (r):
```r
p1 <- ImageFeaturePlot(nano.obj, fov = "lung5.rep1", features = "KRT17", max.cutoff = "q95")
p2 <- ImageDimPlot(nano.obj, fov = "lung5.rep1", alpha = 0.3, molecules = "KRT17", nmols = 10000) +
    NoLegend()
p1 + p2
```

Example 158 (unknown):
```unknown
# Plot some of the molecules which seem to display spatial correlation with each other
ImageDimPlot(nano.obj, fov = "lung5.rep1", group.by = NA, alpha = 0.3, molecules = c("KRT17", "C1QA",
    "IL7R", "TAGLN"), nmols = 20000)
```

Example 159 (r):
```r
# Plot some of the molecules which seem to display spatial correlation with each other
ImageDimPlot(nano.obj, fov = "lung5.rep1", group.by = NA, alpha = 0.3, molecules = c("KRT17", "C1QA",
    "IL7R", "TAGLN"), nmols = 20000)
```

Example 160 (r):
```r
# Plot some of the molecules which seem to display spatial correlation with each other
ImageDimPlot(nano.obj, fov = "lung5.rep1", group.by = NA, alpha = 0.3, molecules = c("KRT17", "C1QA",
    "IL7R", "TAGLN"), nmols = 20000)
```

Example 161 (unknown):
```unknown
basal.crop <- Crop(nano.obj[["lung5.rep1"]], x = c(159500, 164000), y = c(8700, 10500))
nano.obj[["zoom1"]] <- basal.crop
DefaultBoundary(nano.obj[["zoom1"]]) <- "segmentation"
```

Example 162 (r):
```r
basal.crop <- Crop(nano.obj[["lung5.rep1"]], x = c(159500, 164000), y = c(8700, 10500))
nano.obj[["zoom1"]] <- basal.crop
DefaultBoundary(nano.obj[["zoom1"]]) <- "segmentation"
```

Example 163 (r):
```r
basal.crop <- Crop(nano.obj[["lung5.rep1"]], x = c(159500, 164000), y = c(8700, 10500))
nano.obj[["zoom1"]] <- basal.crop
DefaultBoundary(nano.obj[["zoom1"]]) <- "segmentation"
```

Example 164 (unknown):
```unknown
ImageDimPlot(nano.obj, fov = "zoom1", cols = "polychrome", coord.fixed = FALSE)
```

Example 165 (r):
```r
ImageDimPlot(nano.obj, fov = "zoom1", cols = "polychrome", coord.fixed = FALSE)
```

Example 166 (r):
```r
ImageDimPlot(nano.obj, fov = "zoom1", cols = "polychrome", coord.fixed = FALSE)
```

Example 167 (unknown):
```unknown
# note the clouds of TPSAB1 molecules denoting mast cells
ImageDimPlot(nano.obj, fov = "zoom1", cols = "polychrome", alpha = 0.3, molecules = c("KRT17", "IL7R",
    "TPSAB1"), mols.size = 0.3, nmols = 20000, border.color = "black", coord.fixed = FALSE)
```

Example 168 (r):
```r
# note the clouds of TPSAB1 molecules denoting mast cells
ImageDimPlot(nano.obj, fov = "zoom1", cols = "polychrome", alpha = 0.3, molecules = c("KRT17", "IL7R",
    "TPSAB1"), mols.size = 0.3, nmols = 20000, border.color = "black", coord.fixed = FALSE)
```

Example 169 (r):
```r
# note the clouds of TPSAB1 molecules denoting mast cells
ImageDimPlot(nano.obj, fov = "zoom1", cols = "polychrome", alpha = 0.3, molecules = c("KRT17", "IL7R",
    "TPSAB1"), mols.size = 0.3, nmols = 20000, border.color = "black", coord.fixed = FALSE)
```

Example 170 (unknown):
```unknown
LoadAkoya()
```

Example 171 (unknown):
```unknown
codex.obj <- LoadAkoya(filename = "/brahms/hartmana/vignette_data/LN7910_20_008_11022020_reg001_compensated.csv",
    type = "processor", fov = "HBM754.WKLP.262")
```

Example 172 (r):
```r
codex.obj <- LoadAkoya(filename = "/brahms/hartmana/vignette_data/LN7910_20_008_11022020_reg001_compensated.csv",
    type = "processor", fov = "HBM754.WKLP.262")
```

Example 173 (r):
```r
codex.obj <- LoadAkoya(filename = "/brahms/hartmana/vignette_data/LN7910_20_008_11022020_reg001_compensated.csv",
    type = "processor", fov = "HBM754.WKLP.262")
```

Example 174 (unknown):
```unknown
codex.obj <- NormalizeData(object = codex.obj, normalization.method = "CLR", margin = 2)
codex.obj <- ScaleData(codex.obj)
VariableFeatures(codex.obj) <- rownames(codex.obj)  # since the panel is small, treat all features as variable.
codex.obj <- RunPCA(object = codex.obj, npcs = 20, verbose = FALSE)
codex.obj <- RunUMAP(object = codex.obj, dims = 1:20, verbose = FALSE)
codex.obj <- FindNeighbors(object = codex.obj, dims = 1:20, verbose = FALSE)
codex.obj <- FindClusters(object = codex.obj, verbose = FALSE, resolution = 0.4, n.start = 1)
```

Example 175 (r):
```r
codex.obj <- NormalizeData(object = codex.obj, normalization.method = "CLR", margin = 2)
codex.obj <- ScaleData(codex.obj)
VariableFeatures(codex.obj) <- rownames(codex.obj)  # since the panel is small, treat all features as variable.
codex.obj <- RunPCA(object = codex.obj, npcs = 20, verbose = FALSE)
codex.obj <- RunUMAP(object = codex.obj, dims = 1:20, verbose = FALSE)
codex.obj <- FindNeighbors(object = codex.obj, dims = 1:20, verbose = FALSE)
codex.obj <- FindClusters(object = codex.obj, verbose = FALSE, resolution = 0.4, n.start = 1)
```

Example 176 (r):
```r
codex.obj <- NormalizeData(object = codex.obj, normalization.method = "CLR", margin = 2)
codex.obj <- ScaleData(codex.obj)
VariableFeatures(codex.obj) <- rownames(codex.obj)  # since the panel is small, treat all features as variable.
codex.obj <- RunPCA(object = codex.obj, npcs = 20, verbose = FALSE)
codex.obj <- RunUMAP(object = codex.obj, dims = 1:20, verbose = FALSE)
codex.obj <- FindNeighbors(object = codex.obj, dims = 1:20, verbose = FALSE)
codex.obj <- FindClusters(object = codex.obj, verbose = FALSE, resolution = 0.4, n.start = 1)
```

Example 177 (unknown):
```unknown
DimPlot(codex.obj, label = TRUE, label.box = TRUE) + NoLegend()
```

Example 178 (r):
```r
DimPlot(codex.obj, label = TRUE, label.box = TRUE) + NoLegend()
```

Example 179 (r):
```r
DimPlot(codex.obj, label = TRUE, label.box = TRUE) + NoLegend()
```

Example 180 (unknown):
```unknown
ImageDimPlot(codex.obj, cols = "parade")
```

Example 181 (r):
```r
ImageDimPlot(codex.obj, cols = "parade")
```

Example 182 (r):
```r
ImageDimPlot(codex.obj, cols = "parade")
```

Example 183 (unknown):
```unknown
p1 <- ImageFeaturePlot(codex.obj, fov = "HBM754.WKLP.262", features = c("CD34", "CD21", "Lyve1"),
    min.cutoff = "q10", max.cutoff = "q90")
p2 <- ImageDimPlot(codex.obj, fov = "HBM754.WKLP.262", cols = "parade")
p1 + p2
```

Example 184 (r):
```r
p1 <- ImageFeaturePlot(codex.obj, fov = "HBM754.WKLP.262", features = c("CD34", "CD21", "Lyve1"),
    min.cutoff = "q10", max.cutoff = "q90")
p2 <- ImageDimPlot(codex.obj, fov = "HBM754.WKLP.262", cols = "parade")
p1 + p2
```

Example 185 (r):
```r
p1 <- ImageFeaturePlot(codex.obj, fov = "HBM754.WKLP.262", features = c("CD34", "CD21", "Lyve1"),
    min.cutoff = "q10", max.cutoff = "q90")
p2 <- ImageDimPlot(codex.obj, fov = "HBM754.WKLP.262", cols = "parade")
p1 + p2
```

Example 186 (unknown):
```unknown
sessionInfo()
```

Example 187 (r):
```r
sessionInfo()
```

Example 188 (r):
```r
sessionInfo()
```

Example 189 (unknown):
```unknown
## R version 4.4.2 (2024-10-31)
## Platform: x86_64-pc-linux-gnu
## Running under: Ubuntu 20.04.6 LTS
## 
## Matrix products: default
## BLAS:   /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.9.0 
## LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.9.0
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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: America/New_York
## tzcode source: system (glibc)
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
## [1] spacexr_2.2.1      ggplot2_3.5.2      future_1.67.0      Seurat_5.3.1 
## [5] SeuratObject_5.1.0 sp_2.2-0          
## 
## loaded via a namespace (and not attached):
##   [1] RcppAnnoy_0.0.22            splines_4.4.2              
##   [3] later_1.4.2                 tibble_3.2.1               
##   [5] R.oo_1.27.1                 polyclip_1.10-7            
##   [7] fastDummies_1.7.5           lifecycle_1.0.4            
##   [9] sf_1.0-21                   doParallel_1.0.17          
##  [11] globals_0.18.0              lattice_0.22-7             
##  [13] hdf5r_1.3.12                MASS_7.3-65                
##  [15] magrittr_2.0.3              plotly_4.10.4              
##  [17] sass_0.4.10                 rmarkdown_2.29             
##  [19] jquerylib_0.1.4             yaml_2.3.10                
##  [21] httpuv_1.6.16               glmGamPoi_1.18.0           
##  [23] sctransform_0.4.2           spam_2.11-1                
##  [25] spatstat.sparse_3.1-0       reticulate_1.42.0          
##  [27] cowplot_1.1.3               pbapply_1.7-2              
##  [29] DBI_1.2.3                   RColorBrewer_1.1-3         
##  [31] abind_1.4-8                 zlibbioc_1.52.0            
##  [33] Rtsne_0.17                  GenomicRanges_1.58.0       
##  [35] purrr_1.0.4                 presto_1.0.0               
##  [37] R.utils_2.13.0              BiocGenerics_0.52.0        
##  [39] GenomeInfoDbData_1.2.13     IRanges_2.40.1             
##  [41] S4Vectors_0.44.0            ggrepel_0.9.6              
##  [43] irlba_2.3.5.1               listenv_0.9.1              
##  [45] spatstat.utils_3.1-4        units_0.8-7                
##  [47] goftest_1.2-3               RSpectra_0.16-2            
##  [49] spatstat.random_3.4-1       fitdistrplus_1.2-2         
##  [51] parallelly_1.45.1           pkgdown_2.1.3              
##  [53] codetools_0.2-20            DelayedArray_0.32.0        
##  [55] tidyselect_1.2.1            UCSC.utils_1.2.0           
##  [57] farver_2.1.2                matrixStats_1.5.0          
##  [59] stats4_4.4.2                spatstat.explore_3.4-3     
##  [61] jsonlite_2.0.0              e1071_1.7-16               
##  [63] progressr_0.15.1            iterators_1.0.14           
##  [65] ggridges_0.5.6              survival_3.8-3             
##  [67] systemfonts_1.2.3           foreach_1.5.2              
##  [69] tools_4.4.2                 ragg_1.4.0                 
##  [71] ica_1.0-3                   Rcpp_1.1.0                 
##  [73] glue_1.8.0                  gridExtra_2.3              
##  [75] SparseArray_1.6.2           xfun_0.52                  
##  [77] MatrixGenerics_1.18.1       GenomeInfoDb_1.42.3        
##  [79] dplyr_1.1.4                 withr_3.0.2                
##  [81] formatR_1.14                fastmap_1.2.0              
##  [83] digest_0.6.37               R6_2.6.1                   
##  [85] mime_0.13                   textshaping_1.0.1          
##  [87] Cairo_1.6-2                 scattermore_1.2            
##  [89] tensor_1.5                  dichromat_2.0-0.1          
##  [91] spatstat.data_3.1-6         R.methodsS3_1.8.2          
##  [93] tidyr_1.3.1                 generics_0.1.4             
##  [95] data.table_1.17.4           class_7.3-23               
##  [97] httr_1.4.7                  htmlwidgets_1.6.4          
##  [99] S4Arrays_1.6.0              uwot_0.2.3                 
## [101] pkgconfig_2.0.3             gtable_0.3.6               
## [103] lmtest_0.9-40               XVector_0.46.0             
## [105] htmltools_0.5.8.1           dotCall64_1.2              
## [107] scales_1.4.0                Biobase_2.66.0             
## [109] png_0.1-8                   spatstat.univar_3.1-3      
## [111] knitr_1.50                  rstudioapi_0.17.1          
## [113] reshape2_1.4.4              nlme_3.1-168               
## [115] proxy_0.4-27                cachem_1.1.0               
## [117] zoo_1.8-14                  stringr_1.5.1              
## [119] KernSmooth_2.23-26          vipor_0.4.7                
## [121] parallel_4.4.2              miniUI_0.1.2               
## [123] arrow_21.0.0                ggrastr_1.0.2              
## [125] desc_1.4.3                  pillar_1.10.2              
## [127] grid_4.4.2                  vctrs_0.6.5                
## [129] RANN_2.6.2                  promises_1.3.3             
## [131] xtable_1.8-4                cluster_2.1.8.1            
## [133] beeswarm_0.4.0              evaluate_1.0.3             
## [135] cli_3.6.5                   compiler_4.4.2             
## [137] rlang_1.1.6                 crayon_1.5.3               
## [139] future.apply_1.20.0         labeling_0.4.3             
## [141] classInt_0.4-11             ggbeeswarm_0.7.2           
## [143] plyr_1.8.9                  fs_1.6.6                   
## [145] stringi_1.8.7               viridisLite_0.4.2          
## [147] deldir_2.0-4                assertthat_0.2.1           
## [149] lazyeval_0.2.2              spatstat.geom_3.4-1        
## [151] Matrix_1.7-3                RcppHNSW_0.6.0             
## [153] patchwork_1.3.0             bit64_4.6.0-1              
## [155] shiny_1.10.0                SummarizedExperiment_1.36.0
## [157] ROCR_1.0-11                 igraph_2.1.4               
## [159] bslib_0.9.0                 bit_4.6.0
```

Example 190 (unknown):
```unknown
## R version 4.4.2 (2024-10-31)
## Platform: x86_64-pc-linux-gnu
## Running under: Ubuntu 20.04.6 LTS
## 
## Matrix products: default
## BLAS:   /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.9.0 
## LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.9.0
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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: America/New_York
## tzcode source: system (glibc)
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
## [1] spacexr_2.2.1      ggplot2_3.5.2      future_1.67.0      Seurat_5.3.1 
## [5] SeuratObject_5.1.0 sp_2.2-0          
## 
## loaded via a namespace (and not attached):
##   [1] RcppAnnoy_0.0.22            splines_4.4.2              
##   [3] later_1.4.2                 tibble_3.2.1               
##   [5] R.oo_1.27.1                 polyclip_1.10-7            
##   [7] fastDummies_1.7.5           lifecycle_1.0.4            
##   [9] sf_1.0-21                   doParallel_1.0.17          
##  [11] globals_0.18.0              lattice_0.22-7             
##  [13] hdf5r_1.3.12                MASS_7.3-65                
##  [15] magrittr_2.0.3              plotly_4.10.4              
##  [17] sass_0.4.10                 rmarkdown_2.29             
##  [19] jquerylib_0.1.4             yaml_2.3.10                
##  [21] httpuv_1.6.16               glmGamPoi_1.18.0           
##  [23] sctransform_0.4.2           spam_2.11-1                
##  [25] spatstat.sparse_3.1-0       reticulate_1.42.0          
##  [27] cowplot_1.1.3               pbapply_1.7-2              
##  [29] DBI_1.2.3                   RColorBrewer_1.1-3         
##  [31] abind_1.4-8                 zlibbioc_1.52.0            
##  [33] Rtsne_0.17                  GenomicRanges_1.58.0       
##  [35] purrr_1.0.4                 presto_1.0.0               
##  [37] R.utils_2.13.0              BiocGenerics_0.52.0        
##  [39] GenomeInfoDbData_1.2.13     IRanges_2.40.1             
##  [41] S4Vectors_0.44.0            ggrepel_0.9.6              
##  [43] irlba_2.3.5.1               listenv_0.9.1              
##  [45] spatstat.utils_3.1-4        units_0.8-7                
##  [47] goftest_1.2-3               RSpectra_0.16-2            
##  [49] spatstat.random_3.4-1       fitdistrplus_1.2-2         
##  [51] parallelly_1.45.1           pkgdown_2.1.3              
##  [53] codetools_0.2-20            DelayedArray_0.32.0        
##  [55] tidyselect_1.2.1            UCSC.utils_1.2.0           
##  [57] farver_2.1.2                matrixStats_1.5.0          
##  [59] stats4_4.4.2                spatstat.explore_3.4-3     
##  [61] jsonlite_2.0.0              e1071_1.7-16               
##  [63] progressr_0.15.1            iterators_1.0.14           
##  [65] ggridges_0.5.6              survival_3.8-3             
##  [67] systemfonts_1.2.3           foreach_1.5.2              
##  [69] tools_4.4.2                 ragg_1.4.0                 
##  [71] ica_1.0-3                   Rcpp_1.1.0                 
##  [73] glue_1.8.0                  gridExtra_2.3              
##  [75] SparseArray_1.6.2           xfun_0.52                  
##  [77] MatrixGenerics_1.18.1       GenomeInfoDb_1.42.3        
##  [79] dplyr_1.1.4                 withr_3.0.2                
##  [81] formatR_1.14                fastmap_1.2.0              
##  [83] digest_0.6.37               R6_2.6.1                   
##  [85] mime_0.13                   textshaping_1.0.1          
##  [87] Cairo_1.6-2                 scattermore_1.2            
##  [89] tensor_1.5                  dichromat_2.0-0.1          
##  [91] spatstat.data_3.1-6         R.methodsS3_1.8.2          
##  [93] tidyr_1.3.1                 generics_0.1.4             
##  [95] data.table_1.17.4           class_7.3-23               
##  [97] httr_1.4.7                  htmlwidgets_1.6.4          
##  [99] S4Arrays_1.6.0              uwot_0.2.3                 
## [101] pkgconfig_2.0.3             gtable_0.3.6               
## [103] lmtest_0.9-40               XVector_0.46.0             
## [105] htmltools_0.5.8.1           dotCall64_1.2              
## [107] scales_1.4.0                Biobase_2.66.0             
## [109] png_0.1-8                   spatstat.univar_3.1-3      
## [111] knitr_1.50                  rstudioapi_0.17.1          
## [113] reshape2_1.4.4              nlme_3.1-168               
## [115] proxy_0.4-27                cachem_1.1.0               
## [117] zoo_1.8-14                  stringr_1.5.1              
## [119] KernSmooth_2.23-26          vipor_0.4.7                
## [121] parallel_4.4.2              miniUI_0.1.2               
## [123] arrow_21.0.0                ggrastr_1.0.2              
## [125] desc_1.4.3                  pillar_1.10.2              
## [127] grid_4.4.2                  vctrs_0.6.5                
## [129] RANN_2.6.2                  promises_1.3.3             
## [131] xtable_1.8-4                cluster_2.1.8.1            
## [133] beeswarm_0.4.0              evaluate_1.0.3             
## [135] cli_3.6.5                   compiler_4.4.2             
## [137] rlang_1.1.6                 crayon_1.5.3               
## [139] future.apply_1.20.0         labeling_0.4.3             
## [141] classInt_0.4-11             ggbeeswarm_0.7.2           
## [143] plyr_1.8.9                  fs_1.6.6                   
## [145] stringi_1.8.7               viridisLite_0.4.2          
## [147] deldir_2.0-4                assertthat_0.2.1           
## [149] lazyeval_0.2.2              spatstat.geom_3.4-1        
## [151] Matrix_1.7-3                RcppHNSW_0.6.0             
## [153] patchwork_1.3.0             bit64_4.6.0-1              
## [155] shiny_1.10.0                SummarizedExperiment_1.36.0
## [157] ROCR_1.0-11                 igraph_2.1.4               
## [159] bslib_0.9.0                 bit_4.6.0
```

---

## Analysis, visualization, and integration of Visium HD spatial datasets with Seurat • Seurat

**URL:** http://127.0.0.1:9173/seurat/articles/seurat5_bpcells_interaction_vignette/index.html

**Contents:**
- Using BPCells with Seurat Objects
    - Compiled: October 20, 2023
- Load Data
  - Load Data from one h5 file
    - Example Analsyis
    - Saving Seurat objects with on-disk layers
  - Load data from multiple h5ad files
  - Parse Biosciences
- Contents

BPCells is an R package that allows for computationally efficient single-cell analysis. It utilizes bit-packing compression to store counts matrices on disk and C++ code to cache operations.

We leverage the high performance capabilities of BPCells to work with Seurat objects in memory while accessing the counts on disk. In this vignette, we show how to use BPCells to load data, work with a Seurat objects in a more memory-efficient way, and write out Seurat objects with BPCells matrices.

We will show the methods for interacting with both a single dataset in one file or multiple datasets across multiple files using BPCells. BPCells allows us to easily analyze these large datasets in memory, and we encourage users to check out some of our other vignettes here and here to see further applications.

We use BPCells functionality to both load in our data and write the counts layers to bitpacked compressed binary files on disk to improve computation speeds. BPCells has multiple functions for reading in files.

In this section, we will load a dataset of mouse brain cells freely available from 10x Genomics. This includes 1.3 Million single cells that were sequenced on the Illumina NovaSeq 6000. The raw data can be found here.

To read in the file, we will use open_matrix_10x_hdf5, a BPCells function written to read in feature matrices from 10x. We then write a matrix directory, load the matrix, and create a Seurat object.

What if I already have a Seurat Object?

You can use BPCells to convert the matrices in your already created Seurat objects to on-disk matrices. Note, that this is only possible for V5 assays. As an example, if you’d like to convert the counts matrix of your RNA assay to a BPCells matrix, you can use the following:

Once this conversion is done, you can perform typical Seurat functions on the object. For example, we can normalize data and visualize features by automatically accessing the on-disk counts.

If you save your object and load it in in the future, Seurat will access the on-disk matrices by their path, which is stored in the assay level data. saveRDS() can still be used to save your Seurat objects with on-disk matrices as shown below. Note, if you move the object across computers or to a place that no longer has access to the paths where the on-disk matrices are stored, you will have to move the folders that contain the on-disk matrices as well. We are actively working on functionality to make this process easier for users.

If needed, a layer with an on-disk matrix can be converted to an in-memory matrix using the as() function. For the purposes of this demo, we’ll subset the object so that it takes up less space in memory.

You can also download data from multiple matrices. In this section, we create a Seurat object using multiple peripheral blood mononuclear cell (PBMC) samples that are freely available for download from CZI here. We download data from Ahern et al. (2022) Nature, Jin et al. (2021) Science, and Yoshida et al. (2022) Nature. We use the BPCells function to read h5ad files.

When we create the Seurat object with the list of matrices from each publication, we can then see that multiple counts layers exist that represent each dataset. This object contains over a million cells, yet only takes up minimal space in memory!

Here, we show how to load a 1 million cell data set from Parse Biosciences and create a Seurat Object. The data is available for download here

Developed by Paul Hoffman, Satija Lab and Collaborators.

Site built with pkgdown 2.0.7.

**Examples:**

Example 1 (unknown):
```unknown
vignettes/v5/seurat5_bpcells_interaction_vignette.Rmd
```

Example 2 (unknown):
```unknown
seurat5_bpcells_interaction_vignette.Rmd
```

Example 3 (unknown):
```unknown
library(BPCells)
library(Seurat)
library(SeuratObject)
library(SeuratDisk)
library(Azimuth)
```

Example 4 (r):
```r
library(BPCells)
library(Seurat)
library(SeuratObject)
library(SeuratDisk)
library(Azimuth)
```

Example 5 (unknown):
```unknown
brain.data <- open_matrix_10x_hdf5(
  path = "/brahms/hartmana/vignette_data/1M_neurons_filtered_gene_bc_matrices_h5.h5"
)
# Write the matrix to a directory
 write_matrix_dir(
   mat = brain.data,
   dir = '/brahms/hartmana/vignette_data/bpcells/brain_counts')
# Now that we have the matrix on disk, we can load it
brain.mat <- open_matrix_dir(dir = "/brahms/hartmana/vignette_data/bpcells/brain_counts")
brain.mat <- Azimuth:::ConvertEnsembleToSymbol(mat = brain.mat, species = "mouse")

# Create Seurat Object
brain <- CreateSeuratObject(counts = brain.mat)
```

Example 6 (r):
```r
brain.data <- open_matrix_10x_hdf5(
  path = "/brahms/hartmana/vignette_data/1M_neurons_filtered_gene_bc_matrices_h5.h5"
)
# Write the matrix to a directory
 write_matrix_dir(
   mat = brain.data,
   dir = '/brahms/hartmana/vignette_data/bpcells/brain_counts')
# Now that we have the matrix on disk, we can load it
brain.mat <- open_matrix_dir(dir = "/brahms/hartmana/vignette_data/bpcells/brain_counts")
brain.mat <- Azimuth:::ConvertEnsembleToSymbol(mat = brain.mat, species = "mouse")

# Create Seurat Object
brain <- CreateSeuratObject(counts = brain.mat)
```

Example 7 (r):
```r
brain.data <- open_matrix_10x_hdf5(
  path = "/brahms/hartmana/vignette_data/1M_neurons_filtered_gene_bc_matrices_h5.h5"
)
# Write the matrix to a directory
 write_matrix_dir(
   mat = brain.data,
   dir = '/brahms/hartmana/vignette_data/bpcells/brain_counts')
# Now that we have the matrix on disk, we can load it
brain.mat <- open_matrix_dir(dir = "/brahms/hartmana/vignette_data/bpcells/brain_counts")
brain.mat <- Azimuth:::ConvertEnsembleToSymbol(mat = brain.mat, species = "mouse")

# Create Seurat Object
brain <- CreateSeuratObject(counts = brain.mat)
```

Example 8 (unknown):
```unknown
write_matrix_dir(
```

Example 9 (unknown):
```unknown
mat = brain.data,
```

Example 10 (unknown):
```unknown
dir = '/brahms/hartmana/vignette_data/bpcells/brain_counts')
```

Example 11 (unknown):
```unknown
# obj <- readRDS("/path/to/reference.rds")

# # Write the counts layer to a directory
 write_matrix_dir(mat = obj[["RNA"]]$counts, dir = '/brahms/hartmana/vignette_data/bpcells/brain_counts')
 counts.mat <- open_matrix_dir(dir = "/brahms/hartmana/vignette_data/bpcells/brain_counts")

# obj[["RNA"]]$counts <- counts.mat
```

Example 12 (r):
```r
# obj <- readRDS("/path/to/reference.rds")

# # Write the counts layer to a directory
 write_matrix_dir(mat = obj[["RNA"]]$counts, dir = '/brahms/hartmana/vignette_data/bpcells/brain_counts')
 counts.mat <- open_matrix_dir(dir = "/brahms/hartmana/vignette_data/bpcells/brain_counts")

# obj[["RNA"]]$counts <- counts.mat
```

Example 13 (r):
```r
# obj <- readRDS("/path/to/reference.rds")

# # Write the counts layer to a directory
 write_matrix_dir(mat = obj[["RNA"]]$counts, dir = '/brahms/hartmana/vignette_data/bpcells/brain_counts')
 counts.mat <- open_matrix_dir(dir = "/brahms/hartmana/vignette_data/bpcells/brain_counts")

# obj[["RNA"]]$counts <- counts.mat
```

Example 14 (unknown):
```unknown
write_matrix_dir(mat = obj[["RNA"]]$counts, dir = '/brahms/hartmana/vignette_data/bpcells/brain_counts')
```

Example 15 (unknown):
```unknown
counts.mat <- open_matrix_dir(dir = "/brahms/hartmana/vignette_data/bpcells/brain_counts")
```

Example 16 (unknown):
```unknown
VlnPlot(brain, features = c("Sox10", "Slc17a7", "Aif1"), ncol = 3, layer = "counts", alpha = 0.1)
```

Example 17 (r):
```r
VlnPlot(brain, features = c("Sox10", "Slc17a7", "Aif1"), ncol = 3, layer = "counts", alpha = 0.1)
```

Example 18 (r):
```r
VlnPlot(brain, features = c("Sox10", "Slc17a7", "Aif1"), ncol = 3, layer = "counts", alpha = 0.1)
```

Example 19 (unknown):
```unknown
# We then normalize and visualize again
brain <- NormalizeData(brain, normalization.method = "LogNormalize")
VlnPlot(brain, features = c("Sox10", "Slc17a7", "Aif1"), ncol = 3, layer = "data", alpha = 0.1)
```

Example 20 (r):
```r
# We then normalize and visualize again
brain <- NormalizeData(brain, normalization.method = "LogNormalize")
VlnPlot(brain, features = c("Sox10", "Slc17a7", "Aif1"), ncol = 3, layer = "data", alpha = 0.1)
```

Example 21 (r):
```r
# We then normalize and visualize again
brain <- NormalizeData(brain, normalization.method = "LogNormalize")
VlnPlot(brain, features = c("Sox10", "Slc17a7", "Aif1"), ncol = 3, layer = "data", alpha = 0.1)
```

Example 22 (unknown):
```unknown
saveRDS(
   object = brain,
   file = "obj.Rds"
)
```

Example 23 (r):
```r
saveRDS(
   object = brain,
   file = "obj.Rds"
)
```

Example 24 (r):
```r
saveRDS(
   object = brain,
   file = "obj.Rds"
)
```

Example 25 (unknown):
```unknown
object = brain,
```

Example 26 (unknown):
```unknown
file = "obj.Rds"
```

Example 27 (unknown):
```unknown
brain <- subset(brain, downsample = 1000)
brain[["RNA"]]$counts <- as(object = brain[["RNA"]]$counts, Class = "dgCMatrix")
```

Example 28 (r):
```r
brain <- subset(brain, downsample = 1000)
brain[["RNA"]]$counts <- as(object = brain[["RNA"]]$counts, Class = "dgCMatrix")
```

Example 29 (r):
```r
brain <- subset(brain, downsample = 1000)
brain[["RNA"]]$counts <- as(object = brain[["RNA"]]$counts, Class = "dgCMatrix")
```

Example 30 (python):
```python
file.dir <- "/brahms/hartmana/vignette_data/h5ad_files/"
files.set <- c("ahern_pbmc.h5ad", "jin_pbmc.h5ad", "yoshida_pbmc.h5ad")

# Loop through h5ad files and output BPCells matrices on-disk
data.list <- c()
metadata.list <- c()

for (i in 1:length(files.set)) {
  path <- paste0(file.dir, files.set[i])
  data <- open_matrix_anndata_hdf5(path)
   write_matrix_dir(
     mat = data,
     dir = paste0(gsub(".h5ad", "", path), "_BP")
   )
  # Load in BP matrices
  mat <- open_matrix_dir(dir = paste0(gsub(".h5ad", "", path), "_BP"))
  mat <- Azimuth:::ConvertEnsembleToSymbol(mat = mat, species = "human")
  # Get metadata
  metadata.list[[i]] <- LoadH5ADobs(path = path)
  data.list[[i]] <- mat
}
# Name layers
names(data.list) <- c("ahern", "jin", "yoshida")

# Add Metadata
for (i in 1:length(metadata.list)) {
  metadata.list[[i]]$publication <- names(data.list)[i]
}
metadata.list <- lapply(metadata.list, function(x) {
  x <- x[, c("publication", "sex", "cell_type", "donor_id", "disease")]
  return(x)
})
metadata <- Reduce(rbind, metadata.list)
```

Example 31 (r):
```r
file.dir <- "/brahms/hartmana/vignette_data/h5ad_files/"
files.set <- c("ahern_pbmc.h5ad", "jin_pbmc.h5ad", "yoshida_pbmc.h5ad")

# Loop through h5ad files and output BPCells matrices on-disk
data.list <- c()
metadata.list <- c()

for (i in 1:length(files.set)) {
  path <- paste0(file.dir, files.set[i])
  data <- open_matrix_anndata_hdf5(path)
   write_matrix_dir(
     mat = data,
     dir = paste0(gsub(".h5ad", "", path), "_BP")
   )
  # Load in BP matrices
  mat <- open_matrix_dir(dir = paste0(gsub(".h5ad", "", path), "_BP"))
  mat <- Azimuth:::ConvertEnsembleToSymbol(mat = mat, species = "human")
  # Get metadata
  metadata.list[[i]] <- LoadH5ADobs(path = path)
  data.list[[i]] <- mat
}
# Name layers
names(data.list) <- c("ahern", "jin", "yoshida")

# Add Metadata
for (i in 1:length(metadata.list)) {
  metadata.list[[i]]$publication <- names(data.list)[i]
}
metadata.list <- lapply(metadata.list, function(x) {
  x <- x[, c("publication", "sex", "cell_type", "donor_id", "disease")]
  return(x)
})
metadata <- Reduce(rbind, metadata.list)
```

Example 32 (r):
```r
file.dir <- "/brahms/hartmana/vignette_data/h5ad_files/"
files.set <- c("ahern_pbmc.h5ad", "jin_pbmc.h5ad", "yoshida_pbmc.h5ad")

# Loop through h5ad files and output BPCells matrices on-disk
data.list <- c()
metadata.list <- c()

for (i in 1:length(files.set)) {
  path <- paste0(file.dir, files.set[i])
  data <- open_matrix_anndata_hdf5(path)
   write_matrix_dir(
     mat = data,
     dir = paste0(gsub(".h5ad", "", path), "_BP")
   )
  # Load in BP matrices
  mat <- open_matrix_dir(dir = paste0(gsub(".h5ad", "", path), "_BP"))
  mat <- Azimuth:::ConvertEnsembleToSymbol(mat = mat, species = "human")
  # Get metadata
  metadata.list[[i]] <- LoadH5ADobs(path = path)
  data.list[[i]] <- mat
}
# Name layers
names(data.list) <- c("ahern", "jin", "yoshida")

# Add Metadata
for (i in 1:length(metadata.list)) {
  metadata.list[[i]]$publication <- names(data.list)[i]
}
metadata.list <- lapply(metadata.list, function(x) {
  x <- x[, c("publication", "sex", "cell_type", "donor_id", "disease")]
  return(x)
})
metadata <- Reduce(rbind, metadata.list)
```

Example 33 (unknown):
```unknown
write_matrix_dir(
```

Example 34 (unknown):
```unknown
mat = data,
```

Example 35 (unknown):
```unknown
dir = paste0(gsub(".h5ad", "", path), "_BP")
```

Example 36 (python):
```python
merged.object <- CreateSeuratObject(counts = data.list, meta.data = metadata)
merged.object
```

Example 37 (r):
```r
merged.object <- CreateSeuratObject(counts = data.list, meta.data = metadata)
merged.object
```

Example 38 (python):
```python
## An object of class Seurat 
## 26143 features across 1498064 samples within 1 assay 
## Active assay: RNA (26143 features, 0 variable features)
##  3 layers present: counts.ahern, counts.jin, counts.yoshida
```

Example 39 (python):
```python
## An object of class Seurat 
## 26143 features across 1498064 samples within 1 assay 
## Active assay: RNA (26143 features, 0 variable features)
##  3 layers present: counts.ahern, counts.jin, counts.yoshida
```

Example 40 (unknown):
```unknown
saveRDS(
  object = merged.object,
  file = "obj.Rds"
)
```

Example 41 (r):
```r
saveRDS(
  object = merged.object,
  file = "obj.Rds"
)
```

Example 42 (r):
```r
saveRDS(
  object = merged.object,
  file = "obj.Rds"
)
```

Example 43 (unknown):
```unknown
parse.data <- open_matrix_anndata_hdf5(
  "/brahms/hartmana/vignette_data/h5ad_files/ParseBio_PBMC.h5ad"
)
```

Example 44 (r):
```r
parse.data <- open_matrix_anndata_hdf5(
  "/brahms/hartmana/vignette_data/h5ad_files/ParseBio_PBMC.h5ad"
)
```

Example 45 (r):
```r
parse.data <- open_matrix_anndata_hdf5(
  "/brahms/hartmana/vignette_data/h5ad_files/ParseBio_PBMC.h5ad"
)
```

Example 46 (unknown):
```unknown
write_matrix_dir(mat = parse.data, dir = "/brahms/hartmana/vignette_data/bpcells/parse_1m_pbmc")
```

Example 47 (r):
```r
write_matrix_dir(mat = parse.data, dir = "/brahms/hartmana/vignette_data/bpcells/parse_1m_pbmc")
```

Example 48 (r):
```r
write_matrix_dir(mat = parse.data, dir = "/brahms/hartmana/vignette_data/bpcells/parse_1m_pbmc")
```

Example 49 (python):
```python
parse.mat <- open_matrix_dir(dir = "/brahms/hartmana/vignette_data/bpcells/parse_1m_pbmc")
metadata <- readRDS("/brahms/hartmana/vignette_data/ParseBio_PBMC_meta.rds")
metadata$disease <- sapply(strsplit(x = metadata$sample, split = "_"), "[", 1)
parse.object <- CreateSeuratObject(counts = parse.mat, meta.data = metadata)
```

Example 50 (r):
```r
parse.mat <- open_matrix_dir(dir = "/brahms/hartmana/vignette_data/bpcells/parse_1m_pbmc")
metadata <- readRDS("/brahms/hartmana/vignette_data/ParseBio_PBMC_meta.rds")
metadata$disease <- sapply(strsplit(x = metadata$sample, split = "_"), "[", 1)
parse.object <- CreateSeuratObject(counts = parse.mat, meta.data = metadata)
```

Example 51 (r):
```r
parse.mat <- open_matrix_dir(dir = "/brahms/hartmana/vignette_data/bpcells/parse_1m_pbmc")
metadata <- readRDS("/brahms/hartmana/vignette_data/ParseBio_PBMC_meta.rds")
metadata$disease <- sapply(strsplit(x = metadata$sample, split = "_"), "[", 1)
parse.object <- CreateSeuratObject(counts = parse.mat, meta.data = metadata)
```

Example 52 (unknown):
```unknown
saveRDS(
  object = parse.object,
  file = "obj.Rds"
)
```

Example 53 (r):
```r
saveRDS(
  object = parse.object,
  file = "obj.Rds"
)
```

Example 54 (r):
```r
saveRDS(
  object = parse.object,
  file = "obj.Rds"
)
```

Example 55 (unknown):
```unknown
sessionInfo()
```

Example 56 (r):
```r
sessionInfo()
```

Example 57 (r):
```r
sessionInfo()
```

Example 58 (unknown):
```unknown
## R version 4.2.2 Patched (2022-11-10 r83330)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.6 LTS
## 
## Matrix products: default
## BLAS:   /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.9.0
## LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.9.0
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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       
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
## [1] dplyr_1.1.3             biomaRt_2.54.1          Azimuth_0.4.6.9004     
## [4] shinyBS_0.61.1          SeuratDisk_0.0.0.9020   Seurat_4.9.9.9085      
## [7] SeuratObject_4.9.9.9092 sp_2.1-1                BPCells_0.1.0          
## 
## loaded via a namespace (and not attached):
##   [1] rappdirs_0.3.3                    rtracklayer_1.58.0               
##   [3] scattermore_1.2                   R.methodsS3_1.8.2                
##   [5] ragg_1.2.5                        tidyr_1.3.0                      
##   [7] JASPAR2020_0.99.10                ggplot2_3.4.4                    
##   [9] bit64_4.0.5                       knitr_1.44                       
##  [11] irlba_2.3.5.1                     DelayedArray_0.24.0              
##  [13] R.utils_2.12.2                    styler_1.10.2                    
##  [15] data.table_1.14.8                 KEGGREST_1.38.0                  
##  [17] TFBSTools_1.36.0                  RCurl_1.98-1.12                  
##  [19] AnnotationFilter_1.22.0           generics_0.1.3                   
##  [21] BiocGenerics_0.44.0               GenomicFeatures_1.50.4           
##  [23] cowplot_1.1.1                     RSQLite_2.3.1                    
##  [25] RANN_2.6.1                        future_1.33.0                    
##  [27] bit_4.0.5                         tzdb_0.4.0                       
##  [29] spatstat.data_3.0-1               xml2_1.3.5                       
##  [31] httpuv_1.6.11                     SummarizedExperiment_1.28.0      
##  [33] DirichletMultinomial_1.40.0       gargle_1.5.2                     
##  [35] xfun_0.40                         hms_1.1.3                        
##  [37] jquerylib_0.1.4                   evaluate_0.22                    
##  [39] promises_1.2.1                    fansi_1.0.5                      
##  [41] restfulr_0.0.15                   progress_1.2.2                   
##  [43] caTools_1.18.2                    dbplyr_2.3.4                     
##  [45] igraph_1.5.1                      DBI_1.1.3                        
##  [47] htmlwidgets_1.6.2                 spatstat.geom_3.2-5              
##  [49] googledrive_2.1.1                 stats4_4.2.2                     
##  [51] purrr_1.0.2                       ellipsis_0.3.2                   
##  [53] RSpectra_0.16-1                   annotate_1.76.0                  
##  [55] deldir_1.0-9                      MatrixGenerics_1.10.0            
##  [57] vctrs_0.6.4                       Biobase_2.58.0                   
##  [59] Cairo_1.6-0                       ensembldb_2.22.0                 
##  [61] ROCR_1.0-11                       abind_1.4-5                      
##  [63] cachem_1.0.8                      withr_2.5.1                      
##  [65] BSgenome.Hsapiens.UCSC.hg38_1.4.5 BSgenome_1.66.3                  
##  [67] progressr_0.14.0                  presto_1.0.0                     
##  [69] sctransform_0.4.1                 GenomicAlignments_1.34.1         
##  [71] prettyunits_1.1.1                 goftest_1.2-3                    
##  [73] cluster_2.1.4                     dotCall64_1.1-0                  
##  [75] lazyeval_0.2.2                    seqLogo_1.64.0                   
##  [77] crayon_1.5.2                      hdf5r_1.3.8                      
##  [79] spatstat.explore_3.2-3            labeling_0.4.3                   
##  [81] pkgconfig_2.0.3                   GenomeInfoDb_1.34.9              
##  [83] vipor_0.4.5                       nlme_3.1-162                     
##  [85] ProtGenerics_1.30.0               rlang_1.1.1                      
##  [87] globals_0.16.2                    lifecycle_1.0.3                  
##  [89] miniUI_0.1.1.1                    filelock_1.0.2                   
##  [91] fastDummies_1.7.3                 BiocFileCache_2.6.1              
##  [93] SeuratData_0.2.2.9001             ggrastr_1.0.1                    
##  [95] cellranger_1.1.0                  rprojroot_2.0.3                  
##  [97] polyclip_1.10-6                   RcppHNSW_0.5.0                   
##  [99] matrixStats_1.0.0                 lmtest_0.9-40                    
## [101] Matrix_1.6-1.1                    Rhdf5lib_1.20.0                  
## [103] zoo_1.8-12                        beeswarm_0.4.0                   
## [105] googlesheets4_1.1.1               ggridges_0.5.4                   
## [107] png_0.1-8                         viridisLite_0.4.2                
## [109] rjson_0.2.21                      shinydashboard_0.7.2             
## [111] bitops_1.0-7                      R.oo_1.25.0                      
## [113] rhdf5filters_1.10.1               KernSmooth_2.23-22               
## [115] spam_2.9-1                        Biostrings_2.66.0                
## [117] blob_1.2.4                        stringr_1.5.0                    
## [119] parallelly_1.36.0                 spatstat.random_3.1-6            
## [121] R.cache_0.16.0                    readr_2.1.4                      
## [123] S4Vectors_0.36.2                  CNEr_1.34.0                      
## [125] scales_1.2.1                      memoise_2.0.1                    
## [127] magrittr_2.0.3                    plyr_1.8.9                       
## [129] ica_1.0-3                         zlibbioc_1.44.0                  
## [131] compiler_4.2.2                    BiocIO_1.8.0                     
## [133] RColorBrewer_1.1-3                fitdistrplus_1.1-11              
## [135] Rsamtools_2.14.0                  cli_3.6.1                        
## [137] XVector_0.38.0                    listenv_0.9.0                    
## [139] patchwork_1.1.3                   pbapply_1.7-2                    
## [141] MASS_7.3-58.2                     tidyselect_1.2.0                 
## [143] stringi_1.7.12                    textshaping_0.3.6                
## [145] yaml_2.3.7                        ggrepel_0.9.4                    
## [147] grid_4.2.2                        sass_0.4.7                       
## [149] fastmatch_1.1-4                   EnsDb.Hsapiens.v86_2.99.0        
## [151] tools_4.2.2                       future.apply_1.11.0              
## [153] parallel_4.2.2                    rstudioapi_0.14                  
## [155] TFMPvalue_0.0.9                   gridExtra_2.3                    
## [157] farver_2.1.1                      Rtsne_0.16                       
## [159] digest_0.6.33                     pracma_2.4.2                     
## [161] shiny_1.7.5.1                     Rcpp_1.0.11                      
## [163] GenomicRanges_1.50.2              later_1.3.1                      
## [165] RcppAnnoy_0.0.21                  httr_1.4.7                       
## [167] AnnotationDbi_1.60.2              colorspace_2.1-0                 
## [169] XML_3.99-0.14                     fs_1.6.3                         
## [171] tensor_1.5                        reticulate_1.34.0                
## [173] IRanges_2.32.0                    splines_4.2.2                    
## [175] uwot_0.1.16                       RcppRoll_0.3.0                   
## [177] spatstat.utils_3.0-3              pkgdown_2.0.7                    
## [179] plotly_4.10.2                     systemfonts_1.0.4                
## [181] xtable_1.8-4                      jsonlite_1.8.7                   
## [183] poweRlaw_0.70.6                   R6_2.5.1                         
## [185] pillar_1.9.0                      htmltools_0.5.6.1                
## [187] mime_0.12                         glue_1.6.2                       
## [189] fastmap_1.1.1                     DT_0.30                          
## [191] BiocParallel_1.32.6               codetools_0.2-19                 
## [193] Signac_1.12.9000                  utf8_1.2.3                       
## [195] lattice_0.21-9                    bslib_0.5.1                      
## [197] spatstat.sparse_3.0-2             tibble_3.2.1                     
## [199] ggbeeswarm_0.7.1                  curl_5.1.0                       
## [201] leiden_0.4.3                      gtools_3.9.4                     
## [203] shinyjs_2.1.0                     GO.db_3.16.0                     
## [205] survival_3.5-7                    rmarkdown_2.25                   
## [207] desc_1.4.2                        munsell_0.5.0                    
## [209] rhdf5_2.42.1                      GenomeInfoDbData_1.2.9           
## [211] reshape2_1.4.4                    gtable_0.3.4
```

Example 59 (unknown):
```unknown
## R version 4.2.2 Patched (2022-11-10 r83330)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.6 LTS
## 
## Matrix products: default
## BLAS:   /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.9.0
## LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.9.0
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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       
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
## [1] dplyr_1.1.3             biomaRt_2.54.1          Azimuth_0.4.6.9004     
## [4] shinyBS_0.61.1          SeuratDisk_0.0.0.9020   Seurat_4.9.9.9085      
## [7] SeuratObject_4.9.9.9092 sp_2.1-1                BPCells_0.1.0          
## 
## loaded via a namespace (and not attached):
##   [1] rappdirs_0.3.3                    rtracklayer_1.58.0               
##   [3] scattermore_1.2                   R.methodsS3_1.8.2                
##   [5] ragg_1.2.5                        tidyr_1.3.0                      
##   [7] JASPAR2020_0.99.10                ggplot2_3.4.4                    
##   [9] bit64_4.0.5                       knitr_1.44                       
##  [11] irlba_2.3.5.1                     DelayedArray_0.24.0              
##  [13] R.utils_2.12.2                    styler_1.10.2                    
##  [15] data.table_1.14.8                 KEGGREST_1.38.0                  
##  [17] TFBSTools_1.36.0                  RCurl_1.98-1.12                  
##  [19] AnnotationFilter_1.22.0           generics_0.1.3                   
##  [21] BiocGenerics_0.44.0               GenomicFeatures_1.50.4           
##  [23] cowplot_1.1.1                     RSQLite_2.3.1                    
##  [25] RANN_2.6.1                        future_1.33.0                    
##  [27] bit_4.0.5                         tzdb_0.4.0                       
##  [29] spatstat.data_3.0-1               xml2_1.3.5                       
##  [31] httpuv_1.6.11                     SummarizedExperiment_1.28.0      
##  [33] DirichletMultinomial_1.40.0       gargle_1.5.2                     
##  [35] xfun_0.40                         hms_1.1.3                        
##  [37] jquerylib_0.1.4                   evaluate_0.22                    
##  [39] promises_1.2.1                    fansi_1.0.5                      
##  [41] restfulr_0.0.15                   progress_1.2.2                   
##  [43] caTools_1.18.2                    dbplyr_2.3.4                     
##  [45] igraph_1.5.1                      DBI_1.1.3                        
##  [47] htmlwidgets_1.6.2                 spatstat.geom_3.2-5              
##  [49] googledrive_2.1.1                 stats4_4.2.2                     
##  [51] purrr_1.0.2                       ellipsis_0.3.2                   
##  [53] RSpectra_0.16-1                   annotate_1.76.0                  
##  [55] deldir_1.0-9                      MatrixGenerics_1.10.0            
##  [57] vctrs_0.6.4                       Biobase_2.58.0                   
##  [59] Cairo_1.6-0                       ensembldb_2.22.0                 
##  [61] ROCR_1.0-11                       abind_1.4-5                      
##  [63] cachem_1.0.8                      withr_2.5.1                      
##  [65] BSgenome.Hsapiens.UCSC.hg38_1.4.5 BSgenome_1.66.3                  
##  [67] progressr_0.14.0                  presto_1.0.0                     
##  [69] sctransform_0.4.1                 GenomicAlignments_1.34.1         
##  [71] prettyunits_1.1.1                 goftest_1.2-3                    
##  [73] cluster_2.1.4                     dotCall64_1.1-0                  
##  [75] lazyeval_0.2.2                    seqLogo_1.64.0                   
##  [77] crayon_1.5.2                      hdf5r_1.3.8                      
##  [79] spatstat.explore_3.2-3            labeling_0.4.3                   
##  [81] pkgconfig_2.0.3                   GenomeInfoDb_1.34.9              
##  [83] vipor_0.4.5                       nlme_3.1-162                     
##  [85] ProtGenerics_1.30.0               rlang_1.1.1                      
##  [87] globals_0.16.2                    lifecycle_1.0.3                  
##  [89] miniUI_0.1.1.1                    filelock_1.0.2                   
##  [91] fastDummies_1.7.3                 BiocFileCache_2.6.1              
##  [93] SeuratData_0.2.2.9001             ggrastr_1.0.1                    
##  [95] cellranger_1.1.0                  rprojroot_2.0.3                  
##  [97] polyclip_1.10-6                   RcppHNSW_0.5.0                   
##  [99] matrixStats_1.0.0                 lmtest_0.9-40                    
## [101] Matrix_1.6-1.1                    Rhdf5lib_1.20.0                  
## [103] zoo_1.8-12                        beeswarm_0.4.0                   
## [105] googlesheets4_1.1.1               ggridges_0.5.4                   
## [107] png_0.1-8                         viridisLite_0.4.2                
## [109] rjson_0.2.21                      shinydashboard_0.7.2             
## [111] bitops_1.0-7                      R.oo_1.25.0                      
## [113] rhdf5filters_1.10.1               KernSmooth_2.23-22               
## [115] spam_2.9-1                        Biostrings_2.66.0                
## [117] blob_1.2.4                        stringr_1.5.0                    
## [119] parallelly_1.36.0                 spatstat.random_3.1-6            
## [121] R.cache_0.16.0                    readr_2.1.4                      
## [123] S4Vectors_0.36.2                  CNEr_1.34.0                      
## [125] scales_1.2.1                      memoise_2.0.1                    
## [127] magrittr_2.0.3                    plyr_1.8.9                       
## [129] ica_1.0-3                         zlibbioc_1.44.0                  
## [131] compiler_4.2.2                    BiocIO_1.8.0                     
## [133] RColorBrewer_1.1-3                fitdistrplus_1.1-11              
## [135] Rsamtools_2.14.0                  cli_3.6.1                        
## [137] XVector_0.38.0                    listenv_0.9.0                    
## [139] patchwork_1.1.3                   pbapply_1.7-2                    
## [141] MASS_7.3-58.2                     tidyselect_1.2.0                 
## [143] stringi_1.7.12                    textshaping_0.3.6                
## [145] yaml_2.3.7                        ggrepel_0.9.4                    
## [147] grid_4.2.2                        sass_0.4.7                       
## [149] fastmatch_1.1-4                   EnsDb.Hsapiens.v86_2.99.0        
## [151] tools_4.2.2                       future.apply_1.11.0              
## [153] parallel_4.2.2                    rstudioapi_0.14                  
## [155] TFMPvalue_0.0.9                   gridExtra_2.3                    
## [157] farver_2.1.1                      Rtsne_0.16                       
## [159] digest_0.6.33                     pracma_2.4.2                     
## [161] shiny_1.7.5.1                     Rcpp_1.0.11                      
## [163] GenomicRanges_1.50.2              later_1.3.1                      
## [165] RcppAnnoy_0.0.21                  httr_1.4.7                       
## [167] AnnotationDbi_1.60.2              colorspace_2.1-0                 
## [169] XML_3.99-0.14                     fs_1.6.3                         
## [171] tensor_1.5                        reticulate_1.34.0                
## [173] IRanges_2.32.0                    splines_4.2.2                    
## [175] uwot_0.1.16                       RcppRoll_0.3.0                   
## [177] spatstat.utils_3.0-3              pkgdown_2.0.7                    
## [179] plotly_4.10.2                     systemfonts_1.0.4                
## [181] xtable_1.8-4                      jsonlite_1.8.7                   
## [183] poweRlaw_0.70.6                   R6_2.5.1                         
## [185] pillar_1.9.0                      htmltools_0.5.6.1                
## [187] mime_0.12                         glue_1.6.2                       
## [189] fastmap_1.1.1                     DT_0.30                          
## [191] BiocParallel_1.32.6               codetools_0.2-19                 
## [193] Signac_1.12.9000                  utf8_1.2.3                       
## [195] lattice_0.21-9                    bslib_0.5.1                      
## [197] spatstat.sparse_3.0-2             tibble_3.2.1                     
## [199] ggbeeswarm_0.7.1                  curl_5.1.0                       
## [201] leiden_0.4.3                      gtools_3.9.4                     
## [203] shinyjs_2.1.0                     GO.db_3.16.0                     
## [205] survival_3.5-7                    rmarkdown_2.25                   
## [207] desc_1.4.2                        munsell_0.5.0                    
## [209] rhdf5_2.42.1                      GenomeInfoDbData_1.2.9           
## [211] reshape2_1.4.4                    gtable_0.3.4
```

---

## New data visualization methods in v3.0

**URL:** http://127.0.0.1:9173/seurat/archive/v3.1/visualization_vignette/index.html

**Contents:**
- New data visualization methods in v3.0
    - Compiled: 2020-04-17
  - Five visualizations of marker feature expression
  - New additions to FeaturePlot
  - Updated and expanded visualization functions
  - Applying themes to plots
  - Interactive plotting features
  - Plotting Accessories

We’ll demonstrate visualization techniques in Seurat using our previously computed Seurat object from the 2,700 PBMC tutorial. You can download that here

In addition to changes to FeaturePlot, several other plotting functions have been updated and expanded with new features and taking over the role of now-deprecated functions

With Seurat v3.0, all plotting functions return ggplot2-based plots by default, allowing one to easily capture and manipulate plots just like any other ggplot2-based plot.

Seurat utilizes R’s plotly graphing library to create interactive plots. This interactive plotting feature works with any ggplot2-based scatter plots (requires a geom_point layer). To use, simply make a ggplot2-based scatter plot (such as DimPlot or FeaturePlot) and pass the resulting plot to HoverLocator

Another interactive feature provided by Seurat is being able to manually select cells for further investigation. We have found this particularly useful for small clusters that do not always separate using unbiased clustering, but which look tantalizingly distinct. You can now select these cells by creating a ggplot2-based scatter plot (such as with DimPlot or FeaturePlot, and passing the returned plot to CellSelector. CellSelector will return a vector with the names of the points selected, so that you can then set them to a new identity class and perform differential expression.

For example, lets pretend that DCs had merged with monocytes in the clustering, but we wanted to see what was unique about them based on their position in the tSNE plot.

We can then use SetIdent to turn these cells into their own mini-cluster.

Using CellSelector to Automatically Assign Cell Identities

In addition to returning a vector of cell names, CellSelector can also take the selected cells and assign a new identity to them, returning a Seurat object with the identity classes already set. This is done by passing the Seurat object used to make the plot into CellSelector, as well as an identity class. As an example, we’re going to select the same set of cells as before, and set their identity class to “selected”

Along with new functions add interactive functionality to plots, Seurat provides new accessory functions for manipulating and combining plots.

Plotting multiple plots was previously achieved with the CombinePlot function. We are deprecating this functionality in favor of the patchwork system. Below is a brief demonstration but please see the patchwork package website here for more details and examples.

**Examples:**

Example 1 (r):
```r
library(Seurat)
library(ggplot2)
library(patchwork)
pbmc <- readRDS(file = "../data/pbmc3k_final.rds")
pbmc$groups <- sample(c("group1", "group2"), size = ncol(pbmc), replace = TRUE)
features <- c("LYZ", "CCL5", "IL32", "PTPRCAP", "FCGR3A", "PF4")
pbmc
```

Example 2 (r):
```r
library(Seurat)
library(ggplot2)
library(patchwork)
pbmc <- readRDS(file = "../data/pbmc3k_final.rds")
pbmc$groups <- sample(c("group1", "group2"), size = ncol(pbmc), replace = TRUE)
features <- c("LYZ", "CCL5", "IL32", "PTPRCAP", "FCGR3A", "PF4")
pbmc
```

Example 3 (python):
```python
## An object of class Seurat 
## 13714 features across 2638 samples within 1 assay 
## Active assay: RNA (13714 features, 2000 variable features)
##  2 dimensional reductions calculated: pca, umap
```

Example 4 (python):
```python
## An object of class Seurat 
## 13714 features across 2638 samples within 1 assay 
## Active assay: RNA (13714 features, 2000 variable features)
##  2 dimensional reductions calculated: pca, umap
```

Example 5 (r):
```r
# Ridge plots - from ggridges. Visualize single cell expression distributions in each cluster
RidgePlot(pbmc, features = features, ncol = 2)
```

Example 6 (r):
```r
# Ridge plots - from ggridges. Visualize single cell expression distributions in each cluster
RidgePlot(pbmc, features = features, ncol = 2)
```

Example 7 (r):
```r
# Violin plot - Visualize single cell expression distributions in each cluster
VlnPlot(pbmc, features = features)
```

Example 8 (r):
```r
# Violin plot - Visualize single cell expression distributions in each cluster
VlnPlot(pbmc, features = features)
```

Example 9 (r):
```r
# Feature plot - visualize feature expression in low-dimensional space
FeaturePlot(pbmc, features = features)
```

Example 10 (r):
```r
# Feature plot - visualize feature expression in low-dimensional space
FeaturePlot(pbmc, features = features)
```

Example 11 (r):
```r
# Dot plots - the size of the dot corresponds to the percentage of cells expressing the feature
# in each cluster. The color represents the average expression level
DotPlot(pbmc, features = features) + RotatedAxis()
```

Example 12 (r):
```r
# Dot plots - the size of the dot corresponds to the percentage of cells expressing the feature
# in each cluster. The color represents the average expression level
DotPlot(pbmc, features = features) + RotatedAxis()
```

Example 13 (r):
```r
# Single cell heatmap of feature expression
DoHeatmap(subset(pbmc, downsample = 100), features = features, size = 3)
```

Example 14 (r):
```r
# Single cell heatmap of feature expression
DoHeatmap(subset(pbmc, downsample = 100), features = features, size = 3)
```

Example 15 (unknown):
```unknown
FeaturePlot
```

Example 16 (r):
```r
# Plot a legend to map colors to expression levels
FeaturePlot(pbmc, features = "MS4A1")
```

Example 17 (r):
```r
# Plot a legend to map colors to expression levels
FeaturePlot(pbmc, features = "MS4A1")
```

Example 18 (r):
```r
# Adjust the contrast in the plot
FeaturePlot(pbmc, features = "MS4A1", min.cutoff = 1, max.cutoff = 3)
```

Example 19 (r):
```r
# Adjust the contrast in the plot
FeaturePlot(pbmc, features = "MS4A1", min.cutoff = 1, max.cutoff = 3)
```

Example 20 (r):
```r
# Calculate feature-specific contrast levels based on quantiles of non-zero expression.
# Particularly useful when plotting multiple markers
FeaturePlot(pbmc, features = c("MS4A1", "PTPRCAP"), min.cutoff = "q10", max.cutoff = "q90")
```

Example 21 (r):
```r
# Calculate feature-specific contrast levels based on quantiles of non-zero expression.
# Particularly useful when plotting multiple markers
FeaturePlot(pbmc, features = c("MS4A1", "PTPRCAP"), min.cutoff = "q10", max.cutoff = "q90")
```

Example 22 (r):
```r
# Visualize co-expression of two features simultaneously
FeaturePlot(pbmc, features = c("MS4A1", "CD79A"), blend = TRUE)
```

Example 23 (r):
```r
# Visualize co-expression of two features simultaneously
FeaturePlot(pbmc, features = c("MS4A1", "CD79A"), blend = TRUE)
```

Example 24 (r):
```r
# Split visualization to view expression by groups (replaces FeatureHeatmap)
FeaturePlot(pbmc, features = c("MS4A1", "CD79A"), split.by = "groups")
```

Example 25 (r):
```r
# Split visualization to view expression by groups (replaces FeatureHeatmap)
FeaturePlot(pbmc, features = c("MS4A1", "CD79A"), split.by = "groups")
```

Example 26 (unknown):
```unknown
FeaturePlot
```

Example 27 (r):
```r
# Violin plots can also be split on some variable. Simply add the splitting variable to object
# metadata and pass it to the split.by argument
VlnPlot(pbmc, features = "percent.mt", split.by = "groups")
```

Example 28 (r):
```r
# Violin plots can also be split on some variable. Simply add the splitting variable to object
# metadata and pass it to the split.by argument
VlnPlot(pbmc, features = "percent.mt", split.by = "groups")
```

Example 29 (r):
```r
# SplitDotPlotGG has been replaced with the `split.by` parameter for DotPlot
DotPlot(pbmc, features = features, split.by = "groups") + RotatedAxis()
```

Example 30 (r):
```r
# SplitDotPlotGG has been replaced with the `split.by` parameter for DotPlot
DotPlot(pbmc, features = features, split.by = "groups") + RotatedAxis()
```

Example 31 (r):
```r
# DimPlot replaces TSNEPlot, PCAPlot, etc. In addition, it will plot either 'umap', 'tsne', or
# 'pca' by default, in that order
DimPlot(pbmc)
```

Example 32 (r):
```r
# DimPlot replaces TSNEPlot, PCAPlot, etc. In addition, it will plot either 'umap', 'tsne', or
# 'pca' by default, in that order
DimPlot(pbmc)
```

Example 33 (r):
```r
pbmc.no.umap <- pbmc
pbmc.no.umap[["umap"]] <- NULL
DimPlot(pbmc.no.umap) + RotatedAxis()
```

Example 34 (r):
```r
pbmc.no.umap <- pbmc
pbmc.no.umap[["umap"]] <- NULL
DimPlot(pbmc.no.umap) + RotatedAxis()
```

Example 35 (r):
```r
# DoHeatmap now shows a grouping bar, splitting the heatmap into groups or clusters. This can be
# changed with the `group.by` parameter
DoHeatmap(pbmc, features = VariableFeatures(pbmc)[1:100], cells = 1:500, size = 4, angle = 90) + 
    NoLegend()
```

Example 36 (r):
```r
# DoHeatmap now shows a grouping bar, splitting the heatmap into groups or clusters. This can be
# changed with the `group.by` parameter
DoHeatmap(pbmc, features = VariableFeatures(pbmc)[1:100], cells = 1:500, size = 4, angle = 90) + 
    NoLegend()
```

Example 37 (r):
```r
baseplot <- DimPlot(pbmc, reduction = "umap")
# Add custom labels and titles
baseplot + labs(title = "Clustering of 2,700 PBMCs")
```

Example 38 (r):
```r
baseplot <- DimPlot(pbmc, reduction = "umap")
# Add custom labels and titles
baseplot + labs(title = "Clustering of 2,700 PBMCs")
```

Example 39 (r):
```r
# Use community-created themes, overwriting the default Seurat-applied theme Install ggmin with
# devtools::install_github('sjessa/ggmin')
baseplot + ggmin::theme_powerpoint()
```

Example 40 (r):
```r
# Use community-created themes, overwriting the default Seurat-applied theme Install ggmin with
# devtools::install_github('sjessa/ggmin')
baseplot + ggmin::theme_powerpoint()
```

Example 41 (r):
```r
# Seurat also provides several built-in themes, such as DarkTheme; for more details see
# ?SeuratTheme
baseplot + DarkTheme()
```

Example 42 (r):
```r
# Seurat also provides several built-in themes, such as DarkTheme; for more details see
# ?SeuratTheme
baseplot + DarkTheme()
```

Example 43 (r):
```r
# Chain themes together
baseplot + FontSize(x.title = 20, y.title = 20) + NoLegend()
```

Example 44 (r):
```r
# Chain themes together
baseplot + FontSize(x.title = 20, y.title = 20) + NoLegend()
```

Example 45 (unknown):
```unknown
FeaturePlot
```

Example 46 (unknown):
```unknown
HoverLocator
```

Example 47 (r):
```r
# Include additional data to display alongside cell names by passing in a data frame of
# information Works well when using FetchData
plot <- FeaturePlot(pbmc, features = "MS4A1")
HoverLocator(plot = plot, information = FetchData(pbmc, vars = c("ident", "PC_1", "nFeature_RNA")))
```

Example 48 (r):
```r
# Include additional data to display alongside cell names by passing in a data frame of
# information Works well when using FetchData
plot <- FeaturePlot(pbmc, features = "MS4A1")
HoverLocator(plot = plot, information = FetchData(pbmc, vars = c("ident", "PC_1", "nFeature_RNA")))
```

Example 49 (unknown):
```unknown
FeaturePlot
```

Example 50 (unknown):
```unknown
CellSelector
```

Example 51 (unknown):
```unknown
CellSelector
```

Example 52 (r):
```r
pbmc <- RenameIdents(pbmc, DC = "CD14+ Mono")
plot <- DimPlot(pbmc, reduction = "umap")
select.cells <- CellSelector(plot = plot)
```

Example 53 (r):
```r
pbmc <- RenameIdents(pbmc, DC = "CD14+ Mono")
plot <- DimPlot(pbmc, reduction = "umap")
select.cells <- CellSelector(plot = plot)
```

Example 54 (r):
```r
head(select.cells)
```

Example 55 (r):
```r
head(select.cells)
```

Example 56 (unknown):
```unknown
## [1] "AAGATTACCGCCTT-1" "AAGCCATGAACTGC-1" "AATTACGAATTCCT-1" "ACCCGTTGCTTCTA-1"
## [5] "ACGAGGGACAGGAG-1" "ACGTGATGCCATGA-1"
```

Example 57 (unknown):
```unknown
## [1] "AAGATTACCGCCTT-1" "AAGCCATGAACTGC-1" "AATTACGAATTCCT-1" "ACCCGTTGCTTCTA-1"
## [5] "ACGAGGGACAGGAG-1" "ACGTGATGCCATGA-1"
```

Example 58 (r):
```r
Idents(pbmc, cells = select.cells) <- "NewCells"

# Now, we find markers that are specific to the new cells, and find clear DC markers
newcells.markers <- FindMarkers(pbmc, ident.1 = "NewCells", ident.2 = "CD14+ Mono", min.diff.pct = 0.3, 
    only.pos = TRUE)
head(newcells.markers)
```

Example 59 (r):
```r
Idents(pbmc, cells = select.cells) <- "NewCells"

# Now, we find markers that are specific to the new cells, and find clear DC markers
newcells.markers <- FindMarkers(pbmc, ident.1 = "NewCells", ident.2 = "CD14+ Mono", min.diff.pct = 0.3, 
    only.pos = TRUE)
head(newcells.markers)
```

Example 60 (unknown):
```unknown
CellSelector
```

Example 61 (unknown):
```unknown
CellSelector
```

Example 62 (unknown):
```unknown
CellSelector
```

Example 63 (r):
```r
pbmc <- CellSelector(plot = plot, object = pbmc, ident = "selected")
```

Example 64 (r):
```r
pbmc <- CellSelector(plot = plot, object = pbmc, ident = "selected")
```

Example 65 (r):
```r
levels(pbmc)
```

Example 66 (r):
```r
levels(pbmc)
```

Example 67 (unknown):
```unknown
## [1] "selected"     "Naive CD4 T"  "Memory CD4 T" "CD14+ Mono"   "B"           
## [6] "CD8 T"        "FCGR3A+ Mono" "NK"           "Platelet"
```

Example 68 (unknown):
```unknown
## [1] "selected"     "Naive CD4 T"  "Memory CD4 T" "CD14+ Mono"   "B"           
## [6] "CD8 T"        "FCGR3A+ Mono" "NK"           "Platelet"
```

Example 69 (r):
```r
# LabelClusters and LabelPoints will label clusters (a coloring variable) or individual points
# on a ggplot2-based scatter plot
plot <- DimPlot(pbmc, reduction = "pca") + NoLegend()
LabelClusters(plot = plot, id = "ident")
```

Example 70 (r):
```r
# LabelClusters and LabelPoints will label clusters (a coloring variable) or individual points
# on a ggplot2-based scatter plot
plot <- DimPlot(pbmc, reduction = "pca") + NoLegend()
LabelClusters(plot = plot, id = "ident")
```

Example 71 (r):
```r
# Both functions support `repel`, which will intelligently stagger labels and draw connecting
# lines from the labels to the points or clusters
LabelPoints(plot = plot, points = TopCells(object = pbmc[["pca"]]), repel = TRUE)
```

Example 72 (r):
```r
# Both functions support `repel`, which will intelligently stagger labels and draw connecting
# lines from the labels to the points or clusters
LabelPoints(plot = plot, points = TopCells(object = pbmc[["pca"]]), repel = TRUE)
```

Example 73 (unknown):
```unknown
CombinePlot
```

Example 74 (r):
```r
plot1 <- DimPlot(pbmc)
plot2 <- FeatureScatter(pbmc, feature1 = "LYZ", feature2 = "CCL5")
# Combine two plots
plot1 + plot2
```

Example 75 (r):
```r
plot1 <- DimPlot(pbmc)
plot2 <- FeatureScatter(pbmc, feature1 = "LYZ", feature2 = "CCL5")
# Combine two plots
plot1 + plot2
```

Example 76 (r):
```r
# Remove the legend from all plots
(plot1 + plot2) & NoLegend()
```

Example 77 (r):
```r
# Remove the legend from all plots
(plot1 + plot2) & NoLegend()
```

---

## Differential expression testing

**URL:** http://127.0.0.1:9173/seurat/archive/v3.0/de_vignette/index.html

**Contents:**
- Differential expression testing
    - Compiled: 2019-06-24
  - Load in the data
  - Perform default differential expression tests
  - Prefilter features or cells to increase the speed of DE testing
  - Perform DE analysis using alternative tests
  - Acknowledgements

This vignette highlights some example workflows for performing differential expression in Seurat. For demonstration purposes, we will be using the 2,700 PBMC object that is created in the first guided tutorial. You can download the pre-computed object here.

The bulk of Seurat’s differential expression features can be accessed through the FindMarkers function. As a default, Seurat performs differential expression based on the non-parameteric Wilcoxon rank sum test. This replaces the previous default test (‘bimod’). To test for differential expression between two specific groups of cells, specify the ident.1 and ident.2 parameters.

The results data frame has the following columns :

If the ident.2 parameter is omitted or set to NULL, FindMarkers will test for differentially expressed features between the group specified by ident.1 and all other cells.

To increase the speed of marker discovery, particularly for large datasets, Seurat allows for pre-filtering of features or cells. For example, features that are very infrequently detected in either group of cells, or features that are expressed at similar average levels, are unlikely to be differentially expressed. Example use cases of the min.pct, logfc.threshold, min.diff.pct, and max.cells.per.ident parameters are demonstrated below.

The following differential expression tests are currently supported:

For MAST and DESeq2 please ensure that these packages are installed separately in order to use them as part of Seurat. Once installed, use the test.use parameter can be used to specify which DE test to use.

We thank the authors of the MAST and DESeq2 packages for their kind assistance and advice. We also point users to the following study by Charlotte Soneson and Mark Robinson, which performs careful and extensive evaluation of methods for single cell differential expression testing.

**Examples:**

Example 1 (r):
```r
library(Seurat)
pbmc <- readRDS(file = "../data/pbmc3k_final.rds")
```

Example 2 (r):
```r
library(Seurat)
pbmc <- readRDS(file = "../data/pbmc3k_final.rds")
```

Example 3 (unknown):
```unknown
FindMarkers
```

Example 4 (r):
```r
# list options for groups to perform differential expression on
levels(pbmc)
```

Example 5 (r):
```r
# list options for groups to perform differential expression on
levels(pbmc)
```

Example 6 (unknown):
```unknown
## [1] "Naive CD4 T"  "Memory CD4 T" "CD14+ Mono"   "B"           
## [5] "CD8 T"        "FCGR3A+ Mono" "NK"           "DC"          
## [9] "Platelet"
```

Example 7 (unknown):
```unknown
## [1] "Naive CD4 T"  "Memory CD4 T" "CD14+ Mono"   "B"           
## [5] "CD8 T"        "FCGR3A+ Mono" "NK"           "DC"          
## [9] "Platelet"
```

Example 8 (r):
```r
# Find differentially expressed features between CD14+ and FCGR3A+ Monocytes
monocyte.de.markers <- FindMarkers(pbmc, ident.1 = "CD14+ Mono", ident.2 = "FCGR3A+ Mono")
# view results
head(monocyte.de.markers)
```

Example 9 (r):
```r
# Find differentially expressed features between CD14+ and FCGR3A+ Monocytes
monocyte.de.markers <- FindMarkers(pbmc, ident.1 = "CD14+ Mono", ident.2 = "FCGR3A+ Mono")
# view results
head(monocyte.de.markers)
```

Example 10 (unknown):
```unknown
FindMarkers
```

Example 11 (r):
```r
# Find differentially expressed features between CD14+ Monocytes and all other cells, only
# search for positive markers
monocyte.de.markers <- FindMarkers(pbmc, ident.1 = "CD14+ Mono", ident.2 = NULL, only.pos = TRUE)
# view results
head(monocyte.de.markers)
```

Example 12 (r):
```r
# Find differentially expressed features between CD14+ Monocytes and all other cells, only
# search for positive markers
monocyte.de.markers <- FindMarkers(pbmc, ident.1 = "CD14+ Mono", ident.2 = NULL, only.pos = TRUE)
# view results
head(monocyte.de.markers)
```

Example 13 (unknown):
```unknown
logfc.threshold
```

Example 14 (unknown):
```unknown
min.diff.pct
```

Example 15 (unknown):
```unknown
max.cells.per.ident
```

Example 16 (r):
```r
# Pre-filter features that are detected at <50% frequency in either CD14+ Monocytes or FCGR3A+
# Monocytes
head(FindMarkers(pbmc, ident.1 = "CD14+ Mono", ident.2 = "FCGR3A+ Mono", min.pct = 0.5))
```

Example 17 (r):
```r
# Pre-filter features that are detected at <50% frequency in either CD14+ Monocytes or FCGR3A+
# Monocytes
head(FindMarkers(pbmc, ident.1 = "CD14+ Mono", ident.2 = "FCGR3A+ Mono", min.pct = 0.5))
```

Example 18 (r):
```r
# Pre-filter features that have less than a two-fold change between the average expression of
# CD14+ Monocytes vs FCGR3A+ Monocytes
head(FindMarkers(pbmc, ident.1 = "CD14+ Mono", ident.2 = "FCGR3A+ Mono", logfc.threshold = log(2)))
```

Example 19 (r):
```r
# Pre-filter features that have less than a two-fold change between the average expression of
# CD14+ Monocytes vs FCGR3A+ Monocytes
head(FindMarkers(pbmc, ident.1 = "CD14+ Mono", ident.2 = "FCGR3A+ Mono", logfc.threshold = log(2)))
```

Example 20 (r):
```r
# Pre-filter features whose detection percentages across the two groups are similar (within
# 0.25)
head(FindMarkers(pbmc, ident.1 = "CD14+ Mono", ident.2 = "FCGR3A+ Mono", min.diff.pct = 0.25))
```

Example 21 (r):
```r
# Pre-filter features whose detection percentages across the two groups are similar (within
# 0.25)
head(FindMarkers(pbmc, ident.1 = "CD14+ Mono", ident.2 = "FCGR3A+ Mono", min.diff.pct = 0.25))
```

Example 22 (r):
```r
# Increasing min.pct, logfc.threshold, and min.diff.pct, will increase the speed of DE testing,
# but could also miss features that are prefiltered

# Subsample each group to a maximum of 200 cells. Can be very useful for large clusters, or
# computationally-intensive DE tests
head(FindMarkers(pbmc, ident.1 = "CD14+ Mono", ident.2 = "FCGR3A+ Mono", max.cells.per.ident = 200))
```

Example 23 (r):
```r
# Increasing min.pct, logfc.threshold, and min.diff.pct, will increase the speed of DE testing,
# but could also miss features that are prefiltered

# Subsample each group to a maximum of 200 cells. Can be very useful for large clusters, or
# computationally-intensive DE tests
head(FindMarkers(pbmc, ident.1 = "CD14+ Mono", ident.2 = "FCGR3A+ Mono", max.cells.per.ident = 200))
```

Example 24 (r):
```r
# Test for DE features using the MAST package
head(FindMarkers(pbmc, ident.1 = "CD14+ Mono", ident.2 = "FCGR3A+ Mono", test.use = "MAST"))
```

Example 25 (r):
```r
# Test for DE features using the MAST package
head(FindMarkers(pbmc, ident.1 = "CD14+ Mono", ident.2 = "FCGR3A+ Mono", test.use = "MAST"))
```

Example 26 (r):
```r
# Test for DE features using the DESeq2 package. Throws an error if DESeq2 has not already been
# installed Note that the DESeq2 workflows can be computationally intensive for large datasets,
# but are incompatible with some feature pre-filtering options We therefore suggest initially
# limiting the number of cells used for testing
head(FindMarkers(pbmc, ident.1 = "CD14+ Mono", ident.2 = "FCGR3A+ Mono", test.use = "DESeq2", max.cells.per.ident = 50))
```

Example 27 (r):
```r
# Test for DE features using the DESeq2 package. Throws an error if DESeq2 has not already been
# installed Note that the DESeq2 workflows can be computationally intensive for large datasets,
# but are incompatible with some feature pre-filtering options We therefore suggest initially
# limiting the number of cells used for testing
head(FindMarkers(pbmc, ident.1 = "CD14+ Mono", ident.2 = "FCGR3A+ Mono", test.use = "DESeq2", max.cells.per.ident = 50))
```

---

## Analysis, visualization, and integration of Visium HD spatial datasets with Seurat • Seurat

**URL:** http://127.0.0.1:9173/articles_multimodal_vignette.html

**Contents:**
- Using Seurat with multimodal data
    - Compiled: 2023-11-16
- Load in the data
- Setup a Seurat object, add the RNA and protein data
- Cluster cells on the basis of their scRNA-seq profiles
- Visualize multiple modalities side-by-side
- Identify cell surface markers for scRNA-seq clusters
- Additional visualizations of multimodal data
- Loading data from 10X multi-modal experiments
- Additional functionality for multimodal data in Seurat
- Contents

The ability to make simultaneous measurements of multiple data types from the same cell, known as multimodal analysis, represents a new and exciting frontier for single-cell genomics. For example, CITE-seq enables the simultaneous measurements of transcriptomes and cell-surface proteins from the same cell. Other exciting multimodal technologies, such as the 10x multiome kit allow for the paired measurements of cellular transcriptome and chromatin accessibility (i.e scRNA-seq+scATAC-seq). Other modalities that can be measured alongside cellular transcriptomes include genetic perturbations, cellular methylomes, and hashtag oligos from Cell Hashing. We have designed Seurat to enable for the seamless storage, analysis, and exploration of diverse multimodal single-cell datasets.

In this vignette, we present an introductory workflow for creating a multimodal Seurat object and performing an initial analysis. For example, we demonstrate how to cluster a CITE-seq dataset on the basis of the measured cellular transcriptomes, and subsequently discover cell surface proteins that are enriched in each cluster. We note that Seurat also enables more advanced techniques for the analysis of multimodal data, in particular the application of our Weighted Nearest Neighbors (WNN) approach that enables simultaneous clustering of cells based on a weighted combination of both modalities, and you can explore this functionality here.

Here, we analyze a dataset of 8,617 cord blood mononuclear cells (CBMCs), where transcriptomic measurements are paired with abundance estimates for 11 surface proteins, whose levels are quantified with DNA-barcoded antibodies. First, we load in two count matrices : one for the RNA measurements, and one for the antibody-derived tags (ADT). You can download the ADT file here and the RNA file here

Now we create a Seurat object, and add the ADT data as a second assay

The steps below represent a quick clustering of the PBMCs based on the scRNA-seq data. For more detail on individual steps or more advanced options, see our PBMC clustering guided tutorial here

Now that we have obtained clusters from scRNA-seq profiles, we can visualize the expression of either protein or RNA molecules in our dataset. Importantly, Seurat provides a couple ways to switch between modalities, and specify which modality you are interested in analyzing or visualizing. This is particularly important as, in some cases, the same feature can be present in multiple modalities - for example this dataset contains independent measurements of the B cell marker CD19 (both protein and RNA levels).

We can leverage our paired CITE-seq measurements to help annotate clusters derived from scRNA-seq, and to identify both protein and RNA markers.

Seurat is also able to analyze data from multimodal 10X experiments processed using CellRanger v3; as an example, we recreate the plots above using a dataset of 7,900 peripheral blood mononuclear cells (PBMC), freely available from 10X Genomics here.

Seurat v4 also includes additional functionality for the analysis, visualization, and integration of multimodal datasets. For more information, please explore the resources below:

Developed by Rahul Satija, Satija Lab and Collaborators.

Site built with pkgdown 2.0.7.

**Examples:**

Example 1 (unknown):
```unknown
vignettes/multimodal_vignette.Rmd
```

Example 2 (unknown):
```unknown
multimodal_vignette.Rmd
```

Example 3 (unknown):
```unknown
library(Seurat)
library(ggplot2)
library(patchwork)
```

Example 4 (r):
```r
library(Seurat)
library(ggplot2)
library(patchwork)
```

Example 5 (r):
```r
library(Seurat)
library(ggplot2)
library(patchwork)
```

Example 6 (python):
```python
# Load in the RNA UMI matrix

# Note that this dataset also contains ~5% of mouse cells, which we can use as negative
# controls for the protein measurements. For this reason, the gene expression matrix has
# HUMAN_ or MOUSE_ appended to the beginning of each gene.
cbmc.rna <- as.sparse(read.csv(file = "/brahms/shared/vignette-data/GSE100866_CBMC_8K_13AB_10X-RNA_umi.csv.gz",
    sep = ",", header = TRUE, row.names = 1))

# To make life a bit easier going forward, we're going to discard all but the top 100 most
# highly expressed mouse genes, and remove the 'HUMAN_' from the CITE-seq prefix
cbmc.rna <- CollapseSpeciesExpressionMatrix(cbmc.rna)

# Load in the ADT UMI matrix
cbmc.adt <- as.sparse(read.csv(file = "/brahms/shared/vignette-data/GSE100866_CBMC_8K_13AB_10X-ADT_umi.csv.gz",
    sep = ",", header = TRUE, row.names = 1))

# Note that since measurements were made in the same cells, the two matrices have identical
# column names
all.equal(colnames(cbmc.rna), colnames(cbmc.adt))
```

Example 7 (r):
```r
# Load in the RNA UMI matrix

# Note that this dataset also contains ~5% of mouse cells, which we can use as negative
# controls for the protein measurements. For this reason, the gene expression matrix has
# HUMAN_ or MOUSE_ appended to the beginning of each gene.
cbmc.rna <- as.sparse(read.csv(file = "/brahms/shared/vignette-data/GSE100866_CBMC_8K_13AB_10X-RNA_umi.csv.gz",
    sep = ",", header = TRUE, row.names = 1))

# To make life a bit easier going forward, we're going to discard all but the top 100 most
# highly expressed mouse genes, and remove the 'HUMAN_' from the CITE-seq prefix
cbmc.rna <- CollapseSpeciesExpressionMatrix(cbmc.rna)

# Load in the ADT UMI matrix
cbmc.adt <- as.sparse(read.csv(file = "/brahms/shared/vignette-data/GSE100866_CBMC_8K_13AB_10X-ADT_umi.csv.gz",
    sep = ",", header = TRUE, row.names = 1))

# Note that since measurements were made in the same cells, the two matrices have identical
# column names
all.equal(colnames(cbmc.rna), colnames(cbmc.adt))
```

Example 8 (r):
```r
# Load in the RNA UMI matrix

# Note that this dataset also contains ~5% of mouse cells, which we can use as negative
# controls for the protein measurements. For this reason, the gene expression matrix has
# HUMAN_ or MOUSE_ appended to the beginning of each gene.
cbmc.rna <- as.sparse(read.csv(file = "/brahms/shared/vignette-data/GSE100866_CBMC_8K_13AB_10X-RNA_umi.csv.gz",
    sep = ",", header = TRUE, row.names = 1))

# To make life a bit easier going forward, we're going to discard all but the top 100 most
# highly expressed mouse genes, and remove the 'HUMAN_' from the CITE-seq prefix
cbmc.rna <- CollapseSpeciesExpressionMatrix(cbmc.rna)

# Load in the ADT UMI matrix
cbmc.adt <- as.sparse(read.csv(file = "/brahms/shared/vignette-data/GSE100866_CBMC_8K_13AB_10X-ADT_umi.csv.gz",
    sep = ",", header = TRUE, row.names = 1))

# Note that since measurements were made in the same cells, the two matrices have identical
# column names
all.equal(colnames(cbmc.rna), colnames(cbmc.adt))
```

Example 9 (unknown):
```unknown
## [1] TRUE
```

Example 10 (unknown):
```unknown
## [1] TRUE
```

Example 11 (unknown):
```unknown
# creates a Seurat object based on the scRNA-seq data
cbmc <- CreateSeuratObject(counts = cbmc.rna)

# We can see that by default, the cbmc object contains an assay storing RNA measurement
Assays(cbmc)
```

Example 12 (r):
```r
# creates a Seurat object based on the scRNA-seq data
cbmc <- CreateSeuratObject(counts = cbmc.rna)

# We can see that by default, the cbmc object contains an assay storing RNA measurement
Assays(cbmc)
```

Example 13 (r):
```r
# creates a Seurat object based on the scRNA-seq data
cbmc <- CreateSeuratObject(counts = cbmc.rna)

# We can see that by default, the cbmc object contains an assay storing RNA measurement
Assays(cbmc)
```

Example 14 (unknown):
```unknown
## [1] "RNA"
```

Example 15 (unknown):
```unknown
## [1] "RNA"
```

Example 16 (unknown):
```unknown
# create a new assay to store ADT information
adt_assay <- CreateAssay5Object(counts = cbmc.adt)

# add this assay to the previously created Seurat object
cbmc[["ADT"]] <- adt_assay

# Validate that the object now contains multiple assays
Assays(cbmc)
```

Example 17 (r):
```r
# create a new assay to store ADT information
adt_assay <- CreateAssay5Object(counts = cbmc.adt)

# add this assay to the previously created Seurat object
cbmc[["ADT"]] <- adt_assay

# Validate that the object now contains multiple assays
Assays(cbmc)
```

Example 18 (r):
```r
# create a new assay to store ADT information
adt_assay <- CreateAssay5Object(counts = cbmc.adt)

# add this assay to the previously created Seurat object
cbmc[["ADT"]] <- adt_assay

# Validate that the object now contains multiple assays
Assays(cbmc)
```

Example 19 (unknown):
```unknown
## [1] "RNA" "ADT"
```

Example 20 (unknown):
```unknown
## [1] "RNA" "ADT"
```

Example 21 (unknown):
```unknown
# Extract a list of features measured in the ADT assay
rownames(cbmc[["ADT"]])
```

Example 22 (r):
```r
# Extract a list of features measured in the ADT assay
rownames(cbmc[["ADT"]])
```

Example 23 (r):
```r
# Extract a list of features measured in the ADT assay
rownames(cbmc[["ADT"]])
```

Example 24 (unknown):
```unknown
##  [1] "CD3"    "CD4"    "CD8"    "CD45RA" "CD56"   "CD16"   "CD10"   "CD11c" 
##  [9] "CD14"   "CD19"   "CD34"   "CCR5"   "CCR7"
```

Example 25 (unknown):
```unknown
##  [1] "CD3"    "CD4"    "CD8"    "CD45RA" "CD56"   "CD16"   "CD10"   "CD11c" 
##  [9] "CD14"   "CD19"   "CD34"   "CCR5"   "CCR7"
```

Example 26 (unknown):
```unknown
# Note that we can easily switch back and forth between the two assays to specify the default
# for visualization and analysis

# List the current default assay
DefaultAssay(cbmc)
```

Example 27 (r):
```r
# Note that we can easily switch back and forth between the two assays to specify the default
# for visualization and analysis

# List the current default assay
DefaultAssay(cbmc)
```

Example 28 (r):
```r
# Note that we can easily switch back and forth between the two assays to specify the default
# for visualization and analysis

# List the current default assay
DefaultAssay(cbmc)
```

Example 29 (unknown):
```unknown
## [1] "RNA"
```

Example 30 (unknown):
```unknown
## [1] "RNA"
```

Example 31 (unknown):
```unknown
# Switch the default to ADT
DefaultAssay(cbmc) <- "ADT"
DefaultAssay(cbmc)
```

Example 32 (r):
```r
# Switch the default to ADT
DefaultAssay(cbmc) <- "ADT"
DefaultAssay(cbmc)
```

Example 33 (r):
```r
# Switch the default to ADT
DefaultAssay(cbmc) <- "ADT"
DefaultAssay(cbmc)
```

Example 34 (unknown):
```unknown
## [1] "ADT"
```

Example 35 (unknown):
```unknown
## [1] "ADT"
```

Example 36 (unknown):
```unknown
# Note that all operations below are performed on the RNA assay Set and verify that the
# default assay is RNA
DefaultAssay(cbmc) <- "RNA"
DefaultAssay(cbmc)
```

Example 37 (r):
```r
# Note that all operations below are performed on the RNA assay Set and verify that the
# default assay is RNA
DefaultAssay(cbmc) <- "RNA"
DefaultAssay(cbmc)
```

Example 38 (r):
```r
# Note that all operations below are performed on the RNA assay Set and verify that the
# default assay is RNA
DefaultAssay(cbmc) <- "RNA"
DefaultAssay(cbmc)
```

Example 39 (unknown):
```unknown
## [1] "RNA"
```

Example 40 (unknown):
```unknown
## [1] "RNA"
```

Example 41 (unknown):
```unknown
# perform visualization and clustering steps
cbmc <- NormalizeData(cbmc)
cbmc <- FindVariableFeatures(cbmc)
cbmc <- ScaleData(cbmc)
cbmc <- RunPCA(cbmc, verbose = FALSE)
cbmc <- FindNeighbors(cbmc, dims = 1:30)
cbmc <- FindClusters(cbmc, resolution = 0.8, verbose = FALSE)
cbmc <- RunUMAP(cbmc, dims = 1:30)
DimPlot(cbmc, label = TRUE)
```

Example 42 (r):
```r
# perform visualization and clustering steps
cbmc <- NormalizeData(cbmc)
cbmc <- FindVariableFeatures(cbmc)
cbmc <- ScaleData(cbmc)
cbmc <- RunPCA(cbmc, verbose = FALSE)
cbmc <- FindNeighbors(cbmc, dims = 1:30)
cbmc <- FindClusters(cbmc, resolution = 0.8, verbose = FALSE)
cbmc <- RunUMAP(cbmc, dims = 1:30)
DimPlot(cbmc, label = TRUE)
```

Example 43 (r):
```r
# perform visualization and clustering steps
cbmc <- NormalizeData(cbmc)
cbmc <- FindVariableFeatures(cbmc)
cbmc <- ScaleData(cbmc)
cbmc <- RunPCA(cbmc, verbose = FALSE)
cbmc <- FindNeighbors(cbmc, dims = 1:30)
cbmc <- FindClusters(cbmc, resolution = 0.8, verbose = FALSE)
cbmc <- RunUMAP(cbmc, dims = 1:30)
DimPlot(cbmc, label = TRUE)
```

Example 44 (unknown):
```unknown
# Normalize ADT data,
DefaultAssay(cbmc) <- "ADT"
cbmc <- NormalizeData(cbmc, normalization.method = "CLR", margin = 2)
DefaultAssay(cbmc) <- "RNA"

# Note that the following command is an alternative but returns the same result
cbmc <- NormalizeData(cbmc, normalization.method = "CLR", margin = 2, assay = "ADT")

# Now, we will visualize CD14 levels for RNA and protein By setting the default assay, we can
# visualize one or the other
DefaultAssay(cbmc) <- "ADT"
p1 <- FeaturePlot(cbmc, "CD19", cols = c("lightgrey", "darkgreen")) + ggtitle("CD19 protein")
DefaultAssay(cbmc) <- "RNA"
p2 <- FeaturePlot(cbmc, "CD19") + ggtitle("CD19 RNA")

# place plots side-by-side
p1 | p2
```

Example 45 (r):
```r
# Normalize ADT data,
DefaultAssay(cbmc) <- "ADT"
cbmc <- NormalizeData(cbmc, normalization.method = "CLR", margin = 2)
DefaultAssay(cbmc) <- "RNA"

# Note that the following command is an alternative but returns the same result
cbmc <- NormalizeData(cbmc, normalization.method = "CLR", margin = 2, assay = "ADT")

# Now, we will visualize CD14 levels for RNA and protein By setting the default assay, we can
# visualize one or the other
DefaultAssay(cbmc) <- "ADT"
p1 <- FeaturePlot(cbmc, "CD19", cols = c("lightgrey", "darkgreen")) + ggtitle("CD19 protein")
DefaultAssay(cbmc) <- "RNA"
p2 <- FeaturePlot(cbmc, "CD19") + ggtitle("CD19 RNA")

# place plots side-by-side
p1 | p2
```

Example 46 (r):
```r
# Normalize ADT data,
DefaultAssay(cbmc) <- "ADT"
cbmc <- NormalizeData(cbmc, normalization.method = "CLR", margin = 2)
DefaultAssay(cbmc) <- "RNA"

# Note that the following command is an alternative but returns the same result
cbmc <- NormalizeData(cbmc, normalization.method = "CLR", margin = 2, assay = "ADT")

# Now, we will visualize CD14 levels for RNA and protein By setting the default assay, we can
# visualize one or the other
DefaultAssay(cbmc) <- "ADT"
p1 <- FeaturePlot(cbmc, "CD19", cols = c("lightgrey", "darkgreen")) + ggtitle("CD19 protein")
DefaultAssay(cbmc) <- "RNA"
p2 <- FeaturePlot(cbmc, "CD19") + ggtitle("CD19 RNA")

# place plots side-by-side
p1 | p2
```

Example 47 (unknown):
```unknown
# Alternately, we can use specific assay keys to specify a specific modality Identify the key
# for the RNA and protein assays
Key(cbmc[["RNA"]])
```

Example 48 (r):
```r
# Alternately, we can use specific assay keys to specify a specific modality Identify the key
# for the RNA and protein assays
Key(cbmc[["RNA"]])
```

Example 49 (r):
```r
# Alternately, we can use specific assay keys to specify a specific modality Identify the key
# for the RNA and protein assays
Key(cbmc[["RNA"]])
```

Example 50 (unknown):
```unknown
## [1] "rna_"
```

Example 51 (unknown):
```unknown
## [1] "rna_"
```

Example 52 (unknown):
```unknown
Key(cbmc[["ADT"]])
```

Example 53 (r):
```r
Key(cbmc[["ADT"]])
```

Example 54 (r):
```r
Key(cbmc[["ADT"]])
```

Example 55 (unknown):
```unknown
## [1] "adt_"
```

Example 56 (unknown):
```unknown
## [1] "adt_"
```

Example 57 (unknown):
```unknown
# Now, we can include the key in the feature name, which overrides the default assay
p1 <- FeaturePlot(cbmc, "adt_CD19", cols = c("lightgrey", "darkgreen")) + ggtitle("CD19 protein")
p2 <- FeaturePlot(cbmc, "rna_CD19") + ggtitle("CD19 RNA")
p1 | p2
```

Example 58 (r):
```r
# Now, we can include the key in the feature name, which overrides the default assay
p1 <- FeaturePlot(cbmc, "adt_CD19", cols = c("lightgrey", "darkgreen")) + ggtitle("CD19 protein")
p2 <- FeaturePlot(cbmc, "rna_CD19") + ggtitle("CD19 RNA")
p1 | p2
```

Example 59 (r):
```r
# Now, we can include the key in the feature name, which overrides the default assay
p1 <- FeaturePlot(cbmc, "adt_CD19", cols = c("lightgrey", "darkgreen")) + ggtitle("CD19 protein")
p2 <- FeaturePlot(cbmc, "rna_CD19") + ggtitle("CD19 RNA")
p1 | p2
```

Example 60 (unknown):
```unknown
# as we know that CD19 is a B cell marker, we can identify cluster 6 as expressing CD19 on the
# surface
VlnPlot(cbmc, "adt_CD19")
```

Example 61 (r):
```r
# as we know that CD19 is a B cell marker, we can identify cluster 6 as expressing CD19 on the
# surface
VlnPlot(cbmc, "adt_CD19")
```

Example 62 (r):
```r
# as we know that CD19 is a B cell marker, we can identify cluster 6 as expressing CD19 on the
# surface
VlnPlot(cbmc, "adt_CD19")
```

Example 63 (unknown):
```unknown
# we can also identify alternative protein and RNA markers for this cluster through
# differential expression
adt_markers <- FindMarkers(cbmc, ident.1 = 6, assay = "ADT")
rna_markers <- FindMarkers(cbmc, ident.1 = 6, assay = "RNA")

head(adt_markers)
```

Example 64 (r):
```r
# we can also identify alternative protein and RNA markers for this cluster through
# differential expression
adt_markers <- FindMarkers(cbmc, ident.1 = 6, assay = "ADT")
rna_markers <- FindMarkers(cbmc, ident.1 = 6, assay = "RNA")

head(adt_markers)
```

Example 65 (r):
```r
# we can also identify alternative protein and RNA markers for this cluster through
# differential expression
adt_markers <- FindMarkers(cbmc, ident.1 = 6, assay = "ADT")
rna_markers <- FindMarkers(cbmc, ident.1 = 6, assay = "RNA")

head(adt_markers)
```

Example 66 (unknown):
```unknown
##                p_val avg_log2FC pct.1 pct.2     p_val_adj
## CD19   2.067533e-215  2.5741873     1     1 2.687793e-214
## CD45RA 8.108073e-109  0.5300346     1     1 1.054049e-107
## CD4    1.123162e-107 -1.6707420     1     1 1.460110e-106
## CD14   7.212876e-106 -1.0332070     1     1 9.376739e-105
## CD3     1.639633e-87 -1.5823056     1     1  2.131523e-86
## CCR5    2.552859e-63  0.3753989     1     1  3.318716e-62
```

Example 67 (unknown):
```unknown
##                p_val avg_log2FC pct.1 pct.2     p_val_adj
## CD19   2.067533e-215  2.5741873     1     1 2.687793e-214
## CD45RA 8.108073e-109  0.5300346     1     1 1.054049e-107
## CD4    1.123162e-107 -1.6707420     1     1 1.460110e-106
## CD14   7.212876e-106 -1.0332070     1     1 9.376739e-105
## CD3     1.639633e-87 -1.5823056     1     1  2.131523e-86
## CCR5    2.552859e-63  0.3753989     1     1  3.318716e-62
```

Example 68 (unknown):
```unknown
head(rna_markers)
```

Example 69 (r):
```r
head(rna_markers)
```

Example 70 (r):
```r
head(rna_markers)
```

Example 71 (unknown):
```unknown
##       p_val avg_log2FC pct.1 pct.2 p_val_adj
## IGHM      0   6.660187 0.977 0.044         0
## CD79A     0   6.748356 0.965 0.045         0
## TCL1A     0   7.428099 0.904 0.028         0
## CD79B     0   5.525568 0.944 0.089         0
## IGHD      0   7.811884 0.857 0.015         0
## MS4A1     0   7.523215 0.851 0.016         0
```

Example 72 (unknown):
```unknown
##       p_val avg_log2FC pct.1 pct.2 p_val_adj
## IGHM      0   6.660187 0.977 0.044         0
## CD79A     0   6.748356 0.965 0.045         0
## TCL1A     0   7.428099 0.904 0.028         0
## CD79B     0   5.525568 0.944 0.089         0
## IGHD      0   7.811884 0.857 0.015         0
## MS4A1     0   7.523215 0.851 0.016         0
```

Example 73 (unknown):
```unknown
# Draw ADT scatter plots (like biaxial plots for FACS). Note that you can even 'gate' cells if
# desired by using HoverLocator and FeatureLocator
FeatureScatter(cbmc, feature1 = "adt_CD19", feature2 = "adt_CD3")
```

Example 74 (r):
```r
# Draw ADT scatter plots (like biaxial plots for FACS). Note that you can even 'gate' cells if
# desired by using HoverLocator and FeatureLocator
FeatureScatter(cbmc, feature1 = "adt_CD19", feature2 = "adt_CD3")
```

Example 75 (r):
```r
# Draw ADT scatter plots (like biaxial plots for FACS). Note that you can even 'gate' cells if
# desired by using HoverLocator and FeatureLocator
FeatureScatter(cbmc, feature1 = "adt_CD19", feature2 = "adt_CD3")
```

Example 76 (unknown):
```unknown
# view relationship between protein and RNA
FeatureScatter(cbmc, feature1 = "adt_CD3", feature2 = "rna_CD3E")
```

Example 77 (r):
```r
# view relationship between protein and RNA
FeatureScatter(cbmc, feature1 = "adt_CD3", feature2 = "rna_CD3E")
```

Example 78 (r):
```r
# view relationship between protein and RNA
FeatureScatter(cbmc, feature1 = "adt_CD3", feature2 = "rna_CD3E")
```

Example 79 (unknown):
```unknown
FeatureScatter(cbmc, feature1 = "adt_CD4", feature2 = "adt_CD8")
```

Example 80 (r):
```r
FeatureScatter(cbmc, feature1 = "adt_CD4", feature2 = "adt_CD8")
```

Example 81 (r):
```r
FeatureScatter(cbmc, feature1 = "adt_CD4", feature2 = "adt_CD8")
```

Example 82 (unknown):
```unknown
# Let's look at the raw (non-normalized) ADT counts. You can see the values are quite high,
# particularly in comparison to RNA values. This is due to the significantly higher protein
# copy number in cells, which significantly reduces 'drop-out' in ADT data
FeatureScatter(cbmc, feature1 = "adt_CD4", feature2 = "adt_CD8", slot = "counts")
```

Example 83 (r):
```r
# Let's look at the raw (non-normalized) ADT counts. You can see the values are quite high,
# particularly in comparison to RNA values. This is due to the significantly higher protein
# copy number in cells, which significantly reduces 'drop-out' in ADT data
FeatureScatter(cbmc, feature1 = "adt_CD4", feature2 = "adt_CD8", slot = "counts")
```

Example 84 (r):
```r
# Let's look at the raw (non-normalized) ADT counts. You can see the values are quite high,
# particularly in comparison to RNA values. This is due to the significantly higher protein
# copy number in cells, which significantly reduces 'drop-out' in ADT data
FeatureScatter(cbmc, feature1 = "adt_CD4", feature2 = "adt_CD8", slot = "counts")
```

Example 85 (unknown):
```unknown
pbmc10k.data <- Read10X(data.dir = "/brahms/shared/vignette-data/pbmc10k/filtered_feature_bc_matrix/")
rownames(x = pbmc10k.data[["Antibody Capture"]]) <- gsub(pattern = "_[control_]*TotalSeqB", replacement = "",
    x = rownames(x = pbmc10k.data[["Antibody Capture"]]))

pbmc10k <- CreateSeuratObject(counts = pbmc10k.data[["Gene Expression"]], min.cells = 3, min.features = 200)
pbmc10k <- NormalizeData(pbmc10k)
pbmc10k[["ADT"]] <- CreateAssayObject(pbmc10k.data[["Antibody Capture"]][, colnames(x = pbmc10k)])
pbmc10k <- NormalizeData(pbmc10k, assay = "ADT", normalization.method = "CLR")

plot1 <- FeatureScatter(pbmc10k, feature1 = "adt_CD19", feature2 = "adt_CD3", pt.size = 1)
plot2 <- FeatureScatter(pbmc10k, feature1 = "adt_CD4", feature2 = "adt_CD8a", pt.size = 1)
plot3 <- FeatureScatter(pbmc10k, feature1 = "adt_CD3", feature2 = "CD3E", pt.size = 1)
(plot1 + plot2 + plot3) & NoLegend()
```

Example 86 (r):
```r
pbmc10k.data <- Read10X(data.dir = "/brahms/shared/vignette-data/pbmc10k/filtered_feature_bc_matrix/")
rownames(x = pbmc10k.data[["Antibody Capture"]]) <- gsub(pattern = "_[control_]*TotalSeqB", replacement = "",
    x = rownames(x = pbmc10k.data[["Antibody Capture"]]))

pbmc10k <- CreateSeuratObject(counts = pbmc10k.data[["Gene Expression"]], min.cells = 3, min.features = 200)
pbmc10k <- NormalizeData(pbmc10k)
pbmc10k[["ADT"]] <- CreateAssayObject(pbmc10k.data[["Antibody Capture"]][, colnames(x = pbmc10k)])
pbmc10k <- NormalizeData(pbmc10k, assay = "ADT", normalization.method = "CLR")

plot1 <- FeatureScatter(pbmc10k, feature1 = "adt_CD19", feature2 = "adt_CD3", pt.size = 1)
plot2 <- FeatureScatter(pbmc10k, feature1 = "adt_CD4", feature2 = "adt_CD8a", pt.size = 1)
plot3 <- FeatureScatter(pbmc10k, feature1 = "adt_CD3", feature2 = "CD3E", pt.size = 1)
(plot1 + plot2 + plot3) & NoLegend()
```

Example 87 (r):
```r
pbmc10k.data <- Read10X(data.dir = "/brahms/shared/vignette-data/pbmc10k/filtered_feature_bc_matrix/")
rownames(x = pbmc10k.data[["Antibody Capture"]]) <- gsub(pattern = "_[control_]*TotalSeqB", replacement = "",
    x = rownames(x = pbmc10k.data[["Antibody Capture"]]))

pbmc10k <- CreateSeuratObject(counts = pbmc10k.data[["Gene Expression"]], min.cells = 3, min.features = 200)
pbmc10k <- NormalizeData(pbmc10k)
pbmc10k[["ADT"]] <- CreateAssayObject(pbmc10k.data[["Antibody Capture"]][, colnames(x = pbmc10k)])
pbmc10k <- NormalizeData(pbmc10k, assay = "ADT", normalization.method = "CLR")

plot1 <- FeatureScatter(pbmc10k, feature1 = "adt_CD19", feature2 = "adt_CD3", pt.size = 1)
plot2 <- FeatureScatter(pbmc10k, feature1 = "adt_CD4", feature2 = "adt_CD8a", pt.size = 1)
plot3 <- FeatureScatter(pbmc10k, feature1 = "adt_CD3", feature2 = "CD3E", pt.size = 1)
(plot1 + plot2 + plot3) & NoLegend()
```

Example 88 (unknown):
```unknown
plot <- FeatureScatter(cbmc, feature1 = "adt_CD19", feature2 = "adt_CD3") + NoLegend() + theme(axis.title = element_text(size = 18),
    legend.text = element_text(size = 18))
ggsave(filename = "../output/images/citeseq_plot.jpg", height = 7, width = 12, plot = plot, quality = 50)
```

Example 89 (r):
```r
plot <- FeatureScatter(cbmc, feature1 = "adt_CD19", feature2 = "adt_CD3") + NoLegend() + theme(axis.title = element_text(size = 18),
    legend.text = element_text(size = 18))
ggsave(filename = "../output/images/citeseq_plot.jpg", height = 7, width = 12, plot = plot, quality = 50)
```

Example 90 (r):
```r
plot <- FeatureScatter(cbmc, feature1 = "adt_CD19", feature2 = "adt_CD3") + NoLegend() + theme(axis.title = element_text(size = 18),
    legend.text = element_text(size = 18))
ggsave(filename = "../output/images/citeseq_plot.jpg", height = 7, width = 12, plot = plot, quality = 50)
```

Example 91 (unknown):
```unknown
sessionInfo()
```

Example 92 (r):
```r
sessionInfo()
```

Example 93 (r):
```r
sessionInfo()
```

Example 94 (unknown):
```unknown
## R version 4.2.2 Patched (2022-11-10 r83330)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.6 LTS
## 
## Matrix products: default
## BLAS:   /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.9.0
## LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.9.0
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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       
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
## [1] patchwork_1.1.3    ggplot2_3.4.4      Seurat_5.0.1  testthat_3.2.0    
## [5] SeuratObject_5.0.1 sp_2.1-1          
## 
## loaded via a namespace (and not attached):
##   [1] spam_2.10-0            systemfonts_1.0.4      plyr_1.8.9            
##   [4] igraph_1.5.1           lazyeval_0.2.2         splines_4.2.2         
##   [7] RcppHNSW_0.5.0         listenv_0.9.0          scattermore_1.2       
##  [10] usethis_2.1.6          digest_0.6.33          htmltools_0.5.6.1     
##  [13] fansi_1.0.5            magrittr_2.0.3         memoise_2.0.1         
##  [16] tensor_1.5             cluster_2.1.4          ROCR_1.0-11           
##  [19] limma_3.54.1           remotes_2.4.2.1        globals_0.16.2        
##  [22] matrixStats_1.0.0      R.utils_2.12.2         pkgdown_2.0.7         
##  [25] spatstat.sparse_3.0-3  prettyunits_1.2.0      colorspace_2.1-0      
##  [28] ggrepel_0.9.4          textshaping_0.3.6      xfun_0.40             
##  [31] dplyr_1.1.3            callr_3.7.3            crayon_1.5.2          
##  [34] jsonlite_1.8.7         progressr_0.14.0       spatstat.data_3.0-3   
##  [37] survival_3.5-7         zoo_1.8-12             glue_1.6.2            
##  [40] polyclip_1.10-6        gtable_0.3.4           leiden_0.4.3          
##  [43] pkgbuild_1.4.2         future.apply_1.11.0    abind_1.4-5           
##  [46] scales_1.2.1           spatstat.random_3.2-1  miniUI_0.1.1.1        
##  [49] Rcpp_1.0.11            viridisLite_0.4.2      xtable_1.8-4          
##  [52] reticulate_1.34.0      dotCall64_1.1-0        profvis_0.3.7         
##  [55] htmlwidgets_1.6.2      httr_1.4.7             RColorBrewer_1.1-3    
##  [58] ellipsis_0.3.2         ica_1.0-3              R.methodsS3_1.8.2     
##  [61] farver_2.1.1           urlchecker_1.0.1       pkgconfig_2.0.3       
##  [64] uwot_0.1.16            sass_0.4.7             deldir_1.0-9          
##  [67] utf8_1.2.4             labeling_0.4.3         tidyselect_1.2.0      
##  [70] rlang_1.1.1            reshape2_1.4.4         later_1.3.1           
##  [73] munsell_0.5.0          tools_4.2.2            cachem_1.0.8          
##  [76] cli_3.6.1              generics_0.1.3         devtools_2.4.5        
##  [79] ggridges_0.5.4         evaluate_0.22          stringr_1.5.0         
##  [82] fastmap_1.1.1          goftest_1.2-3          yaml_2.3.7            
##  [85] ragg_1.2.5             processx_3.8.2         knitr_1.45            
##  [88] fs_1.6.3               fitdistrplus_1.1-11    purrr_1.0.2           
##  [91] RANN_2.6.1             nlme_3.1-162           pbapply_1.7-2         
##  [94] future_1.33.0          mime_0.12              formatR_1.14          
##  [97] R.oo_1.25.0            ggrastr_1.0.1          brio_1.1.3            
## [100] compiler_4.2.2         rstudioapi_0.14        beeswarm_0.4.0        
## [103] plotly_4.10.3          png_0.1-8              spatstat.utils_3.0-4  
## [106] tibble_3.2.1           bslib_0.5.1            stringi_1.7.12        
## [109] highr_0.10             ps_1.7.5               desc_1.4.2            
## [112] RSpectra_0.16-1        lattice_0.21-9         Matrix_1.6-1.1        
## [115] vctrs_0.6.4            pillar_1.9.0           lifecycle_1.0.4       
## [118] spatstat.geom_3.2-7    lmtest_0.9-40          jquerylib_0.1.4       
## [121] RcppAnnoy_0.0.21       data.table_1.14.8      cowplot_1.1.1         
## [124] irlba_2.3.5.1          httpuv_1.6.12          R6_2.5.1              
## [127] promises_1.2.1         KernSmooth_2.23-22     gridExtra_2.3         
## [130] vipor_0.4.5            parallelly_1.36.0      sessioninfo_1.2.2     
## [133] codetools_0.2-19       fastDummies_1.7.3      MASS_7.3-58.2         
## [136] pkgload_1.3.3          rprojroot_2.0.4        withr_2.5.2           
## [139] presto_1.0.0           sctransform_0.4.1      parallel_4.2.2        
## [142] grid_4.2.2             tidyr_1.3.0            rmarkdown_2.25        
## [145] Rtsne_0.16             spatstat.explore_3.2-5 shiny_1.7.5.1         
## [148] ggbeeswarm_0.7.1
```

Example 95 (unknown):
```unknown
## R version 4.2.2 Patched (2022-11-10 r83330)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.6 LTS
## 
## Matrix products: default
## BLAS:   /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.9.0
## LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.9.0
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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       
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
## [1] patchwork_1.1.3    ggplot2_3.4.4      Seurat_5.0.1  testthat_3.2.0    
## [5] SeuratObject_5.0.1 sp_2.1-1          
## 
## loaded via a namespace (and not attached):
##   [1] spam_2.10-0            systemfonts_1.0.4      plyr_1.8.9            
##   [4] igraph_1.5.1           lazyeval_0.2.2         splines_4.2.2         
##   [7] RcppHNSW_0.5.0         listenv_0.9.0          scattermore_1.2       
##  [10] usethis_2.1.6          digest_0.6.33          htmltools_0.5.6.1     
##  [13] fansi_1.0.5            magrittr_2.0.3         memoise_2.0.1         
##  [16] tensor_1.5             cluster_2.1.4          ROCR_1.0-11           
##  [19] limma_3.54.1           remotes_2.4.2.1        globals_0.16.2        
##  [22] matrixStats_1.0.0      R.utils_2.12.2         pkgdown_2.0.7         
##  [25] spatstat.sparse_3.0-3  prettyunits_1.2.0      colorspace_2.1-0      
##  [28] ggrepel_0.9.4          textshaping_0.3.6      xfun_0.40             
##  [31] dplyr_1.1.3            callr_3.7.3            crayon_1.5.2          
##  [34] jsonlite_1.8.7         progressr_0.14.0       spatstat.data_3.0-3   
##  [37] survival_3.5-7         zoo_1.8-12             glue_1.6.2            
##  [40] polyclip_1.10-6        gtable_0.3.4           leiden_0.4.3          
##  [43] pkgbuild_1.4.2         future.apply_1.11.0    abind_1.4-5           
##  [46] scales_1.2.1           spatstat.random_3.2-1  miniUI_0.1.1.1        
##  [49] Rcpp_1.0.11            viridisLite_0.4.2      xtable_1.8-4          
##  [52] reticulate_1.34.0      dotCall64_1.1-0        profvis_0.3.7         
##  [55] htmlwidgets_1.6.2      httr_1.4.7             RColorBrewer_1.1-3    
##  [58] ellipsis_0.3.2         ica_1.0-3              R.methodsS3_1.8.2     
##  [61] farver_2.1.1           urlchecker_1.0.1       pkgconfig_2.0.3       
##  [64] uwot_0.1.16            sass_0.4.7             deldir_1.0-9          
##  [67] utf8_1.2.4             labeling_0.4.3         tidyselect_1.2.0      
##  [70] rlang_1.1.1            reshape2_1.4.4         later_1.3.1           
##  [73] munsell_0.5.0          tools_4.2.2            cachem_1.0.8          
##  [76] cli_3.6.1              generics_0.1.3         devtools_2.4.5        
##  [79] ggridges_0.5.4         evaluate_0.22          stringr_1.5.0         
##  [82] fastmap_1.1.1          goftest_1.2-3          yaml_2.3.7            
##  [85] ragg_1.2.5             processx_3.8.2         knitr_1.45            
##  [88] fs_1.6.3               fitdistrplus_1.1-11    purrr_1.0.2           
##  [91] RANN_2.6.1             nlme_3.1-162           pbapply_1.7-2         
##  [94] future_1.33.0          mime_0.12              formatR_1.14          
##  [97] R.oo_1.25.0            ggrastr_1.0.1          brio_1.1.3            
## [100] compiler_4.2.2         rstudioapi_0.14        beeswarm_0.4.0        
## [103] plotly_4.10.3          png_0.1-8              spatstat.utils_3.0-4  
## [106] tibble_3.2.1           bslib_0.5.1            stringi_1.7.12        
## [109] highr_0.10             ps_1.7.5               desc_1.4.2            
## [112] RSpectra_0.16-1        lattice_0.21-9         Matrix_1.6-1.1        
## [115] vctrs_0.6.4            pillar_1.9.0           lifecycle_1.0.4       
## [118] spatstat.geom_3.2-7    lmtest_0.9-40          jquerylib_0.1.4       
## [121] RcppAnnoy_0.0.21       data.table_1.14.8      cowplot_1.1.1         
## [124] irlba_2.3.5.1          httpuv_1.6.12          R6_2.5.1              
## [127] promises_1.2.1         KernSmooth_2.23-22     gridExtra_2.3         
## [130] vipor_0.4.5            parallelly_1.36.0      sessioninfo_1.2.2     
## [133] codetools_0.2-19       fastDummies_1.7.3      MASS_7.3-58.2         
## [136] pkgload_1.3.3          rprojroot_2.0.4        withr_2.5.2           
## [139] presto_1.0.0           sctransform_0.4.1      parallel_4.2.2        
## [142] grid_4.2.2             tidyr_1.3.0            rmarkdown_2.25        
## [145] Rtsne_0.16             spatstat.explore_3.2-5 shiny_1.7.5.1         
## [148] ggbeeswarm_0.7.1
```

---

## Parallelization in Seurat with future

**URL:** http://127.0.0.1:9173/seurat/archive/v3.1/future_vignette/index.html

**Contents:**
- Parallelization in Seurat with future
    - Compiled: April 17, 2020
  - How to use parallelization in Seurat
  - ‘Futurized’ functions in Seurat
  - Comparison of sequential vs. parallel
  - Frequently asked questions

In Seurat, we have chosen to use the future framework for parallelization. In this vignette, we will demonstrate how you can take advantage of the future implementation of certain Seurat functions from a user’s perspective. If you are interested in learning more about the future framework beyond what is described here, please see the package vignettes here for a comprehensive and detailed description.

To access the parallel version of functions in Seurat, you need to load the future package and set the plan. The plan will specify how the function is executed. The default behavior is to evaluate in a non-parallelized fashion (sequentially). To achieve parallel (asynchronous) behavior, we typically recommend the “multiprocess” strategy. By default, this uses all available cores but you can set the workers parameter to limit the number of concurrently active futures.

The following functions have been written to take advantage of the future framework and will be parallelized if the current plan is set appropriately. Importantly, the way you call the function shouldn’t change.

For example, to run the parallel version of FindMarkers, you simply need to set the plan and call the function as usual.

Here we’ll perform a brief comparison the runtimes for the same function calls with and without parallelization. Note that while we expect that using a parallelized strategy will decrease the runtimes of the functions listed above, the magnitude of that decrease will depend on many factors (e.g. the size of the dataset, the number of workers, specs of the system, the future strategy, etc). The following benchmarks were performed on a desktop computer running Ubuntu 16.04.5 LTS with an Intel(R) Core(TM) i7-6800K CPU @ 3.40GHz and 96 GB of RAM.

Click to see bencharking code

Where did my progress bar go? Unfortantely, the when running these functions in any of the parallel plan modes you will lose the progress bar. This is due to some technical limitations in the future framework and R generally. If you want to monitor function progress, you’ll need to forgo parallelization and use plan("sequential").

What should I do if I keep seeing the following error?

For certain functions, each worker needs access to certain global variables. If these are larger than the default limit, you will see this error. To get around this, you can set options(future.globals.maxSize = X), where X is the maximum allowed size in bytes. So to set it to 1GB, you would run options(future.globals.maxSize = 1000 * 1024^2). Note that this will increase your RAM usage so set this number mindfully.

**Examples:**

Example 1 (r):
```r
library(future)
# check the current active plan
plan()
```

Example 2 (r):
```r
library(future)
# check the current active plan
plan()
```

Example 3 (unknown):
```unknown
## sequential:
## - args: function (expr, envir = parent.frame(), substitute = TRUE, lazy = FALSE, seed = NULL, globals = TRUE, local = TRUE, earlySignal = FALSE, label = NULL, ...)
## - tweaked: FALSE
## - call: NULL
```

Example 4 (unknown):
```unknown
## sequential:
## - args: function (expr, envir = parent.frame(), substitute = TRUE, lazy = FALSE, seed = NULL, globals = TRUE, local = TRUE, earlySignal = FALSE, label = NULL, ...)
## - tweaked: FALSE
## - call: NULL
```

Example 5 (r):
```r
# change the current plan to access parallelization
plan("multiprocess", workers = 4)
plan()
```

Example 6 (r):
```r
# change the current plan to access parallelization
plan("multiprocess", workers = 4)
plan()
```

Example 7 (unknown):
```unknown
## multiprocess:
## - args: function (expr, envir = parent.frame(), substitute = TRUE, lazy = FALSE, seed = NULL, globals = TRUE, workers = 4, gc = FALSE, earlySignal = FALSE, label = NULL, ...)
## - tweaked: TRUE
## - call: plan("multiprocess", workers = 4)
```

Example 8 (unknown):
```unknown
## multiprocess:
## - args: function (expr, envir = parent.frame(), substitute = TRUE, lazy = FALSE, seed = NULL, globals = TRUE, workers = 4, gc = FALSE, earlySignal = FALSE, label = NULL, ...)
## - tweaked: TRUE
## - call: plan("multiprocess", workers = 4)
```

Example 9 (unknown):
```unknown
NormalizeData
```

Example 10 (unknown):
```unknown
FindMarkers
```

Example 11 (unknown):
```unknown
FindIntegrationAnchors
```

Example 12 (unknown):
```unknown
FindClusters
```

Example 13 (unknown):
```unknown
FindMarkers
```

Example 14 (r):
```r
library(Seurat)
pbmc <- readRDS("../data/pbmc3k_final.rds")

# Enable parallelization
plan("multiprocess", workers = 4)
markers <- FindMarkers(pbmc, ident.1 = "NK", verbose = FALSE)
```

Example 15 (r):
```r
library(Seurat)
pbmc <- readRDS("../data/pbmc3k_final.rds")

# Enable parallelization
plan("multiprocess", workers = 4)
markers <- FindMarkers(pbmc, ident.1 = "NK", verbose = FALSE)
```

Example 16 (r):
```r
timing.comparisons <- data.frame(fxn = character(), time = numeric(), strategy = character())
plan("sequential")
start <- Sys.time()
pbmc <- ScaleData(pbmc, vars.to.regress = "percent.mt", verbose = FALSE)
end <- Sys.time()
timing.comparisons <- rbind(timing.comparisons, data.frame(fxn = "ScaleData", time = as.numeric(end - 
    start, units = "secs"), strategy = "sequential"))

start <- Sys.time()
markers <- FindMarkers(pbmc, ident.1 = "NK", verbose = FALSE)
end <- Sys.time()
timing.comparisons <- rbind(timing.comparisons, data.frame(fxn = "FindMarkers", time = as.numeric(end - 
    start, units = "secs"), strategy = "sequential"))

plan("multiprocess", workers = 4)
start <- Sys.time()
pbmc <- ScaleData(pbmc, vars.to.regress = "percent.mt", verbose = FALSE)
end <- Sys.time()
timing.comparisons <- rbind(timing.comparisons, data.frame(fxn = "ScaleData", time = as.numeric(end - 
    start, units = "secs"), strategy = "multiprocess"))

start <- Sys.time()
markers <- FindMarkers(pbmc, ident.1 = "NK", verbose = FALSE)
end <- Sys.time()
timing.comparisons <- rbind(timing.comparisons, data.frame(fxn = "FindMarkers", time = as.numeric(end - 
    start, units = "secs"), strategy = "multiprocess"))
```

Example 17 (r):
```r
timing.comparisons <- data.frame(fxn = character(), time = numeric(), strategy = character())
plan("sequential")
start <- Sys.time()
pbmc <- ScaleData(pbmc, vars.to.regress = "percent.mt", verbose = FALSE)
end <- Sys.time()
timing.comparisons <- rbind(timing.comparisons, data.frame(fxn = "ScaleData", time = as.numeric(end - 
    start, units = "secs"), strategy = "sequential"))

start <- Sys.time()
markers <- FindMarkers(pbmc, ident.1 = "NK", verbose = FALSE)
end <- Sys.time()
timing.comparisons <- rbind(timing.comparisons, data.frame(fxn = "FindMarkers", time = as.numeric(end - 
    start, units = "secs"), strategy = "sequential"))

plan("multiprocess", workers = 4)
start <- Sys.time()
pbmc <- ScaleData(pbmc, vars.to.regress = "percent.mt", verbose = FALSE)
end <- Sys.time()
timing.comparisons <- rbind(timing.comparisons, data.frame(fxn = "ScaleData", time = as.numeric(end - 
    start, units = "secs"), strategy = "multiprocess"))

start <- Sys.time()
markers <- FindMarkers(pbmc, ident.1 = "NK", verbose = FALSE)
end <- Sys.time()
timing.comparisons <- rbind(timing.comparisons, data.frame(fxn = "FindMarkers", time = as.numeric(end - 
    start, units = "secs"), strategy = "multiprocess"))
```

Example 18 (r):
```r
library(ggplot2)
library(cowplot)
ggplot(timing.comparisons, aes(fxn, time)) + geom_bar(aes(fill = strategy), stat = "identity", position = "dodge") + 
    ylab("Time(s)") + xlab("Function") + theme_cowplot()
```

Example 19 (r):
```r
library(ggplot2)
library(cowplot)
ggplot(timing.comparisons, aes(fxn, time)) + geom_bar(aes(fill = strategy), stat = "identity", position = "dodge") + 
    ylab("Time(s)") + xlab("Function") + theme_cowplot()
```

Example 20 (unknown):
```unknown
plan("sequential")
```

Example 21 (unknown):
```unknown
Error in getGlobalsAndPackages(expr, envir = envir, globals = TRUE) : 
  The total size of the X globals that need to be exported for the future expression ('FUN()') is X GiB. This exceeds the maximum allowed size of 500.00 MiB (option 'future.globals.maxSize'). The X largest globals are ...
```

Example 22 (unknown):
```unknown
Error in getGlobalsAndPackages(expr, envir = envir, globals = TRUE) : 
  The total size of the X globals that need to be exported for the future expression ('FUN()') is X GiB. This exceeds the maximum allowed size of 500.00 MiB (option 'future.globals.maxSize'). The X largest globals are ...
```

Example 23 (unknown):
```unknown
options(future.globals.maxSize = X)
```

Example 24 (unknown):
```unknown
options(future.globals.maxSize = 1000 * 1024^2)
```

---

## Analysis, visualization, and integration of spatial datasets with Seurat • Seurat

**URL:** http://127.0.0.1:9173/seurat/articles/spatial_vignette/index.html

**Contents:**
- Analysis, visualization, and integration of spatial datasets with Seurat
    - Compiled: 2025-06-17
- Overview
- 10x Visium
  - Dataset
  - Data preprocessing
  - Gene expression visualization
  - Dimensionality reduction, clustering, and visualization
  - Interactive plotting
  - Identification of Spatially Variable Features
  - Subset out anatomical regions
  - Integration with single-cell data
  - Working with multiple slices in Seurat
  - Acknowledgments
- Slide-seq
  - Dataset
  - Data preprocessing
  - Integration with a scRNA-seq reference
  - Identification of Spatially Variable Features
  - Spatial deconvolution using RCTD

This tutorial demonstrates how to use Seurat (>=3.2) to analyze spatially-resolved RNA-seq data. While the analytical pipelines are similar to the Seurat workflow for single-cell RNA-seq analysis, we introduce updated interaction and visualization tools, with a particular emphasis on the integration of spatial and molecular information. This tutorial will cover the following tasks, which we believe will be common for many spatial analyses:

For our first vignette, we analyze a dataset generated with the Visium technology from 10x Genomics. We will be extending Seurat to work with additional data types in the near-future, including SLIDE-Seq, STARmap, and MERFISH.

First, we load Seurat and the other packages necessary for this vignette.

Here, we will be using a recently released dataset of sagital mouse brain slices generated using the Visium v1 chemistry. There are two serial anterior sections, and two (matched) serial posterior sections.

You can download the data here, and load it into Seurat using the Load10X_Spatial() function. This reads in the output of the spaceranger pipeline, and returns a Seurat object that contains both the spot-level expression data along with the associated image of the tissue slice. You can also use our SeuratData package for easy data access, as demonstrated below. After installing the dataset, you can type ?stxBrain to learn more.

The visium data from 10x consists of the following data types:

The initial preprocessing steps that we perform on the spot by gene expression data are similar to a typical scRNA-seq experiment. We first need to normalize the data in order to account for variance in sequencing depth across data points. We note that the variance in molecular counts / spot can be substantial for spatial datasets, particularly if there are differences in cell density across the tissue. We see substantial heterogeneity here, which requires effective normalization.

These plots demonstrate that the variance in molecular counts across spots is not just technical in nature, but also is dependent on the tissue anatomy. For example, regions of the tissue that are depleted for neurons (such as the cortical white matter), reproducibly exhibit lower molecular counts. As a result, standard approaches (such as the LogNormalize() function), which force each data point to have the same underlying ‘size’ after normalization, can be problematic.

As an alternative, we recommend using sctransform (Hafemeister and Satija, Genome Biology 2019), which which builds regularized negative binomial models of gene expression in order to account for technical artifacts while preserving biological variance. For more details on sctransform, please see the paper here and the Seurat vignette here. sctransform normalizes the data, detects high-variance features, and stores the data in the SCT assay.

To explore the differences in normalization methods, we examine how both the sctransform and log normalization results correlate with the number of UMIs. For this comparison, we first rerun sctransform to store values for all genes and run a log-normalization procedure via NormalizeData().

In Seurat, we have functionality to explore and interact with the inherently visual nature of spatial data. The SpatialFeaturePlot() function in Seurat extends FeaturePlot(), and can overlay molecular data on top of tissue histology. For example, in this data set of the mouse brain, the gene Hpca is a strong hippocampus marker and Ttr is a marker of the choroid plexus.

The default parameters in Seurat emphasize the visualization of molecular data. However, you can also adjust the size of the spots (and their transparency) to improve the visualization of the histology image, by changing the following parameters:

We can then proceed to run dimensionality reduction and clustering on the RNA expression data, using the same workflow as we use for scRNA-seq analysis.

We can then visualize the results of the clustering either in UMAP space (with DimPlot()) or overlaid on the image with SpatialDimPlot().

As there are many colors, it can be challenging to visualize which voxel belongs to which cluster. We have a few strategies to help with this. Setting the label parameter places a colored box at the median of each cluster (see the plot above).

You can also use the cells.highlight parameter to demarcate particular cells of interest on a SpatialDimPlot(). This can be very useful for distinguishing the spatial localization of individual clusters, as we show below:

We have also built in a number of interactive plotting capabilities. Both SpatialDimPlot() and SpatialFeaturePlot() now have an interactive parameter, that when set to TRUE, will open up the Rstudio viewer pane with an interactive Shiny plot. The example below demonstrates an interactive SpatialDimPlot() in which you can hover over spots and view the cell name and current identity class (analogous to the previous do.hover behavior).

For SpatialFeaturePlot(), setting interactive to TRUE brings up an interactive pane in which you can adjust the transparency of the spots, the point size, as well as the Assay and feature being plotted. After exploring the data, selecting the done button will return the last active plot as a ggplot object.

The LinkedDimPlot() function links the UMAP representation to the tissue image representation and allows for interactive selection. For example, you can select a region in the UMAP plot and the corresponding spots in the image representation will be highlighted.

Seurat offers two workflows to identify molecular features that correlate with spatial location within a tissue. The first is to perform differential expression based on pre-annotated anatomical regions within the tissue, which may be determined either from unsupervised clustering or prior knowledge. This strategy works will in this case, as the clusters above exhibit clear spatial restriction.

An alternative approach, implemented in FindSpatiallyVariables(), is to search for features exhibiting spatial patterning in the absence of pre-annotation. The default method (method = 'markvariogram), is inspired by the Trendsceek, which models spatial transcriptomics data as a mark point process and computes a ‘variogram’, which identifies genes whose expression level is dependent on their spatial location. More specifically, this process calculates gamma(r) values measuring the dependence between two spots a certain “r” distance apart. By default, we use an r-value of ‘5’ in these analyses, and only compute these values for variable genes (where variation is calculated independently of spatial location) to save time.

We note that there are multiple methods in the literature to accomplish this task, including SpatialDE, and Splotch. We encourage interested users to explore these methods, and hope to add support for them in the near future.

Now we visualize the expression of the top 6 features identified by this measure.

As with single-cell objects, you can subset the object to focus on a subset of data. Here, we approximately subset the frontal cortex. This process also facilitates the integration of these data with a cortical scRNA-seq dataset in the next section. First, we take a subset of clusters, and then further segment based on exact positions. After subsetting, we can visualize the cortical cells either on the full image, or a cropped image.

In SeuratObject v5.1.0, spatial coordinates are no longer stored directly in the metadata and are instead located in the spatial image structure. To perform spatial filtering, we need to extract the x (image column) and y (image row) positions from the spatial centroids and manually attach them to the metadata prior to subsetting.

At ~50um, spots from the visium assay will encompass the expression profiles of multiple cells. For the growing list of systems where scRNA-seq data is available, users may be interested to ‘deconvolute’ each of the spatial voxels to predict the underlying composition of cell types. In preparing this vignette, we tested a wide variety of decovonlution and integration methods, using a reference scRNA-seq dataset of ~14,000 adult mouse cortical cell taxonomy from the Allen Institute, generated with the SMART-Seq2 protocol. We consistently found superior performance using integration methods (as opposed to deconvolution methods), likely because of substantially different noise models that characterize spatial and single-cell datasets, and integration methods are specifiically designed to be robust to these differences. We therefore apply the ‘anchor’-based integration workflow introduced in Seurat v3, that enables the probabilistic transfer of annotations from a reference to a query set. We therefore follow the label transfer workflow introduced here, taking advantage of sctransform normalization, but anticipate new methods to be developed to accomplish this task.

We first load the data (download available here), pre-process the scRNA-seq reference, and then perform label transfer. The procedure outputs, for each spot, a probabilistic classification for each of the scRNA-seq derived classes. We add these predictions as a new assay in the Seurat object.

Now we get prediction scores for each spot for each class. Of particular interest in the frontal cortex region are the laminar excitatory neurons. Here we can distinguish between distinct sequential layers of these neuronal subtypes, for example:

Based on these prediction scores, we can also predict cell types whose location is spatially restricted. We use the same methods based on marked point processes to define spatially variable features, but use the cell type prediction scores as the “marks” rather than gene expression.

Finally, we show that our integrative procedure is capable of recovering the known spatial localization patterns of both neuronal and non-neuronal subsets, including laminar excitatory, layer-1 astrocytes, and the cortical grey matter.

This dataset of the mouse brain contains another slice corresponding to the other half of the brain. Here we read it in and perform the same initial normalization.

In order to work with multiple slices in the same Seurat object, we provide the merge function.

This then enables joint dimensional reduction and clustering on the underlying RNA expression data.

Finally, the data can be jointly visualized in a single UMAP plot. SpatialDimPlot() and SpatialFeaturePlot() will by default plot all slices as columns and groupings/features as rows.

We would like to thank Nigel Delaney and Stephen Williams for their helpful feedback and contributions to the new spatial Seurat code.

Here, we will be analyzing a dataset generated using Slide-seq v2 of the mouse hippocampus. This tutorial will follow much of the same structure as the spatial vignette for 10x Visium data but is tailored to give a demonstration specific to Slide-seq data.

You can use our SeuratData package for easy data access, as demonstrated below. After installing the dataset, you can type ?ssHippo to see the commands used to create the Seurat object.

The initial preprocessing steps for the bead by gene expression data are similar to other spatial Seurat analyses and to typical scRNA-seq experiments. Here, we note that many beads contain particularly low UMI counts but choose to keep all detected beads for downstream analysis.

We then normalize the data using sctransform and perform a standard scRNA-seq dimensionality reduction and clustering workflow.

We can then visualize the results of the clustering either in UMAP space (with DimPlot()) or in the bead coordinate space with SpatialDimPlot().

To facilitate cell-type annotation of the Slide-seq dataset, we are leveraging an existing mouse single-cell RNA-seq hippocampus dataset, produced in Saunders*, Macosko*, et al. 2018. The data is available for download as a processed Seurat object here, with the raw count matrices available on the DropViz website.

The original annotations from the paper are provided in the cell metadata of the Seurat object. These annotations are provided at several “resolutions”, from broad classes (ref$class) to subclusters within celltypes (ref$subcluster). For the purposes of this vignette, we’ll work off of a modification of the celltype annotations (ref$celltype) which we felt struck a good balance.

We’ll start by running the Seurat label transfer method to predict the major celltype for each bead.

We can then visualize the prediction scores for some of the major expected classes.

As mentioned in the Visium vignette, we can identify spatially variable features in two general ways: differential expression testing between pre-annotated anatomical regions or statistics that measure the dependence of a feature on spatial location.

Here, we demonstrate the latter with an implementation of Moran’s I available via FindSpatiallyVariableFeatures() by setting method = 'moransi'. Moran’s I computes an overall spatial autocorrelation and gives a statistic (similar to a correlation coefficient) that measures the dependence of a feature on spatial location. This allows us to rank features based on how spatially variable their expression is. In order to facilitate quick estimation of this statistic, we implemented a basic binning strategy that will draw a rectangular grid over Slide-seq puck and average the feature and location within each bin. The number of bins in the x and y direction are controlled by the x.cuts and y.cuts parameters respectively. Additionally, while not required, installing the optional Rfast2 package(install.packages('Rfast2')), will significantly decrease the runtime via a more efficient implementation.

Now we visualize the expression of the top 6 features identified by Moran’s I.

While FindTransferAnchors can be used to integrate spot-level data from spatial transcriptomic datasets, Seurat v5 also includes support for the Robust Cell Type Decomposition, a computational approach to deconvolve spot-level data from spatial datasets, when provided with an scRNA-seq reference. RCTD has been shown to accurately annotate spatial data from a variety of technologies, including SLIDE-seq, Visium, and the 10x Xenium in-situ spatial platform.

To run RCTD, we first install the spacexr package from GitHub which implements RCTD.

Counts, cluster, and spot information is extracted from the Seurat query and reference objects to construct Reference and SpatialRNA objects used by RCTD for annotation.

Using the reference and query object, we annotate the dataset and add the cell type labels to the query Seurat object. RCTD parallelizes well, so multiple cores can be specified for faster performance.

Next, plot the RCTD annotations. Because we ran RCTD in doublet mode, the algorithm assigns a first_type and second_type for each barcode or spot.

Developed by Rahul Satija, Satija Lab and Collaborators.

Site built with pkgdown 2.1.3.

**Examples:**

Example 1 (unknown):
```unknown
vignettes/spatial_vignette.Rmd
```

Example 2 (unknown):
```unknown
spatial_vignette.Rmd
```

Example 3 (unknown):
```unknown
library(Seurat)
library(SeuratData)
library(ggplot2)
library(patchwork)
library(dplyr)
```

Example 4 (r):
```r
library(Seurat)
library(SeuratData)
library(ggplot2)
library(patchwork)
library(dplyr)
```

Example 5 (r):
```r
library(Seurat)
library(SeuratData)
library(ggplot2)
library(patchwork)
library(dplyr)
```

Example 6 (unknown):
```unknown
Load10X_Spatial()
```

Example 7 (unknown):
```unknown
InstallData("stxBrain")
```

Example 8 (r):
```r
InstallData("stxBrain")
```

Example 9 (r):
```r
InstallData("stxBrain")
```

Example 10 (unknown):
```unknown
brain <- LoadData("stxBrain", type = "anterior1")
```

Example 11 (r):
```r
brain <- LoadData("stxBrain", type = "anterior1")
```

Example 12 (r):
```r
brain <- LoadData("stxBrain", type = "anterior1")
```

Example 13 (unknown):
```unknown
plot1 <- VlnPlot(brain, features = "nCount_Spatial", pt.size = 0.1) + NoLegend()
plot2 <- SpatialFeaturePlot(brain, features = "nCount_Spatial") + theme(legend.position = "right")
wrap_plots(plot1, plot2)
```

Example 14 (r):
```r
plot1 <- VlnPlot(brain, features = "nCount_Spatial", pt.size = 0.1) + NoLegend()
plot2 <- SpatialFeaturePlot(brain, features = "nCount_Spatial") + theme(legend.position = "right")
wrap_plots(plot1, plot2)
```

Example 15 (r):
```r
plot1 <- VlnPlot(brain, features = "nCount_Spatial", pt.size = 0.1) + NoLegend()
plot2 <- SpatialFeaturePlot(brain, features = "nCount_Spatial") + theme(legend.position = "right")
wrap_plots(plot1, plot2)
```

Example 16 (unknown):
```unknown
LogNormalize()
```

Example 17 (unknown):
```unknown
brain <- SCTransform(brain, assay = "Spatial", verbose = FALSE)
```

Example 18 (r):
```r
brain <- SCTransform(brain, assay = "Spatial", verbose = FALSE)
```

Example 19 (r):
```r
brain <- SCTransform(brain, assay = "Spatial", verbose = FALSE)
```

Example 20 (unknown):
```unknown
NormalizeData()
```

Example 21 (unknown):
```unknown
# rerun normalization to store sctransform residuals for all genes
brain <- SCTransform(brain, assay = "Spatial", return.only.var.genes = FALSE, verbose = FALSE)
# also run standard log normalization for comparison
brain <- NormalizeData(brain, verbose = FALSE, assay = "Spatial")
```

Example 22 (r):
```r
# rerun normalization to store sctransform residuals for all genes
brain <- SCTransform(brain, assay = "Spatial", return.only.var.genes = FALSE, verbose = FALSE)
# also run standard log normalization for comparison
brain <- NormalizeData(brain, verbose = FALSE, assay = "Spatial")
```

Example 23 (r):
```r
# rerun normalization to store sctransform residuals for all genes
brain <- SCTransform(brain, assay = "Spatial", return.only.var.genes = FALSE, verbose = FALSE)
# also run standard log normalization for comparison
brain <- NormalizeData(brain, verbose = FALSE, assay = "Spatial")
```

Example 24 (unknown):
```unknown
# Computes the correlation of the log normalized data and sctransform residuals with the
# number of UMIs
brain <- GroupCorrelation(brain, group.assay = "Spatial", assay = "Spatial", slot = "data", do.plot = FALSE)
brain <- GroupCorrelation(brain, group.assay = "Spatial", assay = "SCT", slot = "scale.data", do.plot = FALSE)
```

Example 25 (r):
```r
# Computes the correlation of the log normalized data and sctransform residuals with the
# number of UMIs
brain <- GroupCorrelation(brain, group.assay = "Spatial", assay = "Spatial", slot = "data", do.plot = FALSE)
brain <- GroupCorrelation(brain, group.assay = "Spatial", assay = "SCT", slot = "scale.data", do.plot = FALSE)
```

Example 26 (r):
```r
# Computes the correlation of the log normalized data and sctransform residuals with the
# number of UMIs
brain <- GroupCorrelation(brain, group.assay = "Spatial", assay = "Spatial", slot = "data", do.plot = FALSE)
brain <- GroupCorrelation(brain, group.assay = "Spatial", assay = "SCT", slot = "scale.data", do.plot = FALSE)
```

Example 27 (unknown):
```unknown
p1 <- GroupCorrelationPlot(brain, assay = "Spatial", cor = "nCount_Spatial_cor") + ggtitle("Log Normalization") +
    theme(plot.title = element_text(hjust = 0.5))
p2 <- GroupCorrelationPlot(brain, assay = "SCT", cor = "nCount_Spatial_cor") + ggtitle("SCTransform Normalization") +
    theme(plot.title = element_text(hjust = 0.5))
p1 + p2
```

Example 28 (r):
```r
p1 <- GroupCorrelationPlot(brain, assay = "Spatial", cor = "nCount_Spatial_cor") + ggtitle("Log Normalization") +
    theme(plot.title = element_text(hjust = 0.5))
p2 <- GroupCorrelationPlot(brain, assay = "SCT", cor = "nCount_Spatial_cor") + ggtitle("SCTransform Normalization") +
    theme(plot.title = element_text(hjust = 0.5))
p1 + p2
```

Example 29 (r):
```r
p1 <- GroupCorrelationPlot(brain, assay = "Spatial", cor = "nCount_Spatial_cor") + ggtitle("Log Normalization") +
    theme(plot.title = element_text(hjust = 0.5))
p2 <- GroupCorrelationPlot(brain, assay = "SCT", cor = "nCount_Spatial_cor") + ggtitle("SCTransform Normalization") +
    theme(plot.title = element_text(hjust = 0.5))
p1 + p2
```

Example 30 (unknown):
```unknown
nCount_Spatial
```

Example 31 (unknown):
```unknown
SpatialFeaturePlot()
```

Example 32 (unknown):
```unknown
FeaturePlot()
```

Example 33 (unknown):
```unknown
SpatialFeaturePlot(brain, features = c("Hpca", "Ttr"))
```

Example 34 (r):
```r
SpatialFeaturePlot(brain, features = c("Hpca", "Ttr"))
```

Example 35 (r):
```r
SpatialFeaturePlot(brain, features = c("Hpca", "Ttr"))
```

Example 36 (python):
```python
library(ggplot2)
plot <- SpatialFeaturePlot(brain, features = c("Ttr")) + theme(legend.text = element_text(size = 0),
    legend.title = element_text(size = 20), legend.key.size = unit(1, "cm"))
jpeg(filename = "../output/images/spatial_vignette_ttr.jpg", height = 700, width = 1200, quality = 50)
print(plot)
```

Example 37 (r):
```r
library(ggplot2)
plot <- SpatialFeaturePlot(brain, features = c("Ttr")) + theme(legend.text = element_text(size = 0),
    legend.title = element_text(size = 20), legend.key.size = unit(1, "cm"))
jpeg(filename = "../output/images/spatial_vignette_ttr.jpg", height = 700, width = 1200, quality = 50)
print(plot)
```

Example 38 (r):
```r
library(ggplot2)
plot <- SpatialFeaturePlot(brain, features = c("Ttr")) + theme(legend.text = element_text(size = 0),
    legend.title = element_text(size = 20), legend.key.size = unit(1, "cm"))
jpeg(filename = "../output/images/spatial_vignette_ttr.jpg", height = 700, width = 1200, quality = 50)
print(plot)
```

Example 39 (unknown):
```unknown
## agg_png 
##       2
```

Example 40 (unknown):
```unknown
## agg_png 
##       2
```

Example 41 (unknown):
```unknown
pt.size.factor
```

Example 42 (unknown):
```unknown
p1 <- SpatialFeaturePlot(brain, features = "Ttr", pt.size.factor = 1)
p2 <- SpatialFeaturePlot(brain, features = "Ttr", alpha = c(0.1, 1))
p1 + p2
```

Example 43 (r):
```r
p1 <- SpatialFeaturePlot(brain, features = "Ttr", pt.size.factor = 1)
p2 <- SpatialFeaturePlot(brain, features = "Ttr", alpha = c(0.1, 1))
p1 + p2
```

Example 44 (r):
```r
p1 <- SpatialFeaturePlot(brain, features = "Ttr", pt.size.factor = 1)
p2 <- SpatialFeaturePlot(brain, features = "Ttr", alpha = c(0.1, 1))
p1 + p2
```

Example 45 (unknown):
```unknown
brain <- RunPCA(brain, assay = "SCT", verbose = FALSE)
brain <- FindNeighbors(brain, reduction = "pca", dims = 1:30)
brain <- FindClusters(brain, verbose = FALSE)
brain <- RunUMAP(brain, reduction = "pca", dims = 1:30)
```

Example 46 (r):
```r
brain <- RunPCA(brain, assay = "SCT", verbose = FALSE)
brain <- FindNeighbors(brain, reduction = "pca", dims = 1:30)
brain <- FindClusters(brain, verbose = FALSE)
brain <- RunUMAP(brain, reduction = "pca", dims = 1:30)
```

Example 47 (r):
```r
brain <- RunPCA(brain, assay = "SCT", verbose = FALSE)
brain <- FindNeighbors(brain, reduction = "pca", dims = 1:30)
brain <- FindClusters(brain, verbose = FALSE)
brain <- RunUMAP(brain, reduction = "pca", dims = 1:30)
```

Example 48 (unknown):
```unknown
SpatialDimPlot()
```

Example 49 (unknown):
```unknown
p1 <- DimPlot(brain, reduction = "umap", label = TRUE)
p2 <- SpatialDimPlot(brain, label = TRUE, label.size = 3)
p1 + p2
```

Example 50 (r):
```r
p1 <- DimPlot(brain, reduction = "umap", label = TRUE)
p2 <- SpatialDimPlot(brain, label = TRUE, label.size = 3)
p1 + p2
```

Example 51 (r):
```r
p1 <- DimPlot(brain, reduction = "umap", label = TRUE)
p2 <- SpatialDimPlot(brain, label = TRUE, label.size = 3)
p1 + p2
```

Example 52 (unknown):
```unknown
cells.highlight
```

Example 53 (unknown):
```unknown
SpatialDimPlot()
```

Example 54 (unknown):
```unknown
SpatialDimPlot(brain, cells.highlight = CellsByIdentities(object = brain, idents = c(2, 1, 4, 3,
    5, 8)), facet.highlight = TRUE, ncol = 3)
```

Example 55 (r):
```r
SpatialDimPlot(brain, cells.highlight = CellsByIdentities(object = brain, idents = c(2, 1, 4, 3,
    5, 8)), facet.highlight = TRUE, ncol = 3)
```

Example 56 (r):
```r
SpatialDimPlot(brain, cells.highlight = CellsByIdentities(object = brain, idents = c(2, 1, 4, 3,
    5, 8)), facet.highlight = TRUE, ncol = 3)
```

Example 57 (unknown):
```unknown
SpatialDimPlot()
```

Example 58 (unknown):
```unknown
SpatialFeaturePlot()
```

Example 59 (unknown):
```unknown
interactive
```

Example 60 (unknown):
```unknown
SpatialDimPlot()
```

Example 61 (unknown):
```unknown
SpatialDimPlot(brain, interactive = TRUE)
```

Example 62 (r):
```r
SpatialDimPlot(brain, interactive = TRUE)
```

Example 63 (r):
```r
SpatialDimPlot(brain, interactive = TRUE)
```

Example 64 (unknown):
```unknown
SpatialFeaturePlot()
```

Example 65 (unknown):
```unknown
SpatialFeaturePlot(brain, features = "Ttr", interactive = TRUE)
```

Example 66 (r):
```r
SpatialFeaturePlot(brain, features = "Ttr", interactive = TRUE)
```

Example 67 (r):
```r
SpatialFeaturePlot(brain, features = "Ttr", interactive = TRUE)
```

Example 68 (unknown):
```unknown
LinkedDimPlot()
```

Example 69 (unknown):
```unknown
LinkedDimPlot(brain)
```

Example 70 (r):
```r
LinkedDimPlot(brain)
```

Example 71 (r):
```r
LinkedDimPlot(brain)
```

Example 72 (unknown):
```unknown
de_markers <- FindMarkers(brain, ident.1 = 5, ident.2 = 6)
SpatialFeaturePlot(object = brain, features = rownames(de_markers)[1:3], alpha = c(0.1, 1), ncol = 3)
```

Example 73 (r):
```r
de_markers <- FindMarkers(brain, ident.1 = 5, ident.2 = 6)
SpatialFeaturePlot(object = brain, features = rownames(de_markers)[1:3], alpha = c(0.1, 1), ncol = 3)
```

Example 74 (r):
```r
de_markers <- FindMarkers(brain, ident.1 = 5, ident.2 = 6)
SpatialFeaturePlot(object = brain, features = rownames(de_markers)[1:3], alpha = c(0.1, 1), ncol = 3)
```

Example 75 (unknown):
```unknown
FindSpatiallyVariables()
```

Example 76 (unknown):
```unknown
method = 'markvariogram
```

Example 77 (unknown):
```unknown
brain <- FindSpatiallyVariableFeatures(brain, assay = "SCT", features = VariableFeatures(brain)[1:1000],
    selection.method = "moransi")
```

Example 78 (r):
```r
brain <- FindSpatiallyVariableFeatures(brain, assay = "SCT", features = VariableFeatures(brain)[1:1000],
    selection.method = "moransi")
```

Example 79 (r):
```r
brain <- FindSpatiallyVariableFeatures(brain, assay = "SCT", features = VariableFeatures(brain)[1:1000],
    selection.method = "moransi")
```

Example 80 (unknown):
```unknown
top.features <- head(SpatiallyVariableFeatures(brain, selection.method = "moransi"), 6)
SpatialFeaturePlot(brain, features = top.features, ncol = 3, alpha = c(0.1, 1))
```

Example 81 (r):
```r
top.features <- head(SpatiallyVariableFeatures(brain, selection.method = "moransi"), 6)
SpatialFeaturePlot(brain, features = top.features, ncol = 3, alpha = c(0.1, 1))
```

Example 82 (r):
```r
top.features <- head(SpatiallyVariableFeatures(brain, selection.method = "moransi"), 6)
SpatialFeaturePlot(brain, features = top.features, ncol = 3, alpha = c(0.1, 1))
```

Example 83 (python):
```python
# Subset to clusters of interest
cortex <- subset(brain, idents = c(1, 2, 3, 4, 6, 7))

# Extract and attach spatial coordinates from anterior1 image
centroids <- cortex[["anterior1"]]@boundaries$centroids
coords <- setNames(as.data.frame(centroids@coords), c("x", "y"))
rownames(coords) <- centroids@cells
cortex$x <- coords[colnames(cortex), "x"]
cortex$y <- coords[colnames(cortex), "y"]

# Perform spatial subsetting using image position Subset to upper right quadrant
cortex <- subset(cortex, y < 2719 | x > 7835, invert = TRUE)

# Further remove cells in lower right quadrant
m <- (9395 - 5747)/(4960 - 7715)
b <- 5747 - m * 7715
cortex <- subset(cortex, y > m * x + b, invert = TRUE)
```

Example 84 (r):
```r
# Subset to clusters of interest
cortex <- subset(brain, idents = c(1, 2, 3, 4, 6, 7))

# Extract and attach spatial coordinates from anterior1 image
centroids <- cortex[["anterior1"]]@boundaries$centroids
coords <- setNames(as.data.frame(centroids@coords), c("x", "y"))
rownames(coords) <- centroids@cells
cortex$x <- coords[colnames(cortex), "x"]
cortex$y <- coords[colnames(cortex), "y"]

# Perform spatial subsetting using image position Subset to upper right quadrant
cortex <- subset(cortex, y < 2719 | x > 7835, invert = TRUE)

# Further remove cells in lower right quadrant
m <- (9395 - 5747)/(4960 - 7715)
b <- 5747 - m * 7715
cortex <- subset(cortex, y > m * x + b, invert = TRUE)
```

Example 85 (r):
```r
# Subset to clusters of interest
cortex <- subset(brain, idents = c(1, 2, 3, 4, 6, 7))

# Extract and attach spatial coordinates from anterior1 image
centroids <- cortex[["anterior1"]]@boundaries$centroids
coords <- setNames(as.data.frame(centroids@coords), c("x", "y"))
rownames(coords) <- centroids@cells
cortex$x <- coords[colnames(cortex), "x"]
cortex$y <- coords[colnames(cortex), "y"]

# Perform spatial subsetting using image position Subset to upper right quadrant
cortex <- subset(cortex, y < 2719 | x > 7835, invert = TRUE)

# Further remove cells in lower right quadrant
m <- (9395 - 5747)/(4960 - 7715)
b <- 5747 - m * 7715
cortex <- subset(cortex, y > m * x + b, invert = TRUE)
```

Example 86 (unknown):
```unknown
# Visualize the subsetted data on full image vs cropped image
p1 <- SpatialDimPlot(cortex, crop = TRUE, label = TRUE)
p2 <- SpatialDimPlot(cortex, crop = FALSE, label = TRUE, pt.size.factor = 1, label.size = 3)
p1 + p2
```

Example 87 (r):
```r
# Visualize the subsetted data on full image vs cropped image
p1 <- SpatialDimPlot(cortex, crop = TRUE, label = TRUE)
p2 <- SpatialDimPlot(cortex, crop = FALSE, label = TRUE, pt.size.factor = 1, label.size = 3)
p1 + p2
```

Example 88 (r):
```r
# Visualize the subsetted data on full image vs cropped image
p1 <- SpatialDimPlot(cortex, crop = TRUE, label = TRUE)
p2 <- SpatialDimPlot(cortex, crop = FALSE, label = TRUE, pt.size.factor = 1, label.size = 3)
p1 + p2
```

Example 89 (unknown):
```unknown
allen_reference <- readRDS("/brahms/shared/vignette-data/allen_cortex.rds")
```

Example 90 (r):
```r
allen_reference <- readRDS("/brahms/shared/vignette-data/allen_cortex.rds")
```

Example 91 (r):
```r
allen_reference <- readRDS("/brahms/shared/vignette-data/allen_cortex.rds")
```

Example 92 (unknown):
```unknown
# note that setting ncells=3000 normalizes the full dataset but learns noise models on 3k
# cells this speeds up SCTransform dramatically with no loss in performance
library(dplyr)
allen_reference <- SCTransform(allen_reference, ncells = 3000, verbose = FALSE) %>%
    RunPCA(verbose = FALSE) %>%
    RunUMAP(dims = 1:30)
```

Example 93 (r):
```r
# note that setting ncells=3000 normalizes the full dataset but learns noise models on 3k
# cells this speeds up SCTransform dramatically with no loss in performance
library(dplyr)
allen_reference <- SCTransform(allen_reference, ncells = 3000, verbose = FALSE) %>%
    RunPCA(verbose = FALSE) %>%
    RunUMAP(dims = 1:30)
```

Example 94 (r):
```r
# note that setting ncells=3000 normalizes the full dataset but learns noise models on 3k
# cells this speeds up SCTransform dramatically with no loss in performance
library(dplyr)
allen_reference <- SCTransform(allen_reference, ncells = 3000, verbose = FALSE) %>%
    RunPCA(verbose = FALSE) %>%
    RunUMAP(dims = 1:30)
```

Example 95 (python):
```python
# After subsetting, we renormalize cortex
cortex <- SCTransform(cortex, assay = "Spatial", verbose = FALSE) %>%
    RunPCA(verbose = FALSE)
# the annotation is stored in the 'subclass' column of object metadata
DimPlot(allen_reference, group.by = "subclass", label = TRUE)
```

Example 96 (r):
```r
# After subsetting, we renormalize cortex
cortex <- SCTransform(cortex, assay = "Spatial", verbose = FALSE) %>%
    RunPCA(verbose = FALSE)
# the annotation is stored in the 'subclass' column of object metadata
DimPlot(allen_reference, group.by = "subclass", label = TRUE)
```

Example 97 (r):
```r
# After subsetting, we renormalize cortex
cortex <- SCTransform(cortex, assay = "Spatial", verbose = FALSE) %>%
    RunPCA(verbose = FALSE)
# the annotation is stored in the 'subclass' column of object metadata
DimPlot(allen_reference, group.by = "subclass", label = TRUE)
```

Example 98 (unknown):
```unknown
anchors <- FindTransferAnchors(reference = allen_reference, query = cortex, normalization.method = "SCT")
predictions.assay <- TransferData(anchorset = anchors, refdata = allen_reference$subclass, prediction.assay = TRUE,
    weight.reduction = cortex[["pca"]], dims = 1:30)
cortex[["predictions"]] <- predictions.assay
```

Example 99 (r):
```r
anchors <- FindTransferAnchors(reference = allen_reference, query = cortex, normalization.method = "SCT")
predictions.assay <- TransferData(anchorset = anchors, refdata = allen_reference$subclass, prediction.assay = TRUE,
    weight.reduction = cortex[["pca"]], dims = 1:30)
cortex[["predictions"]] <- predictions.assay
```

Example 100 (r):
```r
anchors <- FindTransferAnchors(reference = allen_reference, query = cortex, normalization.method = "SCT")
predictions.assay <- TransferData(anchorset = anchors, refdata = allen_reference$subclass, prediction.assay = TRUE,
    weight.reduction = cortex[["pca"]], dims = 1:30)
cortex[["predictions"]] <- predictions.assay
```

Example 101 (unknown):
```unknown
DefaultAssay(cortex) <- "predictions"
SpatialFeaturePlot(cortex, features = c("L2/3 IT", "L4"), pt.size.factor = 1.6, ncol = 2, crop = TRUE)
```

Example 102 (r):
```r
DefaultAssay(cortex) <- "predictions"
SpatialFeaturePlot(cortex, features = c("L2/3 IT", "L4"), pt.size.factor = 1.6, ncol = 2, crop = TRUE)
```

Example 103 (r):
```r
DefaultAssay(cortex) <- "predictions"
SpatialFeaturePlot(cortex, features = c("L2/3 IT", "L4"), pt.size.factor = 1.6, ncol = 2, crop = TRUE)
```

Example 104 (unknown):
```unknown
cortex <- FindSpatiallyVariableFeatures(cortex, assay = "predictions", selection.method = "moransi",
    features = rownames(cortex), r.metric = 5, slot = "data")
top.clusters <- head(SpatiallyVariableFeatures(cortex, selection.method = "moransi"), 4)
SpatialPlot(object = cortex, features = top.clusters, ncol = 2)
```

Example 105 (r):
```r
cortex <- FindSpatiallyVariableFeatures(cortex, assay = "predictions", selection.method = "moransi",
    features = rownames(cortex), r.metric = 5, slot = "data")
top.clusters <- head(SpatiallyVariableFeatures(cortex, selection.method = "moransi"), 4)
SpatialPlot(object = cortex, features = top.clusters, ncol = 2)
```

Example 106 (r):
```r
cortex <- FindSpatiallyVariableFeatures(cortex, assay = "predictions", selection.method = "moransi",
    features = rownames(cortex), r.metric = 5, slot = "data")
top.clusters <- head(SpatiallyVariableFeatures(cortex, selection.method = "moransi"), 4)
SpatialPlot(object = cortex, features = top.clusters, ncol = 2)
```

Example 107 (unknown):
```unknown
SpatialFeaturePlot(cortex, features = c("Astro", "L2/3 IT", "L4", "L5 PT", "L5 IT", "L6 CT", "L6 IT",
    "L6b", "Oligo"), pt.size.factor = 1, ncol = 2, crop = FALSE, alpha = c(0.1, 1))
```

Example 108 (r):
```r
SpatialFeaturePlot(cortex, features = c("Astro", "L2/3 IT", "L4", "L5 PT", "L5 IT", "L6 CT", "L6 IT",
    "L6b", "Oligo"), pt.size.factor = 1, ncol = 2, crop = FALSE, alpha = c(0.1, 1))
```

Example 109 (r):
```r
SpatialFeaturePlot(cortex, features = c("Astro", "L2/3 IT", "L4", "L5 PT", "L5 IT", "L6 CT", "L6 IT",
    "L6b", "Oligo"), pt.size.factor = 1, ncol = 2, crop = FALSE, alpha = c(0.1, 1))
```

Example 110 (unknown):
```unknown
brain2 <- LoadData("stxBrain", type = "posterior1")
brain2 <- SCTransform(brain2, assay = "Spatial", verbose = FALSE)
```

Example 111 (r):
```r
brain2 <- LoadData("stxBrain", type = "posterior1")
brain2 <- SCTransform(brain2, assay = "Spatial", verbose = FALSE)
```

Example 112 (r):
```r
brain2 <- LoadData("stxBrain", type = "posterior1")
brain2 <- SCTransform(brain2, assay = "Spatial", verbose = FALSE)
```

Example 113 (unknown):
```unknown
brain.merge <- merge(brain, brain2)
```

Example 114 (r):
```r
brain.merge <- merge(brain, brain2)
```

Example 115 (r):
```r
brain.merge <- merge(brain, brain2)
```

Example 116 (unknown):
```unknown
DefaultAssay(brain.merge) <- "SCT"
VariableFeatures(brain.merge) <- c(VariableFeatures(brain), VariableFeatures(brain2))
brain.merge <- RunPCA(brain.merge, verbose = FALSE)
brain.merge <- FindNeighbors(brain.merge, dims = 1:30)
brain.merge <- FindClusters(brain.merge, verbose = FALSE)
brain.merge <- RunUMAP(brain.merge, dims = 1:30)
```

Example 117 (r):
```r
DefaultAssay(brain.merge) <- "SCT"
VariableFeatures(brain.merge) <- c(VariableFeatures(brain), VariableFeatures(brain2))
brain.merge <- RunPCA(brain.merge, verbose = FALSE)
brain.merge <- FindNeighbors(brain.merge, dims = 1:30)
brain.merge <- FindClusters(brain.merge, verbose = FALSE)
brain.merge <- RunUMAP(brain.merge, dims = 1:30)
```

Example 118 (r):
```r
DefaultAssay(brain.merge) <- "SCT"
VariableFeatures(brain.merge) <- c(VariableFeatures(brain), VariableFeatures(brain2))
brain.merge <- RunPCA(brain.merge, verbose = FALSE)
brain.merge <- FindNeighbors(brain.merge, dims = 1:30)
brain.merge <- FindClusters(brain.merge, verbose = FALSE)
brain.merge <- RunUMAP(brain.merge, dims = 1:30)
```

Example 119 (unknown):
```unknown
SpatialDimPlot()
```

Example 120 (unknown):
```unknown
SpatialFeaturePlot()
```

Example 121 (unknown):
```unknown
DimPlot(brain.merge, reduction = "umap", group.by = c("ident", "orig.ident"))
```

Example 122 (r):
```r
DimPlot(brain.merge, reduction = "umap", group.by = c("ident", "orig.ident"))
```

Example 123 (r):
```r
DimPlot(brain.merge, reduction = "umap", group.by = c("ident", "orig.ident"))
```

Example 124 (unknown):
```unknown
SpatialDimPlot(brain.merge)
```

Example 125 (r):
```r
SpatialDimPlot(brain.merge)
```

Example 126 (r):
```r
SpatialDimPlot(brain.merge)
```

Example 127 (unknown):
```unknown
SpatialFeaturePlot(brain.merge, features = c("Hpca", "Plp1"))
```

Example 128 (r):
```r
SpatialFeaturePlot(brain.merge, features = c("Hpca", "Plp1"))
```

Example 129 (r):
```r
SpatialFeaturePlot(brain.merge, features = c("Hpca", "Plp1"))
```

Example 130 (unknown):
```unknown
InstallData("ssHippo")
```

Example 131 (r):
```r
InstallData("ssHippo")
```

Example 132 (r):
```r
InstallData("ssHippo")
```

Example 133 (unknown):
```unknown
slide.seq <- LoadData("ssHippo")
```

Example 134 (r):
```r
slide.seq <- LoadData("ssHippo")
```

Example 135 (r):
```r
slide.seq <- LoadData("ssHippo")
```

Example 136 (unknown):
```unknown
plot1 <- VlnPlot(slide.seq, features = "nCount_Spatial", pt.size = 0, log = TRUE) + NoLegend()
slide.seq$log_nCount_Spatial <- log(slide.seq$nCount_Spatial)
plot2 <- SpatialFeaturePlot(slide.seq, features = "log_nCount_Spatial") + theme(legend.position = "right")
wrap_plots(plot1, plot2)
```

Example 137 (r):
```r
plot1 <- VlnPlot(slide.seq, features = "nCount_Spatial", pt.size = 0, log = TRUE) + NoLegend()
slide.seq$log_nCount_Spatial <- log(slide.seq$nCount_Spatial)
plot2 <- SpatialFeaturePlot(slide.seq, features = "log_nCount_Spatial") + theme(legend.position = "right")
wrap_plots(plot1, plot2)
```

Example 138 (r):
```r
plot1 <- VlnPlot(slide.seq, features = "nCount_Spatial", pt.size = 0, log = TRUE) + NoLegend()
slide.seq$log_nCount_Spatial <- log(slide.seq$nCount_Spatial)
plot2 <- SpatialFeaturePlot(slide.seq, features = "log_nCount_Spatial") + theme(legend.position = "right")
wrap_plots(plot1, plot2)
```

Example 139 (unknown):
```unknown
slide.seq <- SCTransform(slide.seq, assay = "Spatial", ncells = 3000, verbose = FALSE)
slide.seq <- RunPCA(slide.seq)
slide.seq <- RunUMAP(slide.seq, dims = 1:30)
slide.seq <- FindNeighbors(slide.seq, dims = 1:30)
slide.seq <- FindClusters(slide.seq, resolution = 0.3, verbose = FALSE)
```

Example 140 (r):
```r
slide.seq <- SCTransform(slide.seq, assay = "Spatial", ncells = 3000, verbose = FALSE)
slide.seq <- RunPCA(slide.seq)
slide.seq <- RunUMAP(slide.seq, dims = 1:30)
slide.seq <- FindNeighbors(slide.seq, dims = 1:30)
slide.seq <- FindClusters(slide.seq, resolution = 0.3, verbose = FALSE)
```

Example 141 (r):
```r
slide.seq <- SCTransform(slide.seq, assay = "Spatial", ncells = 3000, verbose = FALSE)
slide.seq <- RunPCA(slide.seq)
slide.seq <- RunUMAP(slide.seq, dims = 1:30)
slide.seq <- FindNeighbors(slide.seq, dims = 1:30)
slide.seq <- FindClusters(slide.seq, resolution = 0.3, verbose = FALSE)
```

Example 142 (unknown):
```unknown
SpatialDimPlot()
```

Example 143 (unknown):
```unknown
plot1 <- DimPlot(slide.seq, reduction = "umap", label = TRUE)
plot2 <- SpatialDimPlot(slide.seq, stroke = 0)
plot1 + plot2
```

Example 144 (r):
```r
plot1 <- DimPlot(slide.seq, reduction = "umap", label = TRUE)
plot2 <- SpatialDimPlot(slide.seq, stroke = 0)
plot1 + plot2
```

Example 145 (r):
```r
plot1 <- DimPlot(slide.seq, reduction = "umap", label = TRUE)
plot2 <- SpatialDimPlot(slide.seq, stroke = 0)
plot1 + plot2
```

Example 146 (unknown):
```unknown
SpatialDimPlot(slide.seq, cells.highlight = CellsByIdentities(object = slide.seq, idents = c(1,
    6, 13)), facet.highlight = TRUE)
```

Example 147 (r):
```r
SpatialDimPlot(slide.seq, cells.highlight = CellsByIdentities(object = slide.seq, idents = c(1,
    6, 13)), facet.highlight = TRUE)
```

Example 148 (r):
```r
SpatialDimPlot(slide.seq, cells.highlight = CellsByIdentities(object = slide.seq, idents = c(1,
    6, 13)), facet.highlight = TRUE)
```

Example 149 (unknown):
```unknown
ref <- readRDS("/brahms/shared/vignette-data/mouse_hippocampus_reference.rds")
ref <- UpdateSeuratObject(ref)
```

Example 150 (r):
```r
ref <- readRDS("/brahms/shared/vignette-data/mouse_hippocampus_reference.rds")
ref <- UpdateSeuratObject(ref)
```

Example 151 (r):
```r
ref <- readRDS("/brahms/shared/vignette-data/mouse_hippocampus_reference.rds")
ref <- UpdateSeuratObject(ref)
```

Example 152 (unknown):
```unknown
ref$subcluster
```

Example 153 (unknown):
```unknown
ref$celltype
```

Example 154 (unknown):
```unknown
anchors <- FindTransferAnchors(reference = ref, query = slide.seq, normalization.method = "SCT",
    npcs = 50)
predictions.assay <- TransferData(anchorset = anchors, refdata = ref$celltype, prediction.assay = TRUE,
    weight.reduction = slide.seq[["pca"]], dims = 1:50)
slide.seq[["predictions"]] <- predictions.assay
```

Example 155 (r):
```r
anchors <- FindTransferAnchors(reference = ref, query = slide.seq, normalization.method = "SCT",
    npcs = 50)
predictions.assay <- TransferData(anchorset = anchors, refdata = ref$celltype, prediction.assay = TRUE,
    weight.reduction = slide.seq[["pca"]], dims = 1:50)
slide.seq[["predictions"]] <- predictions.assay
```

Example 156 (r):
```r
anchors <- FindTransferAnchors(reference = ref, query = slide.seq, normalization.method = "SCT",
    npcs = 50)
predictions.assay <- TransferData(anchorset = anchors, refdata = ref$celltype, prediction.assay = TRUE,
    weight.reduction = slide.seq[["pca"]], dims = 1:50)
slide.seq[["predictions"]] <- predictions.assay
```

Example 157 (unknown):
```unknown
DefaultAssay(slide.seq) <- "predictions"
SpatialFeaturePlot(slide.seq, features = c("Dentate Principal cells", "CA3 Principal cells", "Entorhinal cortex",
    "Endothelial tip", "Ependymal", "Oligodendrocyte"), alpha = c(0.1, 1))
```

Example 158 (r):
```r
DefaultAssay(slide.seq) <- "predictions"
SpatialFeaturePlot(slide.seq, features = c("Dentate Principal cells", "CA3 Principal cells", "Entorhinal cortex",
    "Endothelial tip", "Ependymal", "Oligodendrocyte"), alpha = c(0.1, 1))
```

Example 159 (r):
```r
DefaultAssay(slide.seq) <- "predictions"
SpatialFeaturePlot(slide.seq, features = c("Dentate Principal cells", "CA3 Principal cells", "Entorhinal cortex",
    "Endothelial tip", "Ependymal", "Oligodendrocyte"), alpha = c(0.1, 1))
```

Example 160 (unknown):
```unknown
slide.seq$predicted.id <- GetTransferPredictions(slide.seq)
Idents(slide.seq) <- "predicted.id"
SpatialDimPlot(slide.seq, cells.highlight = CellsByIdentities(object = slide.seq, idents = c("CA3 Principal cells",
    "Dentate Principal cells", "Endothelial tip")), facet.highlight = TRUE)
```

Example 161 (r):
```r
slide.seq$predicted.id <- GetTransferPredictions(slide.seq)
Idents(slide.seq) <- "predicted.id"
SpatialDimPlot(slide.seq, cells.highlight = CellsByIdentities(object = slide.seq, idents = c("CA3 Principal cells",
    "Dentate Principal cells", "Endothelial tip")), facet.highlight = TRUE)
```

Example 162 (r):
```r
slide.seq$predicted.id <- GetTransferPredictions(slide.seq)
Idents(slide.seq) <- "predicted.id"
SpatialDimPlot(slide.seq, cells.highlight = CellsByIdentities(object = slide.seq, idents = c("CA3 Principal cells",
    "Dentate Principal cells", "Endothelial tip")), facet.highlight = TRUE)
```

Example 163 (unknown):
```unknown
FindSpatiallyVariableFeatures()
```

Example 164 (unknown):
```unknown
method = 'moransi'
```

Example 165 (unknown):
```unknown
install.packages('Rfast2')
```

Example 166 (unknown):
```unknown
DefaultAssay(slide.seq) <- "SCT"
slide.seq <- FindSpatiallyVariableFeatures(slide.seq, assay = "SCT", slot = "scale.data", features = VariableFeatures(slide.seq)[1:1000],
    selection.method = "moransi", x.cuts = 100, y.cuts = 100)
```

Example 167 (r):
```r
DefaultAssay(slide.seq) <- "SCT"
slide.seq <- FindSpatiallyVariableFeatures(slide.seq, assay = "SCT", slot = "scale.data", features = VariableFeatures(slide.seq)[1:1000],
    selection.method = "moransi", x.cuts = 100, y.cuts = 100)
```

Example 168 (r):
```r
DefaultAssay(slide.seq) <- "SCT"
slide.seq <- FindSpatiallyVariableFeatures(slide.seq, assay = "SCT", slot = "scale.data", features = VariableFeatures(slide.seq)[1:1000],
    selection.method = "moransi", x.cuts = 100, y.cuts = 100)
```

Example 169 (unknown):
```unknown
SpatialFeaturePlot(slide.seq, features = head(SpatiallyVariableFeatures(slide.seq, selection.method = "moransi"),
    6), ncol = 3, alpha = c(0.1, 1), max.cutoff = "q95")
```

Example 170 (r):
```r
SpatialFeaturePlot(slide.seq, features = head(SpatiallyVariableFeatures(slide.seq, selection.method = "moransi"),
    6), ncol = 3, alpha = c(0.1, 1), max.cutoff = "q95")
```

Example 171 (r):
```r
SpatialFeaturePlot(slide.seq, features = head(SpatiallyVariableFeatures(slide.seq, selection.method = "moransi"),
    6), ncol = 3, alpha = c(0.1, 1), max.cutoff = "q95")
```

Example 172 (unknown):
```unknown
FindTransferAnchors
```

Example 173 (unknown):
```unknown
devtools::install_github("dmcable/spacexr", build_vignettes = FALSE)
```

Example 174 (r):
```r
devtools::install_github("dmcable/spacexr", build_vignettes = FALSE)
```

Example 175 (r):
```r
devtools::install_github("dmcable/spacexr", build_vignettes = FALSE)
```

Example 176 (unknown):
```unknown
library(spacexr)

# set up reference
ref <- readRDS("../data/mouse_hippocampus_reference.rds")
```

Example 177 (r):
```r
library(spacexr)

# set up reference
ref <- readRDS("../data/mouse_hippocampus_reference.rds")
```

Example 178 (r):
```r
library(spacexr)

# set up reference
ref <- readRDS("../data/mouse_hippocampus_reference.rds")
```

Example 179 (unknown):
```unknown
## Error in gzfile(file, "rb"): cannot open the connection
```

Example 180 (unknown):
```unknown
## Error in gzfile(file, "rb"): cannot open the connection
```

Example 181 (unknown):
```unknown
ref <- UpdateSeuratObject(ref)
Idents(ref) <- "celltype"

# extract information to pass to the RCTD Reference function
counts <- ref[["RNA"]]$counts
cluster <- as.factor(ref$celltype)
names(cluster) <- colnames(ref)
nUMI <- ref$nCount_RNA
names(nUMI) <- colnames(ref)
reference <- Reference(counts, cluster, nUMI)

# set up query with the RCTD function SpatialRNA
slide.seq <- SeuratData::LoadData("ssHippo")
counts <- slide.seq[["Spatial"]]$counts
coords <- GetTissueCoordinates(slide.seq)
colnames(coords) <- c("x", "y")
coords[is.na(colnames(coords))] <- NULL
query <- SpatialRNA(coords, counts, colSums(counts))
```

Example 182 (r):
```r
ref <- UpdateSeuratObject(ref)
Idents(ref) <- "celltype"

# extract information to pass to the RCTD Reference function
counts <- ref[["RNA"]]$counts
cluster <- as.factor(ref$celltype)
names(cluster) <- colnames(ref)
nUMI <- ref$nCount_RNA
names(nUMI) <- colnames(ref)
reference <- Reference(counts, cluster, nUMI)

# set up query with the RCTD function SpatialRNA
slide.seq <- SeuratData::LoadData("ssHippo")
counts <- slide.seq[["Spatial"]]$counts
coords <- GetTissueCoordinates(slide.seq)
colnames(coords) <- c("x", "y")
coords[is.na(colnames(coords))] <- NULL
query <- SpatialRNA(coords, counts, colSums(counts))
```

Example 183 (r):
```r
ref <- UpdateSeuratObject(ref)
Idents(ref) <- "celltype"

# extract information to pass to the RCTD Reference function
counts <- ref[["RNA"]]$counts
cluster <- as.factor(ref$celltype)
names(cluster) <- colnames(ref)
nUMI <- ref$nCount_RNA
names(nUMI) <- colnames(ref)
reference <- Reference(counts, cluster, nUMI)

# set up query with the RCTD function SpatialRNA
slide.seq <- SeuratData::LoadData("ssHippo")
counts <- slide.seq[["Spatial"]]$counts
coords <- GetTissueCoordinates(slide.seq)
colnames(coords) <- c("x", "y")
coords[is.na(colnames(coords))] <- NULL
query <- SpatialRNA(coords, counts, colSums(counts))
```

Example 184 (python):
```python
RCTD <- create.RCTD(query, reference, max_cores = 8)
RCTD <- run.RCTD(RCTD, doublet_mode = "doublet")
slide.seq <- AddMetaData(slide.seq, metadata = RCTD@results$results_df)
```

Example 185 (r):
```r
RCTD <- create.RCTD(query, reference, max_cores = 8)
RCTD <- run.RCTD(RCTD, doublet_mode = "doublet")
slide.seq <- AddMetaData(slide.seq, metadata = RCTD@results$results_df)
```

Example 186 (r):
```r
RCTD <- create.RCTD(query, reference, max_cores = 8)
RCTD <- run.RCTD(RCTD, doublet_mode = "doublet")
slide.seq <- AddMetaData(slide.seq, metadata = RCTD@results$results_df)
```

Example 187 (unknown):
```unknown
second_type
```

Example 188 (unknown):
```unknown
p1 <- SpatialDimPlot(slide.seq, group.by = "first_type")
p2 <- SpatialDimPlot(slide.seq, group.by = "second_type")
p1 | p2
```

Example 189 (r):
```r
p1 <- SpatialDimPlot(slide.seq, group.by = "first_type")
p2 <- SpatialDimPlot(slide.seq, group.by = "second_type")
p1 | p2
```

Example 190 (r):
```r
p1 <- SpatialDimPlot(slide.seq, group.by = "first_type")
p2 <- SpatialDimPlot(slide.seq, group.by = "second_type")
p1 | p2
```

Example 191 (unknown):
```unknown
sessionInfo()
```

Example 192 (r):
```r
sessionInfo()
```

Example 193 (r):
```r
sessionInfo()
```

Example 194 (unknown):
```unknown
## R version 4.4.2 (2024-10-31)
## Platform: x86_64-pc-linux-gnu
## Running under: Ubuntu 20.04.6 LTS
## 
## Matrix products: default
## BLAS:   /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.9.0 
## LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.9.0
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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: America/New_York
## tzcode source: system (glibc)
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
##  [1] spacexr_2.2.1             future_1.58.0            
##  [3] vembedr_0.1.5             htmltools_0.5.8.1        
##  [5] dplyr_1.1.4               patchwork_1.3.0          
##  [7] ggplot2_3.5.2             stxBrain.SeuratData_0.1.2
##  [9] ssHippo.SeuratData_3.1.4  pbmcsca.SeuratData_3.0.0 
## [11] pbmc3k.SeuratData_3.1.4   ifnb.SeuratData_3.1.0    
## [13] bmcite.SeuratData_0.3.0   SeuratData_0.2.2.9002    
## [15] Seurat_5.3.0              SeuratObject_5.1.0       
## [17] sp_2.2-0                 
## 
## loaded via a namespace (and not attached):
##   [1] RcppAnnoy_0.0.22            splines_4.4.2              
##   [3] later_1.4.2                 tibble_3.2.1               
##   [5] polyclip_1.10-7             fastDummies_1.7.5          
##   [7] lifecycle_1.0.4             doParallel_1.0.17          
##   [9] globals_0.18.0              lattice_0.22-7             
##  [11] MASS_7.3-65                 magrittr_2.0.3             
##  [13] plotly_4.10.4               sass_0.4.10                
##  [15] rmarkdown_2.29              jquerylib_0.1.4            
##  [17] yaml_2.3.10                 httpuv_1.6.16              
##  [19] glmGamPoi_1.18.0            sctransform_0.4.2          
##  [21] spam_2.11-1                 spatstat.sparse_3.1-0      
##  [23] reticulate_1.42.0           cowplot_1.1.3              
##  [25] pbapply_1.7-2               RColorBrewer_1.1-3         
##  [27] abind_1.4-8                 zlibbioc_1.52.0            
##  [29] quadprog_1.5-8              Rtsne_0.17                 
##  [31] GenomicRanges_1.58.0        purrr_1.0.4                
##  [33] presto_1.0.0                BiocGenerics_0.52.0        
##  [35] rappdirs_0.3.3              GenomeInfoDbData_1.2.13    
##  [37] IRanges_2.40.1              S4Vectors_0.44.0           
##  [39] ggrepel_0.9.6               irlba_2.3.5.1              
##  [41] listenv_0.9.1               spatstat.utils_3.1-4       
##  [43] goftest_1.2-3               RSpectra_0.16-2            
##  [45] spatstat.random_3.4-1       fitdistrplus_1.2-2         
##  [47] parallelly_1.45.0           pkgdown_2.1.3              
##  [49] DelayedMatrixStats_1.28.1   codetools_0.2-20           
##  [51] DelayedArray_0.32.0         tidyselect_1.2.1           
##  [53] UCSC.utils_1.2.0            farver_2.1.2               
##  [55] matrixStats_1.5.0           stats4_4.4.2               
##  [57] spatstat.explore_3.4-3      jsonlite_2.0.0             
##  [59] progressr_0.15.1            iterators_1.0.14           
##  [61] ggridges_0.5.6              survival_3.8-3             
##  [63] systemfonts_1.2.3           foreach_1.5.2              
##  [65] tools_4.4.2                 ragg_1.4.0                 
##  [67] ica_1.0-3                   Rcpp_1.0.14                
##  [69] glue_1.8.0                  gridExtra_2.3              
##  [71] SparseArray_1.6.2           xfun_0.52                  
##  [73] MatrixGenerics_1.18.1       GenomeInfoDb_1.42.3        
##  [75] withr_3.0.2                 formatR_1.14               
##  [77] fastmap_1.2.0               digest_0.6.37              
##  [79] R6_2.6.1                    mime_0.13                  
##  [81] textshaping_1.0.1           scattermore_1.2            
##  [83] tensor_1.5                  dichromat_2.0-0.1          
##  [85] spatstat.data_3.1-6         tidyr_1.3.1                
##  [87] generics_0.1.4              data.table_1.17.4          
##  [89] httr_1.4.7                  htmlwidgets_1.6.4          
##  [91] S4Arrays_1.6.0              uwot_0.2.3                 
##  [93] pkgconfig_2.0.3             gtable_0.3.6               
##  [95] lmtest_0.9-40               XVector_0.46.0             
##  [97] dotCall64_1.2               scales_1.4.0               
##  [99] Biobase_2.66.0              png_0.1-8                  
## [101] spatstat.univar_3.1-3       knitr_1.50                 
## [103] rstudioapi_0.17.1           reshape2_1.4.4             
## [105] nlme_3.1-168                cachem_1.1.0               
## [107] zoo_1.8-14                  stringr_1.5.1              
## [109] KernSmooth_2.23-26          parallel_4.4.2             
## [111] miniUI_0.1.2                vipor_0.4.7                
## [113] ggrastr_1.0.2               desc_1.4.3                 
## [115] pillar_1.10.2               grid_4.4.2                 
## [117] vctrs_0.6.5                 RANN_2.6.2                 
## [119] promises_1.3.3              xtable_1.8-4               
## [121] cluster_2.1.8.1             beeswarm_0.4.0             
## [123] evaluate_1.0.3              cli_3.6.5                  
## [125] compiler_4.4.2              rlang_1.1.6                
## [127] crayon_1.5.3                future.apply_1.11.3        
## [129] labeling_0.4.3              plyr_1.8.9                 
## [131] fs_1.6.6                    ggbeeswarm_0.7.2           
## [133] stringi_1.8.7               viridisLite_0.4.2          
## [135] deldir_2.0-4                assertthat_0.2.1           
## [137] lazyeval_0.2.2              spatstat.geom_3.4-1        
## [139] Matrix_1.7-3                RcppHNSW_0.6.0             
## [141] sparseMatrixStats_1.18.0    shiny_1.10.0               
## [143] SummarizedExperiment_1.36.0 ROCR_1.0-11                
## [145] igraph_2.1.4                bslib_0.9.0                
## [147] ape_5.8-1
```

Example 195 (unknown):
```unknown
## R version 4.4.2 (2024-10-31)
## Platform: x86_64-pc-linux-gnu
## Running under: Ubuntu 20.04.6 LTS
## 
## Matrix products: default
## BLAS:   /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.9.0 
## LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.9.0
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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: America/New_York
## tzcode source: system (glibc)
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
##  [1] spacexr_2.2.1             future_1.58.0            
##  [3] vembedr_0.1.5             htmltools_0.5.8.1        
##  [5] dplyr_1.1.4               patchwork_1.3.0          
##  [7] ggplot2_3.5.2             stxBrain.SeuratData_0.1.2
##  [9] ssHippo.SeuratData_3.1.4  pbmcsca.SeuratData_3.0.0 
## [11] pbmc3k.SeuratData_3.1.4   ifnb.SeuratData_3.1.0    
## [13] bmcite.SeuratData_0.3.0   SeuratData_0.2.2.9002    
## [15] Seurat_5.3.0              SeuratObject_5.1.0       
## [17] sp_2.2-0                 
## 
## loaded via a namespace (and not attached):
##   [1] RcppAnnoy_0.0.22            splines_4.4.2              
##   [3] later_1.4.2                 tibble_3.2.1               
##   [5] polyclip_1.10-7             fastDummies_1.7.5          
##   [7] lifecycle_1.0.4             doParallel_1.0.17          
##   [9] globals_0.18.0              lattice_0.22-7             
##  [11] MASS_7.3-65                 magrittr_2.0.3             
##  [13] plotly_4.10.4               sass_0.4.10                
##  [15] rmarkdown_2.29              jquerylib_0.1.4            
##  [17] yaml_2.3.10                 httpuv_1.6.16              
##  [19] glmGamPoi_1.18.0            sctransform_0.4.2          
##  [21] spam_2.11-1                 spatstat.sparse_3.1-0      
##  [23] reticulate_1.42.0           cowplot_1.1.3              
##  [25] pbapply_1.7-2               RColorBrewer_1.1-3         
##  [27] abind_1.4-8                 zlibbioc_1.52.0            
##  [29] quadprog_1.5-8              Rtsne_0.17                 
##  [31] GenomicRanges_1.58.0        purrr_1.0.4                
##  [33] presto_1.0.0                BiocGenerics_0.52.0        
##  [35] rappdirs_0.3.3              GenomeInfoDbData_1.2.13    
##  [37] IRanges_2.40.1              S4Vectors_0.44.0           
##  [39] ggrepel_0.9.6               irlba_2.3.5.1              
##  [41] listenv_0.9.1               spatstat.utils_3.1-4       
##  [43] goftest_1.2-3               RSpectra_0.16-2            
##  [45] spatstat.random_3.4-1       fitdistrplus_1.2-2         
##  [47] parallelly_1.45.0           pkgdown_2.1.3              
##  [49] DelayedMatrixStats_1.28.1   codetools_0.2-20           
##  [51] DelayedArray_0.32.0         tidyselect_1.2.1           
##  [53] UCSC.utils_1.2.0            farver_2.1.2               
##  [55] matrixStats_1.5.0           stats4_4.4.2               
##  [57] spatstat.explore_3.4-3      jsonlite_2.0.0             
##  [59] progressr_0.15.1            iterators_1.0.14           
##  [61] ggridges_0.5.6              survival_3.8-3             
##  [63] systemfonts_1.2.3           foreach_1.5.2              
##  [65] tools_4.4.2                 ragg_1.4.0                 
##  [67] ica_1.0-3                   Rcpp_1.0.14                
##  [69] glue_1.8.0                  gridExtra_2.3              
##  [71] SparseArray_1.6.2           xfun_0.52                  
##  [73] MatrixGenerics_1.18.1       GenomeInfoDb_1.42.3        
##  [75] withr_3.0.2                 formatR_1.14               
##  [77] fastmap_1.2.0               digest_0.6.37              
##  [79] R6_2.6.1                    mime_0.13                  
##  [81] textshaping_1.0.1           scattermore_1.2            
##  [83] tensor_1.5                  dichromat_2.0-0.1          
##  [85] spatstat.data_3.1-6         tidyr_1.3.1                
##  [87] generics_0.1.4              data.table_1.17.4          
##  [89] httr_1.4.7                  htmlwidgets_1.6.4          
##  [91] S4Arrays_1.6.0              uwot_0.2.3                 
##  [93] pkgconfig_2.0.3             gtable_0.3.6               
##  [95] lmtest_0.9-40               XVector_0.46.0             
##  [97] dotCall64_1.2               scales_1.4.0               
##  [99] Biobase_2.66.0              png_0.1-8                  
## [101] spatstat.univar_3.1-3       knitr_1.50                 
## [103] rstudioapi_0.17.1           reshape2_1.4.4             
## [105] nlme_3.1-168                cachem_1.1.0               
## [107] zoo_1.8-14                  stringr_1.5.1              
## [109] KernSmooth_2.23-26          parallel_4.4.2             
## [111] miniUI_0.1.2                vipor_0.4.7                
## [113] ggrastr_1.0.2               desc_1.4.3                 
## [115] pillar_1.10.2               grid_4.4.2                 
## [117] vctrs_0.6.5                 RANN_2.6.2                 
## [119] promises_1.3.3              xtable_1.8-4               
## [121] cluster_2.1.8.1             beeswarm_0.4.0             
## [123] evaluate_1.0.3              cli_3.6.5                  
## [125] compiler_4.4.2              rlang_1.1.6                
## [127] crayon_1.5.3                future.apply_1.11.3        
## [129] labeling_0.4.3              plyr_1.8.9                 
## [131] fs_1.6.6                    ggbeeswarm_0.7.2           
## [133] stringi_1.8.7               viridisLite_0.4.2          
## [135] deldir_2.0-4                assertthat_0.2.1           
## [137] lazyeval_0.2.2              spatstat.geom_3.4-1        
## [139] Matrix_1.7-3                RcppHNSW_0.6.0             
## [141] sparseMatrixStats_1.18.0    shiny_1.10.0               
## [143] SummarizedExperiment_1.36.0 ROCR_1.0-11                
## [145] igraph_2.1.4                bslib_0.9.0                
## [147] ape_5.8-1
```

---

## Installation Instructions for Seurat • Seurat

**URL:** http://127.0.0.1:9173/articles_install.html

**Contents:**
- Installation Instructions for Seurat
- Seurat 5: Install from GitHub
- Install from CRAN
- Install previous versions of Seurat
  - Install any version 3 release
  - Install the last version 2 release (2.3.4)
  - Older versions of Seurat
- Install the development version of Seurat
- Docker
- Contents

To install Seurat, R version 4.0 or greater is required. We also recommend installing R Studio.

Copy the code below to install Seurat v5:

The following packages are not required but are used in many Seurat v5 vignettes:

Seurat v5 utilizes BPCells to support analysis of extremely large datasets:

For more information on BPCells installation, please see the installation instructions. For macOS users, the following GitHub issues concerning M1 chip installation and compiler compatibility may be of use.

Seurat is available on CRAN for all platforms. To install, run:

If you see the warning message below, enter y:

Any of the Seurat version 3 releases can be installed with the following command:

To facilitate easy re-installation of the last version 2 release, we are hosting the binaries on our website. These can be installed with the following command:

Old versions of Seurat, from Seurat v2.0.1 and up, are hosted in CRAN’s archive. To install an old version of Seurat, run:

For versions of Seurat older than those not hosted on CRAN (versions 1.3.0 and 1.4.0), please download the packaged source code from our releases page and install from the tarball.

Install the development version of Seurat - directly from GitHub.

We provide docker images for Seurat via dockerhub.

To pull the latest image from the command line:

To use as a base image in a new Dockerfile:

Developed by Paul Hoffman, Satija Lab and Collaborators.

Site built with pkgdown 2.0.7.

**Examples:**

Example 1 (unknown):
```unknown
vignettes/install.Rmd
```

Example 2 (unknown):
```unknown
install.Rmd
```

Example 3 (unknown):
```unknown
remotes::install_github("satijalab/seurat", "seurat5", quiet = TRUE)
```

Example 4 (r):
```r
remotes::install_github("satijalab/seurat", "seurat5", quiet = TRUE)
```

Example 5 (r):
```r
remotes::install_github("satijalab/seurat", "seurat5", quiet = TRUE)
```

Example 6 (unknown):
```unknown
remotes::install_github("satijalab/seurat-data", "seurat5", quiet = TRUE)
remotes::install_github("satijalab/azimuth", "seurat5", quiet = TRUE)
remotes::install_github("satijalab/seurat-wrappers", "seurat5", quiet = TRUE)
remotes::install_github("stuart-lab/signac", "seurat5", quiet = TRUE)
```

Example 7 (r):
```r
remotes::install_github("satijalab/seurat-data", "seurat5", quiet = TRUE)
remotes::install_github("satijalab/azimuth", "seurat5", quiet = TRUE)
remotes::install_github("satijalab/seurat-wrappers", "seurat5", quiet = TRUE)
remotes::install_github("stuart-lab/signac", "seurat5", quiet = TRUE)
```

Example 8 (r):
```r
remotes::install_github("satijalab/seurat-data", "seurat5", quiet = TRUE)
remotes::install_github("satijalab/azimuth", "seurat5", quiet = TRUE)
remotes::install_github("satijalab/seurat-wrappers", "seurat5", quiet = TRUE)
remotes::install_github("stuart-lab/signac", "seurat5", quiet = TRUE)
```

Example 9 (unknown):
```unknown
remotes::install_github("bnprks/BPCells/r")
```

Example 10 (r):
```r
remotes::install_github("bnprks/BPCells/r")
```

Example 11 (r):
```r
remotes::install_github("bnprks/BPCells/r")
```

Example 12 (unknown):
```unknown
# Enter commands in R (or R studio, if installed)
install.packages('Seurat')
library(Seurat)
```

Example 13 (r):
```r
# Enter commands in R (or R studio, if installed)
install.packages('Seurat')
library(Seurat)
```

Example 14 (r):
```r
# Enter commands in R (or R studio, if installed)
install.packages('Seurat')
library(Seurat)
```

Example 15 (python):
```python
package which is only available in source form, and may need compilation of C/C++/Fortran: 'Seurat'
Do you want to attempt to install these from sources?
y/n:
```

Example 16 (r):
```r
package which is only available in source form, and may need compilation of C/C++/Fortran: 'Seurat'
Do you want to attempt to install these from sources?
y/n:
```

Example 17 (r):
```r
package which is only available in source form, and may need compilation of C/C++/Fortran: 'Seurat'
Do you want to attempt to install these from sources?
y/n:
```

Example 18 (unknown):
```unknown
remotes::install_version("Seurat", version = "3.X.X")
```

Example 19 (r):
```r
remotes::install_version("Seurat", version = "3.X.X")
```

Example 20 (r):
```r
remotes::install_version("Seurat", version = "3.X.X")
```

Example 21 (unknown):
```unknown
source("https://z.umn.edu/archived-seurat")
```

Example 22 (r):
```r
source("https://z.umn.edu/archived-seurat")
```

Example 23 (r):
```r
source("https://z.umn.edu/archived-seurat")
```

Example 24 (unknown):
```unknown
# Enter commands in R (or R studio, if installed)
# Install the remotes package 
install.packages('remotes')
# Replace '2.3.0' with your desired version
remotes::install_version(package = 'Seurat', version = package_version('2.3.0'))
library(Seurat)
```

Example 25 (r):
```r
# Enter commands in R (or R studio, if installed)
# Install the remotes package 
install.packages('remotes')
# Replace '2.3.0' with your desired version
remotes::install_version(package = 'Seurat', version = package_version('2.3.0'))
library(Seurat)
```

Example 26 (r):
```r
# Enter commands in R (or R studio, if installed)
# Install the remotes package 
install.packages('remotes')
# Replace '2.3.0' with your desired version
remotes::install_version(package = 'Seurat', version = package_version('2.3.0'))
library(Seurat)
```

Example 27 (unknown):
```unknown
# Enter commands in R (or R studio, if installed)
# Install the remotes package
install.packages('remotes')
remotes::install_github(repo = 'satijalab/seurat', ref = 'develop')
library(Seurat)
```

Example 28 (r):
```r
# Enter commands in R (or R studio, if installed)
# Install the remotes package
install.packages('remotes')
remotes::install_github(repo = 'satijalab/seurat', ref = 'develop')
library(Seurat)
```

Example 29 (r):
```r
# Enter commands in R (or R studio, if installed)
# Install the remotes package
install.packages('remotes')
remotes::install_github(repo = 'satijalab/seurat', ref = 'develop')
library(Seurat)
```

Example 30 (unknown):
```unknown
docker pull satijalab/seurat:latest
```

Example 31 (unknown):
```unknown
docker pull satijalab/seurat:latest
```

Example 32 (bash):
```bash
docker pull satijalab/seurat:latest
```

Example 33 (unknown):
```unknown
FROM satijalab/seurat:latest
```

Example 34 (unknown):
```unknown
FROM satijalab/seurat:latest
```

Example 35 (bash):
```bash
FROM satijalab/seurat:latest
```

---

## Parallelization in Seurat with future

**URL:** http://127.0.0.1:9173/seurat/archive/v3.0/future_vignette/index.html

**Contents:**
- Parallelization in Seurat with future
    - Compiled: June 24, 2019
  - How to use parallelization in Seurat
  - ‘Futurized’ functions in Seurat
  - Comparison of sequential vs. parallel
  - Frequently asked questions

In Seurat, we have chosen to use the future framework for parallelization. In this vignette, we will demonstrate how you can take advantage of the future implementation of certain Seurat functions from a user’s perspective. If you are interested in learning more about the future framework beyond what is described here, please see the package vignettes here for a comprehensive and detailed description.

To access the parallel version of functions in Seurat, you need to load the future package and set the plan. The plan will specify how the function is executed. The default behavior is to evaluate in a non-parallelized fashion (sequentially). To achieve parallel (asynchronous) behavior, we typically recommend the “multiprocess” strategy. By default, this uses all available cores but you can set the workers parameter to limit the number of concurrently active futures.

The following functions have been written to take advantage of the future framework and will be parallelized if the current plan is set appropriately. Importantly, the way you call the function shouldn’t change.

For example, to run the parallel version of FindMarkers, you simply need to set the plan and call the function as usual.

Here we’ll perform a brief comparison the runtimes for the same function calls with and without parallelization. Note that while we expect that using a parallelized strategy will decrease the runtimes of the functions listed above, the magnitude of that decrease will depend on many factors (e.g. the size of the dataset, the number of workers, specs of the system, the future strategy, etc). The following benchmarks were performed on a desktop computer running Ubuntu 16.04.5 LTS with an Intel(R) Core(TM) i7-6800K CPU @ 3.40GHz and 96 GB of RAM.

Click to see bencharking code

Where did my progress bar go? Unfortantely, the when running these functions in any of the parallel plan modes you will lose the progress bar. This is due to some technical limitations in the future framework and R generally. If you want to monitor function progress, you’ll need to forgo parallelization and use plan("sequential").

For certain functions, each worker needs access to certain global variables. If these are larger than the default limit, you will see this error. To get around this, you can set options(future.globals.maxSize = X), where X is the maximum allowed size in bytes. So to set it to 1GB, you would run options(future.globals.maxSize = 1000 * 1024^2). Note that this will increase your RAM usage so set this number mindfully.

**Examples:**

Example 1 (r):
```r
library(future)
# check the current active plan
plan()
```

Example 2 (r):
```r
library(future)
# check the current active plan
plan()
```

Example 3 (unknown):
```unknown
## sequential:
## - args: function (expr, envir = parent.frame(), substitute = TRUE, lazy = FALSE, seed = NULL, globals = TRUE, local = TRUE, earlySignal = FALSE, label = NULL, ...)
## - tweaked: FALSE
## - call: plan("default", .init = FALSE)
```

Example 4 (unknown):
```unknown
## sequential:
## - args: function (expr, envir = parent.frame(), substitute = TRUE, lazy = FALSE, seed = NULL, globals = TRUE, local = TRUE, earlySignal = FALSE, label = NULL, ...)
## - tweaked: FALSE
## - call: plan("default", .init = FALSE)
```

Example 5 (r):
```r
# change the current plan to access parallelization
plan("multiprocess", workers = 4)
plan()
```

Example 6 (r):
```r
# change the current plan to access parallelization
plan("multiprocess", workers = 4)
plan()
```

Example 7 (unknown):
```unknown
## multiprocess:
## - args: function (expr, envir = parent.frame(), substitute = TRUE, lazy = FALSE, seed = NULL, globals = TRUE, workers = 4, gc = FALSE, earlySignal = FALSE, label = NULL, ...)
## - tweaked: TRUE
## - call: plan("multiprocess", workers = 4)
```

Example 8 (unknown):
```unknown
## multiprocess:
## - args: function (expr, envir = parent.frame(), substitute = TRUE, lazy = FALSE, seed = NULL, globals = TRUE, workers = 4, gc = FALSE, earlySignal = FALSE, label = NULL, ...)
## - tweaked: TRUE
## - call: plan("multiprocess", workers = 4)
```

Example 9 (unknown):
```unknown
NormalizeData
```

Example 10 (unknown):
```unknown
FindMarkers
```

Example 11 (unknown):
```unknown
FindIntegrationAnchors
```

Example 12 (unknown):
```unknown
FindClusters
```

Example 13 (unknown):
```unknown
FindMarkers
```

Example 14 (r):
```r
library(Seurat)
pbmc <- readRDS("../data/pbmc3k_final.rds")

# Enable parallelization
plan("multiprocess", workers = 4)
markers <- FindMarkers(pbmc, ident.1 = "NK", verbose = FALSE)
```

Example 15 (r):
```r
library(Seurat)
pbmc <- readRDS("../data/pbmc3k_final.rds")

# Enable parallelization
plan("multiprocess", workers = 4)
markers <- FindMarkers(pbmc, ident.1 = "NK", verbose = FALSE)
```

Example 16 (r):
```r
library(cowplot)
```

Example 17 (r):
```r
library(cowplot)
```

Example 18 (r):
```r
timing.comparisons <- data.frame(fxn = character(), time = numeric(), strategy = character())
plan("sequential")
start <- Sys.time()
pbmc <- ScaleData(pbmc, vars.to.regress = "percent.mt", verbose = FALSE)
end <- Sys.time()
timing.comparisons <- rbind(timing.comparisons, data.frame(fxn = "ScaleData", time = as.numeric(end - 
    start, units = "secs"), strategy = "sequential"))

start <- Sys.time()
markers <- FindMarkers(pbmc, ident.1 = "NK", verbose = FALSE)
end <- Sys.time()
timing.comparisons <- rbind(timing.comparisons, data.frame(fxn = "FindMarkers", time = as.numeric(end - 
    start, units = "secs"), strategy = "sequential"))

plan("multiprocess", workers = 4)
start <- Sys.time()
pbmc <- ScaleData(pbmc, vars.to.regress = "percent.mt", verbose = FALSE)
end <- Sys.time()
timing.comparisons <- rbind(timing.comparisons, data.frame(fxn = "ScaleData", time = as.numeric(end - 
    start, units = "secs"), strategy = "multiprocess"))

start <- Sys.time()
markers <- FindMarkers(pbmc, ident.1 = "NK", verbose = FALSE)
end <- Sys.time()
timing.comparisons <- rbind(timing.comparisons, data.frame(fxn = "FindMarkers", time = as.numeric(end - 
    start, units = "secs"), strategy = "multiprocess"))
```

Example 19 (r):
```r
timing.comparisons <- data.frame(fxn = character(), time = numeric(), strategy = character())
plan("sequential")
start <- Sys.time()
pbmc <- ScaleData(pbmc, vars.to.regress = "percent.mt", verbose = FALSE)
end <- Sys.time()
timing.comparisons <- rbind(timing.comparisons, data.frame(fxn = "ScaleData", time = as.numeric(end - 
    start, units = "secs"), strategy = "sequential"))

start <- Sys.time()
markers <- FindMarkers(pbmc, ident.1 = "NK", verbose = FALSE)
end <- Sys.time()
timing.comparisons <- rbind(timing.comparisons, data.frame(fxn = "FindMarkers", time = as.numeric(end - 
    start, units = "secs"), strategy = "sequential"))

plan("multiprocess", workers = 4)
start <- Sys.time()
pbmc <- ScaleData(pbmc, vars.to.regress = "percent.mt", verbose = FALSE)
end <- Sys.time()
timing.comparisons <- rbind(timing.comparisons, data.frame(fxn = "ScaleData", time = as.numeric(end - 
    start, units = "secs"), strategy = "multiprocess"))

start <- Sys.time()
markers <- FindMarkers(pbmc, ident.1 = "NK", verbose = FALSE)
end <- Sys.time()
timing.comparisons <- rbind(timing.comparisons, data.frame(fxn = "FindMarkers", time = as.numeric(end - 
    start, units = "secs"), strategy = "multiprocess"))
```

Example 20 (r):
```r
ggplot(timing.comparisons, aes(fxn, time)) + geom_bar(aes(fill = strategy), stat = "identity", position = "dodge") + 
    ylab("Time(s)") + xlab("Function")
```

Example 21 (r):
```r
ggplot(timing.comparisons, aes(fxn, time)) + geom_bar(aes(fill = strategy), stat = "identity", position = "dodge") + 
    ylab("Time(s)") + xlab("Function")
```

Example 22 (unknown):
```unknown
plan("sequential")
```

Example 23 (unknown):
```unknown
Error in getGlobalsAndPackages(expr, envir = envir, globals = TRUE) : 
  The total size of the X globals that need to be exported for the future expression ('FUN()') is X GiB. This exceeds the maximum allowed size of 500.00 MiB (option 'future.globals.maxSize'). The X largest globals are ...
```

Example 24 (unknown):
```unknown
Error in getGlobalsAndPackages(expr, envir = envir, globals = TRUE) : 
  The total size of the X globals that need to be exported for the future expression ('FUN()') is X GiB. This exceeds the maximum allowed size of 500.00 MiB (option 'future.globals.maxSize'). The X largest globals are ...
```

Example 25 (unknown):
```unknown
options(future.globals.maxSize = X)
```

Example 26 (unknown):
```unknown
options(future.globals.maxSize = 1000 * 1024^2)
```

---

## Analysis, visualization, and integration of Visium HD spatial datasets with Seurat • Seurat

**URL:** http://127.0.0.1:9173/seurat/articles/pbmc3k_tutorial/index.html

**Contents:**
- Seurat - Guided Clustering Tutorial
    - Compiled: October 31, 2023
- Setup the Seurat Object
- Standard pre-processing workflow
  - QC and selecting cells for further analysis
- Normalizing the data
- Identification of highly variable features (feature selection)
- Scaling the data
- Perform linear dimensional reduction
- Determine the ‘dimensionality’ of the dataset
- Cluster the cells
- Run non-linear dimensional reduction (UMAP/tSNE)
- Finding differentially expressed features (cluster biomarkers)
- Assigning cell type identity to clusters
- Contents

For this tutorial, we will be analyzing the a dataset of Peripheral Blood Mononuclear Cells (PBMC) freely available from 10X Genomics. There are 2,700 single cells that were sequenced on the Illumina NextSeq 500. The raw data can be found here.

We start by reading in the data. The Read10X() function reads in the output of the cellranger pipeline from 10X, returning a unique molecular identified (UMI) count matrix. The values in this matrix represent the number of molecules for each feature (i.e. gene; row) that are detected in each cell (column). Note that more recent versions of cellranger now also output using the h5 file format, which can be read in using the Read10X_h5() function in Seurat.

We next use the count matrix to create a Seurat object. The object serves as a container that contains both data (like the count matrix) and analysis (like PCA, or clustering results) for a single-cell dataset. For more information, check out our [Seurat object interaction vignette], or our GitHub Wiki. For example, in Seurat v5, the count matrix is stored in pbmc[["RNA"]]$counts.

What does data in a count matrix look like?

The . values in the matrix represent 0s (no molecules detected). Since most values in an scRNA-seq matrix are 0, Seurat uses a sparse-matrix representation whenever possible. This results in significant memory and speed savings for Drop-seq/inDrop/10x data.

The steps below encompass the standard pre-processing workflow for scRNA-seq data in Seurat. These represent the selection and filtration of cells based on QC metrics, data normalization and scaling, and the detection of highly variable features.

Seurat allows you to easily explore QC metrics and filter cells based on any user-defined criteria. A few QC metrics commonly used by the community include

Where are QC metrics stored in Seurat?

In the example below, we visualize QC metrics, and use these to filter cells.

After removing unwanted cells from the dataset, the next step is to normalize the data. By default, we employ a global-scaling normalization method “LogNormalize” that normalizes the feature expression measurements for each cell by the total expression, multiplies this by a scale factor (10,000 by default), and log-transforms the result. In Seurat v5, Normalized values are stored in pbmc[["RNA"]]$data.

For clarity, in this previous line of code (and in future commands), we provide the default values for certain parameters in the function call. However, this isn’t required and the same behavior can be achieved with:

While this method of normalization is standard and widely used in scRNA-seq analysis, global-scaling relies on an assumption that each cell originally contains the same number of RNA molecules. We and others have developed alternative workflows for the single cell preprocessing that do not make these assumptions. For users who are interested, please check out our SCTransform() normalization workflow. The method is described in ourpaper, with a separate vignette using Seurat here. The use of SCTransform replaces the need to run NormalizeData, FindVariableFeatures, or ScaleData (described below.)

We next calculate a subset of features that exhibit high cell-to-cell variation in the dataset (i.e, they are highly expressed in some cells, and lowly expressed in others). We and others have found that focusing on these genes in downstream analysis helps to highlight biological signal in single-cell datasets.

Our procedure in Seurat is described in detail here, and improves on previous versions by directly modeling the mean-variance relationship inherent in single-cell data, and is implemented in the FindVariableFeatures() function. By default, we return 2,000 features per dataset. These will be used in downstream analysis, like PCA.

Next, we apply a linear transformation (‘scaling’) that is a standard pre-processing step prior to dimensional reduction techniques like PCA. The ScaleData() function:

How can I remove unwanted sources of variation

In Seurat, we also use the ScaleData() function to remove unwanted sources of variation from a single-cell dataset. For example, we could ‘regress out’ heterogeneity associated with (for example) cell cycle stage, or mitochondrial contamination i.e.:

Next we perform PCA on the scaled data. By default, only the previously determined variable features are used as input, but can be defined using features argument if you wish to choose a different subset (if you do want to use a custom subset of features, make sure you pass these to ScaleData first).

For the first principal components, Seurat outputs a list of genes with the most positive and negative loadings, representing modules of genes that exhibit either correlation (or anti-correlation) across single-cells in the dataset.

Seurat provides several useful ways of visualizing both cells and features that define the PCA, including VizDimReduction(), DimPlot(), and DimHeatmap()

In particular DimHeatmap() allows for easy exploration of the primary sources of heterogeneity in a dataset, and can be useful when trying to decide which PCs to include for further downstream analyses. Both cells and features are ordered according to their PCA scores. Setting cells to a number plots the ‘extreme’ cells on both ends of the spectrum, which dramatically speeds plotting for large datasets. Though clearly a supervised analysis, we find this to be a valuable tool for exploring correlated feature sets.

To overcome the extensive technical noise in any single feature for scRNA-seq data, Seurat clusters cells based on their PCA scores, with each PC essentially representing a ‘metafeature’ that combines information across a correlated feature set. The top principal components therefore represent a robust compression of the dataset. However, how many components should we choose to include? 10? 20? 100?

In Macosko et al, we implemented a resampling test inspired by the JackStraw procedure. While still available in Seurat (see previous vignette), this is a slow and computationally expensive procedure, and we is no longer routinely used in single cell analysis.

An alternative heuristic method generates an ‘Elbow plot’: a ranking of principle components based on the percentage of variance explained by each one (ElbowPlot() function). In this example, we can observe an ‘elbow’ around PC9-10, suggesting that the majority of true signal is captured in the first 10 PCs.

Identifying the true dimensionality of a dataset – can be challenging/uncertain for the user. We therefore suggest these multiple approaches for users. The first is more supervised, exploring PCs to determine relevant sources of heterogeneity, and could be used in conjunction with GSEA for example. The second (ElbowPlot) The third is a heuristic that is commonly used, and can be calculated instantly. In this example, we might have been justified in choosing anything between PC 7-12 as a cutoff.

We chose 10 here, but encourage users to consider the following:

Seurat applies a graph-based clustering approach, building upon initial strategies in (Macosko et al). Importantly, the distance metric which drives the clustering analysis (based on previously identified PCs) remains the same. However, our approach to partitioning the cellular distance matrix into clusters has dramatically improved. Our approach was heavily inspired by recent manuscripts which applied graph-based clustering approaches to scRNA-seq data [SNN-Cliq, Xu and Su, Bioinformatics, 2015] and CyTOF data [PhenoGraph, Levine et al., Cell, 2015]. Briefly, these methods embed cells in a graph structure - for example a K-nearest neighbor (KNN) graph, with edges drawn between cells with similar feature expression patterns, and then attempt to partition this graph into highly interconnected ‘quasi-cliques’ or ‘communities’.

As in PhenoGraph, we first construct a KNN graph based on the euclidean distance in PCA space, and refine the edge weights between any two cells based on the shared overlap in their local neighborhoods (Jaccard similarity). This step is performed using the FindNeighbors() function, and takes as input the previously defined dimensionality of the dataset (first 10 PCs).

To cluster the cells, we next apply modularity optimization techniques such as the Louvain algorithm (default) or SLM [SLM, Blondel et al., Journal of Statistical Mechanics], to iteratively group cells together, with the goal of optimizing the standard modularity function. The FindClusters() function implements this procedure, and contains a resolution parameter that sets the ‘granularity’ of the downstream clustering, with increased values leading to a greater number of clusters. We find that setting this parameter between 0.4-1.2 typically returns good results for single-cell datasets of around 3K cells. Optimal resolution often increases for larger datasets. The clusters can be found using the Idents() function.

Seurat offers several non-linear dimensional reduction techniques, such as tSNE and UMAP, to visualize and explore these datasets. The goal of these algorithms is to learn underlying structure in the dataset, in order to place similar cells together in low-dimensional space. Therefore, cells that are grouped together within graph-based clusters determined above should co-localize on these dimension reduction plots.

While we and others have routinely found 2D visualization techniques like tSNE and UMAP to be valuable tools for exploring datasets, all visualization techniques have limitations, and cannot fully represent the complexity of the underlying data. In particular, these methods aim to preserve local distances in the dataset (i.e. ensuring that cells with very similar gene expression profiles co-localize), but often do not preserve more global relationships. We encourage users to leverage techniques like UMAP for visualization, but to avoid drawing biological conclusions solely on the basis of visualization techniques.

You can save the object at this point so that it can easily be loaded back in without having to rerun the computationally intensive steps performed above, or easily shared with collaborators.

Seurat can help you find markers that define clusters via differential expression (DE). By default, it identifies positive and negative markers of a single cluster (specified in ident.1), compared to all other cells. FindAllMarkers() automates this process for all clusters, but you can also test groups of clusters vs. each other, or against all cells.

In Seurat v5, we use the presto package (as described here and available for installation here), to dramatically improve the speed of DE analysis, particularly for large datasets. For users who are not using presto, you can examine the documentation for this function (?FindMarkers) to explore the min.pct and logfc.threshold parameters, which can be increased in order to increase the speed of DE testing.

Seurat has several tests for differential expression which can be set with the test.use parameter (see our DE vignette for details). For example, the ROC test returns the ‘classification power’ for any individual marker (ranging from 0 - random, to 1 - perfect).

We include several tools for visualizing marker expression. VlnPlot() (shows expression probability distributions across clusters), and FeaturePlot() (visualizes feature expression on a tSNE or PCA plot) are our most commonly used visualizations. We also suggest exploring RidgePlot(), CellScatter(), and DotPlot() as additional methods to view your dataset.

DoHeatmap() generates an expression heatmap for given cells and features. In this case, we are plotting the top 20 markers (or all markers if less than 20) for each cluster.

Fortunately in the case of this dataset, we can use canonical markers to easily match the unbiased clustering to known cell types:

Developed by Rahul Satija, Satija Lab and Collaborators.

Site built with pkgdown 2.0.7.

**Examples:**

Example 1 (unknown):
```unknown
vignettes/pbmc3k_tutorial.Rmd
```

Example 2 (unknown):
```unknown
pbmc3k_tutorial.Rmd
```

Example 3 (unknown):
```unknown
Read10X_h5()
```

Example 4 (unknown):
```unknown
pbmc[["RNA"]]$counts
```

Example 5 (unknown):
```unknown
library(dplyr)
library(Seurat)
library(patchwork)

# Load the PBMC dataset
pbmc.data <- Read10X(data.dir = "/brahms/mollag/practice/filtered_gene_bc_matrices/hg19/")
# Initialize the Seurat object with the raw (non-normalized data).
pbmc <- CreateSeuratObject(counts = pbmc.data, project = "pbmc3k", min.cells = 3, min.features = 200)
pbmc
```

Example 6 (r):
```r
library(dplyr)
library(Seurat)
library(patchwork)

# Load the PBMC dataset
pbmc.data <- Read10X(data.dir = "/brahms/mollag/practice/filtered_gene_bc_matrices/hg19/")
# Initialize the Seurat object with the raw (non-normalized data).
pbmc <- CreateSeuratObject(counts = pbmc.data, project = "pbmc3k", min.cells = 3, min.features = 200)
pbmc
```

Example 7 (r):
```r
library(dplyr)
library(Seurat)
library(patchwork)

# Load the PBMC dataset
pbmc.data <- Read10X(data.dir = "/brahms/mollag/practice/filtered_gene_bc_matrices/hg19/")
# Initialize the Seurat object with the raw (non-normalized data).
pbmc <- CreateSeuratObject(counts = pbmc.data, project = "pbmc3k", min.cells = 3, min.features = 200)
pbmc
```

Example 8 (python):
```python
## An object of class Seurat 
## 13714 features across 2700 samples within 1 assay 
## Active assay: RNA (13714 features, 0 variable features)
##  1 layer present: counts
```

Example 9 (python):
```python
## An object of class Seurat 
## 13714 features across 2700 samples within 1 assay 
## Active assay: RNA (13714 features, 0 variable features)
##  1 layer present: counts
```

Example 10 (unknown):
```unknown
# Lets examine a few genes in the first thirty cells
pbmc.data[c("CD3D", "TCL1A", "MS4A1"), 1:30]
```

Example 11 (r):
```r
# Lets examine a few genes in the first thirty cells
pbmc.data[c("CD3D", "TCL1A", "MS4A1"), 1:30]
```

Example 12 (r):
```r
# Lets examine a few genes in the first thirty cells
pbmc.data[c("CD3D", "TCL1A", "MS4A1"), 1:30]
```

Example 13 (python):
```python
## 3 x 30 sparse Matrix of class "dgCMatrix"
##                                                                    
## CD3D  4 . 10 . . 1 2 3 1 . . 2 7 1 . . 1 3 . 2  3 . . . . . 3 4 1 5
## TCL1A . .  . . . . . . 1 . . . . . . . . . . .  . 1 . . . . . . . .
## MS4A1 . 6  . . . . . . 1 1 1 . . . . . . . . . 36 1 2 . . 2 . . . .
```

Example 14 (python):
```python
## 3 x 30 sparse Matrix of class "dgCMatrix"
##                                                                    
## CD3D  4 . 10 . . 1 2 3 1 . . 2 7 1 . . 1 3 . 2  3 . . . . . 3 4 1 5
## TCL1A . .  . . . . . . 1 . . . . . . . . . . .  . 1 . . . . . . . .
## MS4A1 . 6  . . . . . . 1 1 1 . . . . . . . . . 36 1 2 . . 2 . . . .
```

Example 15 (unknown):
```unknown
dense.size <- object.size(as.matrix(pbmc.data))
dense.size
```

Example 16 (r):
```r
dense.size <- object.size(as.matrix(pbmc.data))
dense.size
```

Example 17 (r):
```r
dense.size <- object.size(as.matrix(pbmc.data))
dense.size
```

Example 18 (unknown):
```unknown
## 709591472 bytes
```

Example 19 (unknown):
```unknown
## 709591472 bytes
```

Example 20 (unknown):
```unknown
sparse.size <- object.size(pbmc.data)
sparse.size
```

Example 21 (r):
```r
sparse.size <- object.size(pbmc.data)
sparse.size
```

Example 22 (r):
```r
sparse.size <- object.size(pbmc.data)
sparse.size
```

Example 23 (unknown):
```unknown
## 29905192 bytes
```

Example 24 (unknown):
```unknown
## 29905192 bytes
```

Example 25 (unknown):
```unknown
dense.size/sparse.size
```

Example 26 (r):
```r
dense.size/sparse.size
```

Example 27 (r):
```r
dense.size/sparse.size
```

Example 28 (unknown):
```unknown
## 23.7 bytes
```

Example 29 (unknown):
```unknown
## 23.7 bytes
```

Example 30 (unknown):
```unknown
PercentageFeatureSet()
```

Example 31 (python):
```python
# The [[ operator can add columns to object metadata. This is a great place to stash QC stats
pbmc[["percent.mt"]] <- PercentageFeatureSet(pbmc, pattern = "^MT-")
```

Example 32 (r):
```r
# The [[ operator can add columns to object metadata. This is a great place to stash QC stats
pbmc[["percent.mt"]] <- PercentageFeatureSet(pbmc, pattern = "^MT-")
```

Example 33 (r):
```r
# The [[ operator can add columns to object metadata. This is a great place to stash QC stats
pbmc[["percent.mt"]] <- PercentageFeatureSet(pbmc, pattern = "^MT-")
```

Example 34 (unknown):
```unknown
CreateSeuratObject()
```

Example 35 (unknown):
```unknown
# Show QC metrics for the first 5 cells
head(pbmc@meta.data, 5)
```

Example 36 (r):
```r
# Show QC metrics for the first 5 cells
head(pbmc@meta.data, 5)
```

Example 37 (r):
```r
# Show QC metrics for the first 5 cells
head(pbmc@meta.data, 5)
```

Example 38 (unknown):
```unknown
##                  orig.ident nCount_RNA nFeature_RNA percent.mt
## AAACATACAACCAC-1     pbmc3k       2419          779  3.0177759
## AAACATTGAGCTAC-1     pbmc3k       4903         1352  3.7935958
## AAACATTGATCAGC-1     pbmc3k       3147         1129  0.8897363
## AAACCGTGCTTCCG-1     pbmc3k       2639          960  1.7430845
## AAACCGTGTATGCG-1     pbmc3k        980          521  1.2244898
```

Example 39 (unknown):
```unknown
##                  orig.ident nCount_RNA nFeature_RNA percent.mt
## AAACATACAACCAC-1     pbmc3k       2419          779  3.0177759
## AAACATTGAGCTAC-1     pbmc3k       4903         1352  3.7935958
## AAACATTGATCAGC-1     pbmc3k       3147         1129  0.8897363
## AAACCGTGCTTCCG-1     pbmc3k       2639          960  1.7430845
## AAACCGTGTATGCG-1     pbmc3k        980          521  1.2244898
```

Example 40 (unknown):
```unknown
# Visualize QC metrics as a violin plot
VlnPlot(pbmc, features = c("nFeature_RNA", "nCount_RNA", "percent.mt"), ncol = 3)
```

Example 41 (r):
```r
# Visualize QC metrics as a violin plot
VlnPlot(pbmc, features = c("nFeature_RNA", "nCount_RNA", "percent.mt"), ncol = 3)
```

Example 42 (r):
```r
# Visualize QC metrics as a violin plot
VlnPlot(pbmc, features = c("nFeature_RNA", "nCount_RNA", "percent.mt"), ncol = 3)
```

Example 43 (python):
```python
# FeatureScatter is typically used to visualize feature-feature relationships, but can be used
# for anything calculated by the object, i.e. columns in object metadata, PC scores etc.

plot1 <- FeatureScatter(pbmc, feature1 = "nCount_RNA", feature2 = "percent.mt")
plot2 <- FeatureScatter(pbmc, feature1 = "nCount_RNA", feature2 = "nFeature_RNA")
plot1 + plot2
```

Example 44 (r):
```r
# FeatureScatter is typically used to visualize feature-feature relationships, but can be used
# for anything calculated by the object, i.e. columns in object metadata, PC scores etc.

plot1 <- FeatureScatter(pbmc, feature1 = "nCount_RNA", feature2 = "percent.mt")
plot2 <- FeatureScatter(pbmc, feature1 = "nCount_RNA", feature2 = "nFeature_RNA")
plot1 + plot2
```

Example 45 (r):
```r
# FeatureScatter is typically used to visualize feature-feature relationships, but can be used
# for anything calculated by the object, i.e. columns in object metadata, PC scores etc.

plot1 <- FeatureScatter(pbmc, feature1 = "nCount_RNA", feature2 = "percent.mt")
plot2 <- FeatureScatter(pbmc, feature1 = "nCount_RNA", feature2 = "nFeature_RNA")
plot1 + plot2
```

Example 46 (unknown):
```unknown
pbmc <- subset(pbmc, subset = nFeature_RNA > 200 & nFeature_RNA < 2500 & percent.mt < 5)
```

Example 47 (r):
```r
pbmc <- subset(pbmc, subset = nFeature_RNA > 200 & nFeature_RNA < 2500 & percent.mt < 5)
```

Example 48 (r):
```r
pbmc <- subset(pbmc, subset = nFeature_RNA > 200 & nFeature_RNA < 2500 & percent.mt < 5)
```

Example 49 (unknown):
```unknown
pbmc[["RNA"]]$data
```

Example 50 (unknown):
```unknown
pbmc <- NormalizeData(pbmc, normalization.method = "LogNormalize", scale.factor = 10000)
```

Example 51 (r):
```r
pbmc <- NormalizeData(pbmc, normalization.method = "LogNormalize", scale.factor = 10000)
```

Example 52 (r):
```r
pbmc <- NormalizeData(pbmc, normalization.method = "LogNormalize", scale.factor = 10000)
```

Example 53 (unknown):
```unknown
pbmc <- NormalizeData(pbmc)
```

Example 54 (r):
```r
pbmc <- NormalizeData(pbmc)
```

Example 55 (r):
```r
pbmc <- NormalizeData(pbmc)
```

Example 56 (unknown):
```unknown
SCTransform()
```

Example 57 (unknown):
```unknown
SCTransform
```

Example 58 (unknown):
```unknown
NormalizeData
```

Example 59 (unknown):
```unknown
FindVariableFeatures
```

Example 60 (unknown):
```unknown
FindVariableFeatures()
```

Example 61 (unknown):
```unknown
pbmc <- FindVariableFeatures(pbmc, selection.method = "vst", nfeatures = 2000)

# Identify the 10 most highly variable genes
top10 <- head(VariableFeatures(pbmc), 10)

# plot variable features with and without labels
plot1 <- VariableFeaturePlot(pbmc)
plot2 <- LabelPoints(plot = plot1, points = top10, repel = TRUE)
plot1 + plot2
```

Example 62 (r):
```r
pbmc <- FindVariableFeatures(pbmc, selection.method = "vst", nfeatures = 2000)

# Identify the 10 most highly variable genes
top10 <- head(VariableFeatures(pbmc), 10)

# plot variable features with and without labels
plot1 <- VariableFeaturePlot(pbmc)
plot2 <- LabelPoints(plot = plot1, points = top10, repel = TRUE)
plot1 + plot2
```

Example 63 (r):
```r
pbmc <- FindVariableFeatures(pbmc, selection.method = "vst", nfeatures = 2000)

# Identify the 10 most highly variable genes
top10 <- head(VariableFeatures(pbmc), 10)

# plot variable features with and without labels
plot1 <- VariableFeaturePlot(pbmc)
plot2 <- LabelPoints(plot = plot1, points = top10, repel = TRUE)
plot1 + plot2
```

Example 64 (unknown):
```unknown
ScaleData()
```

Example 65 (unknown):
```unknown
pbmc[["RNA"]]$scale.data
```

Example 66 (unknown):
```unknown
all.genes <- rownames(pbmc)
pbmc <- ScaleData(pbmc, features = all.genes)
```

Example 67 (r):
```r
all.genes <- rownames(pbmc)
pbmc <- ScaleData(pbmc, features = all.genes)
```

Example 68 (r):
```r
all.genes <- rownames(pbmc)
pbmc <- ScaleData(pbmc, features = all.genes)
```

Example 69 (unknown):
```unknown
ScaleData()
```

Example 70 (unknown):
```unknown
pbmc <- ScaleData(pbmc, vars.to.regress = "percent.mt")
```

Example 71 (r):
```r
pbmc <- ScaleData(pbmc, vars.to.regress = "percent.mt")
```

Example 72 (r):
```r
pbmc <- ScaleData(pbmc, vars.to.regress = "percent.mt")
```

Example 73 (unknown):
```unknown
SCTransform()
```

Example 74 (unknown):
```unknown
ScaleData()
```

Example 75 (unknown):
```unknown
SCTransform()
```

Example 76 (unknown):
```unknown
vars.to.regress
```

Example 77 (unknown):
```unknown
pbmc <- RunPCA(pbmc, features = VariableFeatures(object = pbmc))
```

Example 78 (r):
```r
pbmc <- RunPCA(pbmc, features = VariableFeatures(object = pbmc))
```

Example 79 (r):
```r
pbmc <- RunPCA(pbmc, features = VariableFeatures(object = pbmc))
```

Example 80 (unknown):
```unknown
VizDimReduction()
```

Example 81 (unknown):
```unknown
DimHeatmap()
```

Example 82 (python):
```python
# Examine and visualize PCA results a few different ways
print(pbmc[["pca"]], dims = 1:5, nfeatures = 5)
```

Example 83 (r):
```r
# Examine and visualize PCA results a few different ways
print(pbmc[["pca"]], dims = 1:5, nfeatures = 5)
```

Example 84 (r):
```r
# Examine and visualize PCA results a few different ways
print(pbmc[["pca"]], dims = 1:5, nfeatures = 5)
```

Example 85 (unknown):
```unknown
## PC_ 1 
## Positive:  CST3, TYROBP, LST1, AIF1, FTL 
## Negative:  MALAT1, LTB, IL32, IL7R, CD2 
## PC_ 2 
## Positive:  CD79A, MS4A1, TCL1A, HLA-DQA1, HLA-DQB1 
## Negative:  NKG7, PRF1, CST7, GZMB, GZMA 
## PC_ 3 
## Positive:  HLA-DQA1, CD79A, CD79B, HLA-DQB1, HLA-DPB1 
## Negative:  PPBP, PF4, SDPR, SPARC, GNG11 
## PC_ 4 
## Positive:  HLA-DQA1, CD79B, CD79A, MS4A1, HLA-DQB1 
## Negative:  VIM, IL7R, S100A6, IL32, S100A8 
## PC_ 5 
## Positive:  GZMB, NKG7, S100A8, FGFBP2, GNLY 
## Negative:  LTB, IL7R, CKB, VIM, MS4A7
```

Example 86 (unknown):
```unknown
## PC_ 1 
## Positive:  CST3, TYROBP, LST1, AIF1, FTL 
## Negative:  MALAT1, LTB, IL32, IL7R, CD2 
## PC_ 2 
## Positive:  CD79A, MS4A1, TCL1A, HLA-DQA1, HLA-DQB1 
## Negative:  NKG7, PRF1, CST7, GZMB, GZMA 
## PC_ 3 
## Positive:  HLA-DQA1, CD79A, CD79B, HLA-DQB1, HLA-DPB1 
## Negative:  PPBP, PF4, SDPR, SPARC, GNG11 
## PC_ 4 
## Positive:  HLA-DQA1, CD79B, CD79A, MS4A1, HLA-DQB1 
## Negative:  VIM, IL7R, S100A6, IL32, S100A8 
## PC_ 5 
## Positive:  GZMB, NKG7, S100A8, FGFBP2, GNLY 
## Negative:  LTB, IL7R, CKB, VIM, MS4A7
```

Example 87 (unknown):
```unknown
VizDimLoadings(pbmc, dims = 1:2, reduction = "pca")
```

Example 88 (r):
```r
VizDimLoadings(pbmc, dims = 1:2, reduction = "pca")
```

Example 89 (r):
```r
VizDimLoadings(pbmc, dims = 1:2, reduction = "pca")
```

Example 90 (unknown):
```unknown
DimPlot(pbmc, reduction = "pca") + NoLegend()
```

Example 91 (r):
```r
DimPlot(pbmc, reduction = "pca") + NoLegend()
```

Example 92 (r):
```r
DimPlot(pbmc, reduction = "pca") + NoLegend()
```

Example 93 (unknown):
```unknown
DimHeatmap()
```

Example 94 (unknown):
```unknown
DimHeatmap(pbmc, dims = 1, cells = 500, balanced = TRUE)
```

Example 95 (r):
```r
DimHeatmap(pbmc, dims = 1, cells = 500, balanced = TRUE)
```

Example 96 (r):
```r
DimHeatmap(pbmc, dims = 1, cells = 500, balanced = TRUE)
```

Example 97 (unknown):
```unknown
DimHeatmap(pbmc, dims = 1:15, cells = 500, balanced = TRUE)
```

Example 98 (r):
```r
DimHeatmap(pbmc, dims = 1:15, cells = 500, balanced = TRUE)
```

Example 99 (r):
```r
DimHeatmap(pbmc, dims = 1:15, cells = 500, balanced = TRUE)
```

Example 100 (unknown):
```unknown
ElbowPlot()
```

Example 101 (unknown):
```unknown
ElbowPlot(pbmc)
```

Example 102 (r):
```r
ElbowPlot(pbmc)
```

Example 103 (r):
```r
ElbowPlot(pbmc)
```

Example 104 (unknown):
```unknown
FindNeighbors()
```

Example 105 (unknown):
```unknown
FindClusters()
```

Example 106 (unknown):
```unknown
pbmc <- FindNeighbors(pbmc, dims = 1:10)
pbmc <- FindClusters(pbmc, resolution = 0.5)
```

Example 107 (r):
```r
pbmc <- FindNeighbors(pbmc, dims = 1:10)
pbmc <- FindClusters(pbmc, resolution = 0.5)
```

Example 108 (r):
```r
pbmc <- FindNeighbors(pbmc, dims = 1:10)
pbmc <- FindClusters(pbmc, resolution = 0.5)
```

Example 109 (unknown):
```unknown
## Modularity Optimizer version 1.3.0 by Ludo Waltman and Nees Jan van Eck
## 
## Number of nodes: 2638
## Number of edges: 95965
## 
## Running Louvain algorithm...
## Maximum modularity in 10 random starts: 0.8723
## Number of communities: 9
## Elapsed time: 0 seconds
```

Example 110 (unknown):
```unknown
## Modularity Optimizer version 1.3.0 by Ludo Waltman and Nees Jan van Eck
## 
## Number of nodes: 2638
## Number of edges: 95965
## 
## Running Louvain algorithm...
## Maximum modularity in 10 random starts: 0.8723
## Number of communities: 9
## Elapsed time: 0 seconds
```

Example 111 (unknown):
```unknown
# Look at cluster IDs of the first 5 cells
head(Idents(pbmc), 5)
```

Example 112 (r):
```r
# Look at cluster IDs of the first 5 cells
head(Idents(pbmc), 5)
```

Example 113 (r):
```r
# Look at cluster IDs of the first 5 cells
head(Idents(pbmc), 5)
```

Example 114 (unknown):
```unknown
## AAACATACAACCAC-1 AAACATTGAGCTAC-1 AAACATTGATCAGC-1 AAACCGTGCTTCCG-1 
##                2                3                2                1 
## AAACCGTGTATGCG-1 
##                6 
## Levels: 0 1 2 3 4 5 6 7 8
```

Example 115 (unknown):
```unknown
## AAACATACAACCAC-1 AAACATTGAGCTAC-1 AAACATTGATCAGC-1 AAACCGTGCTTCCG-1 
##                2                3                2                1 
## AAACCGTGTATGCG-1 
##                6 
## Levels: 0 1 2 3 4 5 6 7 8
```

Example 116 (unknown):
```unknown
pbmc <- RunUMAP(pbmc, dims = 1:10)
```

Example 117 (r):
```r
pbmc <- RunUMAP(pbmc, dims = 1:10)
```

Example 118 (r):
```r
pbmc <- RunUMAP(pbmc, dims = 1:10)
```

Example 119 (unknown):
```unknown
# note that you can set `label = TRUE` or use the LabelClusters function to help label
# individual clusters
DimPlot(pbmc, reduction = "umap")
```

Example 120 (r):
```r
# note that you can set `label = TRUE` or use the LabelClusters function to help label
# individual clusters
DimPlot(pbmc, reduction = "umap")
```

Example 121 (r):
```r
# note that you can set `label = TRUE` or use the LabelClusters function to help label
# individual clusters
DimPlot(pbmc, reduction = "umap")
```

Example 122 (unknown):
```unknown
saveRDS(pbmc, file = "../output/pbmc_tutorial.rds")
```

Example 123 (r):
```r
saveRDS(pbmc, file = "../output/pbmc_tutorial.rds")
```

Example 124 (r):
```r
saveRDS(pbmc, file = "../output/pbmc_tutorial.rds")
```

Example 125 (unknown):
```unknown
FindAllMarkers()
```

Example 126 (unknown):
```unknown
?FindMarkers
```

Example 127 (unknown):
```unknown
logfc.threshold
```

Example 128 (unknown):
```unknown
# find all markers of cluster 2
cluster2.markers <- FindMarkers(pbmc, ident.1 = 2)
head(cluster2.markers, n = 5)
```

Example 129 (r):
```r
# find all markers of cluster 2
cluster2.markers <- FindMarkers(pbmc, ident.1 = 2)
head(cluster2.markers, n = 5)
```

Example 130 (r):
```r
# find all markers of cluster 2
cluster2.markers <- FindMarkers(pbmc, ident.1 = 2)
head(cluster2.markers, n = 5)
```

Example 131 (unknown):
```unknown
##             p_val avg_log2FC pct.1 pct.2    p_val_adj
## IL32 2.593535e-91  1.3221171 0.949 0.466 3.556774e-87
## LTB  7.994465e-87  1.3450377 0.981 0.644 1.096361e-82
## CD3D 3.922451e-70  1.0562099 0.922 0.433 5.379250e-66
## IL7R 1.130870e-66  1.4256944 0.748 0.327 1.550876e-62
## LDHB 4.082189e-65  0.9765875 0.953 0.614 5.598314e-61
```

Example 132 (unknown):
```unknown
##             p_val avg_log2FC pct.1 pct.2    p_val_adj
## IL32 2.593535e-91  1.3221171 0.949 0.466 3.556774e-87
## LTB  7.994465e-87  1.3450377 0.981 0.644 1.096361e-82
## CD3D 3.922451e-70  1.0562099 0.922 0.433 5.379250e-66
## IL7R 1.130870e-66  1.4256944 0.748 0.327 1.550876e-62
## LDHB 4.082189e-65  0.9765875 0.953 0.614 5.598314e-61
```

Example 133 (python):
```python
# find all markers distinguishing cluster 5 from clusters 0 and 3
cluster5.markers <- FindMarkers(pbmc, ident.1 = 5, ident.2 = c(0, 3))
head(cluster5.markers, n = 5)
```

Example 134 (r):
```r
# find all markers distinguishing cluster 5 from clusters 0 and 3
cluster5.markers <- FindMarkers(pbmc, ident.1 = 5, ident.2 = c(0, 3))
head(cluster5.markers, n = 5)
```

Example 135 (r):
```r
# find all markers distinguishing cluster 5 from clusters 0 and 3
cluster5.markers <- FindMarkers(pbmc, ident.1 = 5, ident.2 = c(0, 3))
head(cluster5.markers, n = 5)
```

Example 136 (unknown):
```unknown
##                       p_val avg_log2FC pct.1 pct.2     p_val_adj
## FCGR3A        2.150929e-209   6.832372 0.975 0.039 2.949784e-205
## IFITM3        6.103366e-199   6.181000 0.975 0.048 8.370156e-195
## CFD           8.891428e-198   6.052575 0.938 0.037 1.219370e-193
## CD68          2.374425e-194   5.493138 0.926 0.035 3.256286e-190
## RP11-290F20.3 9.308287e-191   6.335402 0.840 0.016 1.276538e-186
```

Example 137 (unknown):
```unknown
##                       p_val avg_log2FC pct.1 pct.2     p_val_adj
## FCGR3A        2.150929e-209   6.832372 0.975 0.039 2.949784e-205
## IFITM3        6.103366e-199   6.181000 0.975 0.048 8.370156e-195
## CFD           8.891428e-198   6.052575 0.938 0.037 1.219370e-193
## CD68          2.374425e-194   5.493138 0.926 0.035 3.256286e-190
## RP11-290F20.3 9.308287e-191   6.335402 0.840 0.016 1.276538e-186
```

Example 138 (unknown):
```unknown
# find markers for every cluster compared to all remaining cells, report only the positive
# ones
pbmc.markers <- FindAllMarkers(pbmc, only.pos = TRUE)
pbmc.markers %>%
    group_by(cluster) %>%
    dplyr::filter(avg_log2FC > 1)
```

Example 139 (r):
```r
# find markers for every cluster compared to all remaining cells, report only the positive
# ones
pbmc.markers <- FindAllMarkers(pbmc, only.pos = TRUE)
pbmc.markers %>%
    group_by(cluster) %>%
    dplyr::filter(avg_log2FC > 1)
```

Example 140 (r):
```r
# find markers for every cluster compared to all remaining cells, report only the positive
# ones
pbmc.markers <- FindAllMarkers(pbmc, only.pos = TRUE)
pbmc.markers %>%
    group_by(cluster) %>%
    dplyr::filter(avg_log2FC > 1)
```

Example 141 (unknown):
```unknown
## # A tibble: 7,046 × 7
## # Groups:   cluster [9]
##        p_val avg_log2FC pct.1 pct.2 p_val_adj cluster gene     
##        <dbl>      <dbl> <dbl> <dbl>     <dbl> <fct>   <chr>    
##  1 1.74e-109       1.19 0.897 0.593 2.39e-105 0       LDHB     
##  2 1.17e- 83       2.37 0.435 0.108 1.60e- 79 0       CCR7     
##  3 8.94e- 79       1.09 0.838 0.403 1.23e- 74 0       CD3D     
##  4 3.05e- 53       1.02 0.722 0.399 4.19e- 49 0       CD3E     
##  5 3.28e- 49       2.10 0.333 0.103 4.50e- 45 0       LEF1     
##  6 6.66e- 49       1.25 0.623 0.358 9.13e- 45 0       NOSIP    
##  7 9.31e- 44       2.02 0.328 0.11  1.28e- 39 0       PRKCQ-AS1
##  8 4.69e- 43       1.53 0.435 0.184 6.43e- 39 0       PIK3IP1  
##  9 1.47e- 39       2.70 0.195 0.04  2.01e- 35 0       FHIT     
## 10 2.44e- 33       1.94 0.262 0.087 3.34e- 29 0       MAL      
## # ℹ 7,036 more rows
```

Example 142 (unknown):
```unknown
## # A tibble: 7,046 × 7
## # Groups:   cluster [9]
##        p_val avg_log2FC pct.1 pct.2 p_val_adj cluster gene     
##        <dbl>      <dbl> <dbl> <dbl>     <dbl> <fct>   <chr>    
##  1 1.74e-109       1.19 0.897 0.593 2.39e-105 0       LDHB     
##  2 1.17e- 83       2.37 0.435 0.108 1.60e- 79 0       CCR7     
##  3 8.94e- 79       1.09 0.838 0.403 1.23e- 74 0       CD3D     
##  4 3.05e- 53       1.02 0.722 0.399 4.19e- 49 0       CD3E     
##  5 3.28e- 49       2.10 0.333 0.103 4.50e- 45 0       LEF1     
##  6 6.66e- 49       1.25 0.623 0.358 9.13e- 45 0       NOSIP    
##  7 9.31e- 44       2.02 0.328 0.11  1.28e- 39 0       PRKCQ-AS1
##  8 4.69e- 43       1.53 0.435 0.184 6.43e- 39 0       PIK3IP1  
##  9 1.47e- 39       2.70 0.195 0.04  2.01e- 35 0       FHIT     
## 10 2.44e- 33       1.94 0.262 0.087 3.34e- 29 0       MAL      
## # ℹ 7,036 more rows
```

Example 143 (unknown):
```unknown
cluster0.markers <- FindMarkers(pbmc, ident.1 = 0, logfc.threshold = 0.25, test.use = "roc", only.pos = TRUE)
```

Example 144 (r):
```r
cluster0.markers <- FindMarkers(pbmc, ident.1 = 0, logfc.threshold = 0.25, test.use = "roc", only.pos = TRUE)
```

Example 145 (r):
```r
cluster0.markers <- FindMarkers(pbmc, ident.1 = 0, logfc.threshold = 0.25, test.use = "roc", only.pos = TRUE)
```

Example 146 (unknown):
```unknown
FeaturePlot()
```

Example 147 (unknown):
```unknown
RidgePlot()
```

Example 148 (unknown):
```unknown
CellScatter()
```

Example 149 (unknown):
```unknown
VlnPlot(pbmc, features = c("MS4A1", "CD79A"))
```

Example 150 (r):
```r
VlnPlot(pbmc, features = c("MS4A1", "CD79A"))
```

Example 151 (r):
```r
VlnPlot(pbmc, features = c("MS4A1", "CD79A"))
```

Example 152 (unknown):
```unknown
# you can plot raw counts as well
VlnPlot(pbmc, features = c("NKG7", "PF4"), slot = "counts", log = TRUE)
```

Example 153 (r):
```r
# you can plot raw counts as well
VlnPlot(pbmc, features = c("NKG7", "PF4"), slot = "counts", log = TRUE)
```

Example 154 (r):
```r
# you can plot raw counts as well
VlnPlot(pbmc, features = c("NKG7", "PF4"), slot = "counts", log = TRUE)
```

Example 155 (unknown):
```unknown
FeaturePlot(pbmc, features = c("MS4A1", "GNLY", "CD3E", "CD14", "FCER1A", "FCGR3A", "LYZ", "PPBP",
    "CD8A"))
```

Example 156 (r):
```r
FeaturePlot(pbmc, features = c("MS4A1", "GNLY", "CD3E", "CD14", "FCER1A", "FCGR3A", "LYZ", "PPBP",
    "CD8A"))
```

Example 157 (r):
```r
FeaturePlot(pbmc, features = c("MS4A1", "GNLY", "CD3E", "CD14", "FCER1A", "FCGR3A", "LYZ", "PPBP",
    "CD8A"))
```

Example 158 (unknown):
```unknown
DoHeatmap()
```

Example 159 (unknown):
```unknown
pbmc.markers %>%
    group_by(cluster) %>%
    dplyr::filter(avg_log2FC > 1) %>%
    slice_head(n = 10) %>%
    ungroup() -> top10
DoHeatmap(pbmc, features = top10$gene) + NoLegend()
```

Example 160 (r):
```r
pbmc.markers %>%
    group_by(cluster) %>%
    dplyr::filter(avg_log2FC > 1) %>%
    slice_head(n = 10) %>%
    ungroup() -> top10
DoHeatmap(pbmc, features = top10$gene) + NoLegend()
```

Example 161 (r):
```r
pbmc.markers %>%
    group_by(cluster) %>%
    dplyr::filter(avg_log2FC > 1) %>%
    slice_head(n = 10) %>%
    ungroup() -> top10
DoHeatmap(pbmc, features = top10$gene) + NoLegend()
```

Example 162 (unknown):
```unknown
new.cluster.ids <- c("Naive CD4 T", "CD14+ Mono", "Memory CD4 T", "B", "CD8 T", "FCGR3A+ Mono",
    "NK", "DC", "Platelet")
names(new.cluster.ids) <- levels(pbmc)
pbmc <- RenameIdents(pbmc, new.cluster.ids)
DimPlot(pbmc, reduction = "umap", label = TRUE, pt.size = 0.5) + NoLegend()
```

Example 163 (r):
```r
new.cluster.ids <- c("Naive CD4 T", "CD14+ Mono", "Memory CD4 T", "B", "CD8 T", "FCGR3A+ Mono",
    "NK", "DC", "Platelet")
names(new.cluster.ids) <- levels(pbmc)
pbmc <- RenameIdents(pbmc, new.cluster.ids)
DimPlot(pbmc, reduction = "umap", label = TRUE, pt.size = 0.5) + NoLegend()
```

Example 164 (r):
```r
new.cluster.ids <- c("Naive CD4 T", "CD14+ Mono", "Memory CD4 T", "B", "CD8 T", "FCGR3A+ Mono",
    "NK", "DC", "Platelet")
names(new.cluster.ids) <- levels(pbmc)
pbmc <- RenameIdents(pbmc, new.cluster.ids)
DimPlot(pbmc, reduction = "umap", label = TRUE, pt.size = 0.5) + NoLegend()
```

Example 165 (unknown):
```unknown
library(ggplot2)
plot <- DimPlot(pbmc, reduction = "umap", label = TRUE, label.size = 4.5) + xlab("UMAP 1") + ylab("UMAP 2") +
    theme(axis.title = element_text(size = 18), legend.text = element_text(size = 18)) + guides(colour = guide_legend(override.aes = list(size = 10)))
ggsave(filename = "../output/images/pbmc3k_umap.jpg", height = 7, width = 12, plot = plot, quality = 50)
```

Example 166 (r):
```r
library(ggplot2)
plot <- DimPlot(pbmc, reduction = "umap", label = TRUE, label.size = 4.5) + xlab("UMAP 1") + ylab("UMAP 2") +
    theme(axis.title = element_text(size = 18), legend.text = element_text(size = 18)) + guides(colour = guide_legend(override.aes = list(size = 10)))
ggsave(filename = "../output/images/pbmc3k_umap.jpg", height = 7, width = 12, plot = plot, quality = 50)
```

Example 167 (r):
```r
library(ggplot2)
plot <- DimPlot(pbmc, reduction = "umap", label = TRUE, label.size = 4.5) + xlab("UMAP 1") + ylab("UMAP 2") +
    theme(axis.title = element_text(size = 18), legend.text = element_text(size = 18)) + guides(colour = guide_legend(override.aes = list(size = 10)))
ggsave(filename = "../output/images/pbmc3k_umap.jpg", height = 7, width = 12, plot = plot, quality = 50)
```

Example 168 (unknown):
```unknown
saveRDS(pbmc, file = "../output/pbmc3k_final.rds")
```

Example 169 (r):
```r
saveRDS(pbmc, file = "../output/pbmc3k_final.rds")
```

Example 170 (r):
```r
saveRDS(pbmc, file = "../output/pbmc3k_final.rds")
```

Example 171 (unknown):
```unknown
sessionInfo()
```

Example 172 (r):
```r
sessionInfo()
```

Example 173 (r):
```r
sessionInfo()
```

Example 174 (unknown):
```unknown
## R version 4.2.2 Patched (2022-11-10 r83330)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.6 LTS
## 
## Matrix products: default
## BLAS:   /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.9.0
## LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.9.0
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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       
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
## [1] ggplot2_3.4.4      patchwork_1.1.3    Seurat_5.0.0       SeuratObject_5.0.0
## [5] sp_2.1-1           dplyr_1.1.3       
## 
## loaded via a namespace (and not attached):
##   [1] spam_2.10-0            systemfonts_1.0.4      plyr_1.8.9            
##   [4] igraph_1.5.1           lazyeval_0.2.2         splines_4.2.2         
##   [7] RcppHNSW_0.5.0         listenv_0.9.0          scattermore_1.2       
##  [10] digest_0.6.33          htmltools_0.5.6.1      fansi_1.0.5           
##  [13] magrittr_2.0.3         memoise_2.0.1          tensor_1.5            
##  [16] cluster_2.1.4          ROCR_1.0-11            limma_3.54.1          
##  [19] globals_0.16.2         matrixStats_1.0.0      R.utils_2.12.2        
##  [22] pkgdown_2.0.7          spatstat.sparse_3.0-3  colorspace_2.1-0      
##  [25] ggrepel_0.9.4          textshaping_0.3.6      xfun_0.40             
##  [28] jsonlite_1.8.7         progressr_0.14.0       spatstat.data_3.0-3   
##  [31] survival_3.5-7         zoo_1.8-12             glue_1.6.2            
##  [34] polyclip_1.10-6        gtable_0.3.4           leiden_0.4.3          
##  [37] future.apply_1.11.0    abind_1.4-5            scales_1.2.1          
##  [40] spatstat.random_3.2-1  miniUI_0.1.1.1         Rcpp_1.0.11           
##  [43] viridisLite_0.4.2      xtable_1.8-4           reticulate_1.34.0     
##  [46] dotCall64_1.1-0        htmlwidgets_1.6.2      httr_1.4.7            
##  [49] RColorBrewer_1.1-3     ellipsis_0.3.2         ica_1.0-3             
##  [52] pkgconfig_2.0.3        R.methodsS3_1.8.2      farver_2.1.1          
##  [55] sass_0.4.7             uwot_0.1.16            deldir_1.0-9          
##  [58] utf8_1.2.4             tidyselect_1.2.0       labeling_0.4.3        
##  [61] rlang_1.1.1            reshape2_1.4.4         later_1.3.1           
##  [64] munsell_0.5.0          tools_4.2.2            cachem_1.0.8          
##  [67] cli_3.6.1              generics_0.1.3         ggridges_0.5.4        
##  [70] evaluate_0.22          stringr_1.5.0          fastmap_1.1.1         
##  [73] yaml_2.3.7             ragg_1.2.5             goftest_1.2-3         
##  [76] knitr_1.45             fs_1.6.3               fitdistrplus_1.1-11   
##  [79] purrr_1.0.2            RANN_2.6.1             pbapply_1.7-2         
##  [82] future_1.33.0          nlme_3.1-162           mime_0.12             
##  [85] formatR_1.14           ggrastr_1.0.1          R.oo_1.25.0           
##  [88] compiler_4.2.2         beeswarm_0.4.0         plotly_4.10.3         
##  [91] png_0.1-8              spatstat.utils_3.0-4   tibble_3.2.1          
##  [94] bslib_0.5.1            stringi_1.7.12         highr_0.10            
##  [97] desc_1.4.2             RSpectra_0.16-1        lattice_0.21-9        
## [100] Matrix_1.6-1.1         vctrs_0.6.4            pillar_1.9.0          
## [103] lifecycle_1.0.3        spatstat.geom_3.2-7    lmtest_0.9-40         
## [106] jquerylib_0.1.4        RcppAnnoy_0.0.21       data.table_1.14.8     
## [109] cowplot_1.1.1          irlba_2.3.5.1          httpuv_1.6.12         
## [112] R6_2.5.1               promises_1.2.1         KernSmooth_2.23-22    
## [115] gridExtra_2.3          vipor_0.4.5            parallelly_1.36.0     
## [118] codetools_0.2-19       fastDummies_1.7.3      MASS_7.3-58.2         
## [121] rprojroot_2.0.3        withr_2.5.2            presto_1.0.0          
## [124] sctransform_0.4.1      parallel_4.2.2         grid_4.2.2            
## [127] tidyr_1.3.0            rmarkdown_2.25         Rtsne_0.16            
## [130] spatstat.explore_3.2-5 shiny_1.7.5.1          ggbeeswarm_0.7.1
```

Example 175 (unknown):
```unknown
## R version 4.2.2 Patched (2022-11-10 r83330)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.6 LTS
## 
## Matrix products: default
## BLAS:   /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.9.0
## LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.9.0
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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       
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
## [1] ggplot2_3.4.4      patchwork_1.1.3    Seurat_5.0.0       SeuratObject_5.0.0
## [5] sp_2.1-1           dplyr_1.1.3       
## 
## loaded via a namespace (and not attached):
##   [1] spam_2.10-0            systemfonts_1.0.4      plyr_1.8.9            
##   [4] igraph_1.5.1           lazyeval_0.2.2         splines_4.2.2         
##   [7] RcppHNSW_0.5.0         listenv_0.9.0          scattermore_1.2       
##  [10] digest_0.6.33          htmltools_0.5.6.1      fansi_1.0.5           
##  [13] magrittr_2.0.3         memoise_2.0.1          tensor_1.5            
##  [16] cluster_2.1.4          ROCR_1.0-11            limma_3.54.1          
##  [19] globals_0.16.2         matrixStats_1.0.0      R.utils_2.12.2        
##  [22] pkgdown_2.0.7          spatstat.sparse_3.0-3  colorspace_2.1-0      
##  [25] ggrepel_0.9.4          textshaping_0.3.6      xfun_0.40             
##  [28] jsonlite_1.8.7         progressr_0.14.0       spatstat.data_3.0-3   
##  [31] survival_3.5-7         zoo_1.8-12             glue_1.6.2            
##  [34] polyclip_1.10-6        gtable_0.3.4           leiden_0.4.3          
##  [37] future.apply_1.11.0    abind_1.4-5            scales_1.2.1          
##  [40] spatstat.random_3.2-1  miniUI_0.1.1.1         Rcpp_1.0.11           
##  [43] viridisLite_0.4.2      xtable_1.8-4           reticulate_1.34.0     
##  [46] dotCall64_1.1-0        htmlwidgets_1.6.2      httr_1.4.7            
##  [49] RColorBrewer_1.1-3     ellipsis_0.3.2         ica_1.0-3             
##  [52] pkgconfig_2.0.3        R.methodsS3_1.8.2      farver_2.1.1          
##  [55] sass_0.4.7             uwot_0.1.16            deldir_1.0-9          
##  [58] utf8_1.2.4             tidyselect_1.2.0       labeling_0.4.3        
##  [61] rlang_1.1.1            reshape2_1.4.4         later_1.3.1           
##  [64] munsell_0.5.0          tools_4.2.2            cachem_1.0.8          
##  [67] cli_3.6.1              generics_0.1.3         ggridges_0.5.4        
##  [70] evaluate_0.22          stringr_1.5.0          fastmap_1.1.1         
##  [73] yaml_2.3.7             ragg_1.2.5             goftest_1.2-3         
##  [76] knitr_1.45             fs_1.6.3               fitdistrplus_1.1-11   
##  [79] purrr_1.0.2            RANN_2.6.1             pbapply_1.7-2         
##  [82] future_1.33.0          nlme_3.1-162           mime_0.12             
##  [85] formatR_1.14           ggrastr_1.0.1          R.oo_1.25.0           
##  [88] compiler_4.2.2         beeswarm_0.4.0         plotly_4.10.3         
##  [91] png_0.1-8              spatstat.utils_3.0-4   tibble_3.2.1          
##  [94] bslib_0.5.1            stringi_1.7.12         highr_0.10            
##  [97] desc_1.4.2             RSpectra_0.16-1        lattice_0.21-9        
## [100] Matrix_1.6-1.1         vctrs_0.6.4            pillar_1.9.0          
## [103] lifecycle_1.0.3        spatstat.geom_3.2-7    lmtest_0.9-40         
## [106] jquerylib_0.1.4        RcppAnnoy_0.0.21       data.table_1.14.8     
## [109] cowplot_1.1.1          irlba_2.3.5.1          httpuv_1.6.12         
## [112] R6_2.5.1               promises_1.2.1         KernSmooth_2.23-22    
## [115] gridExtra_2.3          vipor_0.4.5            parallelly_1.36.0     
## [118] codetools_0.2-19       fastDummies_1.7.3      MASS_7.3-58.2         
## [121] rprojroot_2.0.3        withr_2.5.2            presto_1.0.0          
## [124] sctransform_0.4.1      parallel_4.2.2         grid_4.2.2            
## [127] tidyr_1.3.0            rmarkdown_2.25         Rtsne_0.16            
## [130] spatstat.explore_3.2-5 shiny_1.7.5.1          ggbeeswarm_0.7.1
```

---

## Analysis, visualization, and integration of Visium HD spatial datasets with Seurat • Seurat

**URL:** http://127.0.0.1:9173/seurat/install_v5.html

**Contents:**
- Installation Instructions for Seurat
- Seurat 5: Install from CRAN
- Install previous versions of Seurat
  - Install Seurat v4
  - Older versions of Seurat
- Install the development version of Seurat
- Docker
- Contents

To install Seurat, R version 4.0 or greater is required. We also recommend installing R Studio.

Seurat is available on CRAN for all platforms. To install, run:

Seurat does not require, but makes use of, packages developed by other labs that can substantially enhance speed and performance. These include presto (Korunsky/Raychaudhari labs), BPCells (Greenleaf Lab), and glmGamPoi (Huber Lab). We recommend users install these along with Seurat:

We also recommend installing these additional packages, which are used in our vignettes, and enhance the functionality of Seurat:

Seurat v4.4.0 can be installed with the following commands:

Old versions of Seurat, from Seurat v2.0.1 and up, are hosted in CRAN’s archive. To install an old version of Seurat, run:

For versions of Seurat older than those not hosted on CRAN (versions 1.3.0 and 1.4.0), please download the packaged source code from our releases page and install from the tarball.

Install the development version of Seurat - directly from GitHub.

We provide docker images for Seurat via dockerhub.

To pull the latest image from the command line:

To use as a base image in a new Dockerfile:

Developed by Rahul Satija, Satija Lab and Collaborators.

Site built with pkgdown 2.0.7.

**Examples:**

Example 1 (unknown):
```unknown
vignettes/install_v5.Rmd
```

Example 2 (unknown):
```unknown
install_v5.Rmd
```

Example 3 (unknown):
```unknown
# Enter commands in R (or R studio, if installed)
install.packages('Seurat')
library(Seurat)
```

Example 4 (r):
```r
# Enter commands in R (or R studio, if installed)
install.packages('Seurat')
library(Seurat)
```

Example 5 (r):
```r
# Enter commands in R (or R studio, if installed)
install.packages('Seurat')
library(Seurat)
```

Example 6 (unknown):
```unknown
setRepositories(ind = 1:3, addURLs = c('https://satijalab.r-universe.dev', 'https://bnprks.r-universe.dev/'))
install.packages(c("BPCells", "presto", "glmGamPoi"))
```

Example 7 (r):
```r
setRepositories(ind = 1:3, addURLs = c('https://satijalab.r-universe.dev', 'https://bnprks.r-universe.dev/'))
install.packages(c("BPCells", "presto", "glmGamPoi"))
```

Example 8 (r):
```r
setRepositories(ind = 1:3, addURLs = c('https://satijalab.r-universe.dev', 'https://bnprks.r-universe.dev/'))
install.packages(c("BPCells", "presto", "glmGamPoi"))
```

Example 9 (unknown):
```unknown
# Install the remotes package
if (!requireNamespace("remotes", quietly = TRUE)) {
  install.packages("remotes")
}
install.packages('Signac')
remotes::install_github("satijalab/seurat-data", quiet = TRUE)
remotes::install_github("satijalab/azimuth", quiet = TRUE)
remotes::install_github("satijalab/seurat-wrappers", quiet = TRUE)
```

Example 10 (r):
```r
# Install the remotes package
if (!requireNamespace("remotes", quietly = TRUE)) {
  install.packages("remotes")
}
install.packages('Signac')
remotes::install_github("satijalab/seurat-data", quiet = TRUE)
remotes::install_github("satijalab/azimuth", quiet = TRUE)
remotes::install_github("satijalab/seurat-wrappers", quiet = TRUE)
```

Example 11 (r):
```r
# Install the remotes package
if (!requireNamespace("remotes", quietly = TRUE)) {
  install.packages("remotes")
}
install.packages('Signac')
remotes::install_github("satijalab/seurat-data", quiet = TRUE)
remotes::install_github("satijalab/azimuth", quiet = TRUE)
remotes::install_github("satijalab/seurat-wrappers", quiet = TRUE)
```

Example 12 (unknown):
```unknown
remotes::install_version("SeuratObject", "4.1.4", repos = c("https://satijalab.r-universe.dev", getOption("repos")))
remotes::install_version("Seurat", "4.4.0", repos = c("https://satijalab.r-universe.dev", getOption("repos")))
```

Example 13 (r):
```r
remotes::install_version("SeuratObject", "4.1.4", repos = c("https://satijalab.r-universe.dev", getOption("repos")))
remotes::install_version("Seurat", "4.4.0", repos = c("https://satijalab.r-universe.dev", getOption("repos")))
```

Example 14 (r):
```r
remotes::install_version("SeuratObject", "4.1.4", repos = c("https://satijalab.r-universe.dev", getOption("repos")))
remotes::install_version("Seurat", "4.4.0", repos = c("https://satijalab.r-universe.dev", getOption("repos")))
```

Example 15 (unknown):
```unknown
# Install the remotes package 
install.packages('remotes')
# Replace 'X.X.X' with your desired version
remotes::install_version(package = 'Seurat', version = package_version('X.X.X'))
```

Example 16 (r):
```r
# Install the remotes package 
install.packages('remotes')
# Replace 'X.X.X' with your desired version
remotes::install_version(package = 'Seurat', version = package_version('X.X.X'))
```

Example 17 (r):
```r
# Install the remotes package 
install.packages('remotes')
# Replace 'X.X.X' with your desired version
remotes::install_version(package = 'Seurat', version = package_version('X.X.X'))
```

Example 18 (unknown):
```unknown
# Enter commands in R (or R studio, if installed)
# Install the remotes package
install.packages('remotes')
remotes::install_github(repo = 'satijalab/seurat', ref = 'develop')
library(Seurat)
```

Example 19 (r):
```r
# Enter commands in R (or R studio, if installed)
# Install the remotes package
install.packages('remotes')
remotes::install_github(repo = 'satijalab/seurat', ref = 'develop')
library(Seurat)
```

Example 20 (r):
```r
# Enter commands in R (or R studio, if installed)
# Install the remotes package
install.packages('remotes')
remotes::install_github(repo = 'satijalab/seurat', ref = 'develop')
library(Seurat)
```

Example 21 (unknown):
```unknown
docker pull satijalab/seurat:latest
```

Example 22 (unknown):
```unknown
docker pull satijalab/seurat:latest
```

Example 23 (bash):
```bash
docker pull satijalab/seurat:latest
```

Example 24 (unknown):
```unknown
FROM satijalab/seurat:latest
```

Example 25 (unknown):
```unknown
FROM satijalab/seurat:latest
```

Example 26 (bash):
```bash
FROM satijalab/seurat:latest
```

---

## Analysis, visualization, and integration of Visium HD spatial datasets with Seurat • Seurat

**URL:** http://127.0.0.1:9173/seurat/articles/hashing_vignette/index.html

**Contents:**
- Demultiplexing with hashtag oligos (HTOs)
    - Compiled: 2023-11-14
- 8-HTO dataset from human PBMCs
  - Basic setup
  - Adding HTO data as an independent assay
  - Demultiplex cells based on HTO enrichment
  - Visualize demultiplexing results
- 12-HTO dataset from four human cell lines
  - Create Seurat object, add HTO data and perform normalization
  - Demultiplex data
  - Visualize demultiplexing results
  - Visualize RNA clustering
- Contents

Developed in collaboration with the Technology Innovation Group at NYGC, Cell Hashing uses oligo-tagged antibodies against ubiquitously expressed surface proteins to place a “sample barcode” on each single cell, enabling different samples to be multiplexed together and run in a single experiment. For more information, please refer to this paper.

This vignette will give a brief demonstration on how to work with data produced with Cell Hashing in Seurat. Applied to two datasets, we can successfully demultiplex cells to their the original sample-of-origin, and identify cross-sample doublets.

Setup Seurat object and add in the HTO data

You can read more about working with multi-modal data here

Here we use the Seurat function HTODemux() to assign single cells back to their sample origins.

Output from running HTODemux() is saved in the object metadata. We can visualize how many cells are classified as singlets, doublets and negative/ambiguous cells.

Visualize enrichment for selected HTOs with ridge plots

Visualize pairs of HTO signals to confirm mutual exclusivity in singlets

Compare number of UMIs for singlets, doublets and negative cells

Generate a two dimensional tSNE embedding for HTOs. Here we are grouping cells by singlets and doublets for simplicity.

Create an HTO heatmap, based on Figure 1C in the Cell Hashing paper.

Cluster and visualize cells using the usual scRNA-seq workflow, and examine for the potential presence of batch effects.

Distribution of selected HTOs grouped by classification, displayed by ridge plots

Visualize HTO signals in a heatmap

Developed by Rahul Satija, Satija Lab and Collaborators.

Site built with pkgdown 2.0.7.

**Examples:**

Example 1 (unknown):
```unknown
vignettes/hashing_vignette.Rmd
```

Example 2 (unknown):
```unknown
hashing_vignette.Rmd
```

Example 3 (unknown):
```unknown
library(Seurat)
```

Example 4 (r):
```r
library(Seurat)
```

Example 5 (r):
```r
library(Seurat)
```

Example 6 (python):
```python
# Load in the UMI matrix
pbmc.umis <- readRDS("/brahms/shared/vignette-data/pbmc_umi_mtx.rds")

# For generating a hashtag count matrix from FASTQ files, please refer to
# https://github.com/Hoohm/CITE-seq-Count.  Load in the HTO count matrix
pbmc.htos <- readRDS("/brahms/shared/vignette-data/pbmc_hto_mtx.rds")

# Select cell barcodes detected by both RNA and HTO In the example datasets we have already
# filtered the cells for you, but perform this step for clarity.
joint.bcs <- intersect(colnames(pbmc.umis), colnames(pbmc.htos))

# Subset RNA and HTO counts by joint cell barcodes
pbmc.umis <- pbmc.umis[, joint.bcs]
pbmc.htos <- as.matrix(pbmc.htos[, joint.bcs])

# Confirm that the HTO have the correct names
rownames(pbmc.htos)
```

Example 7 (r):
```r
# Load in the UMI matrix
pbmc.umis <- readRDS("/brahms/shared/vignette-data/pbmc_umi_mtx.rds")

# For generating a hashtag count matrix from FASTQ files, please refer to
# https://github.com/Hoohm/CITE-seq-Count.  Load in the HTO count matrix
pbmc.htos <- readRDS("/brahms/shared/vignette-data/pbmc_hto_mtx.rds")

# Select cell barcodes detected by both RNA and HTO In the example datasets we have already
# filtered the cells for you, but perform this step for clarity.
joint.bcs <- intersect(colnames(pbmc.umis), colnames(pbmc.htos))

# Subset RNA and HTO counts by joint cell barcodes
pbmc.umis <- pbmc.umis[, joint.bcs]
pbmc.htos <- as.matrix(pbmc.htos[, joint.bcs])

# Confirm that the HTO have the correct names
rownames(pbmc.htos)
```

Example 8 (r):
```r
# Load in the UMI matrix
pbmc.umis <- readRDS("/brahms/shared/vignette-data/pbmc_umi_mtx.rds")

# For generating a hashtag count matrix from FASTQ files, please refer to
# https://github.com/Hoohm/CITE-seq-Count.  Load in the HTO count matrix
pbmc.htos <- readRDS("/brahms/shared/vignette-data/pbmc_hto_mtx.rds")

# Select cell barcodes detected by both RNA and HTO In the example datasets we have already
# filtered the cells for you, but perform this step for clarity.
joint.bcs <- intersect(colnames(pbmc.umis), colnames(pbmc.htos))

# Subset RNA and HTO counts by joint cell barcodes
pbmc.umis <- pbmc.umis[, joint.bcs]
pbmc.htos <- as.matrix(pbmc.htos[, joint.bcs])

# Confirm that the HTO have the correct names
rownames(pbmc.htos)
```

Example 9 (unknown):
```unknown
## [1] "HTO_A" "HTO_B" "HTO_C" "HTO_D" "HTO_E" "HTO_F" "HTO_G" "HTO_H"
```

Example 10 (unknown):
```unknown
## [1] "HTO_A" "HTO_B" "HTO_C" "HTO_D" "HTO_E" "HTO_F" "HTO_G" "HTO_H"
```

Example 11 (unknown):
```unknown
# Setup Seurat object
pbmc.hashtag <- CreateSeuratObject(counts = Matrix::Matrix(as.matrix(pbmc.umis), sparse = T))

# Normalize RNA data with log normalization
pbmc.hashtag <- NormalizeData(pbmc.hashtag)
# Find and scale variable features
pbmc.hashtag <- FindVariableFeatures(pbmc.hashtag, selection.method = "mean.var.plot")
pbmc.hashtag <- ScaleData(pbmc.hashtag, features = VariableFeatures(pbmc.hashtag))
```

Example 12 (r):
```r
# Setup Seurat object
pbmc.hashtag <- CreateSeuratObject(counts = Matrix::Matrix(as.matrix(pbmc.umis), sparse = T))

# Normalize RNA data with log normalization
pbmc.hashtag <- NormalizeData(pbmc.hashtag)
# Find and scale variable features
pbmc.hashtag <- FindVariableFeatures(pbmc.hashtag, selection.method = "mean.var.plot")
pbmc.hashtag <- ScaleData(pbmc.hashtag, features = VariableFeatures(pbmc.hashtag))
```

Example 13 (r):
```r
# Setup Seurat object
pbmc.hashtag <- CreateSeuratObject(counts = Matrix::Matrix(as.matrix(pbmc.umis), sparse = T))

# Normalize RNA data with log normalization
pbmc.hashtag <- NormalizeData(pbmc.hashtag)
# Find and scale variable features
pbmc.hashtag <- FindVariableFeatures(pbmc.hashtag, selection.method = "mean.var.plot")
pbmc.hashtag <- ScaleData(pbmc.hashtag, features = VariableFeatures(pbmc.hashtag))
```

Example 14 (python):
```python
# Add HTO data as a new assay independent from RNA
pbmc.hashtag[["HTO"]] <- CreateAssayObject(counts = pbmc.htos)
# Normalize HTO data, here we use centered log-ratio (CLR) transformation
pbmc.hashtag <- NormalizeData(pbmc.hashtag, assay = "HTO", normalization.method = "CLR")
```

Example 15 (r):
```r
# Add HTO data as a new assay independent from RNA
pbmc.hashtag[["HTO"]] <- CreateAssayObject(counts = pbmc.htos)
# Normalize HTO data, here we use centered log-ratio (CLR) transformation
pbmc.hashtag <- NormalizeData(pbmc.hashtag, assay = "HTO", normalization.method = "CLR")
```

Example 16 (r):
```r
# Add HTO data as a new assay independent from RNA
pbmc.hashtag[["HTO"]] <- CreateAssayObject(counts = pbmc.htos)
# Normalize HTO data, here we use centered log-ratio (CLR) transformation
pbmc.hashtag <- NormalizeData(pbmc.hashtag, assay = "HTO", normalization.method = "CLR")
```

Example 17 (unknown):
```unknown
# If you have a very large dataset we suggest using k_function = 'clara'. This is a k-medoid
# clustering function for large applications You can also play with additional parameters (see
# documentation for HTODemux()) to adjust the threshold for classification Here we are using
# the default settings
pbmc.hashtag <- HTODemux(pbmc.hashtag, assay = "HTO", positive.quantile = 0.99)
```

Example 18 (r):
```r
# If you have a very large dataset we suggest using k_function = 'clara'. This is a k-medoid
# clustering function for large applications You can also play with additional parameters (see
# documentation for HTODemux()) to adjust the threshold for classification Here we are using
# the default settings
pbmc.hashtag <- HTODemux(pbmc.hashtag, assay = "HTO", positive.quantile = 0.99)
```

Example 19 (r):
```r
# If you have a very large dataset we suggest using k_function = 'clara'. This is a k-medoid
# clustering function for large applications You can also play with additional parameters (see
# documentation for HTODemux()) to adjust the threshold for classification Here we are using
# the default settings
pbmc.hashtag <- HTODemux(pbmc.hashtag, assay = "HTO", positive.quantile = 0.99)
```

Example 20 (unknown):
```unknown
# Global classification results
table(pbmc.hashtag$HTO_classification.global)
```

Example 21 (r):
```r
# Global classification results
table(pbmc.hashtag$HTO_classification.global)
```

Example 22 (r):
```r
# Global classification results
table(pbmc.hashtag$HTO_classification.global)
```

Example 23 (javascript):
```javascript
## 
##  Doublet Negative  Singlet 
##     2598      346    13972
```

Example 24 (javascript):
```javascript
## 
##  Doublet Negative  Singlet 
##     2598      346    13972
```

Example 25 (unknown):
```unknown
# Group cells based on the max HTO signal
Idents(pbmc.hashtag) <- "HTO_maxID"
RidgePlot(pbmc.hashtag, assay = "HTO", features = rownames(pbmc.hashtag[["HTO"]])[1:2], ncol = 2)
```

Example 26 (r):
```r
# Group cells based on the max HTO signal
Idents(pbmc.hashtag) <- "HTO_maxID"
RidgePlot(pbmc.hashtag, assay = "HTO", features = rownames(pbmc.hashtag[["HTO"]])[1:2], ncol = 2)
```

Example 27 (r):
```r
# Group cells based on the max HTO signal
Idents(pbmc.hashtag) <- "HTO_maxID"
RidgePlot(pbmc.hashtag, assay = "HTO", features = rownames(pbmc.hashtag[["HTO"]])[1:2], ncol = 2)
```

Example 28 (unknown):
```unknown
FeatureScatter(pbmc.hashtag, feature1 = "hto_HTO-A", feature2 = "hto_HTO-B")
```

Example 29 (r):
```r
FeatureScatter(pbmc.hashtag, feature1 = "hto_HTO-A", feature2 = "hto_HTO-B")
```

Example 30 (r):
```r
FeatureScatter(pbmc.hashtag, feature1 = "hto_HTO-A", feature2 = "hto_HTO-B")
```

Example 31 (unknown):
```unknown
Idents(pbmc.hashtag) <- "HTO_classification.global"
VlnPlot(pbmc.hashtag, features = "nCount_RNA", pt.size = 0.1, log = TRUE)
```

Example 32 (r):
```r
Idents(pbmc.hashtag) <- "HTO_classification.global"
VlnPlot(pbmc.hashtag, features = "nCount_RNA", pt.size = 0.1, log = TRUE)
```

Example 33 (r):
```r
Idents(pbmc.hashtag) <- "HTO_classification.global"
VlnPlot(pbmc.hashtag, features = "nCount_RNA", pt.size = 0.1, log = TRUE)
```

Example 34 (python):
```python
# First, we will remove negative cells from the object
pbmc.hashtag.subset <- subset(pbmc.hashtag, idents = "Negative", invert = TRUE)

# Calculate a tSNE embedding of the HTO data
DefaultAssay(pbmc.hashtag.subset) <- "HTO"
pbmc.hashtag.subset <- ScaleData(pbmc.hashtag.subset, features = rownames(pbmc.hashtag.subset),
    verbose = FALSE)
pbmc.hashtag.subset <- RunPCA(pbmc.hashtag.subset, features = rownames(pbmc.hashtag.subset), approx = FALSE)
pbmc.hashtag.subset <- RunTSNE(pbmc.hashtag.subset, dims = 1:8, perplexity = 100)
DimPlot(pbmc.hashtag.subset)
```

Example 35 (r):
```r
# First, we will remove negative cells from the object
pbmc.hashtag.subset <- subset(pbmc.hashtag, idents = "Negative", invert = TRUE)

# Calculate a tSNE embedding of the HTO data
DefaultAssay(pbmc.hashtag.subset) <- "HTO"
pbmc.hashtag.subset <- ScaleData(pbmc.hashtag.subset, features = rownames(pbmc.hashtag.subset),
    verbose = FALSE)
pbmc.hashtag.subset <- RunPCA(pbmc.hashtag.subset, features = rownames(pbmc.hashtag.subset), approx = FALSE)
pbmc.hashtag.subset <- RunTSNE(pbmc.hashtag.subset, dims = 1:8, perplexity = 100)
DimPlot(pbmc.hashtag.subset)
```

Example 36 (r):
```r
# First, we will remove negative cells from the object
pbmc.hashtag.subset <- subset(pbmc.hashtag, idents = "Negative", invert = TRUE)

# Calculate a tSNE embedding of the HTO data
DefaultAssay(pbmc.hashtag.subset) <- "HTO"
pbmc.hashtag.subset <- ScaleData(pbmc.hashtag.subset, features = rownames(pbmc.hashtag.subset),
    verbose = FALSE)
pbmc.hashtag.subset <- RunPCA(pbmc.hashtag.subset, features = rownames(pbmc.hashtag.subset), approx = FALSE)
pbmc.hashtag.subset <- RunTSNE(pbmc.hashtag.subset, dims = 1:8, perplexity = 100)
DimPlot(pbmc.hashtag.subset)
```

Example 37 (javascript):
```javascript
# You can also visualize the more detailed classification result by running Idents(object) <-
# 'HTO_classification' before plotting. Here, you can see that each of the small clouds on the
# tSNE plot corresponds to one of the 28 possible doublet combinations.
```

Example 38 (r):
```r
# You can also visualize the more detailed classification result by running Idents(object) <-
# 'HTO_classification' before plotting. Here, you can see that each of the small clouds on the
# tSNE plot corresponds to one of the 28 possible doublet combinations.
```

Example 39 (r):
```r
# You can also visualize the more detailed classification result by running Idents(object) <-
# 'HTO_classification' before plotting. Here, you can see that each of the small clouds on the
# tSNE plot corresponds to one of the 28 possible doublet combinations.
```

Example 40 (unknown):
```unknown
# To increase the efficiency of plotting, you can subsample cells using the num.cells argument
HTOHeatmap(pbmc.hashtag, assay = "HTO", ncells = 5000)
```

Example 41 (r):
```r
# To increase the efficiency of plotting, you can subsample cells using the num.cells argument
HTOHeatmap(pbmc.hashtag, assay = "HTO", ncells = 5000)
```

Example 42 (r):
```r
# To increase the efficiency of plotting, you can subsample cells using the num.cells argument
HTOHeatmap(pbmc.hashtag, assay = "HTO", ncells = 5000)
```

Example 43 (javascript):
```javascript
# Extract the singlets
pbmc.singlet <- subset(pbmc.hashtag, idents = "Singlet")

# Select the top 1000 most variable features
pbmc.singlet <- FindVariableFeatures(pbmc.singlet, selection.method = "mean.var.plot")

# Scaling RNA data, we only scale the variable features here for efficiency
pbmc.singlet <- ScaleData(pbmc.singlet, features = VariableFeatures(pbmc.singlet))

# Run PCA
pbmc.singlet <- RunPCA(pbmc.singlet, features = VariableFeatures(pbmc.singlet))
```

Example 44 (r):
```r
# Extract the singlets
pbmc.singlet <- subset(pbmc.hashtag, idents = "Singlet")

# Select the top 1000 most variable features
pbmc.singlet <- FindVariableFeatures(pbmc.singlet, selection.method = "mean.var.plot")

# Scaling RNA data, we only scale the variable features here for efficiency
pbmc.singlet <- ScaleData(pbmc.singlet, features = VariableFeatures(pbmc.singlet))

# Run PCA
pbmc.singlet <- RunPCA(pbmc.singlet, features = VariableFeatures(pbmc.singlet))
```

Example 45 (r):
```r
# Extract the singlets
pbmc.singlet <- subset(pbmc.hashtag, idents = "Singlet")

# Select the top 1000 most variable features
pbmc.singlet <- FindVariableFeatures(pbmc.singlet, selection.method = "mean.var.plot")

# Scaling RNA data, we only scale the variable features here for efficiency
pbmc.singlet <- ScaleData(pbmc.singlet, features = VariableFeatures(pbmc.singlet))

# Run PCA
pbmc.singlet <- RunPCA(pbmc.singlet, features = VariableFeatures(pbmc.singlet))
```

Example 46 (javascript):
```javascript
# We select the top 10 PCs for clustering and tSNE based on PCElbowPlot
pbmc.singlet <- FindNeighbors(pbmc.singlet, reduction = "pca", dims = 1:10)
pbmc.singlet <- FindClusters(pbmc.singlet, resolution = 0.6, verbose = FALSE)
pbmc.singlet <- RunTSNE(pbmc.singlet, reduction = "pca", dims = 1:10)

# Projecting singlet identities on TSNE visualization
DimPlot(pbmc.singlet, group.by = "HTO_classification")
```

Example 47 (r):
```r
# We select the top 10 PCs for clustering and tSNE based on PCElbowPlot
pbmc.singlet <- FindNeighbors(pbmc.singlet, reduction = "pca", dims = 1:10)
pbmc.singlet <- FindClusters(pbmc.singlet, resolution = 0.6, verbose = FALSE)
pbmc.singlet <- RunTSNE(pbmc.singlet, reduction = "pca", dims = 1:10)

# Projecting singlet identities on TSNE visualization
DimPlot(pbmc.singlet, group.by = "HTO_classification")
```

Example 48 (r):
```r
# We select the top 10 PCs for clustering and tSNE based on PCElbowPlot
pbmc.singlet <- FindNeighbors(pbmc.singlet, reduction = "pca", dims = 1:10)
pbmc.singlet <- FindClusters(pbmc.singlet, resolution = 0.6, verbose = FALSE)
pbmc.singlet <- RunTSNE(pbmc.singlet, reduction = "pca", dims = 1:10)

# Projecting singlet identities on TSNE visualization
DimPlot(pbmc.singlet, group.by = "HTO_classification")
```

Example 49 (unknown):
```unknown
# Read in UMI count matrix for RNA
hto12.umis <- readRDS("/brahms/shared/vignette-data/hto12_umi_mtx.rds")

# Read in HTO count matrix
hto12.htos <- readRDS("/brahms/shared/vignette-data/hto12_hto_mtx.rds")

# Select cell barcodes detected in both RNA and HTO
cells.use <- intersect(rownames(hto12.htos), colnames(hto12.umis))

# Create Seurat object and add HTO data
hto12 <- CreateSeuratObject(counts = Matrix::Matrix(as.matrix(hto12.umis[, cells.use]), sparse = T),
    min.features = 300)
hto12[["HTO"]] <- CreateAssayObject(counts = t(x = hto12.htos[colnames(hto12), 1:12]))

# Normalize data
hto12 <- NormalizeData(hto12)
hto12 <- NormalizeData(hto12, assay = "HTO", normalization.method = "CLR")
```

Example 50 (r):
```r
# Read in UMI count matrix for RNA
hto12.umis <- readRDS("/brahms/shared/vignette-data/hto12_umi_mtx.rds")

# Read in HTO count matrix
hto12.htos <- readRDS("/brahms/shared/vignette-data/hto12_hto_mtx.rds")

# Select cell barcodes detected in both RNA and HTO
cells.use <- intersect(rownames(hto12.htos), colnames(hto12.umis))

# Create Seurat object and add HTO data
hto12 <- CreateSeuratObject(counts = Matrix::Matrix(as.matrix(hto12.umis[, cells.use]), sparse = T),
    min.features = 300)
hto12[["HTO"]] <- CreateAssayObject(counts = t(x = hto12.htos[colnames(hto12), 1:12]))

# Normalize data
hto12 <- NormalizeData(hto12)
hto12 <- NormalizeData(hto12, assay = "HTO", normalization.method = "CLR")
```

Example 51 (r):
```r
# Read in UMI count matrix for RNA
hto12.umis <- readRDS("/brahms/shared/vignette-data/hto12_umi_mtx.rds")

# Read in HTO count matrix
hto12.htos <- readRDS("/brahms/shared/vignette-data/hto12_hto_mtx.rds")

# Select cell barcodes detected in both RNA and HTO
cells.use <- intersect(rownames(hto12.htos), colnames(hto12.umis))

# Create Seurat object and add HTO data
hto12 <- CreateSeuratObject(counts = Matrix::Matrix(as.matrix(hto12.umis[, cells.use]), sparse = T),
    min.features = 300)
hto12[["HTO"]] <- CreateAssayObject(counts = t(x = hto12.htos[colnames(hto12), 1:12]))

# Normalize data
hto12 <- NormalizeData(hto12)
hto12 <- NormalizeData(hto12, assay = "HTO", normalization.method = "CLR")
```

Example 52 (unknown):
```unknown
hto12 <- HTODemux(hto12, assay = "HTO", positive.quantile = 0.99)
```

Example 53 (r):
```r
hto12 <- HTODemux(hto12, assay = "HTO", positive.quantile = 0.99)
```

Example 54 (r):
```r
hto12 <- HTODemux(hto12, assay = "HTO", positive.quantile = 0.99)
```

Example 55 (unknown):
```unknown
RidgePlot(hto12, assay = "HTO", features = c("HEK-A", "K562-B", "KG1-A", "THP1-C"), ncol = 2)
```

Example 56 (r):
```r
RidgePlot(hto12, assay = "HTO", features = c("HEK-A", "K562-B", "KG1-A", "THP1-C"), ncol = 2)
```

Example 57 (r):
```r
RidgePlot(hto12, assay = "HTO", features = c("HEK-A", "K562-B", "KG1-A", "THP1-C"), ncol = 2)
```

Example 58 (unknown):
```unknown
HTOHeatmap(hto12, assay = "HTO")
```

Example 59 (r):
```r
HTOHeatmap(hto12, assay = "HTO")
```

Example 60 (r):
```r
HTOHeatmap(hto12, assay = "HTO")
```

Example 61 (unknown):
```unknown
# Remove the negative cells
hto12 <- subset(hto12, idents = "Negative", invert = TRUE)

# Run PCA on most variable features
hto12 <- FindVariableFeatures(hto12, selection.method = "mean.var.plot")
hto12 <- ScaleData(hto12, features = VariableFeatures(hto12))
hto12 <- RunPCA(hto12)
hto12 <- RunTSNE(hto12, dims = 1:5, perplexity = 100)
DimPlot(hto12) + NoLegend()
```

Example 62 (r):
```r
# Remove the negative cells
hto12 <- subset(hto12, idents = "Negative", invert = TRUE)

# Run PCA on most variable features
hto12 <- FindVariableFeatures(hto12, selection.method = "mean.var.plot")
hto12 <- ScaleData(hto12, features = VariableFeatures(hto12))
hto12 <- RunPCA(hto12)
hto12 <- RunTSNE(hto12, dims = 1:5, perplexity = 100)
DimPlot(hto12) + NoLegend()
```

Example 63 (r):
```r
# Remove the negative cells
hto12 <- subset(hto12, idents = "Negative", invert = TRUE)

# Run PCA on most variable features
hto12 <- FindVariableFeatures(hto12, selection.method = "mean.var.plot")
hto12 <- ScaleData(hto12, features = VariableFeatures(hto12))
hto12 <- RunPCA(hto12)
hto12 <- RunTSNE(hto12, dims = 1:5, perplexity = 100)
DimPlot(hto12) + NoLegend()
```

Example 64 (unknown):
```unknown
sessionInfo()
```

Example 65 (r):
```r
sessionInfo()
```

Example 66 (r):
```r
sessionInfo()
```

Example 67 (unknown):
```unknown
## R version 4.2.2 Patched (2022-11-10 r83330)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.6 LTS
## 
## Matrix products: default
## BLAS:   /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.9.0
## LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.9.0
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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       
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
## [1] Seurat_5.0.0       SeuratObject_5.0.0 sp_2.1-1          
## 
## loaded via a namespace (and not attached):
##   [1] ggbeeswarm_0.7.1       Rtsne_0.16             colorspace_2.1-0      
##   [4] deldir_1.0-9           ellipsis_0.3.2         ggridges_0.5.4        
##   [7] rprojroot_2.0.4        RcppHNSW_0.5.0         fs_1.6.3              
##  [10] spatstat.data_3.0-3    farver_2.1.1           leiden_0.4.3          
##  [13] listenv_0.9.0          ggrepel_0.9.4          RSpectra_0.16-1       
##  [16] fansi_1.0.5            codetools_0.2-19       splines_4.2.2         
##  [19] cachem_1.0.8           knitr_1.45             polyclip_1.10-6       
##  [22] spam_2.10-0            jsonlite_1.8.7         ica_1.0-3             
##  [25] cluster_2.1.4          png_0.1-8              uwot_0.1.16           
##  [28] spatstat.sparse_3.0-3  sctransform_0.4.1      shiny_1.7.5.1         
##  [31] compiler_4.2.2         httr_1.4.7             Matrix_1.6-1.1        
##  [34] fastmap_1.1.1          lazyeval_0.2.2         cli_3.6.1             
##  [37] later_1.3.1            formatR_1.14           htmltools_0.5.6.1     
##  [40] tools_4.2.2            igraph_1.5.1           dotCall64_1.1-0       
##  [43] gtable_0.3.4           glue_1.6.2             reshape2_1.4.4        
##  [46] RANN_2.6.1             dplyr_1.1.3            Rcpp_1.0.11           
##  [49] scattermore_1.2        jquerylib_0.1.4        pkgdown_2.0.7         
##  [52] vctrs_0.6.4            nlme_3.1-162           spatstat.explore_3.2-5
##  [55] progressr_0.14.0       lmtest_0.9-40          spatstat.random_3.2-1 
##  [58] xfun_0.40              stringr_1.5.0          globals_0.16.2        
##  [61] mime_0.12              miniUI_0.1.1.1         lifecycle_1.0.4       
##  [64] irlba_2.3.5.1          goftest_1.2-3          future_1.33.0         
##  [67] MASS_7.3-58.2          zoo_1.8-12             scales_1.2.1          
##  [70] spatstat.utils_3.0-4   ragg_1.2.5             promises_1.2.1        
##  [73] parallel_4.2.2         RColorBrewer_1.1-3     yaml_2.3.7            
##  [76] gridExtra_2.3          memoise_2.0.1          reticulate_1.34.0     
##  [79] pbapply_1.7-2          ggrastr_1.0.1          ggplot2_3.4.4         
##  [82] sass_0.4.7             stringi_1.7.12         highr_0.10            
##  [85] desc_1.4.2             fastDummies_1.7.3      rlang_1.1.1           
##  [88] pkgconfig_2.0.3        systemfonts_1.0.4      matrixStats_1.0.0     
##  [91] evaluate_0.22          lattice_0.21-9         tensor_1.5            
##  [94] ROCR_1.0-11            purrr_1.0.2            labeling_0.4.3        
##  [97] patchwork_1.1.3        htmlwidgets_1.6.2      cowplot_1.1.1         
## [100] tidyselect_1.2.0       parallelly_1.36.0      RcppAnnoy_0.0.21      
## [103] plyr_1.8.9             magrittr_2.0.3         R6_2.5.1              
## [106] generics_0.1.3         withr_2.5.2            pillar_1.9.0          
## [109] fitdistrplus_1.1-11    abind_1.4-5            survival_3.5-7        
## [112] tibble_3.2.1           future.apply_1.11.0    KernSmooth_2.23-22    
## [115] utf8_1.2.4             spatstat.geom_3.2-7    plotly_4.10.3         
## [118] rmarkdown_2.25         grid_4.2.2             data.table_1.14.8     
## [121] digest_0.6.33          xtable_1.8-4           tidyr_1.3.0           
## [124] httpuv_1.6.12          textshaping_0.3.6      munsell_0.5.0         
## [127] beeswarm_0.4.0         viridisLite_0.4.2      vipor_0.4.5           
## [130] bslib_0.5.1
```

Example 68 (unknown):
```unknown
## R version 4.2.2 Patched (2022-11-10 r83330)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.6 LTS
## 
## Matrix products: default
## BLAS:   /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.9.0
## LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.9.0
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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       
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
## [1] Seurat_5.0.0       SeuratObject_5.0.0 sp_2.1-1          
## 
## loaded via a namespace (and not attached):
##   [1] ggbeeswarm_0.7.1       Rtsne_0.16             colorspace_2.1-0      
##   [4] deldir_1.0-9           ellipsis_0.3.2         ggridges_0.5.4        
##   [7] rprojroot_2.0.4        RcppHNSW_0.5.0         fs_1.6.3              
##  [10] spatstat.data_3.0-3    farver_2.1.1           leiden_0.4.3          
##  [13] listenv_0.9.0          ggrepel_0.9.4          RSpectra_0.16-1       
##  [16] fansi_1.0.5            codetools_0.2-19       splines_4.2.2         
##  [19] cachem_1.0.8           knitr_1.45             polyclip_1.10-6       
##  [22] spam_2.10-0            jsonlite_1.8.7         ica_1.0-3             
##  [25] cluster_2.1.4          png_0.1-8              uwot_0.1.16           
##  [28] spatstat.sparse_3.0-3  sctransform_0.4.1      shiny_1.7.5.1         
##  [31] compiler_4.2.2         httr_1.4.7             Matrix_1.6-1.1        
##  [34] fastmap_1.1.1          lazyeval_0.2.2         cli_3.6.1             
##  [37] later_1.3.1            formatR_1.14           htmltools_0.5.6.1     
##  [40] tools_4.2.2            igraph_1.5.1           dotCall64_1.1-0       
##  [43] gtable_0.3.4           glue_1.6.2             reshape2_1.4.4        
##  [46] RANN_2.6.1             dplyr_1.1.3            Rcpp_1.0.11           
##  [49] scattermore_1.2        jquerylib_0.1.4        pkgdown_2.0.7         
##  [52] vctrs_0.6.4            nlme_3.1-162           spatstat.explore_3.2-5
##  [55] progressr_0.14.0       lmtest_0.9-40          spatstat.random_3.2-1 
##  [58] xfun_0.40              stringr_1.5.0          globals_0.16.2        
##  [61] mime_0.12              miniUI_0.1.1.1         lifecycle_1.0.4       
##  [64] irlba_2.3.5.1          goftest_1.2-3          future_1.33.0         
##  [67] MASS_7.3-58.2          zoo_1.8-12             scales_1.2.1          
##  [70] spatstat.utils_3.0-4   ragg_1.2.5             promises_1.2.1        
##  [73] parallel_4.2.2         RColorBrewer_1.1-3     yaml_2.3.7            
##  [76] gridExtra_2.3          memoise_2.0.1          reticulate_1.34.0     
##  [79] pbapply_1.7-2          ggrastr_1.0.1          ggplot2_3.4.4         
##  [82] sass_0.4.7             stringi_1.7.12         highr_0.10            
##  [85] desc_1.4.2             fastDummies_1.7.3      rlang_1.1.1           
##  [88] pkgconfig_2.0.3        systemfonts_1.0.4      matrixStats_1.0.0     
##  [91] evaluate_0.22          lattice_0.21-9         tensor_1.5            
##  [94] ROCR_1.0-11            purrr_1.0.2            labeling_0.4.3        
##  [97] patchwork_1.1.3        htmlwidgets_1.6.2      cowplot_1.1.1         
## [100] tidyselect_1.2.0       parallelly_1.36.0      RcppAnnoy_0.0.21      
## [103] plyr_1.8.9             magrittr_2.0.3         R6_2.5.1              
## [106] generics_0.1.3         withr_2.5.2            pillar_1.9.0          
## [109] fitdistrplus_1.1-11    abind_1.4-5            survival_3.5-7        
## [112] tibble_3.2.1           future.apply_1.11.0    KernSmooth_2.23-22    
## [115] utf8_1.2.4             spatstat.geom_3.2-7    plotly_4.10.3         
## [118] rmarkdown_2.25         grid_4.2.2             data.table_1.14.8     
## [121] digest_0.6.33          xtable_1.8-4           tidyr_1.3.0           
## [124] httpuv_1.6.12          textshaping_0.3.6      munsell_0.5.0         
## [127] beeswarm_0.4.0         viridisLite_0.4.2      vipor_0.4.5           
## [130] bslib_0.5.1
```

---

## Analysis, visualization, and integration of Visium HD spatial datasets with Seurat • Seurat

**URL:** http://127.0.0.1:9173/seurat/announcements.html

**Contents:**
- News
- Changes in Seurat v5
- Contents

We are excited to release Seurat v5 on CRAN, where it is now the default version for new installs. Seurat v5 is designed to be backwards compatible with Seurat v4 so existing code will continue to run, but we have made some changes to the software that will affect user results. We note that users who aim to reproduce their previous workflows in Seurat v4 can still install this version using the instructions on our install page.

In particular, we have made changes to:

Seurat Object and Assay class: Seurat v5 now includes support for additional assay and data types, including on-disk matrices. To facilitate this, we have introduced an updated Seurat v5 assay. Users can check out this [vignette for more information]. Briefly, Seurat v5 assays store data in layers (previously referred to as ‘slots’).

For example, these layers can store: raw counts (layer='counts'), normalized data (layer='data'), or z-scored/variance-stabilized data (layer='scale.data').

Data can be accessed using the $ accessor (i.e. obj[["RNA"]]$counts), or the `LayerData function (i.e. LayerData(obj, assay="RNA", layer='counts').

We’ve designed these updates to minimize changes for users. Existing Seurat functions and workflows from v4 continue to work in v5. For example, the command GetAssayData(obj, assay="RNA", slot='counts'), will run successfully in both Seurat v4 and Seurat v5.

Integration workflow: Seurat v5 introduces a streamlined integration and data transfer workflows that performs integration in low-dimensional space, and improves speed and memory efficiency. The results of integration are not identical between the two workflows, but users can still run the v4 integration workflow in Seurat v5 if they wish.

In previous versions of Seurat, the integration workflow required a list of multiple Seurat objects as input. In Seurat v5, all the data can be kept as a single object, but prior to integration, users can simply split the layers. See our introduction to integration vignette for more information.

Differential expression: Seurat v5 now uses the presto package (from the Korunsky and Raychaudhari labs), when available, to perform differential expression analysis. Using presto can dramatically speed up DE testing, and we encourage users to install it. In addition, in Seurat v5 we implement a pseudocount (when calculating log-FC) at the group level instead of the cell level. As a result, users will observe higher logFC estimates in v5 - but should note that these estimates may be more unstable - particularly for genes that are very lowly expressed in one of the two groups. We gratefully acknowledge feedback from the McCarthy and Pachter labs on this topic.

Pseudobulk analysis: Once a single-cell dataset has been analyzed to annotate cell subpopulations, pseudobulk analyses (i.e. aggregating together cells within a given subpopulation and sample) can reduce noise, improve quantification of lowly expressed genes, and reduce the size of the data matrix. In Seurat v5, we encourage the use of the AggregateExpression function to perform pseudobulk analysis. Check out our differential expression vignette as well as our pancreatic/healthy PBMC comparison, for examples of how to use AggregateExpression to perform robust differential expression of scRNA-seq data from multiple different conditions.

Developed by Rahul Satija, Satija Lab and Collaborators.

Site built with pkgdown 2.0.7.

**Examples:**

Example 1 (unknown):
```unknown
vignettes/announcements.Rmd
```

Example 2 (unknown):
```unknown
announcements.Rmd
```

Example 3 (unknown):
```unknown
(layer='counts')
```

Example 4 (unknown):
```unknown
(layer='data')
```

Example 5 (unknown):
```unknown
(layer='scale.data')
```

Example 6 (unknown):
```unknown
obj[["RNA"]]$counts
```

Example 7 (unknown):
```unknown
LayerData(obj, assay="RNA", layer='counts')
```

Example 8 (unknown):
```unknown
GetAssayData(obj, assay="RNA", slot='counts')
```

Example 9 (unknown):
```unknown
SCTransform
```

Example 10 (unknown):
```unknown
vst.flavor = "v1"
```

Example 11 (unknown):
```unknown
SCTransform
```

Example 12 (unknown):
```unknown
AggregateExpression
```

Example 13 (unknown):
```unknown
AggregateExpression
```

---

## Mapping and annotating query datasets • Seurat

**URL:** http://127.0.0.1:9173/seurat/archive/v4.3/integration_mapping/index.html

**Contents:**
- Mapping and annotating query datasets
    - Compiled: 2023-03-27
- Introduction to single-cell reference mapping
- Dataset preprocessing
- Integration of 3 pancreatic islet cell datasets
- Cell type classification using an integrated reference
- Unimodal UMAP Projection
- Contents

In this vignette, we first build an integrated reference and then demonstrate how to leverage this reference to annotate new query datasets. Generating an integrated reference follows the same workflow described in more detail in the integration introduction vignette. Once generated, this reference can be used to analyze additional query datasets through tasks like cell type label transfer and projecting query cells onto reference UMAPs. Notably, this does not require correction of the underlying raw query data and can therefore be an efficient strategy if a high quality reference is available.

For the purposes of this example, we’ve chosen human pancreatic islet cell datasets produced across four technologies, CelSeq (GSE81076) CelSeq2 (GSE85241), Fluidigm C1 (GSE86469), and SMART-Seq2 (E-MTAB-5061). For convenience, we distribute this dataset through our SeuratData package. The metadata contains the technology (tech column) and cell type annotations (celltype column) for each cell in the four datasets. library(Seurat) library(SeuratData) InstallData("panc8")To construct a reference, we will identify ‘anchors’ between the individual datasets. First, we split the combined object into a list, with each dataset as an element (this is only necessary because the data was bundled together for easy distribution). data("panc8") pancreas.list <- SplitObject(panc8, split.by = "tech") pancreas.list <- pancreas.list[c("celseq", "celseq2", "fluidigmc1", "smartseq2")]Prior to finding anchors, we perform standard preprocessing (log-normalization), and identify variable features individually for each. Note that Seurat implements an improved method for variable feature selection based on a variance stabilizing transformation ("vst") for (i in 1:length(pancreas.list)) { pancreas.list[[i]] <- NormalizeData(pancreas.list[[i]], verbose = FALSE) pancreas.list[[i]] <- FindVariableFeatures(pancreas.list[[i]], selection.method = "vst", nfeatures = 2000, verbose = FALSE) }

To construct a reference, we will identify ‘anchors’ between the individual datasets. First, we split the combined object into a list, with each dataset as an element (this is only necessary because the data was bundled together for easy distribution). data("panc8") pancreas.list <- SplitObject(panc8, split.by = "tech") pancreas.list <- pancreas.list[c("celseq", "celseq2", "fluidigmc1", "smartseq2")]Prior to finding anchors, we perform standard preprocessing (log-normalization), and identify variable features individually for each. Note that Seurat implements an improved method for variable feature selection based on a variance stabilizing transformation ("vst") for (i in 1:length(pancreas.list)) { pancreas.list[[i]] <- NormalizeData(pancreas.list[[i]], verbose = FALSE) pancreas.list[[i]] <- FindVariableFeatures(pancreas.list[[i]], selection.method = "vst", nfeatures = 2000, verbose = FALSE) }

Prior to finding anchors, we perform standard preprocessing (log-normalization), and identify variable features individually for each. Note that Seurat implements an improved method for variable feature selection based on a variance stabilizing transformation ("vst") for (i in 1:length(pancreas.list)) { pancreas.list[[i]] <- NormalizeData(pancreas.list[[i]], verbose = FALSE) pancreas.list[[i]] <- FindVariableFeatures(pancreas.list[[i]], selection.method = "vst", nfeatures = 2000, verbose = FALSE) }

Next, we identify anchors using the FindIntegrationAnchors() function, which takes a list of Seurat objects as input. Here, we integrate three of the objects into a reference (we will use the fourth later in this vignette as a query dataset to demonstrate mapping).We use all default parameters here for identifying anchors, including the ‘dimensionality’ of the dataset (30; feel free to try varying this parameter over a broad range, for example between 10 and 50). reference.list <- pancreas.list[c("celseq", "celseq2", "smartseq2")] pancreas.anchors <- FindIntegrationAnchors(object.list = reference.list, dims = 1:30)We then pass these anchors to the IntegrateData() function, which returns a Seurat object.The returned object will contain a new Assay, which holds an integrated (or ‘batch-corrected’) expression matrix for all cells, enabling them to be jointly analyzed. pancreas.integrated <- IntegrateData(anchorset = pancreas.anchors, dims = 1:30)After running IntegrateData(), the Seurat object will contain a new Assay with the integrated expression matrix. Note that the original (uncorrected values) are still stored in the object in the “RNA” assay, so you can switch back and forth.We can then use this new integrated matrix for downstream analysis and visualization. Here we scale the integrated data, run PCA, and visualize the results with UMAP. The integrated datasets cluster by cell type, instead of by technology. library(ggplot2) library(cowplot) library(patchwork) # switch to integrated assay. The variable features of this assay are automatically set during # IntegrateData DefaultAssay(pancreas.integrated) <- "integrated" # Run the standard workflow for visualization and clustering pancreas.integrated <- ScaleData(pancreas.integrated, verbose = FALSE) pancreas.integrated <- RunPCA(pancreas.integrated, npcs = 30, verbose = FALSE) pancreas.integrated <- RunUMAP(pancreas.integrated, reduction = "pca", dims = 1:30, verbose = FALSE) p1 <- DimPlot(pancreas.integrated, reduction = "umap", group.by = "tech") p2 <- DimPlot(pancreas.integrated, reduction = "umap", group.by = "celltype", label = TRUE, repel = TRUE) + NoLegend() p1 + p2

We then pass these anchors to the IntegrateData() function, which returns a Seurat object.The returned object will contain a new Assay, which holds an integrated (or ‘batch-corrected’) expression matrix for all cells, enabling them to be jointly analyzed. pancreas.integrated <- IntegrateData(anchorset = pancreas.anchors, dims = 1:30)After running IntegrateData(), the Seurat object will contain a new Assay with the integrated expression matrix. Note that the original (uncorrected values) are still stored in the object in the “RNA” assay, so you can switch back and forth.We can then use this new integrated matrix for downstream analysis and visualization. Here we scale the integrated data, run PCA, and visualize the results with UMAP. The integrated datasets cluster by cell type, instead of by technology. library(ggplot2) library(cowplot) library(patchwork) # switch to integrated assay. The variable features of this assay are automatically set during # IntegrateData DefaultAssay(pancreas.integrated) <- "integrated" # Run the standard workflow for visualization and clustering pancreas.integrated <- ScaleData(pancreas.integrated, verbose = FALSE) pancreas.integrated <- RunPCA(pancreas.integrated, npcs = 30, verbose = FALSE) pancreas.integrated <- RunUMAP(pancreas.integrated, reduction = "pca", dims = 1:30, verbose = FALSE) p1 <- DimPlot(pancreas.integrated, reduction = "umap", group.by = "tech") p2 <- DimPlot(pancreas.integrated, reduction = "umap", group.by = "celltype", label = TRUE, repel = TRUE) + NoLegend() p1 + p2

After running IntegrateData(), the Seurat object will contain a new Assay with the integrated expression matrix. Note that the original (uncorrected values) are still stored in the object in the “RNA” assay, so you can switch back and forth.We can then use this new integrated matrix for downstream analysis and visualization. Here we scale the integrated data, run PCA, and visualize the results with UMAP. The integrated datasets cluster by cell type, instead of by technology. library(ggplot2) library(cowplot) library(patchwork) # switch to integrated assay. The variable features of this assay are automatically set during # IntegrateData DefaultAssay(pancreas.integrated) <- "integrated" # Run the standard workflow for visualization and clustering pancreas.integrated <- ScaleData(pancreas.integrated, verbose = FALSE) pancreas.integrated <- RunPCA(pancreas.integrated, npcs = 30, verbose = FALSE) pancreas.integrated <- RunUMAP(pancreas.integrated, reduction = "pca", dims = 1:30, verbose = FALSE) p1 <- DimPlot(pancreas.integrated, reduction = "umap", group.by = "tech") p2 <- DimPlot(pancreas.integrated, reduction = "umap", group.by = "celltype", label = TRUE, repel = TRUE) + NoLegend() p1 + p2

We can then use this new integrated matrix for downstream analysis and visualization. Here we scale the integrated data, run PCA, and visualize the results with UMAP. The integrated datasets cluster by cell type, instead of by technology. library(ggplot2) library(cowplot) library(patchwork) # switch to integrated assay. The variable features of this assay are automatically set during # IntegrateData DefaultAssay(pancreas.integrated) <- "integrated" # Run the standard workflow for visualization and clustering pancreas.integrated <- ScaleData(pancreas.integrated, verbose = FALSE) pancreas.integrated <- RunPCA(pancreas.integrated, npcs = 30, verbose = FALSE) pancreas.integrated <- RunUMAP(pancreas.integrated, reduction = "pca", dims = 1:30, verbose = FALSE) p1 <- DimPlot(pancreas.integrated, reduction = "umap", group.by = "tech") p2 <- DimPlot(pancreas.integrated, reduction = "umap", group.by = "celltype", label = TRUE, repel = TRUE) + NoLegend() p1 + p2

Seurat also supports the projection of reference data (or meta data) onto a query object. While many of the methods are conserved (both procedures begin by identifying anchors), there are two important distinctions between data transfer and integration:In data transfer, Seurat does not correct or modify the query expression data.In data transfer, Seurat has an option (set by default) to project the PCA structure of a reference onto the query, instead of learning a joint structure with CCA. We generally suggest using this option when projecting data between scRNA-seq datasets.After finding anchors, we use the TransferData() function to classify the query cells based on reference data (a vector of reference cell type labels). TransferData() returns a matrix with predicted IDs and prediction scores, which we can add to the query metadata. pancreas.query <- pancreas.list[["fluidigmc1"]] pancreas.anchors <- FindTransferAnchors(reference = pancreas.integrated, query = pancreas.query, dims = 1:30, reference.reduction = "pca") predictions <- TransferData(anchorset = pancreas.anchors, refdata = pancreas.integrated$celltype, dims = 1:30) pancreas.query <- AddMetaData(pancreas.query, metadata = predictions)Because we have the original label annotations from our full integrated analysis, we can evaluate how well our predicted cell type annotations match the full reference. In this example, we find that there is a high agreement in cell type classification, with over 96% of cells being labeled correctly. pancreas.query$prediction.match <- pancreas.query$predicted.id == pancreas.query$celltype table(pancreas.query$prediction.match)## ## FALSE TRUE ## 21 617To verify this further, we can examine some canonical cell type markers for specific pancreatic islet cell populations. Note that even though some of these cell types are only represented by one or two cells (e.g. epsilon cells), we are still able to classify them correctly. table(pancreas.query$predicted.id)## ## acinar activated_stellate alpha beta ## 22 17 253 256 ## delta ductal endothelial gamma ## 22 30 12 18 ## macrophage mast schwann ## 1 2 5 VlnPlot(pancreas.query, c("REG1A", "PPY", "SST", "GHRL", "VWF", "SOX10"), group.by = "predicted.id")

After finding anchors, we use the TransferData() function to classify the query cells based on reference data (a vector of reference cell type labels). TransferData() returns a matrix with predicted IDs and prediction scores, which we can add to the query metadata. pancreas.query <- pancreas.list[["fluidigmc1"]] pancreas.anchors <- FindTransferAnchors(reference = pancreas.integrated, query = pancreas.query, dims = 1:30, reference.reduction = "pca") predictions <- TransferData(anchorset = pancreas.anchors, refdata = pancreas.integrated$celltype, dims = 1:30) pancreas.query <- AddMetaData(pancreas.query, metadata = predictions)Because we have the original label annotations from our full integrated analysis, we can evaluate how well our predicted cell type annotations match the full reference. In this example, we find that there is a high agreement in cell type classification, with over 96% of cells being labeled correctly. pancreas.query$prediction.match <- pancreas.query$predicted.id == pancreas.query$celltype table(pancreas.query$prediction.match)## ## FALSE TRUE ## 21 617To verify this further, we can examine some canonical cell type markers for specific pancreatic islet cell populations. Note that even though some of these cell types are only represented by one or two cells (e.g. epsilon cells), we are still able to classify them correctly. table(pancreas.query$predicted.id)## ## acinar activated_stellate alpha beta ## 22 17 253 256 ## delta ductal endothelial gamma ## 22 30 12 18 ## macrophage mast schwann ## 1 2 5 VlnPlot(pancreas.query, c("REG1A", "PPY", "SST", "GHRL", "VWF", "SOX10"), group.by = "predicted.id")

Because we have the original label annotations from our full integrated analysis, we can evaluate how well our predicted cell type annotations match the full reference. In this example, we find that there is a high agreement in cell type classification, with over 96% of cells being labeled correctly. pancreas.query$prediction.match <- pancreas.query$predicted.id == pancreas.query$celltype table(pancreas.query$prediction.match)## ## FALSE TRUE ## 21 617To verify this further, we can examine some canonical cell type markers for specific pancreatic islet cell populations. Note that even though some of these cell types are only represented by one or two cells (e.g. epsilon cells), we are still able to classify them correctly. table(pancreas.query$predicted.id)## ## acinar activated_stellate alpha beta ## 22 17 253 256 ## delta ductal endothelial gamma ## 22 30 12 18 ## macrophage mast schwann ## 1 2 5 VlnPlot(pancreas.query, c("REG1A", "PPY", "SST", "GHRL", "VWF", "SOX10"), group.by = "predicted.id")

To verify this further, we can examine some canonical cell type markers for specific pancreatic islet cell populations. Note that even though some of these cell types are only represented by one or two cells (e.g. epsilon cells), we are still able to classify them correctly. table(pancreas.query$predicted.id)## ## acinar activated_stellate alpha beta ## 22 17 253 256 ## delta ductal endothelial gamma ## 22 30 12 18 ## macrophage mast schwann ## 1 2 5 VlnPlot(pancreas.query, c("REG1A", "PPY", "SST", "GHRL", "VWF", "SOX10"), group.by = "predicted.id")

In Seurat v4, we also enable projection of a query onto the reference UMAP structure. This can be achieved by computing the reference UMAP model and then calling MapQuery() instead of TransferData(). pancreas.integrated <- RunUMAP(pancreas.integrated, dims = 1:30, reduction = "pca", return.model = TRUE) pancreas.query <- MapQuery(anchorset = pancreas.anchors, reference = pancreas.integrated, query = pancreas.query, refdata = list(celltype = "celltype"), reference.reduction = "pca", reduction.model = "umap")What is MapQuery doing?MapQuery() is a wrapper around three functions: TransferData(), IntegrateEmbeddings(), and ProjectUMAP(). TransferData() is used to transfer cell type labels and impute the ADT values; IntegrateEmbeddings() is used to integrate reference with query by correcting the query’s projected low-dimensional embeddings; and finally ProjectUMAP() is used to project the query data onto the UMAP structure of the reference. The equivalent code for doing this with the intermediate functions is below: pancreas.query <- TransferData(anchorset = pancreas.anchors, reference = pancreas.integrated, query = pancreas.query, refdata = list(celltype = "celltype")) pancreas.query <- IntegrateEmbeddings(anchorset = pancreas.anchors, reference = pancreas.integrated, query = pancreas.query, new.reduction.name = "ref.pca") pancreas.query <- ProjectUMAP(query = pancreas.query, query.reduction = "ref.pca", reference = pancreas.integrated, reference.reduction = "pca", reduction.model = "umap")We can now visualize the query cells alongside our reference. p1 <- DimPlot(pancreas.integrated, reduction = "umap", group.by = "celltype", label = TRUE, label.size = 3, repel = TRUE) + NoLegend() + ggtitle("Reference annotations") p2 <- DimPlot(pancreas.query, reduction = "ref.umap", group.by = "predicted.celltype", label = TRUE, label.size = 3, repel = TRUE) + NoLegend() + ggtitle("Query transferred labels") p1 + p2Session Info sessionInfo()## R version 4.2.0 (2022-04-22) ## Platform: x86_64-pc-linux-gnu (64-bit) ## Running under: Ubuntu 20.04.5 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/liblapack.so.3 ## ## locale: ## [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C ## [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8 ## [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 ## ## attached base packages: ## [1] stats graphics grDevices utils datasets methods base ## ## other attached packages: ## [1] patchwork_1.1.2 cowplot_1.1.1 ## [3] ggplot2_3.4.1 thp1.eccite.SeuratData_3.1.5 ## [5] stxBrain.SeuratData_0.1.1 ssHippo.SeuratData_3.1.4 ## [7] pbmcsca.SeuratData_3.0.0 pbmcMultiome.SeuratData_0.1.2 ## [9] pbmc3k.SeuratData_3.1.4 panc8.SeuratData_3.0.2 ## [11] ifnb.SeuratData_3.1.0 hcabm40k.SeuratData_3.0.0 ## [13] bmcite.SeuratData_0.3.0 SeuratData_0.2.2 ## [15] SeuratObject_4.1.3 Seurat_4.3.0 ## ## loaded via a namespace (and not attached): ## [1] systemfonts_1.0.4 plyr_1.8.8 igraph_1.4.1 ## [4] lazyeval_0.2.2 sp_1.6-0 splines_4.2.0 ## [7] listenv_0.9.0 scattermore_0.8 digest_0.6.31 ## [10] htmltools_0.5.4 fansi_1.0.4 magrittr_2.0.3 ## [13] memoise_2.0.1 tensor_1.5 cluster_2.1.3 ## [16] ROCR_1.0-11 globals_0.16.2 matrixStats_0.63.0 ## [19] pkgdown_2.0.7 spatstat.sparse_3.0-0 colorspace_2.1-0 ## [22] rappdirs_0.3.3 ggrepel_0.9.3 textshaping_0.3.6 ## [25] xfun_0.37 dplyr_1.1.0 crayon_1.5.2 ## [28] jsonlite_1.8.4 progressr_0.13.0 spatstat.data_3.0-0 ## [31] survival_3.3-1 zoo_1.8-11 glue_1.6.2 ## [34] polyclip_1.10-4 gtable_0.3.1 leiden_0.4.3 ## [37] future.apply_1.10.0 abind_1.4-5 scales_1.2.1 ## [40] spatstat.random_3.1-3 miniUI_0.1.1.1 Rcpp_1.0.10 ## [43] viridisLite_0.4.1 xtable_1.8-4 reticulate_1.28 ## [46] htmlwidgets_1.6.1 httr_1.4.5 RColorBrewer_1.1-3 ## [49] ellipsis_0.3.2 ica_1.0-3 farver_2.1.1 ## [52] pkgconfig_2.0.3 sass_0.4.5 uwot_0.1.14 ## [55] deldir_1.0-6 utf8_1.2.3 tidyselect_1.2.0 ## [58] labeling_0.4.2 rlang_1.0.6 reshape2_1.4.4 ## [61] later_1.3.0 munsell_0.5.0 tools_4.2.0 ## [64] cachem_1.0.7 cli_3.6.0 generics_0.1.3 ## [67] ggridges_0.5.4 evaluate_0.20 stringr_1.5.0 ## [70] fastmap_1.1.1 yaml_2.3.7 ragg_1.2.5 ## [73] goftest_1.2-3 knitr_1.42 fs_1.6.1 ## [76] fitdistrplus_1.1-8 purrr_1.0.1 RANN_2.6.1 ## [79] pbapply_1.7-0 future_1.31.0 nlme_3.1-157 ## [82] mime_0.12 formatR_1.14 compiler_4.2.0 ## [85] plotly_4.10.1 png_0.1-8 spatstat.utils_3.0-1 ## [88] tibble_3.1.8 bslib_0.4.2 stringi_1.7.12 ## [91] highr_0.10 desc_1.4.2 lattice_0.20-45 ## [94] Matrix_1.5-3 vctrs_0.5.2 pillar_1.8.1 ## [97] lifecycle_1.0.3 spatstat.geom_3.0-6 lmtest_0.9-40 ## [100] jquerylib_0.1.4 RcppAnnoy_0.0.20 data.table_1.14.8 ## [103] irlba_2.3.5.1 httpuv_1.6.9 R6_2.5.1 ## [106] promises_1.2.0.1 KernSmooth_2.23-20 gridExtra_2.3 ## [109] parallelly_1.34.0 codetools_0.2-18 MASS_7.3-56 ## [112] rprojroot_2.0.3 withr_2.5.0 sctransform_0.3.5 ## [115] parallel_4.2.0 grid_4.2.0 tidyr_1.3.0 ## [118] rmarkdown_2.20 Rtsne_0.16 spatstat.explore_3.0-6 ## [121] shiny_1.7.4

MapQuery() is a wrapper around three functions: TransferData(), IntegrateEmbeddings(), and ProjectUMAP(). TransferData() is used to transfer cell type labels and impute the ADT values; IntegrateEmbeddings() is used to integrate reference with query by correcting the query’s projected low-dimensional embeddings; and finally ProjectUMAP() is used to project the query data onto the UMAP structure of the reference. The equivalent code for doing this with the intermediate functions is below: pancreas.query <- TransferData(anchorset = pancreas.anchors, reference = pancreas.integrated, query = pancreas.query, refdata = list(celltype = "celltype")) pancreas.query <- IntegrateEmbeddings(anchorset = pancreas.anchors, reference = pancreas.integrated, query = pancreas.query, new.reduction.name = "ref.pca") pancreas.query <- ProjectUMAP(query = pancreas.query, query.reduction = "ref.pca", reference = pancreas.integrated, reference.reduction = "pca", reduction.model = "umap")

MapQuery() is a wrapper around three functions: TransferData(), IntegrateEmbeddings(), and ProjectUMAP(). TransferData() is used to transfer cell type labels and impute the ADT values; IntegrateEmbeddings() is used to integrate reference with query by correcting the query’s projected low-dimensional embeddings; and finally ProjectUMAP() is used to project the query data onto the UMAP structure of the reference. The equivalent code for doing this with the intermediate functions is below: pancreas.query <- TransferData(anchorset = pancreas.anchors, reference = pancreas.integrated, query = pancreas.query, refdata = list(celltype = "celltype")) pancreas.query <- IntegrateEmbeddings(anchorset = pancreas.anchors, reference = pancreas.integrated, query = pancreas.query, new.reduction.name = "ref.pca") pancreas.query <- ProjectUMAP(query = pancreas.query, query.reduction = "ref.pca", reference = pancreas.integrated, reference.reduction = "pca", reduction.model = "umap")

We can now visualize the query cells alongside our reference. p1 <- DimPlot(pancreas.integrated, reduction = "umap", group.by = "celltype", label = TRUE, label.size = 3, repel = TRUE) + NoLegend() + ggtitle("Reference annotations") p2 <- DimPlot(pancreas.query, reduction = "ref.umap", group.by = "predicted.celltype", label = TRUE, label.size = 3, repel = TRUE) + NoLegend() + ggtitle("Query transferred labels") p1 + p2Session Info sessionInfo()## R version 4.2.0 (2022-04-22) ## Platform: x86_64-pc-linux-gnu (64-bit) ## Running under: Ubuntu 20.04.5 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/liblapack.so.3 ## ## locale: ## [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C ## [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8 ## [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 ## ## attached base packages: ## [1] stats graphics grDevices utils datasets methods base ## ## other attached packages: ## [1] patchwork_1.1.2 cowplot_1.1.1 ## [3] ggplot2_3.4.1 thp1.eccite.SeuratData_3.1.5 ## [5] stxBrain.SeuratData_0.1.1 ssHippo.SeuratData_3.1.4 ## [7] pbmcsca.SeuratData_3.0.0 pbmcMultiome.SeuratData_0.1.2 ## [9] pbmc3k.SeuratData_3.1.4 panc8.SeuratData_3.0.2 ## [11] ifnb.SeuratData_3.1.0 hcabm40k.SeuratData_3.0.0 ## [13] bmcite.SeuratData_0.3.0 SeuratData_0.2.2 ## [15] SeuratObject_4.1.3 Seurat_4.3.0 ## ## loaded via a namespace (and not attached): ## [1] systemfonts_1.0.4 plyr_1.8.8 igraph_1.4.1 ## [4] lazyeval_0.2.2 sp_1.6-0 splines_4.2.0 ## [7] listenv_0.9.0 scattermore_0.8 digest_0.6.31 ## [10] htmltools_0.5.4 fansi_1.0.4 magrittr_2.0.3 ## [13] memoise_2.0.1 tensor_1.5 cluster_2.1.3 ## [16] ROCR_1.0-11 globals_0.16.2 matrixStats_0.63.0 ## [19] pkgdown_2.0.7 spatstat.sparse_3.0-0 colorspace_2.1-0 ## [22] rappdirs_0.3.3 ggrepel_0.9.3 textshaping_0.3.6 ## [25] xfun_0.37 dplyr_1.1.0 crayon_1.5.2 ## [28] jsonlite_1.8.4 progressr_0.13.0 spatstat.data_3.0-0 ## [31] survival_3.3-1 zoo_1.8-11 glue_1.6.2 ## [34] polyclip_1.10-4 gtable_0.3.1 leiden_0.4.3 ## [37] future.apply_1.10.0 abind_1.4-5 scales_1.2.1 ## [40] spatstat.random_3.1-3 miniUI_0.1.1.1 Rcpp_1.0.10 ## [43] viridisLite_0.4.1 xtable_1.8-4 reticulate_1.28 ## [46] htmlwidgets_1.6.1 httr_1.4.5 RColorBrewer_1.1-3 ## [49] ellipsis_0.3.2 ica_1.0-3 farver_2.1.1 ## [52] pkgconfig_2.0.3 sass_0.4.5 uwot_0.1.14 ## [55] deldir_1.0-6 utf8_1.2.3 tidyselect_1.2.0 ## [58] labeling_0.4.2 rlang_1.0.6 reshape2_1.4.4 ## [61] later_1.3.0 munsell_0.5.0 tools_4.2.0 ## [64] cachem_1.0.7 cli_3.6.0 generics_0.1.3 ## [67] ggridges_0.5.4 evaluate_0.20 stringr_1.5.0 ## [70] fastmap_1.1.1 yaml_2.3.7 ragg_1.2.5 ## [73] goftest_1.2-3 knitr_1.42 fs_1.6.1 ## [76] fitdistrplus_1.1-8 purrr_1.0.1 RANN_2.6.1 ## [79] pbapply_1.7-0 future_1.31.0 nlme_3.1-157 ## [82] mime_0.12 formatR_1.14 compiler_4.2.0 ## [85] plotly_4.10.1 png_0.1-8 spatstat.utils_3.0-1 ## [88] tibble_3.1.8 bslib_0.4.2 stringi_1.7.12 ## [91] highr_0.10 desc_1.4.2 lattice_0.20-45 ## [94] Matrix_1.5-3 vctrs_0.5.2 pillar_1.8.1 ## [97] lifecycle_1.0.3 spatstat.geom_3.0-6 lmtest_0.9-40 ## [100] jquerylib_0.1.4 RcppAnnoy_0.0.20 data.table_1.14.8 ## [103] irlba_2.3.5.1 httpuv_1.6.9 R6_2.5.1 ## [106] promises_1.2.0.1 KernSmooth_2.23-20 gridExtra_2.3 ## [109] parallelly_1.34.0 codetools_0.2-18 MASS_7.3-56 ## [112] rprojroot_2.0.3 withr_2.5.0 sctransform_0.3.5 ## [115] parallel_4.2.0 grid_4.2.0 tidyr_1.3.0 ## [118] rmarkdown_2.20 Rtsne_0.16 spatstat.explore_3.0-6 ## [121] shiny_1.7.4

Session Info sessionInfo()## R version 4.2.0 (2022-04-22) ## Platform: x86_64-pc-linux-gnu (64-bit) ## Running under: Ubuntu 20.04.5 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/liblapack.so.3 ## ## locale: ## [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C ## [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8 ## [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 ## ## attached base packages: ## [1] stats graphics grDevices utils datasets methods base ## ## other attached packages: ## [1] patchwork_1.1.2 cowplot_1.1.1 ## [3] ggplot2_3.4.1 thp1.eccite.SeuratData_3.1.5 ## [5] stxBrain.SeuratData_0.1.1 ssHippo.SeuratData_3.1.4 ## [7] pbmcsca.SeuratData_3.0.0 pbmcMultiome.SeuratData_0.1.2 ## [9] pbmc3k.SeuratData_3.1.4 panc8.SeuratData_3.0.2 ## [11] ifnb.SeuratData_3.1.0 hcabm40k.SeuratData_3.0.0 ## [13] bmcite.SeuratData_0.3.0 SeuratData_0.2.2 ## [15] SeuratObject_4.1.3 Seurat_4.3.0 ## ## loaded via a namespace (and not attached): ## [1] systemfonts_1.0.4 plyr_1.8.8 igraph_1.4.1 ## [4] lazyeval_0.2.2 sp_1.6-0 splines_4.2.0 ## [7] listenv_0.9.0 scattermore_0.8 digest_0.6.31 ## [10] htmltools_0.5.4 fansi_1.0.4 magrittr_2.0.3 ## [13] memoise_2.0.1 tensor_1.5 cluster_2.1.3 ## [16] ROCR_1.0-11 globals_0.16.2 matrixStats_0.63.0 ## [19] pkgdown_2.0.7 spatstat.sparse_3.0-0 colorspace_2.1-0 ## [22] rappdirs_0.3.3 ggrepel_0.9.3 textshaping_0.3.6 ## [25] xfun_0.37 dplyr_1.1.0 crayon_1.5.2 ## [28] jsonlite_1.8.4 progressr_0.13.0 spatstat.data_3.0-0 ## [31] survival_3.3-1 zoo_1.8-11 glue_1.6.2 ## [34] polyclip_1.10-4 gtable_0.3.1 leiden_0.4.3 ## [37] future.apply_1.10.0 abind_1.4-5 scales_1.2.1 ## [40] spatstat.random_3.1-3 miniUI_0.1.1.1 Rcpp_1.0.10 ## [43] viridisLite_0.4.1 xtable_1.8-4 reticulate_1.28 ## [46] htmlwidgets_1.6.1 httr_1.4.5 RColorBrewer_1.1-3 ## [49] ellipsis_0.3.2 ica_1.0-3 farver_2.1.1 ## [52] pkgconfig_2.0.3 sass_0.4.5 uwot_0.1.14 ## [55] deldir_1.0-6 utf8_1.2.3 tidyselect_1.2.0 ## [58] labeling_0.4.2 rlang_1.0.6 reshape2_1.4.4 ## [61] later_1.3.0 munsell_0.5.0 tools_4.2.0 ## [64] cachem_1.0.7 cli_3.6.0 generics_0.1.3 ## [67] ggridges_0.5.4 evaluate_0.20 stringr_1.5.0 ## [70] fastmap_1.1.1 yaml_2.3.7 ragg_1.2.5 ## [73] goftest_1.2-3 knitr_1.42 fs_1.6.1 ## [76] fitdistrplus_1.1-8 purrr_1.0.1 RANN_2.6.1 ## [79] pbapply_1.7-0 future_1.31.0 nlme_3.1-157 ## [82] mime_0.12 formatR_1.14 compiler_4.2.0 ## [85] plotly_4.10.1 png_0.1-8 spatstat.utils_3.0-1 ## [88] tibble_3.1.8 bslib_0.4.2 stringi_1.7.12 ## [91] highr_0.10 desc_1.4.2 lattice_0.20-45 ## [94] Matrix_1.5-3 vctrs_0.5.2 pillar_1.8.1 ## [97] lifecycle_1.0.3 spatstat.geom_3.0-6 lmtest_0.9-40 ## [100] jquerylib_0.1.4 RcppAnnoy_0.0.20 data.table_1.14.8 ## [103] irlba_2.3.5.1 httpuv_1.6.9 R6_2.5.1 ## [106] promises_1.2.0.1 KernSmooth_2.23-20 gridExtra_2.3 ## [109] parallelly_1.34.0 codetools_0.2-18 MASS_7.3-56 ## [112] rprojroot_2.0.3 withr_2.5.0 sctransform_0.3.5 ## [115] parallel_4.2.0 grid_4.2.0 tidyr_1.3.0 ## [118] rmarkdown_2.20 Rtsne_0.16 spatstat.explore_3.0-6 ## [121] shiny_1.7.4

sessionInfo()## R version 4.2.0 (2022-04-22) ## Platform: x86_64-pc-linux-gnu (64-bit) ## Running under: Ubuntu 20.04.5 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/liblapack.so.3 ## ## locale: ## [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C ## [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8 ## [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 ## ## attached base packages: ## [1] stats graphics grDevices utils datasets methods base ## ## other attached packages: ## [1] patchwork_1.1.2 cowplot_1.1.1 ## [3] ggplot2_3.4.1 thp1.eccite.SeuratData_3.1.5 ## [5] stxBrain.SeuratData_0.1.1 ssHippo.SeuratData_3.1.4 ## [7] pbmcsca.SeuratData_3.0.0 pbmcMultiome.SeuratData_0.1.2 ## [9] pbmc3k.SeuratData_3.1.4 panc8.SeuratData_3.0.2 ## [11] ifnb.SeuratData_3.1.0 hcabm40k.SeuratData_3.0.0 ## [13] bmcite.SeuratData_0.3.0 SeuratData_0.2.2 ## [15] SeuratObject_4.1.3 Seurat_4.3.0 ## ## loaded via a namespace (and not attached): ## [1] systemfonts_1.0.4 plyr_1.8.8 igraph_1.4.1 ## [4] lazyeval_0.2.2 sp_1.6-0 splines_4.2.0 ## [7] listenv_0.9.0 scattermore_0.8 digest_0.6.31 ## [10] htmltools_0.5.4 fansi_1.0.4 magrittr_2.0.3 ## [13] memoise_2.0.1 tensor_1.5 cluster_2.1.3 ## [16] ROCR_1.0-11 globals_0.16.2 matrixStats_0.63.0 ## [19] pkgdown_2.0.7 spatstat.sparse_3.0-0 colorspace_2.1-0 ## [22] rappdirs_0.3.3 ggrepel_0.9.3 textshaping_0.3.6 ## [25] xfun_0.37 dplyr_1.1.0 crayon_1.5.2 ## [28] jsonlite_1.8.4 progressr_0.13.0 spatstat.data_3.0-0 ## [31] survival_3.3-1 zoo_1.8-11 glue_1.6.2 ## [34] polyclip_1.10-4 gtable_0.3.1 leiden_0.4.3 ## [37] future.apply_1.10.0 abind_1.4-5 scales_1.2.1 ## [40] spatstat.random_3.1-3 miniUI_0.1.1.1 Rcpp_1.0.10 ## [43] viridisLite_0.4.1 xtable_1.8-4 reticulate_1.28 ## [46] htmlwidgets_1.6.1 httr_1.4.5 RColorBrewer_1.1-3 ## [49] ellipsis_0.3.2 ica_1.0-3 farver_2.1.1 ## [52] pkgconfig_2.0.3 sass_0.4.5 uwot_0.1.14 ## [55] deldir_1.0-6 utf8_1.2.3 tidyselect_1.2.0 ## [58] labeling_0.4.2 rlang_1.0.6 reshape2_1.4.4 ## [61] later_1.3.0 munsell_0.5.0 tools_4.2.0 ## [64] cachem_1.0.7 cli_3.6.0 generics_0.1.3 ## [67] ggridges_0.5.4 evaluate_0.20 stringr_1.5.0 ## [70] fastmap_1.1.1 yaml_2.3.7 ragg_1.2.5 ## [73] goftest_1.2-3 knitr_1.42 fs_1.6.1 ## [76] fitdistrplus_1.1-8 purrr_1.0.1 RANN_2.6.1 ## [79] pbapply_1.7-0 future_1.31.0 nlme_3.1-157 ## [82] mime_0.12 formatR_1.14 compiler_4.2.0 ## [85] plotly_4.10.1 png_0.1-8 spatstat.utils_3.0-1 ## [88] tibble_3.1.8 bslib_0.4.2 stringi_1.7.12 ## [91] highr_0.10 desc_1.4.2 lattice_0.20-45 ## [94] Matrix_1.5-3 vctrs_0.5.2 pillar_1.8.1 ## [97] lifecycle_1.0.3 spatstat.geom_3.0-6 lmtest_0.9-40 ## [100] jquerylib_0.1.4 RcppAnnoy_0.0.20 data.table_1.14.8 ## [103] irlba_2.3.5.1 httpuv_1.6.9 R6_2.5.1 ## [106] promises_1.2.0.1 KernSmooth_2.23-20 gridExtra_2.3 ## [109] parallelly_1.34.0 codetools_0.2-18 MASS_7.3-56 ## [112] rprojroot_2.0.3 withr_2.5.0 sctransform_0.3.5 ## [115] parallel_4.2.0 grid_4.2.0 tidyr_1.3.0 ## [118] rmarkdown_2.20 Rtsne_0.16 spatstat.explore_3.0-6 ## [121] shiny_1.7.4

Developed by Paul Hoffman, Satija Lab and Collaborators.

Developed by Paul Hoffman, Satija Lab and Collaborators.

Site built with pkgdown 2.0.7.

Site built with pkgdown 2.0.7.

**Examples:**

Example 1 (unknown):
```unknown
vignettes/integration_mapping.Rmd
```

Example 2 (unknown):
```unknown
integration_mapping.Rmd
```

Example 3 (unknown):
```unknown
library(Seurat)
library(SeuratData)
```

Example 4 (r):
```r
library(Seurat)
library(SeuratData)
```

Example 5 (r):
```r
library(Seurat)
library(SeuratData)
```

Example 6 (unknown):
```unknown
InstallData("panc8")
```

Example 7 (r):
```r
InstallData("panc8")
```

Example 8 (r):
```r
InstallData("panc8")
```

Example 9 (unknown):
```unknown
data("panc8")
pancreas.list <- SplitObject(panc8, split.by = "tech")
pancreas.list <- pancreas.list[c("celseq", "celseq2", "fluidigmc1", "smartseq2")]
```

Example 10 (r):
```r
data("panc8")
pancreas.list <- SplitObject(panc8, split.by = "tech")
pancreas.list <- pancreas.list[c("celseq", "celseq2", "fluidigmc1", "smartseq2")]
```

Example 11 (r):
```r
data("panc8")
pancreas.list <- SplitObject(panc8, split.by = "tech")
pancreas.list <- pancreas.list[c("celseq", "celseq2", "fluidigmc1", "smartseq2")]
```

Example 12 (unknown):
```unknown
for (i in 1:length(pancreas.list)) {
    pancreas.list[[i]] <- NormalizeData(pancreas.list[[i]], verbose = FALSE)
    pancreas.list[[i]] <- FindVariableFeatures(pancreas.list[[i]], selection.method = "vst", nfeatures = 2000,
        verbose = FALSE)
}
```

Example 13 (r):
```r
for (i in 1:length(pancreas.list)) {
    pancreas.list[[i]] <- NormalizeData(pancreas.list[[i]], verbose = FALSE)
    pancreas.list[[i]] <- FindVariableFeatures(pancreas.list[[i]], selection.method = "vst", nfeatures = 2000,
        verbose = FALSE)
}
```

Example 14 (r):
```r
for (i in 1:length(pancreas.list)) {
    pancreas.list[[i]] <- NormalizeData(pancreas.list[[i]], verbose = FALSE)
    pancreas.list[[i]] <- FindVariableFeatures(pancreas.list[[i]], selection.method = "vst", nfeatures = 2000,
        verbose = FALSE)
}
```

Example 15 (unknown):
```unknown
FindIntegrationAnchors()
```

Example 16 (unknown):
```unknown
reference.list <- pancreas.list[c("celseq", "celseq2", "smartseq2")]
pancreas.anchors <- FindIntegrationAnchors(object.list = reference.list, dims = 1:30)
```

Example 17 (r):
```r
reference.list <- pancreas.list[c("celseq", "celseq2", "smartseq2")]
pancreas.anchors <- FindIntegrationAnchors(object.list = reference.list, dims = 1:30)
```

Example 18 (r):
```r
reference.list <- pancreas.list[c("celseq", "celseq2", "smartseq2")]
pancreas.anchors <- FindIntegrationAnchors(object.list = reference.list, dims = 1:30)
```

Example 19 (unknown):
```unknown
IntegrateData()
```

Example 20 (unknown):
```unknown
pancreas.integrated <- IntegrateData(anchorset = pancreas.anchors, dims = 1:30)
```

Example 21 (r):
```r
pancreas.integrated <- IntegrateData(anchorset = pancreas.anchors, dims = 1:30)
```

Example 22 (r):
```r
pancreas.integrated <- IntegrateData(anchorset = pancreas.anchors, dims = 1:30)
```

Example 23 (unknown):
```unknown
IntegrateData()
```

Example 24 (unknown):
```unknown
library(ggplot2)
library(cowplot)
library(patchwork)
# switch to integrated assay. The variable features of this assay are automatically set during
# IntegrateData
DefaultAssay(pancreas.integrated) <- "integrated"
# Run the standard workflow for visualization and clustering
pancreas.integrated <- ScaleData(pancreas.integrated, verbose = FALSE)
pancreas.integrated <- RunPCA(pancreas.integrated, npcs = 30, verbose = FALSE)
pancreas.integrated <- RunUMAP(pancreas.integrated, reduction = "pca", dims = 1:30, verbose = FALSE)
p1 <- DimPlot(pancreas.integrated, reduction = "umap", group.by = "tech")
p2 <- DimPlot(pancreas.integrated, reduction = "umap", group.by = "celltype", label = TRUE, repel = TRUE) +
    NoLegend()
p1 + p2
```

Example 25 (r):
```r
library(ggplot2)
library(cowplot)
library(patchwork)
# switch to integrated assay. The variable features of this assay are automatically set during
# IntegrateData
DefaultAssay(pancreas.integrated) <- "integrated"
# Run the standard workflow for visualization and clustering
pancreas.integrated <- ScaleData(pancreas.integrated, verbose = FALSE)
pancreas.integrated <- RunPCA(pancreas.integrated, npcs = 30, verbose = FALSE)
pancreas.integrated <- RunUMAP(pancreas.integrated, reduction = "pca", dims = 1:30, verbose = FALSE)
p1 <- DimPlot(pancreas.integrated, reduction = "umap", group.by = "tech")
p2 <- DimPlot(pancreas.integrated, reduction = "umap", group.by = "celltype", label = TRUE, repel = TRUE) +
    NoLegend()
p1 + p2
```

Example 26 (r):
```r
library(ggplot2)
library(cowplot)
library(patchwork)
# switch to integrated assay. The variable features of this assay are automatically set during
# IntegrateData
DefaultAssay(pancreas.integrated) <- "integrated"
# Run the standard workflow for visualization and clustering
pancreas.integrated <- ScaleData(pancreas.integrated, verbose = FALSE)
pancreas.integrated <- RunPCA(pancreas.integrated, npcs = 30, verbose = FALSE)
pancreas.integrated <- RunUMAP(pancreas.integrated, reduction = "pca", dims = 1:30, verbose = FALSE)
p1 <- DimPlot(pancreas.integrated, reduction = "umap", group.by = "tech")
p2 <- DimPlot(pancreas.integrated, reduction = "umap", group.by = "celltype", label = TRUE, repel = TRUE) +
    NoLegend()
p1 + p2
```

Example 27 (unknown):
```unknown
TransferData()
```

Example 28 (unknown):
```unknown
TransferData()
```

Example 29 (python):
```python
pancreas.query <- pancreas.list[["fluidigmc1"]]
pancreas.anchors <- FindTransferAnchors(reference = pancreas.integrated, query = pancreas.query,
    dims = 1:30, reference.reduction = "pca")
predictions <- TransferData(anchorset = pancreas.anchors, refdata = pancreas.integrated$celltype,
    dims = 1:30)
pancreas.query <- AddMetaData(pancreas.query, metadata = predictions)
```

Example 30 (r):
```r
pancreas.query <- pancreas.list[["fluidigmc1"]]
pancreas.anchors <- FindTransferAnchors(reference = pancreas.integrated, query = pancreas.query,
    dims = 1:30, reference.reduction = "pca")
predictions <- TransferData(anchorset = pancreas.anchors, refdata = pancreas.integrated$celltype,
    dims = 1:30)
pancreas.query <- AddMetaData(pancreas.query, metadata = predictions)
```

Example 31 (r):
```r
pancreas.query <- pancreas.list[["fluidigmc1"]]
pancreas.anchors <- FindTransferAnchors(reference = pancreas.integrated, query = pancreas.query,
    dims = 1:30, reference.reduction = "pca")
predictions <- TransferData(anchorset = pancreas.anchors, refdata = pancreas.integrated$celltype,
    dims = 1:30)
pancreas.query <- AddMetaData(pancreas.query, metadata = predictions)
```

Example 32 (unknown):
```unknown
pancreas.query$prediction.match <- pancreas.query$predicted.id == pancreas.query$celltype
table(pancreas.query$prediction.match)
```

Example 33 (r):
```r
pancreas.query$prediction.match <- pancreas.query$predicted.id == pancreas.query$celltype
table(pancreas.query$prediction.match)
```

Example 34 (r):
```r
pancreas.query$prediction.match <- pancreas.query$predicted.id == pancreas.query$celltype
table(pancreas.query$prediction.match)
```

Example 35 (unknown):
```unknown
## 
## FALSE  TRUE 
##    21   617
```

Example 36 (unknown):
```unknown
## 
## FALSE  TRUE 
##    21   617
```

Example 37 (unknown):
```unknown
table(pancreas.query$predicted.id)
```

Example 38 (r):
```r
table(pancreas.query$predicted.id)
```

Example 39 (r):
```r
table(pancreas.query$predicted.id)
```

Example 40 (unknown):
```unknown
## 
##             acinar activated_stellate              alpha               beta 
##                 22                 17                253                256 
##              delta             ductal        endothelial              gamma 
##                 22                 30                 12                 18 
##         macrophage               mast            schwann 
##                  1                  2                  5
```

Example 41 (unknown):
```unknown
## 
##             acinar activated_stellate              alpha               beta 
##                 22                 17                253                256 
##              delta             ductal        endothelial              gamma 
##                 22                 30                 12                 18 
##         macrophage               mast            schwann 
##                  1                  2                  5
```

Example 42 (unknown):
```unknown
VlnPlot(pancreas.query, c("REG1A", "PPY", "SST", "GHRL", "VWF", "SOX10"), group.by = "predicted.id")
```

Example 43 (r):
```r
VlnPlot(pancreas.query, c("REG1A", "PPY", "SST", "GHRL", "VWF", "SOX10"), group.by = "predicted.id")
```

Example 44 (r):
```r
VlnPlot(pancreas.query, c("REG1A", "PPY", "SST", "GHRL", "VWF", "SOX10"), group.by = "predicted.id")
```

Example 45 (unknown):
```unknown
TransferData()
```

Example 46 (unknown):
```unknown
pancreas.integrated <- RunUMAP(pancreas.integrated, dims = 1:30, reduction = "pca", return.model = TRUE)
pancreas.query <- MapQuery(anchorset = pancreas.anchors, reference = pancreas.integrated, query = pancreas.query,
    refdata = list(celltype = "celltype"), reference.reduction = "pca", reduction.model = "umap")
```

Example 47 (r):
```r
pancreas.integrated <- RunUMAP(pancreas.integrated, dims = 1:30, reduction = "pca", return.model = TRUE)
pancreas.query <- MapQuery(anchorset = pancreas.anchors, reference = pancreas.integrated, query = pancreas.query,
    refdata = list(celltype = "celltype"), reference.reduction = "pca", reduction.model = "umap")
```

Example 48 (r):
```r
pancreas.integrated <- RunUMAP(pancreas.integrated, dims = 1:30, reduction = "pca", return.model = TRUE)
pancreas.query <- MapQuery(anchorset = pancreas.anchors, reference = pancreas.integrated, query = pancreas.query,
    refdata = list(celltype = "celltype"), reference.reduction = "pca", reduction.model = "umap")
```

Example 49 (unknown):
```unknown
TransferData()
```

Example 50 (unknown):
```unknown
IntegrateEmbeddings()
```

Example 51 (unknown):
```unknown
ProjectUMAP()
```

Example 52 (unknown):
```unknown
TransferData()
```

Example 53 (unknown):
```unknown
IntegrateEmbeddings()
```

Example 54 (unknown):
```unknown
ProjectUMAP()
```

Example 55 (unknown):
```unknown
pancreas.query <- TransferData(anchorset = pancreas.anchors, reference = pancreas.integrated, query = pancreas.query,
    refdata = list(celltype = "celltype"))
pancreas.query <- IntegrateEmbeddings(anchorset = pancreas.anchors, reference = pancreas.integrated,
    query = pancreas.query, new.reduction.name = "ref.pca")
pancreas.query <- ProjectUMAP(query = pancreas.query, query.reduction = "ref.pca", reference = pancreas.integrated,
    reference.reduction = "pca", reduction.model = "umap")
```

Example 56 (r):
```r
pancreas.query <- TransferData(anchorset = pancreas.anchors, reference = pancreas.integrated, query = pancreas.query,
    refdata = list(celltype = "celltype"))
pancreas.query <- IntegrateEmbeddings(anchorset = pancreas.anchors, reference = pancreas.integrated,
    query = pancreas.query, new.reduction.name = "ref.pca")
pancreas.query <- ProjectUMAP(query = pancreas.query, query.reduction = "ref.pca", reference = pancreas.integrated,
    reference.reduction = "pca", reduction.model = "umap")
```

Example 57 (r):
```r
pancreas.query <- TransferData(anchorset = pancreas.anchors, reference = pancreas.integrated, query = pancreas.query,
    refdata = list(celltype = "celltype"))
pancreas.query <- IntegrateEmbeddings(anchorset = pancreas.anchors, reference = pancreas.integrated,
    query = pancreas.query, new.reduction.name = "ref.pca")
pancreas.query <- ProjectUMAP(query = pancreas.query, query.reduction = "ref.pca", reference = pancreas.integrated,
    reference.reduction = "pca", reduction.model = "umap")
```

Example 58 (unknown):
```unknown
p1 <- DimPlot(pancreas.integrated, reduction = "umap", group.by = "celltype", label = TRUE, label.size = 3,
    repel = TRUE) + NoLegend() + ggtitle("Reference annotations")
p2 <- DimPlot(pancreas.query, reduction = "ref.umap", group.by = "predicted.celltype", label = TRUE,
    label.size = 3, repel = TRUE) + NoLegend() + ggtitle("Query transferred labels")
p1 + p2
```

Example 59 (r):
```r
p1 <- DimPlot(pancreas.integrated, reduction = "umap", group.by = "celltype", label = TRUE, label.size = 3,
    repel = TRUE) + NoLegend() + ggtitle("Reference annotations")
p2 <- DimPlot(pancreas.query, reduction = "ref.umap", group.by = "predicted.celltype", label = TRUE,
    label.size = 3, repel = TRUE) + NoLegend() + ggtitle("Query transferred labels")
p1 + p2
```

Example 60 (r):
```r
p1 <- DimPlot(pancreas.integrated, reduction = "umap", group.by = "celltype", label = TRUE, label.size = 3,
    repel = TRUE) + NoLegend() + ggtitle("Reference annotations")
p2 <- DimPlot(pancreas.query, reduction = "ref.umap", group.by = "predicted.celltype", label = TRUE,
    label.size = 3, repel = TRUE) + NoLegend() + ggtitle("Query transferred labels")
p1 + p2
```

Example 61 (unknown):
```unknown
sessionInfo()
```

Example 62 (r):
```r
sessionInfo()
```

Example 63 (r):
```r
sessionInfo()
```

Example 64 (unknown):
```unknown
## R version 4.2.0 (2022-04-22)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.5 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/liblapack.so.3
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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       
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
##  [1] patchwork_1.1.2               cowplot_1.1.1                
##  [3] ggplot2_3.4.1                 thp1.eccite.SeuratData_3.1.5 
##  [5] stxBrain.SeuratData_0.1.1     ssHippo.SeuratData_3.1.4     
##  [7] pbmcsca.SeuratData_3.0.0      pbmcMultiome.SeuratData_0.1.2
##  [9] pbmc3k.SeuratData_3.1.4       panc8.SeuratData_3.0.2       
## [11] ifnb.SeuratData_3.1.0         hcabm40k.SeuratData_3.0.0    
## [13] bmcite.SeuratData_0.3.0       SeuratData_0.2.2             
## [15] SeuratObject_4.1.3            Seurat_4.3.0                 
## 
## loaded via a namespace (and not attached):
##   [1] systemfonts_1.0.4      plyr_1.8.8             igraph_1.4.1          
##   [4] lazyeval_0.2.2         sp_1.6-0               splines_4.2.0         
##   [7] listenv_0.9.0          scattermore_0.8        digest_0.6.31         
##  [10] htmltools_0.5.4        fansi_1.0.4            magrittr_2.0.3        
##  [13] memoise_2.0.1          tensor_1.5             cluster_2.1.3         
##  [16] ROCR_1.0-11            globals_0.16.2         matrixStats_0.63.0    
##  [19] pkgdown_2.0.7          spatstat.sparse_3.0-0  colorspace_2.1-0      
##  [22] rappdirs_0.3.3         ggrepel_0.9.3          textshaping_0.3.6     
##  [25] xfun_0.37              dplyr_1.1.0            crayon_1.5.2          
##  [28] jsonlite_1.8.4         progressr_0.13.0       spatstat.data_3.0-0   
##  [31] survival_3.3-1         zoo_1.8-11             glue_1.6.2            
##  [34] polyclip_1.10-4        gtable_0.3.1           leiden_0.4.3          
##  [37] future.apply_1.10.0    abind_1.4-5            scales_1.2.1          
##  [40] spatstat.random_3.1-3  miniUI_0.1.1.1         Rcpp_1.0.10           
##  [43] viridisLite_0.4.1      xtable_1.8-4           reticulate_1.28       
##  [46] htmlwidgets_1.6.1      httr_1.4.5             RColorBrewer_1.1-3    
##  [49] ellipsis_0.3.2         ica_1.0-3              farver_2.1.1          
##  [52] pkgconfig_2.0.3        sass_0.4.5             uwot_0.1.14           
##  [55] deldir_1.0-6           utf8_1.2.3             tidyselect_1.2.0      
##  [58] labeling_0.4.2         rlang_1.0.6            reshape2_1.4.4        
##  [61] later_1.3.0            munsell_0.5.0          tools_4.2.0           
##  [64] cachem_1.0.7           cli_3.6.0              generics_0.1.3        
##  [67] ggridges_0.5.4         evaluate_0.20          stringr_1.5.0         
##  [70] fastmap_1.1.1          yaml_2.3.7             ragg_1.2.5            
##  [73] goftest_1.2-3          knitr_1.42             fs_1.6.1              
##  [76] fitdistrplus_1.1-8     purrr_1.0.1            RANN_2.6.1            
##  [79] pbapply_1.7-0          future_1.31.0          nlme_3.1-157          
##  [82] mime_0.12              formatR_1.14           compiler_4.2.0        
##  [85] plotly_4.10.1          png_0.1-8              spatstat.utils_3.0-1  
##  [88] tibble_3.1.8           bslib_0.4.2            stringi_1.7.12        
##  [91] highr_0.10             desc_1.4.2             lattice_0.20-45       
##  [94] Matrix_1.5-3           vctrs_0.5.2            pillar_1.8.1          
##  [97] lifecycle_1.0.3        spatstat.geom_3.0-6    lmtest_0.9-40         
## [100] jquerylib_0.1.4        RcppAnnoy_0.0.20       data.table_1.14.8     
## [103] irlba_2.3.5.1          httpuv_1.6.9           R6_2.5.1              
## [106] promises_1.2.0.1       KernSmooth_2.23-20     gridExtra_2.3         
## [109] parallelly_1.34.0      codetools_0.2-18       MASS_7.3-56           
## [112] rprojroot_2.0.3        withr_2.5.0            sctransform_0.3.5     
## [115] parallel_4.2.0         grid_4.2.0             tidyr_1.3.0           
## [118] rmarkdown_2.20         Rtsne_0.16             spatstat.explore_3.0-6
## [121] shiny_1.7.4
```

Example 65 (unknown):
```unknown
## R version 4.2.0 (2022-04-22)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.5 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/liblapack.so.3
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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       
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
##  [1] patchwork_1.1.2               cowplot_1.1.1                
##  [3] ggplot2_3.4.1                 thp1.eccite.SeuratData_3.1.5 
##  [5] stxBrain.SeuratData_0.1.1     ssHippo.SeuratData_3.1.4     
##  [7] pbmcsca.SeuratData_3.0.0      pbmcMultiome.SeuratData_0.1.2
##  [9] pbmc3k.SeuratData_3.1.4       panc8.SeuratData_3.0.2       
## [11] ifnb.SeuratData_3.1.0         hcabm40k.SeuratData_3.0.0    
## [13] bmcite.SeuratData_0.3.0       SeuratData_0.2.2             
## [15] SeuratObject_4.1.3            Seurat_4.3.0                 
## 
## loaded via a namespace (and not attached):
##   [1] systemfonts_1.0.4      plyr_1.8.8             igraph_1.4.1          
##   [4] lazyeval_0.2.2         sp_1.6-0               splines_4.2.0         
##   [7] listenv_0.9.0          scattermore_0.8        digest_0.6.31         
##  [10] htmltools_0.5.4        fansi_1.0.4            magrittr_2.0.3        
##  [13] memoise_2.0.1          tensor_1.5             cluster_2.1.3         
##  [16] ROCR_1.0-11            globals_0.16.2         matrixStats_0.63.0    
##  [19] pkgdown_2.0.7          spatstat.sparse_3.0-0  colorspace_2.1-0      
##  [22] rappdirs_0.3.3         ggrepel_0.9.3          textshaping_0.3.6     
##  [25] xfun_0.37              dplyr_1.1.0            crayon_1.5.2          
##  [28] jsonlite_1.8.4         progressr_0.13.0       spatstat.data_3.0-0   
##  [31] survival_3.3-1         zoo_1.8-11             glue_1.6.2            
##  [34] polyclip_1.10-4        gtable_0.3.1           leiden_0.4.3          
##  [37] future.apply_1.10.0    abind_1.4-5            scales_1.2.1          
##  [40] spatstat.random_3.1-3  miniUI_0.1.1.1         Rcpp_1.0.10           
##  [43] viridisLite_0.4.1      xtable_1.8-4           reticulate_1.28       
##  [46] htmlwidgets_1.6.1      httr_1.4.5             RColorBrewer_1.1-3    
##  [49] ellipsis_0.3.2         ica_1.0-3              farver_2.1.1          
##  [52] pkgconfig_2.0.3        sass_0.4.5             uwot_0.1.14           
##  [55] deldir_1.0-6           utf8_1.2.3             tidyselect_1.2.0      
##  [58] labeling_0.4.2         rlang_1.0.6            reshape2_1.4.4        
##  [61] later_1.3.0            munsell_0.5.0          tools_4.2.0           
##  [64] cachem_1.0.7           cli_3.6.0              generics_0.1.3        
##  [67] ggridges_0.5.4         evaluate_0.20          stringr_1.5.0         
##  [70] fastmap_1.1.1          yaml_2.3.7             ragg_1.2.5            
##  [73] goftest_1.2-3          knitr_1.42             fs_1.6.1              
##  [76] fitdistrplus_1.1-8     purrr_1.0.1            RANN_2.6.1            
##  [79] pbapply_1.7-0          future_1.31.0          nlme_3.1-157          
##  [82] mime_0.12              formatR_1.14           compiler_4.2.0        
##  [85] plotly_4.10.1          png_0.1-8              spatstat.utils_3.0-1  
##  [88] tibble_3.1.8           bslib_0.4.2            stringi_1.7.12        
##  [91] highr_0.10             desc_1.4.2             lattice_0.20-45       
##  [94] Matrix_1.5-3           vctrs_0.5.2            pillar_1.8.1          
##  [97] lifecycle_1.0.3        spatstat.geom_3.0-6    lmtest_0.9-40         
## [100] jquerylib_0.1.4        RcppAnnoy_0.0.20       data.table_1.14.8     
## [103] irlba_2.3.5.1          httpuv_1.6.9           R6_2.5.1              
## [106] promises_1.2.0.1       KernSmooth_2.23-20     gridExtra_2.3         
## [109] parallelly_1.34.0      codetools_0.2-18       MASS_7.3-56           
## [112] rprojroot_2.0.3        withr_2.5.0            sctransform_0.3.5     
## [115] parallel_4.2.0         grid_4.2.0             tidyr_1.3.0           
## [118] rmarkdown_2.20         Rtsne_0.16             spatstat.explore_3.0-6
## [121] shiny_1.7.4
```

---

## Integration and Label Transfer

**URL:** http://127.0.0.1:9173/seurat/archive/v3.2/integration/index.html

**Contents:**
- Integration and Label Transfer
    - Compiled: 2020-10-02
  - Intro: Seurat v3 Integration
  - Standard Workflow
    - Dataset preprocessing
    - Integration of 3 pancreatic islet cell datasets
    - Cell type classification using an integrated reference
  - SCTransform
  - Reference-based
  - Reciprocal PCA

As described in Stuart*, Butler*, et al. Cell 2019, Seurat v3 introduces new methods for the integration of multiple single-cell datasets. These methods aim to identify shared cell states that are present across different datasets, even if they were collected from different individuals, experimental conditions, technologies, or even species.

Our method aims to first identify 'anchors' between pairs of datasets. These represent pairwise correspondences between individual cells (one in each dataset), that we hypothesize originate from the same biological state. These 'anchors' are then used to harmonize the datasets, or transfer information from one dataset to another. Below, we demonstrate multiple applications of integrative analysis, and also introduce new functionality beyond what was described in the 2019 manuscript. To help guide users, we briefly introduce these vignettes below:

In this example workflow, we demonstrate two new methods we recently introduced in our paper, Comprehensive Integration of Single Cell Data:

For the purposes of this example, we've chosen human pancreatic islet cell datasets produced across four technologies, CelSeq (GSE81076) CelSeq2 (GSE85241), Fluidigm C1 (GSE86469), and SMART-Seq2 (E-MTAB-5061). For convienence, we distribute this dataset through our SeuratData package.

The code for the new methodology is implemented in Seurat v3. You can download and install from CRAN with install.packages.

In addition to new methods, Seurat v3 includes a number of improvements aiming to improve the Seurat object and user interaction. To help users familiarize themselves with these changes, we put together a command cheat sheet for common tasks.

Load in the dataset. The metadata contains the technology (tech column) and cell type annotations (celltype column) for each cell in the four datasets.

To construct a reference, we will identify 'anchors' between the individual datasets. First, we split the combined object into a list, with each dataset as an element.

Prior to finding anchors, we perform standard preprocessing (log-normalization), and identify variable features individually for each. Note that Seurat v3 implements an improved method for variable feature selection based on a variance stabilizing transformation ("vst")

Next, we identify anchors using the FindIntegrationAnchors function, which takes a list of Seurat objects as input. Here, we integrate three of the objects into a reference (we will use the fourth later in this vignette)

We then pass these anchors to the IntegrateData function, which returns a Seurat object.

After running IntegrateData, the Seurat object will contain a new Assay with the integrated expression matrix. Note that the original (uncorrected values) are still stored in the object in the "RNA" assay, so you can switch back and forth.

We can then use this new integrated matrix for downstream analysis and visualization. Here we scale the integrated data, run PCA, and visualize the results with UMAP. The integrated datasets cluster by cell type, instead of by technology.

Seurat v3 also supports the projection of reference data (or meta data) onto a query object. While many of the methods are conserved (both procedures begin by identifying anchors), there are two important distinctions between data transfer and integration:

After finding anchors, we use the TransferData function to classify the query cells based on reference data (a vector of reference cell type labels). TransferData returns a matrix with predicted IDs and prediction scores, which we can add to the query metadata.

Because we have the original label annotations from our full integrated analysis, we can evaluate how well our predicted cell type annotations match the full reference. In this example, we find that there is a high agreement in cell type classification, with over 97% of cells being labeled correctly.

To verify this further, we can examine some canonical cell type markers for specific pancreatic islet cell populations. Note that even though some of these cell types are only represented by one or two cells (e.g. epsilon cells), we are still able to classify them correctly.

On the previous tab, we demonstrate how to integrate datasets after each has been pre-processed using standard log-normalization. Here, we modify the workflow to take advantage of our improved pre-processing and normalization workflow: SCTransform. You can read more about SCTransform in our recent preprint, and see how to apply it to a single dataset in a separate vignette. We suggest exploring these resources before proceeding.

Conceptually, this workflow is very similar to what we have previously introduced, where we 'correct' (or harmonize) log-normalized expression values across datasets. Here, instead, we will harmonize the Pearson residuals that are output from SCTransform. As demonstrated below, the workflow consists of the following steps:

First, setup the Seurat object list, and run SCTransform on each object separately:

Next, select features for downstream integration, and run PrepSCTIntegration, which ensures that all necessary Pearson residuals have been calculated.

Next, identify anchors and integrate the datasets. Commands are identical to the standard workflow, but make sure to set normalization.method = 'SCT':

Now proceed with downstream analysis (i.e. visualization, clustering) on the integrated dataset. Commands are identical to the standard workflow, but do not run the ScaleData function after integration. You can see that after integration, cells group by their biological cell type (which has been pre-annotated), instead of by their underlying technology.

To further demonstrate this workflow, we next apply it to a series of human PBMC datasets from eight different technologies, produced as a systematic technology benchmark by the Human Cell Atlas. Data was downloaded from the Broad Single Cell Portal. For convienence, we distribute this dataset through our SeuratData package.

Note that again, cells are grouped together by shared biological subtype, instead of by technology. In this case, the authors labeled "CellType" in each dataset independently, and you can see that this is consistent with our integrated analysis:

However, our integrated analysis reveals finer subdivisions amongst these broad cell types, since the combined dataset has substantially greater statistical power. We don't do a full clustering here on the integrated dataset, but note that we can observe subpopulations of CD4+ (Memory/Naive), CD8 (multiple cytotoxic populations), and B cells (multiple developmental stages). Below, we visualize the expression of the original measurements on our integrated visualization (note that you can add split.by = 'Method to make these plots for each technology independently)"

Here, we present an additional modification to the Seurat integration workflow, which we refer to as 'Reference-based' integration. In the previous workflows, we identify anchors between all pairs of datasets. While this gives datasets equal weight in downstream integration, it can also become computationally intensive. For example, when integrating 10 different datasets, we perform 45 different pairwise comparisons.

As an alternative, we introduce here the possibility of specifying one or more of the datasets as the 'reference' for integrated analysis, with the remainder designated as 'query' datasets. In this workflow, we do not identify anchors between pairs of query datasets, reducing the number of comparisons. For example, when integrating 10 datasets with one specified as a reference, we perform only 9 comparisons. Reference-based integration can be applied to either log-normalized or SCTransform-normalized datasets.

In practice, we often observe very similar results between the approaches, but with substantially reduced computational time. We demonstrate this using the same PBMC analysis as in the previous tab with highly concordant outputs. We therefore recommend this workflow for users who are integrating a large number of datasets, and desire increased computational efficiency.

This approach does require users to pre-select datasets to serve as a reference. In this example, we use the 10X v3 dataset, as the dataset contains both high cell number and high sensitivity. Users can apply similar criteria when selecting a reference. Furthermore, you can change this setting in the workflow below (for example, try selecting the 10X v2, or Drop-seq datasets as a reference), with only very minor differences in the final result.

The workflow is demonstrated below. Commands are identical to the previous tab, except that we specify a reference argument in the FindIntegrationAnchors function. Data was originally downloaded from the Broad Single Cell Portal but for convienence, we distribute this dataset through our SeuratData package.

For very large datasets, Canonical Correlation Analysis can sometimes become a prohibitively computationally expensive step. In this workflow, we introduce an alternate form of dimension reduction, reciprocal PCA, to identify an effective space in which to find anchors. When determining anchors between any two datasets using reciprocal PCA, we project each dataset into the other's PCA space and constrain the anchors by the same mutual neighborhood requirement. All downstream integration steps remain the same and we are able to 'correct' (or harmonize) the datasets.

As demonstrated below, the workflow consists of the following steps:

In general, we observe strikingly similar results between the two workflows, but with substantial reduction in compute time and memory when using reciprocal PCA. However, if the datasets are highly divergent (for example, cross-modality mapping or cross-species mapping), where only a small subset of features can be used to facilitate integration, and you may observe superior results using CCA.

For large studies with many datasets, we recommend also combining reciprocal PCA with reference-based integration, or SCTransform normalization (see details on previous tab).

For these examples, we will be using the "Immune Cell Atlas" data from the Human Cell Atlas which can be found here. First, we will integrate a randomly downsampled version of this dataset and then the full dataset. The randomly downsampled version contains 40K cells (5K from each donor) and is available through our new SeuratData package.

After acquiring the data, we first perform standard normalization and variable feature selection.

Next, select features for downstream integration, and run PCA on each object in the list, which is required for running the reciprocal PCA workflow.

Since this dataset contains both men and women, we will chose one male and one female (BM1 and BM2) to use in the reference-based workflow. We determined donor sex by examining the expression of the XIST gene. Next, identify anchors and integrate the datasets. Commands are identical to the standard workflow, but make sure to set reduction = 'rpca':

Now proceed with downstream analysis (i.e. visualization, clustering) on the integrated dataset. Commands are identical to the standard workflow.

To further demonstrate this workflow, we next apply it to the full dataset. While we do not provide this through SeuratData, you can find the counts matrix on the HCA Data Portal site. The commands below are identical to the 40k integration except we've increased the dimensionality to 50 to reflect the increased cell number and diversity.

**Examples:**

Example 1 (unknown):
```unknown
install.packages
```

Example 2 (r):
```r
install.packages("Seurat")
```

Example 3 (r):
```r
install.packages("Seurat")
```

Example 4 (r):
```r
library(Seurat)
library(SeuratData)
```

Example 5 (r):
```r
library(Seurat)
library(SeuratData)
```

Example 6 (r):
```r
InstallData("panc8")
```

Example 7 (r):
```r
InstallData("panc8")
```

Example 8 (r):
```r
data("panc8")
pancreas.list <- SplitObject(panc8, split.by = "tech")
pancreas.list <- pancreas.list[c("celseq", "celseq2", "fluidigmc1", "smartseq2")]
```

Example 9 (r):
```r
data("panc8")
pancreas.list <- SplitObject(panc8, split.by = "tech")
pancreas.list <- pancreas.list[c("celseq", "celseq2", "fluidigmc1", "smartseq2")]
```

Example 10 (r):
```r
for (i in 1:length(pancreas.list)) {
    pancreas.list[[i]] <- NormalizeData(pancreas.list[[i]], verbose = FALSE)
    pancreas.list[[i]] <- FindVariableFeatures(pancreas.list[[i]], selection.method = "vst", 
        nfeatures = 2000, verbose = FALSE)
}
```

Example 11 (r):
```r
for (i in 1:length(pancreas.list)) {
    pancreas.list[[i]] <- NormalizeData(pancreas.list[[i]], verbose = FALSE)
    pancreas.list[[i]] <- FindVariableFeatures(pancreas.list[[i]], selection.method = "vst", 
        nfeatures = 2000, verbose = FALSE)
}
```

Example 12 (unknown):
```unknown
FindIntegrationAnchors
```

Example 13 (r):
```r
reference.list <- pancreas.list[c("celseq", "celseq2", "smartseq2")]
pancreas.anchors <- FindIntegrationAnchors(object.list = reference.list, dims = 1:30)
```

Example 14 (r):
```r
reference.list <- pancreas.list[c("celseq", "celseq2", "smartseq2")]
pancreas.anchors <- FindIntegrationAnchors(object.list = reference.list, dims = 1:30)
```

Example 15 (unknown):
```unknown
IntegrateData
```

Example 16 (r):
```r
pancreas.integrated <- IntegrateData(anchorset = pancreas.anchors, dims = 1:30)
```

Example 17 (r):
```r
pancreas.integrated <- IntegrateData(anchorset = pancreas.anchors, dims = 1:30)
```

Example 18 (unknown):
```unknown
IntegrateData
```

Example 19 (r):
```r
library(ggplot2)
library(cowplot)
library(patchwork)
# switch to integrated assay. The variable features of this assay are automatically
# set during IntegrateData
DefaultAssay(pancreas.integrated) <- "integrated"

# Run the standard workflow for visualization and clustering
pancreas.integrated <- ScaleData(pancreas.integrated, verbose = FALSE)
pancreas.integrated <- RunPCA(pancreas.integrated, npcs = 30, verbose = FALSE)
pancreas.integrated <- RunUMAP(pancreas.integrated, reduction = "pca", dims = 1:30)
p1 <- DimPlot(pancreas.integrated, reduction = "umap", group.by = "tech")
p2 <- DimPlot(pancreas.integrated, reduction = "umap", group.by = "celltype", label = TRUE, 
    repel = TRUE) + NoLegend()
p1 + p2
```

Example 20 (r):
```r
library(ggplot2)
library(cowplot)
library(patchwork)
# switch to integrated assay. The variable features of this assay are automatically
# set during IntegrateData
DefaultAssay(pancreas.integrated) <- "integrated"

# Run the standard workflow for visualization and clustering
pancreas.integrated <- ScaleData(pancreas.integrated, verbose = FALSE)
pancreas.integrated <- RunPCA(pancreas.integrated, npcs = 30, verbose = FALSE)
pancreas.integrated <- RunUMAP(pancreas.integrated, reduction = "pca", dims = 1:30)
p1 <- DimPlot(pancreas.integrated, reduction = "umap", group.by = "tech")
p2 <- DimPlot(pancreas.integrated, reduction = "umap", group.by = "celltype", label = TRUE, 
    repel = TRUE) + NoLegend()
p1 + p2
```

Example 21 (unknown):
```unknown
TransferData
```

Example 22 (unknown):
```unknown
TransferData
```

Example 23 (r):
```r
pancreas.query <- pancreas.list[["fluidigmc1"]]
pancreas.anchors <- FindTransferAnchors(reference = pancreas.integrated, query = pancreas.query, 
    dims = 1:30)
predictions <- TransferData(anchorset = pancreas.anchors, refdata = pancreas.integrated$celltype, 
    dims = 1:30)
pancreas.query <- AddMetaData(pancreas.query, metadata = predictions)
```

Example 24 (r):
```r
pancreas.query <- pancreas.list[["fluidigmc1"]]
pancreas.anchors <- FindTransferAnchors(reference = pancreas.integrated, query = pancreas.query, 
    dims = 1:30)
predictions <- TransferData(anchorset = pancreas.anchors, refdata = pancreas.integrated$celltype, 
    dims = 1:30)
pancreas.query <- AddMetaData(pancreas.query, metadata = predictions)
```

Example 25 (r):
```r
pancreas.query$prediction.match <- pancreas.query$predicted.id == pancreas.query$celltype
table(pancreas.query$prediction.match)
```

Example 26 (r):
```r
pancreas.query$prediction.match <- pancreas.query$predicted.id == pancreas.query$celltype
table(pancreas.query$prediction.match)
```

Example 27 (unknown):
```unknown
## 
## FALSE  TRUE 
##    18   620
```

Example 28 (unknown):
```unknown
## 
## FALSE  TRUE 
##    18   620
```

Example 29 (r):
```r
table(pancreas.query$predicted.id)
```

Example 30 (r):
```r
table(pancreas.query$predicted.id)
```

Example 31 (unknown):
```unknown
## 
##             acinar activated_stellate              alpha               beta 
##                 21                 17                248                258 
##              delta             ductal        endothelial            epsilon 
##                 22                 33                 13                  1 
##              gamma         macrophage               mast            schwann 
##                 17                  1                  2                  5
```

Example 32 (unknown):
```unknown
## 
##             acinar activated_stellate              alpha               beta 
##                 21                 17                248                258 
##              delta             ductal        endothelial            epsilon 
##                 22                 33                 13                  1 
##              gamma         macrophage               mast            schwann 
##                 17                  1                  2                  5
```

Example 33 (r):
```r
VlnPlot(pancreas.query, c("REG1A", "PPY", "SST", "GHRL", "VWF", "SOX10"), group.by = "predicted.id")
```

Example 34 (r):
```r
VlnPlot(pancreas.query, c("REG1A", "PPY", "SST", "GHRL", "VWF", "SOX10"), group.by = "predicted.id")
```

Example 35 (r):
```r
library(Seurat)
library(ggplot2)
library(patchwork)
options(future.globals.maxSize = 4000 * 1024^2)
data("panc8")
pancreas.list <- SplitObject(panc8, split.by = "tech")
pancreas.list <- pancreas.list[c("celseq", "celseq2", "fluidigmc1", "smartseq2")]
for (i in 1:length(pancreas.list)) {
    pancreas.list[[i]] <- SCTransform(pancreas.list[[i]], verbose = FALSE)
}
```

Example 36 (r):
```r
library(Seurat)
library(ggplot2)
library(patchwork)
options(future.globals.maxSize = 4000 * 1024^2)
data("panc8")
pancreas.list <- SplitObject(panc8, split.by = "tech")
pancreas.list <- pancreas.list[c("celseq", "celseq2", "fluidigmc1", "smartseq2")]
for (i in 1:length(pancreas.list)) {
    pancreas.list[[i]] <- SCTransform(pancreas.list[[i]], verbose = FALSE)
}
```

Example 37 (unknown):
```unknown
PrepSCTIntegration
```

Example 38 (r):
```r
pancreas.features <- SelectIntegrationFeatures(object.list = pancreas.list, nfeatures = 3000)
pancreas.list <- PrepSCTIntegration(object.list = pancreas.list, anchor.features = pancreas.features, 
    verbose = FALSE)
```

Example 39 (r):
```r
pancreas.features <- SelectIntegrationFeatures(object.list = pancreas.list, nfeatures = 3000)
pancreas.list <- PrepSCTIntegration(object.list = pancreas.list, anchor.features = pancreas.features, 
    verbose = FALSE)
```

Example 40 (unknown):
```unknown
normalization.method = 'SCT'
```

Example 41 (r):
```r
pancreas.anchors <- FindIntegrationAnchors(object.list = pancreas.list, normalization.method = "SCT", 
    anchor.features = pancreas.features, verbose = FALSE)
pancreas.integrated <- IntegrateData(anchorset = pancreas.anchors, normalization.method = "SCT", 
    verbose = FALSE)
```

Example 42 (r):
```r
pancreas.anchors <- FindIntegrationAnchors(object.list = pancreas.list, normalization.method = "SCT", 
    anchor.features = pancreas.features, verbose = FALSE)
pancreas.integrated <- IntegrateData(anchorset = pancreas.anchors, normalization.method = "SCT", 
    verbose = FALSE)
```

Example 43 (r):
```r
pancreas.integrated <- RunPCA(pancreas.integrated, verbose = FALSE)
pancreas.integrated <- RunUMAP(pancreas.integrated, dims = 1:30)
plots <- DimPlot(pancreas.integrated, group.by = c("tech", "celltype"))
plots & theme(legend.position = "top") & guides(color = guide_legend(nrow = 3, byrow = TRUE, 
    override.aes = list(size = 3)))
```

Example 44 (r):
```r
pancreas.integrated <- RunPCA(pancreas.integrated, verbose = FALSE)
pancreas.integrated <- RunUMAP(pancreas.integrated, dims = 1:30)
plots <- DimPlot(pancreas.integrated, group.by = c("tech", "celltype"))
plots & theme(legend.position = "top") & guides(color = guide_legend(nrow = 3, byrow = TRUE, 
    override.aes = list(size = 3)))
```

Example 45 (r):
```r
InstallData("pbmcsca")
```

Example 46 (r):
```r
InstallData("pbmcsca")
```

Example 47 (r):
```r
data("pbmcsca")
pbmc.list <- SplitObject(pbmcsca, split.by = "Method")
for (i in names(pbmc.list)) {
    pbmc.list[[i]] <- SCTransform(pbmc.list[[i]], verbose = FALSE)
}
pbmc.features <- SelectIntegrationFeatures(object.list = pbmc.list, nfeatures = 3000)
pbmc.list <- PrepSCTIntegration(object.list = pbmc.list, anchor.features = pbmc.features)
pbmc.anchors <- FindIntegrationAnchors(object.list = pbmc.list, normalization.method = "SCT", 
    anchor.features = pbmc.features)
pbmc.integrated <- IntegrateData(anchorset = pbmc.anchors, normalization.method = "SCT")

pbmc.integrated <- RunPCA(object = pbmc.integrated, verbose = FALSE)
pbmc.integrated <- RunUMAP(object = pbmc.integrated, dims = 1:30)
```

Example 48 (r):
```r
data("pbmcsca")
pbmc.list <- SplitObject(pbmcsca, split.by = "Method")
for (i in names(pbmc.list)) {
    pbmc.list[[i]] <- SCTransform(pbmc.list[[i]], verbose = FALSE)
}
pbmc.features <- SelectIntegrationFeatures(object.list = pbmc.list, nfeatures = 3000)
pbmc.list <- PrepSCTIntegration(object.list = pbmc.list, anchor.features = pbmc.features)
pbmc.anchors <- FindIntegrationAnchors(object.list = pbmc.list, normalization.method = "SCT", 
    anchor.features = pbmc.features)
pbmc.integrated <- IntegrateData(anchorset = pbmc.anchors, normalization.method = "SCT")

pbmc.integrated <- RunPCA(object = pbmc.integrated, verbose = FALSE)
pbmc.integrated <- RunUMAP(object = pbmc.integrated, dims = 1:30)
```

Example 49 (r):
```r
plots <- DimPlot(pbmc.integrated, group.by = c("Method", "CellType"))
plots & theme(legend.position = "top") & guides(color = guide_legend(nrow = 4, byrow = TRUE, 
    override.aes = list(size = 2.5)))
```

Example 50 (r):
```r
plots <- DimPlot(pbmc.integrated, group.by = c("Method", "CellType"))
plots & theme(legend.position = "top") & guides(color = guide_legend(nrow = 4, byrow = TRUE, 
    override.aes = list(size = 2.5)))
```

Example 51 (r):
```r
DimPlot(pbmc.integrated, group.by = "CellType", split.by = "Method", ncol = 3)
```

Example 52 (r):
```r
DimPlot(pbmc.integrated, group.by = "CellType", split.by = "Method", ncol = 3)
```

Example 53 (unknown):
```unknown
split.by = 'Method
```

Example 54 (r):
```r
DefaultAssay(pbmc.integrated) <- "RNA"
# Normalize RNA data for visualization purposes
pbmc.integrated <- NormalizeData(pbmc.integrated, verbose = FALSE)
FeaturePlot(pbmc.integrated, c("CCR7", "S100A4", "GZMB", "GZMK", "GZMH", "TCL1A"))
```

Example 55 (r):
```r
DefaultAssay(pbmc.integrated) <- "RNA"
# Normalize RNA data for visualization purposes
pbmc.integrated <- NormalizeData(pbmc.integrated, verbose = FALSE)
FeaturePlot(pbmc.integrated, c("CCR7", "S100A4", "GZMB", "GZMK", "GZMH", "TCL1A"))
```

Example 56 (unknown):
```unknown
FindIntegrationAnchors
```

Example 57 (r):
```r
library(Seurat)
library(SeuratData)
library(ggplot2)
library(patchwork)
```

Example 58 (r):
```r
library(Seurat)
library(SeuratData)
library(ggplot2)
library(patchwork)
```

Example 59 (r):
```r
InstallData("pbmcsca")
```

Example 60 (r):
```r
InstallData("pbmcsca")
```

Example 61 (r):
```r
data("pbmcsca")
pbmc.list <- SplitObject(pbmcsca, split.by = "Method")
for (i in names(pbmc.list)) {
    pbmc.list[[i]] <- SCTransform(pbmc.list[[i]], verbose = FALSE)
}
pbmc.features <- SelectIntegrationFeatures(object.list = pbmc.list, nfeatures = 3000)
pbmc.list <- PrepSCTIntegration(object.list = pbmc.list, anchor.features = pbmc.features)

# This command returns dataset 5.  We can also specify multiple refs. (i.e. c(5,6))
reference_dataset <- which(names(pbmc.list) == "10x Chromium (v3)")

pbmc.anchors <- FindIntegrationAnchors(object.list = pbmc.list, normalization.method = "SCT", 
    anchor.features = pbmc.features, reference = reference_dataset)
pbmc.integrated <- IntegrateData(anchorset = pbmc.anchors, normalization.method = "SCT")

pbmc.integrated <- RunPCA(object = pbmc.integrated, verbose = FALSE)
pbmc.integrated <- RunUMAP(object = pbmc.integrated, dims = 1:30)
```

Example 62 (r):
```r
data("pbmcsca")
pbmc.list <- SplitObject(pbmcsca, split.by = "Method")
for (i in names(pbmc.list)) {
    pbmc.list[[i]] <- SCTransform(pbmc.list[[i]], verbose = FALSE)
}
pbmc.features <- SelectIntegrationFeatures(object.list = pbmc.list, nfeatures = 3000)
pbmc.list <- PrepSCTIntegration(object.list = pbmc.list, anchor.features = pbmc.features)

# This command returns dataset 5.  We can also specify multiple refs. (i.e. c(5,6))
reference_dataset <- which(names(pbmc.list) == "10x Chromium (v3)")

pbmc.anchors <- FindIntegrationAnchors(object.list = pbmc.list, normalization.method = "SCT", 
    anchor.features = pbmc.features, reference = reference_dataset)
pbmc.integrated <- IntegrateData(anchorset = pbmc.anchors, normalization.method = "SCT")

pbmc.integrated <- RunPCA(object = pbmc.integrated, verbose = FALSE)
pbmc.integrated <- RunUMAP(object = pbmc.integrated, dims = 1:30)
```

Example 63 (r):
```r
plots <- DimPlot(pbmc.integrated, group.by = c("Method", "CellType"))
plots & theme(legend.position = "top") & guides(color = guide_legend(nrow = 4, byrow = TRUE, 
    override.aes = list(size = 2.5)))
```

Example 64 (r):
```r
plots <- DimPlot(pbmc.integrated, group.by = c("Method", "CellType"))
plots & theme(legend.position = "top") & guides(color = guide_legend(nrow = 4, byrow = TRUE, 
    override.aes = list(size = 2.5)))
```

Example 65 (r):
```r
DefaultAssay(pbmc.integrated) <- "RNA"
# Normalize RNA data for visualization purposes
pbmc.integrated <- NormalizeData(pbmc.integrated, verbose = FALSE)
FeaturePlot(pbmc.integrated, c("CCR7", "S100A4", "GZMB", "GZMK", "GZMH", "TCL1A"))
```

Example 66 (r):
```r
DefaultAssay(pbmc.integrated) <- "RNA"
# Normalize RNA data for visualization purposes
pbmc.integrated <- NormalizeData(pbmc.integrated, verbose = FALSE)
FeaturePlot(pbmc.integrated, c("CCR7", "S100A4", "GZMB", "GZMK", "GZMH", "TCL1A"))
```

Example 67 (r):
```r
library(Seurat)
library(SeuratData)
```

Example 68 (r):
```r
library(Seurat)
library(SeuratData)
```

Example 69 (r):
```r
# Get data from seurat-data
InstallData(pkgs = "bm40k.SeuratData")
```

Example 70 (r):
```r
# Get data from seurat-data
InstallData(pkgs = "bm40k.SeuratData")
```

Example 71 (r):
```r
library(ggplot2)
# load in the data
data(hcabm40k)
bm40k.list <- SplitObject(hcabm40k, split.by = "orig.ident")
bm40k.list <- lapply(X = bm40k.list, FUN = function(x) {
    x <- NormalizeData(x, verbose = FALSE)
    x <- FindVariableFeatures(x, verbose = FALSE)
})
```

Example 72 (r):
```r
library(ggplot2)
# load in the data
data(hcabm40k)
bm40k.list <- SplitObject(hcabm40k, split.by = "orig.ident")
bm40k.list <- lapply(X = bm40k.list, FUN = function(x) {
    x <- NormalizeData(x, verbose = FALSE)
    x <- FindVariableFeatures(x, verbose = FALSE)
})
```

Example 73 (r):
```r
features <- SelectIntegrationFeatures(object.list = bm40k.list)
bm40k.list <- lapply(X = bm40k.list, FUN = function(x) {
    x <- ScaleData(x, features = features, verbose = FALSE)
    x <- RunPCA(x, features = features, verbose = FALSE)
})
```

Example 74 (r):
```r
features <- SelectIntegrationFeatures(object.list = bm40k.list)
bm40k.list <- lapply(X = bm40k.list, FUN = function(x) {
    x <- ScaleData(x, features = features, verbose = FALSE)
    x <- RunPCA(x, features = features, verbose = FALSE)
})
```

Example 75 (unknown):
```unknown
reduction = 'rpca'
```

Example 76 (r):
```r
anchors <- FindIntegrationAnchors(object.list = bm40k.list, reference = c(1, 2), reduction = "rpca", 
    dims = 1:30)
bm40k.integrated <- IntegrateData(anchorset = anchors, dims = 1:30)
```

Example 77 (r):
```r
anchors <- FindIntegrationAnchors(object.list = bm40k.list, reference = c(1, 2), reduction = "rpca", 
    dims = 1:30)
bm40k.integrated <- IntegrateData(anchorset = anchors, dims = 1:30)
```

Example 78 (r):
```r
bm40k.integrated <- ScaleData(bm40k.integrated, verbose = FALSE)
bm40k.integrated <- RunPCA(bm40k.integrated, verbose = FALSE)
bm40k.integrated <- RunUMAP(bm40k.integrated, dims = 1:30)
```

Example 79 (r):
```r
bm40k.integrated <- ScaleData(bm40k.integrated, verbose = FALSE)
bm40k.integrated <- RunPCA(bm40k.integrated, verbose = FALSE)
bm40k.integrated <- RunUMAP(bm40k.integrated, dims = 1:30)
```

Example 80 (r):
```r
DimPlot(bm40k.integrated, group.by = "orig.ident")
```

Example 81 (r):
```r
DimPlot(bm40k.integrated, group.by = "orig.ident")
```

Example 82 (r):
```r
bm280k.data <- Read10X_h5("../data/ica_bone_marrow_h5.h5")
bm280k <- CreateSeuratObject(counts = bm280k.data, min.cells = 100, min.features = 500)
bm280k.list <- SplitObject(bm280k, split.by = "orig.ident")
bm280k.list <- lapply(X = bm280k.list, FUN = function(x) {
    x <- NormalizeData(x, verbose = FALSE)
    x <- FindVariableFeatures(x, verbose = FALSE)
})
```

Example 83 (r):
```r
bm280k.data <- Read10X_h5("../data/ica_bone_marrow_h5.h5")
bm280k <- CreateSeuratObject(counts = bm280k.data, min.cells = 100, min.features = 500)
bm280k.list <- SplitObject(bm280k, split.by = "orig.ident")
bm280k.list <- lapply(X = bm280k.list, FUN = function(x) {
    x <- NormalizeData(x, verbose = FALSE)
    x <- FindVariableFeatures(x, verbose = FALSE)
})
```

Example 84 (r):
```r
features <- SelectIntegrationFeatures(object.list = bm280k.list)
bm280k.list <- lapply(X = bm280k.list, FUN = function(x) {
    x <- ScaleData(x, features = features, verbose = FALSE)
    x <- RunPCA(x, features = features, verbose = FALSE)
})
```

Example 85 (r):
```r
features <- SelectIntegrationFeatures(object.list = bm280k.list)
bm280k.list <- lapply(X = bm280k.list, FUN = function(x) {
    x <- ScaleData(x, features = features, verbose = FALSE)
    x <- RunPCA(x, features = features, verbose = FALSE)
})
```

Example 86 (r):
```r
anchors <- FindIntegrationAnchors(object.list = bm280k.list, reference = c(1, 2), reduction = "rpca", 
    dims = 1:50)
bm280k.integrated <- IntegrateData(anchorset = anchors, dims = 1:50)
```

Example 87 (r):
```r
anchors <- FindIntegrationAnchors(object.list = bm280k.list, reference = c(1, 2), reduction = "rpca", 
    dims = 1:50)
bm280k.integrated <- IntegrateData(anchorset = anchors, dims = 1:50)
```

Example 88 (r):
```r
bm280k.integrated <- ScaleData(bm280k.integrated, verbose = FALSE)
bm280k.integrated <- RunPCA(bm280k.integrated, verbose = FALSE)
bm280k.integrated <- RunUMAP(bm280k.integrated, dims = 1:50)
```

Example 89 (r):
```r
bm280k.integrated <- ScaleData(bm280k.integrated, verbose = FALSE)
bm280k.integrated <- RunPCA(bm280k.integrated, verbose = FALSE)
bm280k.integrated <- RunUMAP(bm280k.integrated, dims = 1:50)
```

Example 90 (r):
```r
DimPlot(bm280k.integrated, group.by = "orig.ident")
```

Example 91 (r):
```r
DimPlot(bm280k.integrated, group.by = "orig.ident")
```

---

## Analysis, visualization, and integration of Visium HD spatial datasets with Seurat • Seurat

**URL:** http://127.0.0.1:9173/articles_install_v5.html

**Contents:**
- Installation Instructions for Seurat
- Seurat 5: Install from CRAN
- Install previous versions of Seurat
  - Install Seurat v4
  - Older versions of Seurat
- Install the development version of Seurat
- Docker
- Contents

To install Seurat, R version 4.0 or greater is required. We also recommend installing R Studio.

Seurat is available on CRAN for all platforms. To install, run:

Seurat does not require, but makes use of, packages developed by other labs that can substantially enhance speed and performance. These include presto (Korunsky/Raychaudhari labs), BPCells (Greenleaf Lab), and glmGamPoi (Huber Lab). We recommend users install these along with Seurat:

We also recommend installing these additional packages, which are used in our vignettes, and enhance the functionality of Seurat:

Seurat v4.4.0 can be installed with the following commands:

Old versions of Seurat, from Seurat v2.0.1 and up, are hosted in CRAN’s archive. To install an old version of Seurat, run:

For versions of Seurat older than those not hosted on CRAN (versions 1.3.0 and 1.4.0), please download the packaged source code from our releases page and install from the tarball.

Install the development version of Seurat - directly from GitHub.

We provide docker images for Seurat via dockerhub.

To pull the latest image from the command line:

To use as a base image in a new Dockerfile:

Developed by Rahul Satija, Satija Lab and Collaborators.

Site built with pkgdown 2.0.7.

**Examples:**

Example 1 (unknown):
```unknown
vignettes/install_v5.Rmd
```

Example 2 (unknown):
```unknown
install_v5.Rmd
```

Example 3 (unknown):
```unknown
# Enter commands in R (or R studio, if installed)
install.packages('Seurat')
library(Seurat)
```

Example 4 (r):
```r
# Enter commands in R (or R studio, if installed)
install.packages('Seurat')
library(Seurat)
```

Example 5 (r):
```r
# Enter commands in R (or R studio, if installed)
install.packages('Seurat')
library(Seurat)
```

Example 6 (unknown):
```unknown
setRepositories(ind = 1:3, addURLs = c('https://satijalab.r-universe.dev', 'https://bnprks.r-universe.dev/'))
install.packages(c("BPCells", "presto", "glmGamPoi"))
```

Example 7 (r):
```r
setRepositories(ind = 1:3, addURLs = c('https://satijalab.r-universe.dev', 'https://bnprks.r-universe.dev/'))
install.packages(c("BPCells", "presto", "glmGamPoi"))
```

Example 8 (r):
```r
setRepositories(ind = 1:3, addURLs = c('https://satijalab.r-universe.dev', 'https://bnprks.r-universe.dev/'))
install.packages(c("BPCells", "presto", "glmGamPoi"))
```

Example 9 (unknown):
```unknown
# Install the remotes package
if (!requireNamespace("remotes", quietly = TRUE)) {
  install.packages("remotes")
}
install.packages('Signac')
remotes::install_github("satijalab/seurat-data", quiet = TRUE)
remotes::install_github("satijalab/azimuth", quiet = TRUE)
remotes::install_github("satijalab/seurat-wrappers", quiet = TRUE)
```

Example 10 (r):
```r
# Install the remotes package
if (!requireNamespace("remotes", quietly = TRUE)) {
  install.packages("remotes")
}
install.packages('Signac')
remotes::install_github("satijalab/seurat-data", quiet = TRUE)
remotes::install_github("satijalab/azimuth", quiet = TRUE)
remotes::install_github("satijalab/seurat-wrappers", quiet = TRUE)
```

Example 11 (r):
```r
# Install the remotes package
if (!requireNamespace("remotes", quietly = TRUE)) {
  install.packages("remotes")
}
install.packages('Signac')
remotes::install_github("satijalab/seurat-data", quiet = TRUE)
remotes::install_github("satijalab/azimuth", quiet = TRUE)
remotes::install_github("satijalab/seurat-wrappers", quiet = TRUE)
```

Example 12 (unknown):
```unknown
remotes::install_version("SeuratObject", "4.1.4", repos = c("https://satijalab.r-universe.dev", getOption("repos")))
remotes::install_version("Seurat", "4.4.0", repos = c("https://satijalab.r-universe.dev", getOption("repos")))
```

Example 13 (r):
```r
remotes::install_version("SeuratObject", "4.1.4", repos = c("https://satijalab.r-universe.dev", getOption("repos")))
remotes::install_version("Seurat", "4.4.0", repos = c("https://satijalab.r-universe.dev", getOption("repos")))
```

Example 14 (r):
```r
remotes::install_version("SeuratObject", "4.1.4", repos = c("https://satijalab.r-universe.dev", getOption("repos")))
remotes::install_version("Seurat", "4.4.0", repos = c("https://satijalab.r-universe.dev", getOption("repos")))
```

Example 15 (unknown):
```unknown
# Install the remotes package 
install.packages('remotes')
# Replace 'X.X.X' with your desired version
remotes::install_version(package = 'Seurat', version = package_version('X.X.X'))
```

Example 16 (r):
```r
# Install the remotes package 
install.packages('remotes')
# Replace 'X.X.X' with your desired version
remotes::install_version(package = 'Seurat', version = package_version('X.X.X'))
```

Example 17 (r):
```r
# Install the remotes package 
install.packages('remotes')
# Replace 'X.X.X' with your desired version
remotes::install_version(package = 'Seurat', version = package_version('X.X.X'))
```

Example 18 (unknown):
```unknown
# Enter commands in R (or R studio, if installed)
# Install the remotes package
install.packages('remotes')
remotes::install_github(repo = 'satijalab/seurat', ref = 'develop')
library(Seurat)
```

Example 19 (r):
```r
# Enter commands in R (or R studio, if installed)
# Install the remotes package
install.packages('remotes')
remotes::install_github(repo = 'satijalab/seurat', ref = 'develop')
library(Seurat)
```

Example 20 (r):
```r
# Enter commands in R (or R studio, if installed)
# Install the remotes package
install.packages('remotes')
remotes::install_github(repo = 'satijalab/seurat', ref = 'develop')
library(Seurat)
```

Example 21 (unknown):
```unknown
docker pull satijalab/seurat:latest
```

Example 22 (unknown):
```unknown
docker pull satijalab/seurat:latest
```

Example 23 (bash):
```bash
docker pull satijalab/seurat:latest
```

Example 24 (unknown):
```unknown
FROM satijalab/seurat:latest
```

Example 25 (unknown):
```unknown
FROM satijalab/seurat:latest
```

Example 26 (bash):
```bash
FROM satijalab/seurat:latest
```

---

## Analysis, visualization, and integration of Visium HD spatial datasets with Seurat • Seurat

**URL:** http://127.0.0.1:9173/seurat/articles/visiumhd_analysis_vignette/index.html

**Contents:**
- Analysis, visualization, and integration of Visium HD spatial datasets with Seurat
    - Compiled: 2024-05-06
- Visium HD support in Seurat
  - Install Seurat Update
  - Load Visium HD data
  - Normalize datasets
  - Visualize gene expression
  - Unsupervised clustering
  - Identifying spatially-defined tissue domains
  - Subset out anatomical regions
  - Integration with scRNA-seq data (deconvolution)
  - Unsupervised clustering: mouse intestine
- Contents

We have previously released support Seurat for sequencing-based spatial transcriptomic (ST) technologies, including 10x visium and SLIDE-seq. We have now updated Seurat to be compatible with the Visium HD technology, which performs profiling at substantially higher spatial resolution than previous versions.

Users can install the Visium HD-compatible release from Github. Existing Seurat workflows for clustering, visualization, and downstream analysis have been updated to support both Visium and Visium HD data.

We note that Visium HD data is generated from spatially patterned olignocleotides labeled in 2um x 2um bins. However, since the data from this resolution is sparse, adjacent bins are pooled together to create 8um and 16um resolutions. 10x recommends the use of 8um binned data for analysis, but Seurat supports in the simultaneous loading of multiple binnings - and stores them in a single object as multiple assays.

In this vignette, we provide an overview of some of the spatial workflows that Seurat supports for analyzing Visium HD data, in particular:

Please note that Visium HD is a new data type, and we expect to update this vignette as we test additional methods for spatial data analysis. We strongly encourage users to explore how different parameter settings affect their results, to analyze data iteratively (and in collaboration with biological experts), and to orthogonally validate unexpected or surprising biological findings.

We focus our analysis on a Visium HD dataset from the mouse brain, available to download here but also run clustering workflow on a dataset from the mouse intestine.

In this vignette we use standard log-normalization for spatial data. We note that the best normalization methods for spatial data are still being developed and evaluated, and encourage users to read manuscripts from the Phipson/Davis and Fan labs to learn more about potential caveats for spatial normalization.

While the standard scRNA-seq clustering workflow can also be applied to spatial datasets - we have observed that when working with Visium HD datasets, the Seurat v5 sketch clustering workflow exhibits improved performance, especially for identifying rare and spatially restricted groups.

As described in Hao et al, Nature Biotechnology 2023 and Hie et al, sketch-based analyses aim to ‘subsample’ large datasets in a way that preserves rare populations. Here, we sketch the Visium HD dataset, perform clustering on the subsampled cells, and then project the cluster labels back to the full dataset.

Details of the sketching procedure and workflow are described in Hao et al, Nature Biotechnology 2023 and the Seurat v5 sketch clustering vignette. Since the full Visium HD dataset fits in memory, we do not use any of the on-disk capabilities of Seurat v5 in this vignette.

Now we can project the cluster labels, and dimensional reductions (PCA and UMAP) that we learned from the 50,000 sketched cells - to the entire dataset, using the ProjectData function.

In the resulting object, for all cells:

We can visualize the clustering results for the sketched cells, as well as the projected clustering results for the full dataset:

Of course, we can now also visualize the unsupervised clusters based on their spatial location. Note that running SpatialDimPlot(object, interactive = TRUE), also enables interactive visualization and exploration.

When there are many different clusters (some of which are spatially restricted and others are mixed), plotting the spatial location of all clusters can be challenging to interpret. We find it helpful to plot the spatial location of different clusters individually. For example, we highlight the spatial localization of a few clusters below, which happen to correspond to different cortical layers:

We can also find and visualize the top gene expression markers for each cluster:

While the previous analyses consider each bin independently, spatial data enables cells to be defined not just by their neighborhood, but also by their broader spatial context.

In Singhal et al., the authors introduce BANKSY, Building Aggregates with a Neighborhood Kernel and Spatial Yardstick (BANKSY). BANKSY performs multiple tasks, but we find it particularly valuable for identifying and segmenting tissue domains. When performing clustering, BANKSY augments a spot’s expression pattern with both the mean and the gradient of gene expression levels in a spot’s broader neighborhood.

We thank the authors for enabling BANKSY to be compatible with Seurat via the SeuratWrappers framework, which requires separate installation of the BANKSY package:

Before running BANKSY, there are two important model parameters that users should consider:

The RunBanksy function creates a new BANKSY assay, which can be used for dimensional reduction and clustering:

As with unsupervised clustering, we can highlight the spatial location of each tissue domain individually:

Users may wish to segment or subset out a restricted region for further downstream analysis. For example, here we create a coordinate-defined segmentation mask marking cortical and hippocampal regions from the entire dataset using the CreateSegmentation function, and then identify cells that fall into this region with the Overlay function.

The list of coordinates is available for download here, and users can identify these boundaries when exploring their own datasets using the interactive=TRUE argument to SpatialDimPlot.

Seurat v5 also includes support for Robust Cell Type Decomposition, a computational approach to deconvolve spot-level data from spatial datasets, when provided with an scRNA-seq reference. RCTD has been shown to accurately annotate spatial data from a variety of technologies, including SLIDE-seq, Visium, and the 10x Xenium in-situ spatial platform. We observe good performance with Visium HD as well.

To run RCTD, we first install the spacexr package from GitHub which implements RCTD. When running RCTD, we follow the instructions from the RCTD vignette.

RCTD takes an scRNA-seq dataset as a reference, and a spatial dataset as a query. For a reference, we use a mouse scRNA-seq dataset from the Allen Brain Atlas, available for download here. The reference scRNAs-eq dataset has been reduced to 200,000 cells (and rare cell types <25 cells have been removed).

We use the cortex Visium HD object as the spatial query. For computational efficiency, we sketch the spatial query dataset, apply RCTD to deconvolute the ‘sketched’ cortical cells and annotate them, and then project these annotations to the full cortical dataset.

We can now look for associations between the scRNA-seq labels of individual bins, and their tissue domain identity (as assigned by BANKSY). By asking which domains the excitatory neuron cells fall in, we can rename the BANKSY clusters as neuronal layers:

Based on this plot, we can now assign cells (even if they are not excitatory neurons) to individual neuronal layers.

Finally, we can visualize the spatial distribution of other cell types, and ask which cortical layers they fall in. For example, in contrast to excitatory neurons, inhibitory (GABAergic) interneurons in the cortex are not spatially restricted to individual layers - but they do show biases.

In our previous analysis of STARmap data, and consistent with previous work, we found that SST and PV interneuron classes tend to be restricted to layers 4-6, while VIP and Lamp5 interneurons tend to be located in layers 2/3. These results were based on an in-situ imaging technology which captures single-cell profiles - and here we ask whether we can find the same result in Visium HD spot-based data.

We recapitulate the same findings, previously identified in in-situ imaging data, in the Visium HD dataset. This highlights that the 8um binning of Visium HD, even though it does not represent true single cell resolution, is capable of accurately localizing scRNA-seq-defined cell types, although we strongly encourage users to orthogonally validate unexpected or surprising biological findings.

We briefly demonstrate our sketch-clustering workflow on a second Visium HD dataset, from the Mouse Small Intestine (FFPE), available for download here. We identify clusters, visualize their spatial locations, and report their top gene expression markers:

We visualize the location of each cluster individually:

Developed by Madeline Kowalski, Harm Wessels.

Site built with pkgdown 2.0.7.

**Examples:**

Example 1 (unknown):
```unknown
vignettes/visiumhd_analysis_vignette.Rmd
```

Example 2 (unknown):
```unknown
visiumhd_analysis_vignette.Rmd
```

Example 3 (unknown):
```unknown
# packages required for Visium HD
install.packages("hdf5r")
install.packages("arrow")
```

Example 4 (r):
```r
# packages required for Visium HD
install.packages("hdf5r")
install.packages("arrow")
```

Example 5 (r):
```r
# packages required for Visium HD
install.packages("hdf5r")
install.packages("arrow")
```

Example 6 (unknown):
```unknown
library(Seurat)
library(ggplot2)
library(patchwork)
library(dplyr)
```

Example 7 (r):
```r
library(Seurat)
library(ggplot2)
library(patchwork)
library(dplyr)
```

Example 8 (r):
```r
library(Seurat)
library(ggplot2)
library(patchwork)
library(dplyr)
```

Example 9 (unknown):
```unknown
localdir <- "/brahms/lis/visium_hd/mouse/new_mousebrain/"
object <- Load10X_Spatial(data.dir = localdir, bin.size = c(8, 16))

# Setting default assay changes between 8um and 16um binning
Assays(object)
DefaultAssay(object) <- "Spatial.008um"
```

Example 10 (r):
```r
localdir <- "/brahms/lis/visium_hd/mouse/new_mousebrain/"
object <- Load10X_Spatial(data.dir = localdir, bin.size = c(8, 16))

# Setting default assay changes between 8um and 16um binning
Assays(object)
DefaultAssay(object) <- "Spatial.008um"
```

Example 11 (r):
```r
localdir <- "/brahms/lis/visium_hd/mouse/new_mousebrain/"
object <- Load10X_Spatial(data.dir = localdir, bin.size = c(8, 16))

# Setting default assay changes between 8um and 16um binning
Assays(object)
DefaultAssay(object) <- "Spatial.008um"
```

Example 12 (unknown):
```unknown
vln.plot <- VlnPlot(object, features = "nCount_Spatial.008um", pt.size = 0) + theme(axis.text = element_text(size = 4)) + NoLegend()
count.plot <- SpatialFeaturePlot(object, features = "nCount_Spatial.008um") + theme(legend.position = "right")

# note that many spots have very few counts, in-part
# due to low cellular density in certain tissue regions
vln.plot | count.plot
```

Example 13 (r):
```r
vln.plot <- VlnPlot(object, features = "nCount_Spatial.008um", pt.size = 0) + theme(axis.text = element_text(size = 4)) + NoLegend()
count.plot <- SpatialFeaturePlot(object, features = "nCount_Spatial.008um") + theme(legend.position = "right")

# note that many spots have very few counts, in-part
# due to low cellular density in certain tissue regions
vln.plot | count.plot
```

Example 14 (r):
```r
vln.plot <- VlnPlot(object, features = "nCount_Spatial.008um", pt.size = 0) + theme(axis.text = element_text(size = 4)) + NoLegend()
count.plot <- SpatialFeaturePlot(object, features = "nCount_Spatial.008um") + theme(legend.position = "right")

# note that many spots have very few counts, in-part
# due to low cellular density in certain tissue regions
vln.plot | count.plot
```

Example 15 (unknown):
```unknown
# normalize both 8um and 16um bins
DefaultAssay(object) <- "Spatial.008um"
object <- NormalizeData(object)

DefaultAssay(object) <- "Spatial.016um"
object <- NormalizeData(object)
```

Example 16 (r):
```r
# normalize both 8um and 16um bins
DefaultAssay(object) <- "Spatial.008um"
object <- NormalizeData(object)

DefaultAssay(object) <- "Spatial.016um"
object <- NormalizeData(object)
```

Example 17 (r):
```r
# normalize both 8um and 16um bins
DefaultAssay(object) <- "Spatial.008um"
object <- NormalizeData(object)

DefaultAssay(object) <- "Spatial.016um"
object <- NormalizeData(object)
```

Example 18 (unknown):
```unknown
pt.size.factor
```

Example 19 (python):
```python
# switch spatial resolution to 16um from 8um
DefaultAssay(object) <- "Spatial.016um"
p1 <- SpatialFeaturePlot(object, features = "Rorb") + ggtitle("Rorb expression (16um)")

# switch back to 8um
DefaultAssay(object) <- "Spatial.008um"
p2 <- SpatialFeaturePlot(object, features = "Hpca") + ggtitle("Hpca expression (8um)")

p1 | p2
```

Example 20 (r):
```r
# switch spatial resolution to 16um from 8um
DefaultAssay(object) <- "Spatial.016um"
p1 <- SpatialFeaturePlot(object, features = "Rorb") + ggtitle("Rorb expression (16um)")

# switch back to 8um
DefaultAssay(object) <- "Spatial.008um"
p2 <- SpatialFeaturePlot(object, features = "Hpca") + ggtitle("Hpca expression (8um)")

p1 | p2
```

Example 21 (r):
```r
# switch spatial resolution to 16um from 8um
DefaultAssay(object) <- "Spatial.016um"
p1 <- SpatialFeaturePlot(object, features = "Rorb") + ggtitle("Rorb expression (16um)")

# switch back to 8um
DefaultAssay(object) <- "Spatial.008um"
p2 <- SpatialFeaturePlot(object, features = "Hpca") + ggtitle("Hpca expression (8um)")

p1 | p2
```

Example 22 (unknown):
```unknown
# note that data is already normalized
DefaultAssay(object) <- "Spatial.008um"
object <- FindVariableFeatures(object)
object <- ScaleData(object)
# we select 50,0000 cells and create a new 'sketch' assay
object <- SketchData(
  object = object,
  ncells = 50000,
  method = "LeverageScore",
  sketched.assay = "sketch"
)
```

Example 23 (r):
```r
# note that data is already normalized
DefaultAssay(object) <- "Spatial.008um"
object <- FindVariableFeatures(object)
object <- ScaleData(object)
# we select 50,0000 cells and create a new 'sketch' assay
object <- SketchData(
  object = object,
  ncells = 50000,
  method = "LeverageScore",
  sketched.assay = "sketch"
)
```

Example 24 (r):
```r
# note that data is already normalized
DefaultAssay(object) <- "Spatial.008um"
object <- FindVariableFeatures(object)
object <- ScaleData(object)
# we select 50,0000 cells and create a new 'sketch' assay
object <- SketchData(
  object = object,
  ncells = 50000,
  method = "LeverageScore",
  sketched.assay = "sketch"
)
```

Example 25 (unknown):
```unknown
# switch analysis to sketched cells
DefaultAssay(object) <- "sketch"

# perform clustering workflow
object <- FindVariableFeatures(object)
object <- ScaleData(object)
object <- RunPCA(object, assay = "sketch", reduction.name = "pca.sketch")
object <- FindNeighbors(object, assay = "sketch", reduction = "pca.sketch", dims = 1:50)
object <- FindClusters(object, cluster.name = "seurat_cluster.sketched", resolution = 3)
object <- RunUMAP(object, reduction = "pca.sketch", reduction.name = "umap.sketch", return.model = T, dims = 1:50)
```

Example 26 (r):
```r
# switch analysis to sketched cells
DefaultAssay(object) <- "sketch"

# perform clustering workflow
object <- FindVariableFeatures(object)
object <- ScaleData(object)
object <- RunPCA(object, assay = "sketch", reduction.name = "pca.sketch")
object <- FindNeighbors(object, assay = "sketch", reduction = "pca.sketch", dims = 1:50)
object <- FindClusters(object, cluster.name = "seurat_cluster.sketched", resolution = 3)
object <- RunUMAP(object, reduction = "pca.sketch", reduction.name = "umap.sketch", return.model = T, dims = 1:50)
```

Example 27 (r):
```r
# switch analysis to sketched cells
DefaultAssay(object) <- "sketch"

# perform clustering workflow
object <- FindVariableFeatures(object)
object <- ScaleData(object)
object <- RunPCA(object, assay = "sketch", reduction.name = "pca.sketch")
object <- FindNeighbors(object, assay = "sketch", reduction = "pca.sketch", dims = 1:50)
object <- FindClusters(object, cluster.name = "seurat_cluster.sketched", resolution = 3)
object <- RunUMAP(object, reduction = "pca.sketch", reduction.name = "umap.sketch", return.model = T, dims = 1:50)
```

Example 28 (unknown):
```unknown
ProjectData
```

Example 29 (unknown):
```unknown
object$seurat_cluster.projected
```

Example 30 (unknown):
```unknown
object[["pca.008um"]]
```

Example 31 (unknown):
```unknown
object[["umap.sketch"]]
```

Example 32 (unknown):
```unknown
object <- ProjectData(
  object = object,
  assay = "Spatial.008um",
  full.reduction = "full.pca.sketch",
  sketched.assay = "sketch",
  sketched.reduction = "pca.sketch",
  umap.model = "umap.sketch",
  dims = 1:50,
  refdata = list(seurat_cluster.projected = "seurat_cluster.sketched")
)
```

Example 33 (r):
```r
object <- ProjectData(
  object = object,
  assay = "Spatial.008um",
  full.reduction = "full.pca.sketch",
  sketched.assay = "sketch",
  sketched.reduction = "pca.sketch",
  umap.model = "umap.sketch",
  dims = 1:50,
  refdata = list(seurat_cluster.projected = "seurat_cluster.sketched")
)
```

Example 34 (r):
```r
object <- ProjectData(
  object = object,
  assay = "Spatial.008um",
  full.reduction = "full.pca.sketch",
  sketched.assay = "sketch",
  sketched.reduction = "pca.sketch",
  umap.model = "umap.sketch",
  dims = 1:50,
  refdata = list(seurat_cluster.projected = "seurat_cluster.sketched")
)
```

Example 35 (unknown):
```unknown
DefaultAssay(object) <- "sketch"
Idents(object) <- "seurat_cluster.sketched"
p1 <- DimPlot(object, reduction = "umap.sketch", label = F) + ggtitle("Sketched clustering (50,000 cells)") + theme(legend.position = "bottom")

# switch to full dataset
DefaultAssay(object) <- "Spatial.008um"
Idents(object) <- "seurat_cluster.projected"
p2 <- DimPlot(object, reduction = "full.umap.sketch", label = F) + ggtitle("Projected clustering (full dataset)") + theme(legend.position = "bottom")

p1 | p2
```

Example 36 (r):
```r
DefaultAssay(object) <- "sketch"
Idents(object) <- "seurat_cluster.sketched"
p1 <- DimPlot(object, reduction = "umap.sketch", label = F) + ggtitle("Sketched clustering (50,000 cells)") + theme(legend.position = "bottom")

# switch to full dataset
DefaultAssay(object) <- "Spatial.008um"
Idents(object) <- "seurat_cluster.projected"
p2 <- DimPlot(object, reduction = "full.umap.sketch", label = F) + ggtitle("Projected clustering (full dataset)") + theme(legend.position = "bottom")

p1 | p2
```

Example 37 (r):
```r
DefaultAssay(object) <- "sketch"
Idents(object) <- "seurat_cluster.sketched"
p1 <- DimPlot(object, reduction = "umap.sketch", label = F) + ggtitle("Sketched clustering (50,000 cells)") + theme(legend.position = "bottom")

# switch to full dataset
DefaultAssay(object) <- "Spatial.008um"
Idents(object) <- "seurat_cluster.projected"
p2 <- DimPlot(object, reduction = "full.umap.sketch", label = F) + ggtitle("Projected clustering (full dataset)") + theme(legend.position = "bottom")

p1 | p2
```

Example 38 (unknown):
```unknown
SpatialDimPlot(object, interactive = TRUE)
```

Example 39 (unknown):
```unknown
SpatialDimPlot(object, label = T, repel = T, label.size = 4)
```

Example 40 (r):
```r
SpatialDimPlot(object, label = T, repel = T, label.size = 4)
```

Example 41 (r):
```r
SpatialDimPlot(object, label = T, repel = T, label.size = 4)
```

Example 42 (unknown):
```unknown
Idents(object) <- "seurat_cluster.projected"
cells <- CellsByIdentities(object, idents = c(0, 4, 32, 34, 35))
p <- SpatialDimPlot(object,
  cells.highlight = cells[setdiff(names(cells), "NA")],
  cols.highlight = c("#FFFF00", "grey50"), facet.highlight = T, combine = T
) + NoLegend()
p
```

Example 43 (r):
```r
Idents(object) <- "seurat_cluster.projected"
cells <- CellsByIdentities(object, idents = c(0, 4, 32, 34, 35))
p <- SpatialDimPlot(object,
  cells.highlight = cells[setdiff(names(cells), "NA")],
  cols.highlight = c("#FFFF00", "grey50"), facet.highlight = T, combine = T
) + NoLegend()
p
```

Example 44 (r):
```r
Idents(object) <- "seurat_cluster.projected"
cells <- CellsByIdentities(object, idents = c(0, 4, 32, 34, 35))
p <- SpatialDimPlot(object,
  cells.highlight = cells[setdiff(names(cells), "NA")],
  cols.highlight = c("#FFFF00", "grey50"), facet.highlight = T, combine = T
) + NoLegend()
p
```

Example 45 (unknown):
```unknown
# Crete downsampled object to make visualization either
DefaultAssay(object) <- "Spatial.008um"
Idents(object) <- "seurat_cluster.projected"
object_subset <- subset(object, cells = Cells(object[["Spatial.008um"]]), downsample = 1000)

# Order clusters by similarity
DefaultAssay(object_subset) <- "Spatial.008um"
Idents(object_subset) <- "seurat_cluster.projected"
object_subset <- BuildClusterTree(object_subset, assay = "Spatial.008um", reduction = "full.pca.sketch", reorder = T)

markers <- FindAllMarkers(object_subset, assay = "Spatial.008um", only.pos = TRUE)
markers %>%
  group_by(cluster) %>%
  dplyr::filter(avg_log2FC > 1) %>%
  slice_head(n = 5) %>%
  ungroup() -> top5

object_subset <- ScaleData(object_subset, assay = "Spatial.008um", features = top5$gene)
p <- DoHeatmap(object_subset, assay = "Spatial.008um", features = top5$gene, size = 2.5) + theme(axis.text = element_text(size = 5.5)) + NoLegend()
p
```

Example 46 (r):
```r
# Crete downsampled object to make visualization either
DefaultAssay(object) <- "Spatial.008um"
Idents(object) <- "seurat_cluster.projected"
object_subset <- subset(object, cells = Cells(object[["Spatial.008um"]]), downsample = 1000)

# Order clusters by similarity
DefaultAssay(object_subset) <- "Spatial.008um"
Idents(object_subset) <- "seurat_cluster.projected"
object_subset <- BuildClusterTree(object_subset, assay = "Spatial.008um", reduction = "full.pca.sketch", reorder = T)

markers <- FindAllMarkers(object_subset, assay = "Spatial.008um", only.pos = TRUE)
markers %>%
  group_by(cluster) %>%
  dplyr::filter(avg_log2FC > 1) %>%
  slice_head(n = 5) %>%
  ungroup() -> top5

object_subset <- ScaleData(object_subset, assay = "Spatial.008um", features = top5$gene)
p <- DoHeatmap(object_subset, assay = "Spatial.008um", features = top5$gene, size = 2.5) + theme(axis.text = element_text(size = 5.5)) + NoLegend()
p
```

Example 47 (r):
```r
# Crete downsampled object to make visualization either
DefaultAssay(object) <- "Spatial.008um"
Idents(object) <- "seurat_cluster.projected"
object_subset <- subset(object, cells = Cells(object[["Spatial.008um"]]), downsample = 1000)

# Order clusters by similarity
DefaultAssay(object_subset) <- "Spatial.008um"
Idents(object_subset) <- "seurat_cluster.projected"
object_subset <- BuildClusterTree(object_subset, assay = "Spatial.008um", reduction = "full.pca.sketch", reorder = T)

markers <- FindAllMarkers(object_subset, assay = "Spatial.008um", only.pos = TRUE)
markers %>%
  group_by(cluster) %>%
  dplyr::filter(avg_log2FC > 1) %>%
  slice_head(n = 5) %>%
  ungroup() -> top5

object_subset <- ScaleData(object_subset, assay = "Spatial.008um", features = top5$gene)
p <- DoHeatmap(object_subset, assay = "Spatial.008um", features = top5$gene, size = 2.5) + theme(axis.text = element_text(size = 5.5)) + NoLegend()
p
```

Example 48 (unknown):
```unknown
SeuratWrappers
```

Example 49 (unknown):
```unknown
if (!requireNamespace("Banksy", quietly = TRUE)) {
  remotes::install_github("prabhakarlab/Banksy@devel")
}
library(SeuratWrappers)
library(Banksy)
```

Example 50 (r):
```r
if (!requireNamespace("Banksy", quietly = TRUE)) {
  remotes::install_github("prabhakarlab/Banksy@devel")
}
library(SeuratWrappers)
library(Banksy)
```

Example 51 (r):
```r
if (!requireNamespace("Banksy", quietly = TRUE)) {
  remotes::install_github("prabhakarlab/Banksy@devel")
}
library(SeuratWrappers)
library(Banksy)
```

Example 52 (unknown):
```unknown
object <- RunBanksy(object,
  lambda = 0.8, verbose = TRUE,
  assay = "Spatial.008um", slot = "data", features = "variable",
  k_geom = 50
)
```

Example 53 (r):
```r
object <- RunBanksy(object,
  lambda = 0.8, verbose = TRUE,
  assay = "Spatial.008um", slot = "data", features = "variable",
  k_geom = 50
)
```

Example 54 (r):
```r
object <- RunBanksy(object,
  lambda = 0.8, verbose = TRUE,
  assay = "Spatial.008um", slot = "data", features = "variable",
  k_geom = 50
)
```

Example 55 (unknown):
```unknown
DefaultAssay(object) <- "BANKSY"
object <- RunPCA(object, assay = "BANKSY", reduction.name = "pca.banksy", features = rownames(object), npcs = 30)
object <- FindNeighbors(object, reduction = "pca.banksy", dims = 1:30)
object <- FindClusters(object, cluster.name = "banksy_cluster", resolution = 0.5)
```

Example 56 (r):
```r
DefaultAssay(object) <- "BANKSY"
object <- RunPCA(object, assay = "BANKSY", reduction.name = "pca.banksy", features = rownames(object), npcs = 30)
object <- FindNeighbors(object, reduction = "pca.banksy", dims = 1:30)
object <- FindClusters(object, cluster.name = "banksy_cluster", resolution = 0.5)
```

Example 57 (r):
```r
DefaultAssay(object) <- "BANKSY"
object <- RunPCA(object, assay = "BANKSY", reduction.name = "pca.banksy", features = rownames(object), npcs = 30)
object <- FindNeighbors(object, reduction = "pca.banksy", dims = 1:30)
object <- FindClusters(object, cluster.name = "banksy_cluster", resolution = 0.5)
```

Example 58 (unknown):
```unknown
Idents(object) <- "banksy_cluster"
p <- SpatialDimPlot(object, group.by = "banksy_cluster", label = T, repel = T, label.size = 4)
p
```

Example 59 (r):
```r
Idents(object) <- "banksy_cluster"
p <- SpatialDimPlot(object, group.by = "banksy_cluster", label = T, repel = T, label.size = 4)
p
```

Example 60 (r):
```r
Idents(object) <- "banksy_cluster"
p <- SpatialDimPlot(object, group.by = "banksy_cluster", label = T, repel = T, label.size = 4)
p
```

Example 61 (unknown):
```unknown
banksy_cells <- CellsByIdentities(object)
p <- SpatialDimPlot(object, cells.highlight = banksy_cells[setdiff(names(banksy_cells), "NA")], cols.highlight = c("#FFFF00", "grey50"), facet.highlight = T, combine = T) + NoLegend()
p
```

Example 62 (r):
```r
banksy_cells <- CellsByIdentities(object)
p <- SpatialDimPlot(object, cells.highlight = banksy_cells[setdiff(names(banksy_cells), "NA")], cols.highlight = c("#FFFF00", "grey50"), facet.highlight = T, combine = T) + NoLegend()
p
```

Example 63 (r):
```r
banksy_cells <- CellsByIdentities(object)
p <- SpatialDimPlot(object, cells.highlight = banksy_cells[setdiff(names(banksy_cells), "NA")], cols.highlight = c("#FFFF00", "grey50"), facet.highlight = T, combine = T) + NoLegend()
p
```

Example 64 (unknown):
```unknown
CreateSegmentation
```

Example 65 (unknown):
```unknown
interactive=TRUE
```

Example 66 (unknown):
```unknown
SpatialDimPlot
```

Example 67 (unknown):
```unknown
cortex.coordinates <- as.data.frame(read.csv("/brahms/lis/visium_hd/final_mouse/cortex-hippocampus_coordinates.csv"))
cortex <- CreateSegmentation(cortex.coordinates)

object[["cortex"]] <- Overlay(object[["slice1.008um"]], cortex)
cortex <- subset(object, cells = Cells(object[["cortex"]]))
```

Example 68 (r):
```r
cortex.coordinates <- as.data.frame(read.csv("/brahms/lis/visium_hd/final_mouse/cortex-hippocampus_coordinates.csv"))
cortex <- CreateSegmentation(cortex.coordinates)

object[["cortex"]] <- Overlay(object[["slice1.008um"]], cortex)
cortex <- subset(object, cells = Cells(object[["cortex"]]))
```

Example 69 (r):
```r
cortex.coordinates <- as.data.frame(read.csv("/brahms/lis/visium_hd/final_mouse/cortex-hippocampus_coordinates.csv"))
cortex <- CreateSegmentation(cortex.coordinates)

object[["cortex"]] <- Overlay(object[["slice1.008um"]], cortex)
cortex <- subset(object, cells = Cells(object[["cortex"]]))
```

Example 70 (unknown):
```unknown
if (!requireNamespace("spacexr", quietly = TRUE)) {
  devtools::install_github("dmcable/spacexr", build_vignettes = FALSE)
}
library(spacexr)
```

Example 71 (r):
```r
if (!requireNamespace("spacexr", quietly = TRUE)) {
  devtools::install_github("dmcable/spacexr", build_vignettes = FALSE)
}
library(spacexr)
```

Example 72 (r):
```r
if (!requireNamespace("spacexr", quietly = TRUE)) {
  devtools::install_github("dmcable/spacexr", build_vignettes = FALSE)
}
library(spacexr)
```

Example 73 (unknown):
```unknown
# sketch the cortical subset of the Visium HD dataset
DefaultAssay(cortex) <- "Spatial.008um"
cortex <- FindVariableFeatures(cortex)
cortex <- SketchData(
  object = cortex,
  ncells = 50000,
  method = "LeverageScore",
  sketched.assay = "sketch"
)

DefaultAssay(cortex) <- "sketch"
cortex <- ScaleData(cortex)
cortex <- RunPCA(cortex, assay = "sketch", reduction.name = "pca.cortex.sketch", verbose = T)
cortex <- FindNeighbors(cortex, reduction = "pca.cortex.sketch", dims = 1:50)
cortex <- RunUMAP(cortex, reduction = "pca.cortex.sketch", reduction.name = "umap.cortex.sketch", return.model = T, dims = 1:50, verbose = T)
```

Example 74 (r):
```r
# sketch the cortical subset of the Visium HD dataset
DefaultAssay(cortex) <- "Spatial.008um"
cortex <- FindVariableFeatures(cortex)
cortex <- SketchData(
  object = cortex,
  ncells = 50000,
  method = "LeverageScore",
  sketched.assay = "sketch"
)

DefaultAssay(cortex) <- "sketch"
cortex <- ScaleData(cortex)
cortex <- RunPCA(cortex, assay = "sketch", reduction.name = "pca.cortex.sketch", verbose = T)
cortex <- FindNeighbors(cortex, reduction = "pca.cortex.sketch", dims = 1:50)
cortex <- RunUMAP(cortex, reduction = "pca.cortex.sketch", reduction.name = "umap.cortex.sketch", return.model = T, dims = 1:50, verbose = T)
```

Example 75 (r):
```r
# sketch the cortical subset of the Visium HD dataset
DefaultAssay(cortex) <- "Spatial.008um"
cortex <- FindVariableFeatures(cortex)
cortex <- SketchData(
  object = cortex,
  ncells = 50000,
  method = "LeverageScore",
  sketched.assay = "sketch"
)

DefaultAssay(cortex) <- "sketch"
cortex <- ScaleData(cortex)
cortex <- RunPCA(cortex, assay = "sketch", reduction.name = "pca.cortex.sketch", verbose = T)
cortex <- FindNeighbors(cortex, reduction = "pca.cortex.sketch", dims = 1:50)
cortex <- RunUMAP(cortex, reduction = "pca.cortex.sketch", reduction.name = "umap.cortex.sketch", return.model = T, dims = 1:50, verbose = T)
```

Example 76 (unknown):
```unknown
# load in the reference scRNA-seq dataset
ref <- readRDS("/brahms/satijar/allen_scRNAseq_ref.Rds")
```

Example 77 (r):
```r
# load in the reference scRNA-seq dataset
ref <- readRDS("/brahms/satijar/allen_scRNAseq_ref.Rds")
```

Example 78 (r):
```r
# load in the reference scRNA-seq dataset
ref <- readRDS("/brahms/satijar/allen_scRNAseq_ref.Rds")
```

Example 79 (unknown):
```unknown
Idents(ref) <- "subclass_label"
counts <- ref[["RNA"]]$counts
cluster <- as.factor(ref$subclass_label)
nUMI <- ref$nCount_RNA
levels(cluster) <- gsub("/", "-", levels(cluster))
cluster <- droplevels(cluster)

# create the RCTD reference object
reference <- Reference(counts, cluster, nUMI)

counts_hd <- cortex[["sketch"]]$counts
cortex_cells_hd <- colnames(cortex[["sketch"]])
coords <- GetTissueCoordinates(cortex)[cortex_cells_hd, 1:2]

# create the RCTD query object
query <- SpatialRNA(coords, counts_hd, colSums(counts_hd))
```

Example 80 (r):
```r
Idents(ref) <- "subclass_label"
counts <- ref[["RNA"]]$counts
cluster <- as.factor(ref$subclass_label)
nUMI <- ref$nCount_RNA
levels(cluster) <- gsub("/", "-", levels(cluster))
cluster <- droplevels(cluster)

# create the RCTD reference object
reference <- Reference(counts, cluster, nUMI)

counts_hd <- cortex[["sketch"]]$counts
cortex_cells_hd <- colnames(cortex[["sketch"]])
coords <- GetTissueCoordinates(cortex)[cortex_cells_hd, 1:2]

# create the RCTD query object
query <- SpatialRNA(coords, counts_hd, colSums(counts_hd))
```

Example 81 (r):
```r
Idents(ref) <- "subclass_label"
counts <- ref[["RNA"]]$counts
cluster <- as.factor(ref$subclass_label)
nUMI <- ref$nCount_RNA
levels(cluster) <- gsub("/", "-", levels(cluster))
cluster <- droplevels(cluster)

# create the RCTD reference object
reference <- Reference(counts, cluster, nUMI)

counts_hd <- cortex[["sketch"]]$counts
cortex_cells_hd <- colnames(cortex[["sketch"]])
coords <- GetTissueCoordinates(cortex)[cortex_cells_hd, 1:2]

# create the RCTD query object
query <- SpatialRNA(coords, counts_hd, colSums(counts_hd))
```

Example 82 (python):
```python
# run RCTD
RCTD <- create.RCTD(query, reference, max_cores = 28)
RCTD <- run.RCTD(RCTD, doublet_mode = "doublet")
# add results back to Seurat object
cortex <- AddMetaData(cortex, metadata = RCTD@results$results_df)
```

Example 83 (r):
```r
# run RCTD
RCTD <- create.RCTD(query, reference, max_cores = 28)
RCTD <- run.RCTD(RCTD, doublet_mode = "doublet")
# add results back to Seurat object
cortex <- AddMetaData(cortex, metadata = RCTD@results$results_df)
```

Example 84 (r):
```r
# run RCTD
RCTD <- create.RCTD(query, reference, max_cores = 28)
RCTD <- run.RCTD(RCTD, doublet_mode = "doublet")
# add results back to Seurat object
cortex <- AddMetaData(cortex, metadata = RCTD@results$results_df)
```

Example 85 (python):
```python
# project RCTD labels from sketched cortical cells to all cortical cells
cortex$first_type <- as.character(cortex$first_type)
cortex$first_type[is.na(cortex$first_type)] <- "Unknown"
cortex <- ProjectData(
  object = cortex,
  assay = "Spatial.008um",
  full.reduction = "pca.cortex",
  sketched.assay = "sketch",
  sketched.reduction = "pca.cortex.sketch",
  umap.model = "umap.cortex.sketch",
  dims = 1:50,
  refdata = list(full_first_type = "first_type")
)
```

Example 86 (r):
```r
# project RCTD labels from sketched cortical cells to all cortical cells
cortex$first_type <- as.character(cortex$first_type)
cortex$first_type[is.na(cortex$first_type)] <- "Unknown"
cortex <- ProjectData(
  object = cortex,
  assay = "Spatial.008um",
  full.reduction = "pca.cortex",
  sketched.assay = "sketch",
  sketched.reduction = "pca.cortex.sketch",
  umap.model = "umap.cortex.sketch",
  dims = 1:50,
  refdata = list(full_first_type = "first_type")
)
```

Example 87 (r):
```r
# project RCTD labels from sketched cortical cells to all cortical cells
cortex$first_type <- as.character(cortex$first_type)
cortex$first_type[is.na(cortex$first_type)] <- "Unknown"
cortex <- ProjectData(
  object = cortex,
  assay = "Spatial.008um",
  full.reduction = "pca.cortex",
  sketched.assay = "sketch",
  sketched.reduction = "pca.cortex.sketch",
  umap.model = "umap.cortex.sketch",
  dims = 1:50,
  refdata = list(full_first_type = "first_type")
)
```

Example 88 (unknown):
```unknown
DefaultAssay(object) <- "Spatial.008um"

# we only ran RCTD on the cortical cells
# set labels to all other cells as "Unknown"
object[[]][, "full_first_type"] <- "Unknown"
object$full_first_type[Cells(cortex)] <- cortex$full_first_type[Cells(cortex)]
```

Example 89 (r):
```r
DefaultAssay(object) <- "Spatial.008um"

# we only ran RCTD on the cortical cells
# set labels to all other cells as "Unknown"
object[[]][, "full_first_type"] <- "Unknown"
object$full_first_type[Cells(cortex)] <- cortex$full_first_type[Cells(cortex)]
```

Example 90 (r):
```r
DefaultAssay(object) <- "Spatial.008um"

# we only ran RCTD on the cortical cells
# set labels to all other cells as "Unknown"
object[[]][, "full_first_type"] <- "Unknown"
object$full_first_type[Cells(cortex)] <- cortex$full_first_type[Cells(cortex)]
```

Example 91 (unknown):
```unknown
Idents(object) <- "full_first_type"

# now we can spatially map the location of any scRNA-seq cell type
# start with Layered (starts with L), excitatory neurons in the cortex
cells <- CellsByIdentities(object)
excitatory_names <- sort(grep("^L.* CTX", names(cells), value = TRUE))
p <- SpatialDimPlot(object, cells.highlight = cells[excitatory_names], cols.highlight = c("#FFFF00", "grey50"), facet.highlight = T, combine = T, ncol = 4)
p
```

Example 92 (r):
```r
Idents(object) <- "full_first_type"

# now we can spatially map the location of any scRNA-seq cell type
# start with Layered (starts with L), excitatory neurons in the cortex
cells <- CellsByIdentities(object)
excitatory_names <- sort(grep("^L.* CTX", names(cells), value = TRUE))
p <- SpatialDimPlot(object, cells.highlight = cells[excitatory_names], cols.highlight = c("#FFFF00", "grey50"), facet.highlight = T, combine = T, ncol = 4)
p
```

Example 93 (r):
```r
Idents(object) <- "full_first_type"

# now we can spatially map the location of any scRNA-seq cell type
# start with Layered (starts with L), excitatory neurons in the cortex
cells <- CellsByIdentities(object)
excitatory_names <- sort(grep("^L.* CTX", names(cells), value = TRUE))
p <- SpatialDimPlot(object, cells.highlight = cells[excitatory_names], cols.highlight = c("#FFFF00", "grey50"), facet.highlight = T, combine = T, ncol = 4)
p
```

Example 94 (javascript):
```javascript
plot_cell_types <- function(data, label) {
  p <- ggplot(data, aes(x = get(label), y = n, fill = full_first_type)) +
    geom_bar(stat = "identity", position = "stack") +
    geom_text(aes(label = ifelse(n >= min_count_to_show_label, full_first_type, "")), position = position_stack(vjust = 0.5), size = 2) +
    xlab(label) +
    ylab("# of Spots") +
    ggtitle(paste0("Distribution of Cell Types across ", label)) +
    theme_minimal()
}

cell_type_banksy_counts <- object[[]] %>%
  dplyr::filter(full_first_type %in% excitatory_names) %>%
  dplyr::count(full_first_type, banksy_cluster)

min_count_to_show_label <- 20

p <- plot_cell_types(cell_type_banksy_counts, "banksy_cluster")
p
```

Example 95 (r):
```r
plot_cell_types <- function(data, label) {
  p <- ggplot(data, aes(x = get(label), y = n, fill = full_first_type)) +
    geom_bar(stat = "identity", position = "stack") +
    geom_text(aes(label = ifelse(n >= min_count_to_show_label, full_first_type, "")), position = position_stack(vjust = 0.5), size = 2) +
    xlab(label) +
    ylab("# of Spots") +
    ggtitle(paste0("Distribution of Cell Types across ", label)) +
    theme_minimal()
}

cell_type_banksy_counts <- object[[]] %>%
  dplyr::filter(full_first_type %in% excitatory_names) %>%
  dplyr::count(full_first_type, banksy_cluster)

min_count_to_show_label <- 20

p <- plot_cell_types(cell_type_banksy_counts, "banksy_cluster")
p
```

Example 96 (r):
```r
plot_cell_types <- function(data, label) {
  p <- ggplot(data, aes(x = get(label), y = n, fill = full_first_type)) +
    geom_bar(stat = "identity", position = "stack") +
    geom_text(aes(label = ifelse(n >= min_count_to_show_label, full_first_type, "")), position = position_stack(vjust = 0.5), size = 2) +
    xlab(label) +
    ylab("# of Spots") +
    ggtitle(paste0("Distribution of Cell Types across ", label)) +
    theme_minimal()
}

cell_type_banksy_counts <- object[[]] %>%
  dplyr::filter(full_first_type %in% excitatory_names) %>%
  dplyr::count(full_first_type, banksy_cluster)

min_count_to_show_label <- 20

p <- plot_cell_types(cell_type_banksy_counts, "banksy_cluster")
p
```

Example 97 (unknown):
```unknown
Idents(object) <- "banksy_cluster"
object$layer_id <- "Unknown"
object$layer_id[WhichCells(object, idents = c(7))] <- "Layer 2/3"
object$layer_id[WhichCells(object, idents = c(15))] <- "Layer 4"
object$layer_id[WhichCells(object, idents = c(5))] <- "Layer 5"
object$layer_id[WhichCells(object, idents = c(1))] <- "Layer 6"
```

Example 98 (r):
```r
Idents(object) <- "banksy_cluster"
object$layer_id <- "Unknown"
object$layer_id[WhichCells(object, idents = c(7))] <- "Layer 2/3"
object$layer_id[WhichCells(object, idents = c(15))] <- "Layer 4"
object$layer_id[WhichCells(object, idents = c(5))] <- "Layer 5"
object$layer_id[WhichCells(object, idents = c(1))] <- "Layer 6"
```

Example 99 (r):
```r
Idents(object) <- "banksy_cluster"
object$layer_id <- "Unknown"
object$layer_id[WhichCells(object, idents = c(7))] <- "Layer 2/3"
object$layer_id[WhichCells(object, idents = c(15))] <- "Layer 4"
object$layer_id[WhichCells(object, idents = c(5))] <- "Layer 5"
object$layer_id[WhichCells(object, idents = c(1))] <- "Layer 6"
```

Example 100 (unknown):
```unknown
# set ID to RCTD label
Idents(object) <- "full_first_type"

# Visualize distribution of 4 interneuron subtypes
inhibitory_names <- c("Sst", "Pvalb", "Vip", "Lamp5")
cell_ids <- CellsByIdentities(object, idents = inhibitory_names)
p <- SpatialDimPlot(object, cells.highlight = cell_ids, cols.highlight = c("#FFFF00", "grey50"), facet.highlight = T, combine = T, ncol = 4)
p
```

Example 101 (r):
```r
# set ID to RCTD label
Idents(object) <- "full_first_type"

# Visualize distribution of 4 interneuron subtypes
inhibitory_names <- c("Sst", "Pvalb", "Vip", "Lamp5")
cell_ids <- CellsByIdentities(object, idents = inhibitory_names)
p <- SpatialDimPlot(object, cells.highlight = cell_ids, cols.highlight = c("#FFFF00", "grey50"), facet.highlight = T, combine = T, ncol = 4)
p
```

Example 102 (r):
```r
# set ID to RCTD label
Idents(object) <- "full_first_type"

# Visualize distribution of 4 interneuron subtypes
inhibitory_names <- c("Sst", "Pvalb", "Vip", "Lamp5")
cell_ids <- CellsByIdentities(object, idents = inhibitory_names)
p <- SpatialDimPlot(object, cells.highlight = cell_ids, cols.highlight = c("#FFFF00", "grey50"), facet.highlight = T, combine = T, ncol = 4)
p
```

Example 103 (unknown):
```unknown
# create barplot to show proportions of cell types of interest
layer_table <- table(object$full_first_type, object$layer_id)[inhibitory_names, 1:4]

neuron_props <- reshape2::melt(prop.table(layer_table), margin = 1)
ggplot(neuron_props, aes(x = Var1, y = value, fill = Var2)) +
  geom_bar(stat = "identity", position = "fill") +
  labs(x = "Cell type", y = "Proportion", fill = "Layer") +
  theme_classic()
```

Example 104 (r):
```r
# create barplot to show proportions of cell types of interest
layer_table <- table(object$full_first_type, object$layer_id)[inhibitory_names, 1:4]

neuron_props <- reshape2::melt(prop.table(layer_table), margin = 1)
ggplot(neuron_props, aes(x = Var1, y = value, fill = Var2)) +
  geom_bar(stat = "identity", position = "fill") +
  labs(x = "Cell type", y = "Proportion", fill = "Layer") +
  theme_classic()
```

Example 105 (r):
```r
# create barplot to show proportions of cell types of interest
layer_table <- table(object$full_first_type, object$layer_id)[inhibitory_names, 1:4]

neuron_props <- reshape2::melt(prop.table(layer_table), margin = 1)
ggplot(neuron_props, aes(x = Var1, y = value, fill = Var2)) +
  geom_bar(stat = "identity", position = "fill") +
  labs(x = "Cell type", y = "Proportion", fill = "Layer") +
  theme_classic()
```

Example 106 (unknown):
```unknown
localdir <- "/brahms/lis/visium_hd/Visium_HD_Public_Data/HD_public_data/Visium_HD_Mouse_Small_Intestine/outs"
object <- Load10X_Spatial(data.dir = localdir, bin.size = 8)
```

Example 107 (r):
```r
localdir <- "/brahms/lis/visium_hd/Visium_HD_Public_Data/HD_public_data/Visium_HD_Mouse_Small_Intestine/outs"
object <- Load10X_Spatial(data.dir = localdir, bin.size = 8)
```

Example 108 (r):
```r
localdir <- "/brahms/lis/visium_hd/Visium_HD_Public_Data/HD_public_data/Visium_HD_Mouse_Small_Intestine/outs"
object <- Load10X_Spatial(data.dir = localdir, bin.size = 8)
```

Example 109 (unknown):
```unknown
DefaultAssay(object) <- "Spatial.008um"
object <- NormalizeData(object)
object <- FindVariableFeatures(object)
object <- ScaleData(object)
```

Example 110 (r):
```r
DefaultAssay(object) <- "Spatial.008um"
object <- NormalizeData(object)
object <- FindVariableFeatures(object)
object <- ScaleData(object)
```

Example 111 (r):
```r
DefaultAssay(object) <- "Spatial.008um"
object <- NormalizeData(object)
object <- FindVariableFeatures(object)
object <- ScaleData(object)
```

Example 112 (unknown):
```unknown
object <- SketchData(
  object = object,
  ncells = 50000,
  method = "LeverageScore",
  sketched.assay = "sketch"
)
```

Example 113 (r):
```r
object <- SketchData(
  object = object,
  ncells = 50000,
  method = "LeverageScore",
  sketched.assay = "sketch"
)
```

Example 114 (r):
```r
object <- SketchData(
  object = object,
  ncells = 50000,
  method = "LeverageScore",
  sketched.assay = "sketch"
)
```

Example 115 (unknown):
```unknown
DefaultAssay(object) <- "sketch"
object <- FindVariableFeatures(object)
object <- ScaleData(object)
object <- RunPCA(object, assay = "sketch", reduction.name = "pca.sketch")
object <- FindNeighbors(object, assay = "sketch", reduction = "pca.sketch", dims = 1:50)
object <- FindClusters(object, cluster.name = "seurat_cluster.sketched", resolution = 3)
object <- RunUMAP(object, reduction = "pca.sketch", reduction.name = "umap.sketch", return.model = T, dims = 1:50)
```

Example 116 (r):
```r
DefaultAssay(object) <- "sketch"
object <- FindVariableFeatures(object)
object <- ScaleData(object)
object <- RunPCA(object, assay = "sketch", reduction.name = "pca.sketch")
object <- FindNeighbors(object, assay = "sketch", reduction = "pca.sketch", dims = 1:50)
object <- FindClusters(object, cluster.name = "seurat_cluster.sketched", resolution = 3)
object <- RunUMAP(object, reduction = "pca.sketch", reduction.name = "umap.sketch", return.model = T, dims = 1:50)
```

Example 117 (r):
```r
DefaultAssay(object) <- "sketch"
object <- FindVariableFeatures(object)
object <- ScaleData(object)
object <- RunPCA(object, assay = "sketch", reduction.name = "pca.sketch")
object <- FindNeighbors(object, assay = "sketch", reduction = "pca.sketch", dims = 1:50)
object <- FindClusters(object, cluster.name = "seurat_cluster.sketched", resolution = 3)
object <- RunUMAP(object, reduction = "pca.sketch", reduction.name = "umap.sketch", return.model = T, dims = 1:50)
```

Example 118 (unknown):
```unknown
object <- ProjectData(
  object = object,
  assay = "Spatial.008um",
  full.reduction = "full.pca.sketch",
  sketched.assay = "sketch",
  sketched.reduction = "pca.sketch",
  umap.model = "umap.sketch",
  dims = 1:50,
  refdata = list(seurat_cluster.projected = "seurat_cluster.sketched")
)
```

Example 119 (r):
```r
object <- ProjectData(
  object = object,
  assay = "Spatial.008um",
  full.reduction = "full.pca.sketch",
  sketched.assay = "sketch",
  sketched.reduction = "pca.sketch",
  umap.model = "umap.sketch",
  dims = 1:50,
  refdata = list(seurat_cluster.projected = "seurat_cluster.sketched")
)
```

Example 120 (r):
```r
object <- ProjectData(
  object = object,
  assay = "Spatial.008um",
  full.reduction = "full.pca.sketch",
  sketched.assay = "sketch",
  sketched.reduction = "pca.sketch",
  umap.model = "umap.sketch",
  dims = 1:50,
  refdata = list(seurat_cluster.projected = "seurat_cluster.sketched")
)
```

Example 121 (unknown):
```unknown
Idents(object) <- "seurat_cluster.projected"
DefaultAssay(object) <- "Spatial.008um"

p1 <- DimPlot(object, reduction = "umap.sketch", label = F) + theme(legend.position = "bottom")
p2 <- SpatialDimPlot(object, label = F) + theme(legend.position = "bottom")
p1 | p2
```

Example 122 (r):
```r
Idents(object) <- "seurat_cluster.projected"
DefaultAssay(object) <- "Spatial.008um"

p1 <- DimPlot(object, reduction = "umap.sketch", label = F) + theme(legend.position = "bottom")
p2 <- SpatialDimPlot(object, label = F) + theme(legend.position = "bottom")
p1 | p2
```

Example 123 (r):
```r
Idents(object) <- "seurat_cluster.projected"
DefaultAssay(object) <- "Spatial.008um"

p1 <- DimPlot(object, reduction = "umap.sketch", label = F) + theme(legend.position = "bottom")
p2 <- SpatialDimPlot(object, label = F) + theme(legend.position = "bottom")
p1 | p2
```

Example 124 (unknown):
```unknown
Idents(object) <- "seurat_cluster.projected"
cells <- CellsByIdentities(object, idents = c(1, 5, 18, 26))
p <- SpatialDimPlot(object, cells.highlight = cells[setdiff(names(cells), "NA")], cols.highlight = c("#FFFF00", "grey50"), facet.highlight = T, combine = T) + NoLegend()
p
```

Example 125 (r):
```r
Idents(object) <- "seurat_cluster.projected"
cells <- CellsByIdentities(object, idents = c(1, 5, 18, 26))
p <- SpatialDimPlot(object, cells.highlight = cells[setdiff(names(cells), "NA")], cols.highlight = c("#FFFF00", "grey50"), facet.highlight = T, combine = T) + NoLegend()
p
```

Example 126 (r):
```r
Idents(object) <- "seurat_cluster.projected"
cells <- CellsByIdentities(object, idents = c(1, 5, 18, 26))
p <- SpatialDimPlot(object, cells.highlight = cells[setdiff(names(cells), "NA")], cols.highlight = c("#FFFF00", "grey50"), facet.highlight = T, combine = T) + NoLegend()
p
```

Example 127 (unknown):
```unknown
DefaultAssay(object) <- "Spatial.008um"
Idents(object) <- "seurat_cluster.projected"
object_subset <- subset(object, cells = Cells(object[["Spatial.008um"]]), downsample = 1000)

DefaultAssay(object_subset) <- "Spatial.008um"
Idents(object_subset) <- "seurat_cluster.projected"
object_subset <- BuildClusterTree(object_subset, assay = "Spatial.008um", reduction = "full.pca.sketch", reorder = T)

markers <- FindAllMarkers(object_subset, assay = "Spatial.008um", only.pos = TRUE)
markers %>%
  group_by(cluster) %>%
  dplyr::filter(avg_log2FC > 1) %>%
  slice_head(n = 5) %>%
  ungroup() -> top5

object_subset <- ScaleData(object_subset, assay = "Spatial.008um", features = top5$gene)
p <- DoHeatmap(object_subset, assay = "Spatial.008um", features = top5$gene, size = 2.5) + theme(axis.text = element_text(size = 5.5)) + NoLegend()
p
```

Example 128 (r):
```r
DefaultAssay(object) <- "Spatial.008um"
Idents(object) <- "seurat_cluster.projected"
object_subset <- subset(object, cells = Cells(object[["Spatial.008um"]]), downsample = 1000)

DefaultAssay(object_subset) <- "Spatial.008um"
Idents(object_subset) <- "seurat_cluster.projected"
object_subset <- BuildClusterTree(object_subset, assay = "Spatial.008um", reduction = "full.pca.sketch", reorder = T)

markers <- FindAllMarkers(object_subset, assay = "Spatial.008um", only.pos = TRUE)
markers %>%
  group_by(cluster) %>%
  dplyr::filter(avg_log2FC > 1) %>%
  slice_head(n = 5) %>%
  ungroup() -> top5

object_subset <- ScaleData(object_subset, assay = "Spatial.008um", features = top5$gene)
p <- DoHeatmap(object_subset, assay = "Spatial.008um", features = top5$gene, size = 2.5) + theme(axis.text = element_text(size = 5.5)) + NoLegend()
p
```

Example 129 (r):
```r
DefaultAssay(object) <- "Spatial.008um"
Idents(object) <- "seurat_cluster.projected"
object_subset <- subset(object, cells = Cells(object[["Spatial.008um"]]), downsample = 1000)

DefaultAssay(object_subset) <- "Spatial.008um"
Idents(object_subset) <- "seurat_cluster.projected"
object_subset <- BuildClusterTree(object_subset, assay = "Spatial.008um", reduction = "full.pca.sketch", reorder = T)

markers <- FindAllMarkers(object_subset, assay = "Spatial.008um", only.pos = TRUE)
markers %>%
  group_by(cluster) %>%
  dplyr::filter(avg_log2FC > 1) %>%
  slice_head(n = 5) %>%
  ungroup() -> top5

object_subset <- ScaleData(object_subset, assay = "Spatial.008um", features = top5$gene)
p <- DoHeatmap(object_subset, assay = "Spatial.008um", features = top5$gene, size = 2.5) + theme(axis.text = element_text(size = 5.5)) + NoLegend()
p
```

Example 130 (unknown):
```unknown
sessionInfo()
```

Example 131 (r):
```r
sessionInfo()
```

Example 132 (r):
```r
sessionInfo()
```

Example 133 (unknown):
```unknown
## R version 4.3.2 (2023-10-31)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.6 LTS
## 
## Matrix products: default
## BLAS:   /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.9.0 
## LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.9.0
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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: America/New_York
## tzcode source: system (glibc)
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
## [1] dplyr_1.1.4             patchwork_1.2.0         ggplot2_3.5.0          
## [4] Seurat_5.1.0      testthat_3.2.1          SeuratObject_5.0.1.9011
## [7] sp_2.1-4               
## 
## loaded via a namespace (and not attached):
##   [1] RColorBrewer_1.1-3     rstudioapi_0.15.0      jsonlite_1.8.8        
##   [4] magrittr_2.0.3         ggbeeswarm_0.7.2       spatstat.utils_3.0-4  
##   [7] farver_2.1.1           rmarkdown_2.26         fs_1.6.3              
##  [10] ragg_1.2.7             vctrs_0.6.5            ROCR_1.0-11           
##  [13] memoise_2.0.1          spatstat.explore_3.2-6 htmltools_0.5.7       
##  [16] usethis_2.2.3          sass_0.4.8             sctransform_0.4.1     
##  [19] parallelly_1.37.1      KernSmooth_2.23-22     bslib_0.6.1           
##  [22] htmlwidgets_1.6.4      desc_1.4.3             ica_1.0-3             
##  [25] plyr_1.8.9             plotly_4.10.4          zoo_1.8-12            
##  [28] cachem_1.0.8           igraph_2.0.2           mime_0.12             
##  [31] lifecycle_1.0.4        pkgconfig_2.0.3        Matrix_1.6-5          
##  [34] R6_2.5.1               fastmap_1.1.1          fitdistrplus_1.1-11   
##  [37] future_1.33.1          shiny_1.8.0            digest_0.6.34         
##  [40] colorspace_2.1-0       tensor_1.5             rprojroot_2.0.4       
##  [43] RSpectra_0.16-1        irlba_2.3.5.1          pkgload_1.3.4         
##  [46] textshaping_0.3.7      labeling_0.4.3         progressr_0.14.0      
##  [49] fansi_1.0.6            spatstat.sparse_3.0-3  polyclip_1.10-6       
##  [52] abind_1.4-5            httr_1.4.7             compiler_4.3.2        
##  [55] remotes_2.4.2.1        withr_3.0.0            fastDummies_1.7.3     
##  [58] highr_0.10             pkgbuild_1.4.3         R.utils_2.12.3        
##  [61] MASS_7.3-60.0.1        sessioninfo_1.2.2      tools_4.3.2           
##  [64] vipor_0.4.7            lmtest_0.9-40          ape_5.7-1             
##  [67] beeswarm_0.4.0         httpuv_1.6.14          future.apply_1.11.1   
##  [70] goftest_1.2-3          R.oo_1.26.0            glue_1.7.0            
##  [73] nlme_3.1-164           R.cache_0.16.0         promises_1.2.1        
##  [76] grid_4.3.2             Rtsne_0.17             cluster_2.1.6         
##  [79] reshape2_1.4.4         generics_0.1.3         gtable_0.3.4          
##  [82] spatstat.data_3.0-4    R.methodsS3_1.8.2      tidyr_1.3.1           
##  [85] data.table_1.15.2      utf8_1.2.4             spatstat.geom_3.2-9   
##  [88] RcppAnnoy_0.0.22       ggrepel_0.9.5          RANN_2.6.1            
##  [91] pillar_1.9.0           stringr_1.5.1          limma_3.58.1          
##  [94] spam_2.10-0            RcppHNSW_0.6.0         later_1.3.2           
##  [97] splines_4.3.2          lattice_0.22-5         deldir_2.0-4          
## [100] survival_3.5-8         tidyselect_1.2.0       miniUI_0.1.1.1        
## [103] pbapply_1.7-2          knitr_1.45             gridExtra_2.3         
## [106] scattermore_1.2        xfun_0.42              statmod_1.5.0         
## [109] brio_1.1.4             devtools_2.4.5         matrixStats_1.2.0     
## [112] stringi_1.8.3          lazyeval_0.2.2         yaml_2.3.8            
## [115] evaluate_0.23          codetools_0.2-20       tibble_3.2.1          
## [118] cli_3.6.2              uwot_0.1.16            xtable_1.8-4          
## [121] reticulate_1.35.0      systemfonts_1.0.5      munsell_0.5.0         
## [124] jquerylib_0.1.4        styler_1.10.2          Rcpp_1.0.12           
## [127] spatstat.random_3.2-3  globals_0.16.2         png_0.1-8             
## [130] ggrastr_1.0.2          parallel_4.3.2         ellipsis_0.3.2        
## [133] pkgdown_2.0.7          presto_1.0.0           dotCall64_1.1-1       
## [136] profvis_0.3.8          urlchecker_1.0.1       listenv_0.9.1         
## [139] viridisLite_0.4.2      scales_1.3.0           ggridges_0.5.6        
## [142] leiden_0.4.3.1         purrr_1.0.2            rlang_1.1.3           
## [145] cowplot_1.1.3
```

Example 134 (unknown):
```unknown
## R version 4.3.2 (2023-10-31)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.6 LTS
## 
## Matrix products: default
## BLAS:   /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.9.0 
## LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.9.0
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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: America/New_York
## tzcode source: system (glibc)
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
## [1] dplyr_1.1.4             patchwork_1.2.0         ggplot2_3.5.0          
## [4] Seurat_5.1.0      testthat_3.2.1          SeuratObject_5.0.1.9011
## [7] sp_2.1-4               
## 
## loaded via a namespace (and not attached):
##   [1] RColorBrewer_1.1-3     rstudioapi_0.15.0      jsonlite_1.8.8        
##   [4] magrittr_2.0.3         ggbeeswarm_0.7.2       spatstat.utils_3.0-4  
##   [7] farver_2.1.1           rmarkdown_2.26         fs_1.6.3              
##  [10] ragg_1.2.7             vctrs_0.6.5            ROCR_1.0-11           
##  [13] memoise_2.0.1          spatstat.explore_3.2-6 htmltools_0.5.7       
##  [16] usethis_2.2.3          sass_0.4.8             sctransform_0.4.1     
##  [19] parallelly_1.37.1      KernSmooth_2.23-22     bslib_0.6.1           
##  [22] htmlwidgets_1.6.4      desc_1.4.3             ica_1.0-3             
##  [25] plyr_1.8.9             plotly_4.10.4          zoo_1.8-12            
##  [28] cachem_1.0.8           igraph_2.0.2           mime_0.12             
##  [31] lifecycle_1.0.4        pkgconfig_2.0.3        Matrix_1.6-5          
##  [34] R6_2.5.1               fastmap_1.1.1          fitdistrplus_1.1-11   
##  [37] future_1.33.1          shiny_1.8.0            digest_0.6.34         
##  [40] colorspace_2.1-0       tensor_1.5             rprojroot_2.0.4       
##  [43] RSpectra_0.16-1        irlba_2.3.5.1          pkgload_1.3.4         
##  [46] textshaping_0.3.7      labeling_0.4.3         progressr_0.14.0      
##  [49] fansi_1.0.6            spatstat.sparse_3.0-3  polyclip_1.10-6       
##  [52] abind_1.4-5            httr_1.4.7             compiler_4.3.2        
##  [55] remotes_2.4.2.1        withr_3.0.0            fastDummies_1.7.3     
##  [58] highr_0.10             pkgbuild_1.4.3         R.utils_2.12.3        
##  [61] MASS_7.3-60.0.1        sessioninfo_1.2.2      tools_4.3.2           
##  [64] vipor_0.4.7            lmtest_0.9-40          ape_5.7-1             
##  [67] beeswarm_0.4.0         httpuv_1.6.14          future.apply_1.11.1   
##  [70] goftest_1.2-3          R.oo_1.26.0            glue_1.7.0            
##  [73] nlme_3.1-164           R.cache_0.16.0         promises_1.2.1        
##  [76] grid_4.3.2             Rtsne_0.17             cluster_2.1.6         
##  [79] reshape2_1.4.4         generics_0.1.3         gtable_0.3.4          
##  [82] spatstat.data_3.0-4    R.methodsS3_1.8.2      tidyr_1.3.1           
##  [85] data.table_1.15.2      utf8_1.2.4             spatstat.geom_3.2-9   
##  [88] RcppAnnoy_0.0.22       ggrepel_0.9.5          RANN_2.6.1            
##  [91] pillar_1.9.0           stringr_1.5.1          limma_3.58.1          
##  [94] spam_2.10-0            RcppHNSW_0.6.0         later_1.3.2           
##  [97] splines_4.3.2          lattice_0.22-5         deldir_2.0-4          
## [100] survival_3.5-8         tidyselect_1.2.0       miniUI_0.1.1.1        
## [103] pbapply_1.7-2          knitr_1.45             gridExtra_2.3         
## [106] scattermore_1.2        xfun_0.42              statmod_1.5.0         
## [109] brio_1.1.4             devtools_2.4.5         matrixStats_1.2.0     
## [112] stringi_1.8.3          lazyeval_0.2.2         yaml_2.3.8            
## [115] evaluate_0.23          codetools_0.2-20       tibble_3.2.1          
## [118] cli_3.6.2              uwot_0.1.16            xtable_1.8-4          
## [121] reticulate_1.35.0      systemfonts_1.0.5      munsell_0.5.0         
## [124] jquerylib_0.1.4        styler_1.10.2          Rcpp_1.0.12           
## [127] spatstat.random_3.2-3  globals_0.16.2         png_0.1-8             
## [130] ggrastr_1.0.2          parallel_4.3.2         ellipsis_0.3.2        
## [133] pkgdown_2.0.7          presto_1.0.0           dotCall64_1.1-1       
## [136] profvis_0.3.8          urlchecker_1.0.1       listenv_0.9.1         
## [139] viridisLite_0.4.2      scales_1.3.0           ggridges_0.5.6        
## [142] leiden_0.4.3.1         purrr_1.0.2            rlang_1.1.3           
## [145] cowplot_1.1.3
```

---

## Differential expression testing

**URL:** http://127.0.0.1:9173/seurat/archive/v2.4/de_vignette/index.html

**Contents:**
- Differential expression testing
    - Satija Lab
    - Compiled: 2018-03-24
  - Load in the data
  - Perform default differential expression tests
  - Prefilter genes or cells to increase the speed of DE testing
  - Perform DE analysis using alternative tests
  - Acknowledgements

This vignette highlights some example workflows for performing differential expression in Seurat. For demonstration purposes, we will be using the 2,700 PBMC object that is created in the first guided tutorial. You can download the pre-computed object here.

The bulk of Seurat’s differential expression features can be accessed through the FindMarkers function. As a default, Seurat performs differential expression based on the non-parameteric Wilcoxon rank sum test. This replaces the previous default test (‘bimod’). To test for differential expression between two specific groups of cells, specify the ident.1 and ident.2 parameters.

The results data frame has the following columns :

If the ident.2 parameter is omitted or set to NULL, FindMarkers will test for differentially expressed genes between the group specified by ident.1 and all other cells.

To increase the speed of marker discovery, particularly for large datasets, Seurat allows for pre-filtering of genes or cells. For example, genes that are very infrequently detected in either group of cells, or genes that are expressed at similar average levels, are unlikely to be differentially expressed. Example use cases of the min.pct, logfc.threshold, min.diff.pct, and max.cells.per.ident parameters are demonstrated below.

The following differential expression tests are currently supported:

For MAST and DESeq2 please ensure that these packages are installed separately in order to use them as part of Seurat. Once installed, use the test.use parameter can be used to specify which DE test to use.

We thank the authors of the MAST and DESeq2 packages for their kind assistance and advice. We also point users to the following study by Charlotte Soneson and Mark Robinson, which performs careful and extensive evaluation of methods for single cell differential expression testing.

**Examples:**

Example 1 (r):
```r
library(Seurat)
pbmc <- readRDS(file = "~/Projects/datasets/pbmc3k_final.rds")
```

Example 2 (r):
```r
library(Seurat)
pbmc <- readRDS(file = "~/Projects/datasets/pbmc3k_final.rds")
```

Example 3 (unknown):
```unknown
FindMarkers
```

Example 4 (r):
```r
# list options for groups to perform differential expression on
levels(pbmc@ident)
```

Example 5 (r):
```r
# list options for groups to perform differential expression on
levels(pbmc@ident)
```

Example 6 (unknown):
```unknown
## [1] "B cells"           "CD4 T cells"       "CD8 T cells"      
## [4] "CD14+ Monocytes"   "Dendritic cells"   "FCGR3A+ Monocytes"
## [7] "Megakaryocytes"    "NK cells"
```

Example 7 (unknown):
```unknown
## [1] "B cells"           "CD4 T cells"       "CD8 T cells"      
## [4] "CD14+ Monocytes"   "Dendritic cells"   "FCGR3A+ Monocytes"
## [7] "Megakaryocytes"    "NK cells"
```

Example 8 (r):
```r
# Find differentially expressed genes between CD14+ and FCGR3A+ Monocytes
monocyte_de_genes <- FindMarkers(pbmc, ident.1 = "CD14+ Monocytes", ident.2 = "FCGR3A+ Monocytes")

# view results
head(monocyte_de_genes)
```

Example 9 (r):
```r
# Find differentially expressed genes between CD14+ and FCGR3A+ Monocytes
monocyte_de_genes <- FindMarkers(pbmc, ident.1 = "CD14+ Monocytes", ident.2 = "FCGR3A+ Monocytes")

# view results
head(monocyte_de_genes)
```

Example 10 (unknown):
```unknown
##               p_val avg_logFC pct.1 pct.2    p_val_adj
## FCGR3A 2.655706e-96 -2.569489 0.134 0.962 3.642036e-92
## LYZ    7.356623e-71  1.738480 1.000 0.987 1.008887e-66
## RHOC   5.664625e-65 -1.602845 0.165 0.854 7.768466e-61
## S100A8 5.369175e-64  2.656454 0.973 0.503 7.363287e-60
## IFITM2 2.099722e-62 -1.432368 0.676 1.000 2.879558e-58
## S100A9 1.540888e-61  2.250824 0.996 0.879 2.113174e-57
```

Example 11 (unknown):
```unknown
##               p_val avg_logFC pct.1 pct.2    p_val_adj
## FCGR3A 2.655706e-96 -2.569489 0.134 0.962 3.642036e-92
## LYZ    7.356623e-71  1.738480 1.000 0.987 1.008887e-66
## RHOC   5.664625e-65 -1.602845 0.165 0.854 7.768466e-61
## S100A8 5.369175e-64  2.656454 0.973 0.503 7.363287e-60
## IFITM2 2.099722e-62 -1.432368 0.676 1.000 2.879558e-58
## S100A9 1.540888e-61  2.250824 0.996 0.879 2.113174e-57
```

Example 12 (unknown):
```unknown
FindMarkers
```

Example 13 (r):
```r
# Find differentially expressed genes between CD14+ Monocytes and all other
# cells, only search for positive markers
monocyte_de_genes <- FindMarkers(pbmc, ident.1 = "CD14+ Monocytes", ident.2 = NULL, 
    only.pos = TRUE)

# view results
head(monocyte_de_genes)
```

Example 14 (r):
```r
# Find differentially expressed genes between CD14+ Monocytes and all other
# cells, only search for positive markers
monocyte_de_genes <- FindMarkers(pbmc, ident.1 = "CD14+ Monocytes", ident.2 = NULL, 
    only.pos = TRUE)

# view results
head(monocyte_de_genes)
```

Example 15 (unknown):
```unknown
##                p_val avg_logFC pct.1 pct.2     p_val_adj
## S100A9  0.000000e+00  3.830954 0.996 0.216  0.000000e+00
## S100A8  0.000000e+00  3.786963 0.973 0.122  0.000000e+00
## LGALS2  0.000000e+00  2.639056 0.908 0.060  0.000000e+00
## FCN1    0.000000e+00  2.367232 0.954 0.151  0.000000e+00
## CD14   5.052830e-289  1.947447 0.662 0.029 6.929451e-285
## TYROBP 1.281069e-283  2.111357 0.994 0.265 1.756858e-279
```

Example 16 (unknown):
```unknown
##                p_val avg_logFC pct.1 pct.2     p_val_adj
## S100A9  0.000000e+00  3.830954 0.996 0.216  0.000000e+00
## S100A8  0.000000e+00  3.786963 0.973 0.122  0.000000e+00
## LGALS2  0.000000e+00  2.639056 0.908 0.060  0.000000e+00
## FCN1    0.000000e+00  2.367232 0.954 0.151  0.000000e+00
## CD14   5.052830e-289  1.947447 0.662 0.029 6.929451e-285
## TYROBP 1.281069e-283  2.111357 0.994 0.265 1.756858e-279
```

Example 17 (unknown):
```unknown
logfc.threshold
```

Example 18 (unknown):
```unknown
min.diff.pct
```

Example 19 (unknown):
```unknown
max.cells.per.ident
```

Example 20 (r):
```r
# Pre-filter genes that are detected at <50% frequency in either CD14+
# Monocytes or FCGR3A+ Monocytes
monocyte_de_genes <- FindMarkers(pbmc, ident.1 = "CD14+ Monocytes", ident.2 = "FCGR3A+ Monocytes", 
    min.pct = 0.5)

# Pre-filter genes that have less than a two-fold change between the average
# expression of CD14+ Monocytes vs FCGR3A+ Monocytes
monocyte_de_genes <- FindMarkers(pbmc, ident.1 = "CD14+ Monocytes", ident.2 = "FCGR3A+ Monocytes", 
    logfc.threshold = log(2))

# Pre-filter genes whose detection percentages across the two groups are
# similar (within 0.25)
monocyte_de_genes <- FindMarkers(pbmc, ident.1 = "CD14+ Monocytes", ident.2 = "FCGR3A+ Monocytes", 
    min.diff.pct = 0.25)

# Increasing min.pct, logfc.threshold, and min.diff.pct, will increase the
# speed of DE testing, but could also miss genes that are prefiltered

# Subsample each group to a maximum of 200 cells. Can be very useful for
# large clusters, or computationally-intensive DE tests
monocyte_de_genes <- FindMarkers(pbmc, ident.1 = "CD14+ Monocytes", ident.2 = "FCGR3A+ Monocytes", 
    max.cells.per.ident = 200)
```

Example 21 (r):
```r
# Pre-filter genes that are detected at <50% frequency in either CD14+
# Monocytes or FCGR3A+ Monocytes
monocyte_de_genes <- FindMarkers(pbmc, ident.1 = "CD14+ Monocytes", ident.2 = "FCGR3A+ Monocytes", 
    min.pct = 0.5)

# Pre-filter genes that have less than a two-fold change between the average
# expression of CD14+ Monocytes vs FCGR3A+ Monocytes
monocyte_de_genes <- FindMarkers(pbmc, ident.1 = "CD14+ Monocytes", ident.2 = "FCGR3A+ Monocytes", 
    logfc.threshold = log(2))

# Pre-filter genes whose detection percentages across the two groups are
# similar (within 0.25)
monocyte_de_genes <- FindMarkers(pbmc, ident.1 = "CD14+ Monocytes", ident.2 = "FCGR3A+ Monocytes", 
    min.diff.pct = 0.25)

# Increasing min.pct, logfc.threshold, and min.diff.pct, will increase the
# speed of DE testing, but could also miss genes that are prefiltered

# Subsample each group to a maximum of 200 cells. Can be very useful for
# large clusters, or computationally-intensive DE tests
monocyte_de_genes <- FindMarkers(pbmc, ident.1 = "CD14+ Monocytes", ident.2 = "FCGR3A+ Monocytes", 
    max.cells.per.ident = 200)
```

Example 22 (r):
```r
# Test for DE genes using the MAST package
monocyte_de_genes <- FindMarkers(pbmc, ident.1 = "CD14+ Monocytes", ident.2 = "FCGR3A+ Monocytes", 
    test.use = "MAST")

# Test for DE genes using the DESeq2 package. Throws an error if DESeq2 has
# not already been installed Note that the DESeq2 workflows can be
# computationally intensive for large datasets, but are incompatible with
# some gene pre-filtering options We therefore suggest initially limiting
# the number of cells used for testing
monocyte_de_genes <- FindMarkers(pbmc, ident.1 = "CD14+ Monocytes", ident.2 = "FCGR3A+ Monocytes", 
    test.use = "DESeq2", max.cells.per.ident = 50)
```

Example 23 (r):
```r
# Test for DE genes using the MAST package
monocyte_de_genes <- FindMarkers(pbmc, ident.1 = "CD14+ Monocytes", ident.2 = "FCGR3A+ Monocytes", 
    test.use = "MAST")

# Test for DE genes using the DESeq2 package. Throws an error if DESeq2 has
# not already been installed Note that the DESeq2 workflows can be
# computationally intensive for large datasets, but are incompatible with
# some gene pre-filtering options We therefore suggest initially limiting
# the number of cells used for testing
monocyte_de_genes <- FindMarkers(pbmc, ident.1 = "CD14+ Monocytes", ident.2 = "FCGR3A+ Monocytes", 
    test.use = "DESeq2", max.cells.per.ident = 50)
```

---

## Analysis, visualization, and integration of Visium HD spatial datasets with Seurat • Seurat

**URL:** http://127.0.0.1:9173/seurat/articles/announcements/index.html

**Contents:**
- News
- Changes in Seurat v5
- Contents

We are excited to release Seurat v5 on CRAN, where it is now the default version for new installs. Seurat v5 is designed to be backwards compatible with Seurat v4 so existing code will continue to run, but we have made some changes to the software that will affect user results. We note that users who aim to reproduce their previous workflows in Seurat v4 can still install this version using the instructions on our install page.

In particular, we have made changes to:

Seurat Object and Assay class: Seurat v5 now includes support for additional assay and data types, including on-disk matrices. To facilitate this, we have introduced an updated Seurat v5 assay. Users can check out this [vignette for more information]. Briefly, Seurat v5 assays store data in layers (previously referred to as ‘slots’).

For example, these layers can store: raw counts (layer='counts'), normalized data (layer='data'), or z-scored/variance-stabilized data (layer='scale.data').

Data can be accessed using the $ accessor (i.e. obj[["RNA"]]$counts), or the `LayerData function (i.e. LayerData(obj, assay="RNA", layer='counts').

We’ve designed these updates to minimize changes for users. Existing Seurat functions and workflows from v4 continue to work in v5. For example, the command GetAssayData(obj, assay="RNA", slot='counts'), will run successfully in both Seurat v4 and Seurat v5.

Integration workflow: Seurat v5 introduces a streamlined integration and data transfer workflows that performs integration in low-dimensional space, and improves speed and memory efficiency. The results of integration are not identical between the two workflows, but users can still run the v4 integration workflow in Seurat v5 if they wish.

In previous versions of Seurat, the integration workflow required a list of multiple Seurat objects as input. In Seurat v5, all the data can be kept as a single object, but prior to integration, users can simply split the layers. See our introduction to integration vignette for more information.

Differential expression: Seurat v5 now uses the presto package (from the Korunsky and Raychaudhari labs), when available, to perform differential expression analysis. Using presto can dramatically speed up DE testing, and we encourage users to install it. In addition, in Seurat v5 we implement a pseudocount (when calculating log-FC) at the group level instead of the cell level. As a result, users will observe higher logFC estimates in v5 - but should note that these estimates may be more unstable - particularly for genes that are very lowly expressed in one of the two groups. We gratefully acknowledge feedback from the McCarthy and Pachter labs on this topic.

Pseudobulk analysis: Once a single-cell dataset has been analyzed to annotate cell subpopulations, pseudobulk analyses (i.e. aggregating together cells within a given subpopulation and sample) can reduce noise, improve quantification of lowly expressed genes, and reduce the size of the data matrix. In Seurat v5, we encourage the use of the AggregateExpression function to perform pseudobulk analysis. Check out our differential expression vignette as well as our pancreatic/healthy PBMC comparison, for examples of how to use AggregateExpression to perform robust differential expression of scRNA-seq data from multiple different conditions.

Developed by Rahul Satija, Satija Lab and Collaborators.

Site built with pkgdown 2.0.7.

**Examples:**

Example 1 (unknown):
```unknown
vignettes/announcements.Rmd
```

Example 2 (unknown):
```unknown
announcements.Rmd
```

Example 3 (unknown):
```unknown
(layer='counts')
```

Example 4 (unknown):
```unknown
(layer='data')
```

Example 5 (unknown):
```unknown
(layer='scale.data')
```

Example 6 (unknown):
```unknown
obj[["RNA"]]$counts
```

Example 7 (unknown):
```unknown
LayerData(obj, assay="RNA", layer='counts')
```

Example 8 (unknown):
```unknown
GetAssayData(obj, assay="RNA", slot='counts')
```

Example 9 (unknown):
```unknown
SCTransform
```

Example 10 (unknown):
```unknown
vst.flavor = "v1"
```

Example 11 (unknown):
```unknown
SCTransform
```

Example 12 (unknown):
```unknown
AggregateExpression
```

Example 13 (unknown):
```unknown
AggregateExpression
```

---

## Analysis, visualization, and integration of Visium HD spatial datasets with Seurat • Seurat

**URL:** http://127.0.0.1:9173/seurat/articles/seurat5_sketch_analysis/index.html

**Contents:**
- Sketch-based analysis in Seurat v5
    - Compiled: 2023-10-31
- Intro: Sketch-based analysis in Seurat v5
- Create a Seurat object with a v5 assay for on-disk storage
- ‘Sketch’ a subset of cells, and load these into memory
- Perform clustering on the sketched dataset
- Extend results to the full datasets
- Perform iterative sub-clustering
- Contents

As single-cell sequencing technologies continue to improve in scalability in throughput, the generation of datasets spanning a million or more cells is becoming increasingly routine. In Seurat v5, we introduce new infrastructure and methods to analyze, interpret, and explore these exciting datasets.

In this vignette, we introduce a sketch-based analysis workflow to analyze a 1.3 million cell dataset of the developing mouse brain, freely available from 10x Genomics. Analyzing datasets of this size with standard workflows can be challenging, slow, and memory-intensive. Here we introduce an alternative workflow that is highly scalable, even to datasets ranging beyond 10 million cells in size. Our ‘sketch-based’ workflow involves three new features in Seurat v5:

Storing expression matrices in memory can be challenging for extremely large scRNA-seq datasets. In Seurat v5, we introduce support for multiple on-disk storage formats.

As introduced in Hie et al, 2019, cell sketching methods aim to compactly summarize large single-cell datasets in a small number of cells, while preserving the presence of both abundant and rare cell types. In Seurat v5, we leverage this idea to select subsamples (‘sketches’) of cells from large datasets that are stored on-disk. However, after sketching, the subsampled cells can be stored in-memory, allowing for interactive and rapid visualization and exploration. We store sketched cells (in-memory) and the full dataset (on-disk) as two assays in the same Seurat object. Users can then easily switch between the two versions, providing the flexibility to perform quick analyses on a subset of cells in-memory, while retaining access to the full dataset on-disk.

We demonstrate the on-disk capabilities in Seurat v5 using the BPCells package developed by Ben Parks in the Greenleaf Lab. This package utilizes bit-packing compression and optimized, streaming-compatible C++ code to substantially improve I/O and computational performance when working with on-disk data. To run this vignette please install Seurat v5, using the installation instructions found here. Additionally, you will need to install the BPcells package, using the installation instructions found here.

We start by loading the 1.3M dataset from 10x Genomics using the open_matrix_dir function from BPCells. Note that in our Introduction to on-disk storage vignette, we demonstrate how to create this on-disk representation. This function does not load the dataset into memory, but instead, creates a connection to the data stored on-disk. We then store this on-disk representation in the Seurat object, which is loaded using readRDS as per usual.

We select a subset (‘sketch’) of 50,000 cells (out of 1.3M). Rather than sampling all cells with uniform probability, we compute and sample based off a ‘leverage score’ for each cell, which reflects the magnitude of its contribution to the gene-covariance matrix, and its importance to the overall dataset. In Hao et al, 2022, we demonstrate that the leverage score is highest for rare populations in a dataset. Therefore, our sketched set of 50,000 cells will oversample rare populations, retaining the biological complexity of the sample while drastically compressing the dataset.

The function SketchData takes a normalized single-cell dataset (stored either on-disk or in-memory), and a set of variable features. It returns a Seurat object with a new assay (sketch), consisting of 50,000 cells, but these cells are now stored in-memory. Users can now easily switch between the in-memory and on-disk representation just by changing the default assay.

Now that we have compressed the dataset, we can perform standard clustering and visualization of a 50,000 cell dataset. After clustering, we can see groups of cells that clearly correspond to precursors of distinct lineages, including endothelial cells (Igfbp7), Excitatory (Neurod6) and Inhibitory (Dlx2) neurons, Intermediate Progenitors (Eomes), Radial Glia (Vim), Cajal-Retzius cells (Reln), Oligodendroytes (Olig1), and extremely rare populations of macrophages (C1qa) that were oversampled in our sketched data.

We can now extend the cluster labels and dimensional reductions learned on the sketched cells to the full dataset. The ProjectData function projects the on-disk data, onto the sketch assay. It returns a Seurat object that includes a

Now that we have performed an initial analysis of the dataset, we can iteratively ‘zoom-in’ on a cell subtype of interest, extract all cells of this type, and perform iterative sub-clustering. For example, we can see that Dlx2+ interneuron precursors are defined by clusters 2, 15, 18, 28 and 40.

We therefore extract all cells from the full on-disk dataset that are present in these clusters. There are 200,892 of them. Since this is a manageable number, we can convert these data from on-disk storage into in-memory storage. We can then proceed with standard clustering.

Note that we can start to see distinct interneuron lineages emerging in this dataset. We can see a clear separation of interneuron precursors that originated from the medial ganglionic eminence (Lhx6) or caudal ganglionic eminence (Nr2f2). We can further see the emergence of Sst (Sst) and Pvalb (Mef2c)-committed interneurons, and a CGE-derived Meis2-expressing progenitor population. These results closely mirror our findings from Mayer, Hafemeister, Bandler* et al, Nature 2018, where we enriched for interneuron precursors using a Dlx6a-cre fate-mapping strategy. Here, we obtain similar results using only computational enrichment, enabled by the large size of the original dataset.

Developed by Rahul Satija, Satija Lab and Collaborators.

Site built with pkgdown 2.0.7.

**Examples:**

Example 1 (unknown):
```unknown
vignettes/seurat5_sketch_analysis.Rmd
```

Example 2 (unknown):
```unknown
seurat5_sketch_analysis.Rmd
```

Example 3 (unknown):
```unknown
library(Seurat)
library(BPCells)
library(ggplot2)
# needs to be set for large dataset analysis
options(future.globals.maxSize = 1e9)
```

Example 4 (r):
```r
library(Seurat)
library(BPCells)
library(ggplot2)
# needs to be set for large dataset analysis
options(future.globals.maxSize = 1e9)
```

Example 5 (r):
```r
library(Seurat)
library(BPCells)
library(ggplot2)
# needs to be set for large dataset analysis
options(future.globals.maxSize = 1e9)
```

Example 6 (unknown):
```unknown
open_matrix_dir
```

Example 7 (unknown):
```unknown
# Read the Seurat object, which contains 1.3M cells stored on-disk as part of the 'RNA' assay
obj <- readRDS("/brahms/hartmana/vignette_data/1p3_million_mouse_brain.rds")
obj
```

Example 8 (r):
```r
# Read the Seurat object, which contains 1.3M cells stored on-disk as part of the 'RNA' assay
obj <- readRDS("/brahms/hartmana/vignette_data/1p3_million_mouse_brain.rds")
obj
```

Example 9 (r):
```r
# Read the Seurat object, which contains 1.3M cells stored on-disk as part of the 'RNA' assay
obj <- readRDS("/brahms/hartmana/vignette_data/1p3_million_mouse_brain.rds")
obj
```

Example 10 (python):
```python
## An object of class Seurat 
## 27282 features across 1306127 samples within 1 assay 
## Active assay: RNA (27282 features, 0 variable features)
##  1 layer present: counts
```

Example 11 (python):
```python
## An object of class Seurat 
## 27282 features across 1306127 samples within 1 assay 
## Active assay: RNA (27282 features, 0 variable features)
##  1 layer present: counts
```

Example 12 (unknown):
```unknown
# Note that since the data is stored on-disk, the object size easily fits in-memory (<1GB)
format(object.size(obj), units = "Mb")
```

Example 13 (r):
```r
# Note that since the data is stored on-disk, the object size easily fits in-memory (<1GB)
format(object.size(obj), units = "Mb")
```

Example 14 (r):
```r
# Note that since the data is stored on-disk, the object size easily fits in-memory (<1GB)
format(object.size(obj), units = "Mb")
```

Example 15 (unknown):
```unknown
## [1] "596.2 Mb"
```

Example 16 (unknown):
```unknown
## [1] "596.2 Mb"
```

Example 17 (unknown):
```unknown
obj <- NormalizeData(obj)
obj <- FindVariableFeatures(obj)
obj <- SketchData(
  object = obj,
  ncells = 50000,
  method = "LeverageScore",
  sketched.assay = "sketch"
)
obj
```

Example 18 (r):
```r
obj <- NormalizeData(obj)
obj <- FindVariableFeatures(obj)
obj <- SketchData(
  object = obj,
  ncells = 50000,
  method = "LeverageScore",
  sketched.assay = "sketch"
)
obj
```

Example 19 (r):
```r
obj <- NormalizeData(obj)
obj <- FindVariableFeatures(obj)
obj <- SketchData(
  object = obj,
  ncells = 50000,
  method = "LeverageScore",
  sketched.assay = "sketch"
)
obj
```

Example 20 (python):
```python
## An object of class Seurat 
## 54564 features across 1306127 samples within 2 assays 
## Active assay: sketch (27282 features, 2000 variable features)
##  2 layers present: counts, data
##  1 other assay present: RNA
```

Example 21 (python):
```python
## An object of class Seurat 
## 54564 features across 1306127 samples within 2 assays 
## Active assay: sketch (27282 features, 2000 variable features)
##  2 layers present: counts, data
##  1 other assay present: RNA
```

Example 22 (unknown):
```unknown
# switch to analyzing the full dataset (on-disk)
DefaultAssay(obj) <- "RNA"
# switch to analyzing the sketched dataset (in-memory)
DefaultAssay(obj) <- "sketch"
```

Example 23 (r):
```r
# switch to analyzing the full dataset (on-disk)
DefaultAssay(obj) <- "RNA"
# switch to analyzing the sketched dataset (in-memory)
DefaultAssay(obj) <- "sketch"
```

Example 24 (r):
```r
# switch to analyzing the full dataset (on-disk)
DefaultAssay(obj) <- "RNA"
# switch to analyzing the sketched dataset (in-memory)
DefaultAssay(obj) <- "sketch"
```

Example 25 (unknown):
```unknown
DefaultAssay(obj) <- "sketch"
obj <- FindVariableFeatures(obj)
obj <- ScaleData(obj)
obj <- RunPCA(obj)
obj <- FindNeighbors(obj, dims = 1:50)
obj <- FindClusters(obj, resolution = 2)
```

Example 26 (r):
```r
DefaultAssay(obj) <- "sketch"
obj <- FindVariableFeatures(obj)
obj <- ScaleData(obj)
obj <- RunPCA(obj)
obj <- FindNeighbors(obj, dims = 1:50)
obj <- FindClusters(obj, resolution = 2)
```

Example 27 (r):
```r
DefaultAssay(obj) <- "sketch"
obj <- FindVariableFeatures(obj)
obj <- ScaleData(obj)
obj <- RunPCA(obj)
obj <- FindNeighbors(obj, dims = 1:50)
obj <- FindClusters(obj, resolution = 2)
```

Example 28 (unknown):
```unknown
## Modularity Optimizer version 1.3.0 by Ludo Waltman and Nees Jan van Eck
## 
## Number of nodes: 50000
## Number of edges: 1992657
## 
## Running Louvain algorithm...
## Maximum modularity in 10 random starts: 0.8766
## Number of communities: 51
## Elapsed time: 19 seconds
```

Example 29 (unknown):
```unknown
## Modularity Optimizer version 1.3.0 by Ludo Waltman and Nees Jan van Eck
## 
## Number of nodes: 50000
## Number of edges: 1992657
## 
## Running Louvain algorithm...
## Maximum modularity in 10 random starts: 0.8766
## Number of communities: 51
## Elapsed time: 19 seconds
```

Example 30 (unknown):
```unknown
obj <- RunUMAP(obj, dims = 1:50, return.model = T)
DimPlot(obj, label = T, label.size = 3, reduction = "umap") + NoLegend()
```

Example 31 (r):
```r
obj <- RunUMAP(obj, dims = 1:50, return.model = T)
DimPlot(obj, label = T, label.size = 3, reduction = "umap") + NoLegend()
```

Example 32 (r):
```r
obj <- RunUMAP(obj, dims = 1:50, return.model = T)
DimPlot(obj, label = T, label.size = 3, reduction = "umap") + NoLegend()
```

Example 33 (unknown):
```unknown
FeaturePlot(
  object = obj,
  features = c(
    "Igfbp7", "Neurod6", "Dlx2", "Gad2",
    "Eomes", "Vim", "Reln", "Olig1", "C1qa"
  ),
  ncol = 3
)
```

Example 34 (r):
```r
FeaturePlot(
  object = obj,
  features = c(
    "Igfbp7", "Neurod6", "Dlx2", "Gad2",
    "Eomes", "Vim", "Reln", "Olig1", "C1qa"
  ),
  ncol = 3
)
```

Example 35 (r):
```r
FeaturePlot(
  object = obj,
  features = c(
    "Igfbp7", "Neurod6", "Dlx2", "Gad2",
    "Eomes", "Vim", "Reln", "Olig1", "C1qa"
  ),
  ncol = 3
)
```

Example 36 (unknown):
```unknown
ProjectData
```

Example 37 (unknown):
```unknown
cluster_full
```

Example 38 (unknown):
```unknown
obj <- ProjectData(
  object = obj,
  assay = "RNA",
  full.reduction = "pca.full",
  sketched.assay = "sketch",
  sketched.reduction = "pca",
  umap.model = "umap",
  dims = 1:50,
  refdata = list(cluster_full = "seurat_clusters")
)
# now that we have projected the full dataset, switch back to analyzing all cells
DefaultAssay(obj) <- "RNA"
```

Example 39 (r):
```r
obj <- ProjectData(
  object = obj,
  assay = "RNA",
  full.reduction = "pca.full",
  sketched.assay = "sketch",
  sketched.reduction = "pca",
  umap.model = "umap",
  dims = 1:50,
  refdata = list(cluster_full = "seurat_clusters")
)
# now that we have projected the full dataset, switch back to analyzing all cells
DefaultAssay(obj) <- "RNA"
```

Example 40 (r):
```r
obj <- ProjectData(
  object = obj,
  assay = "RNA",
  full.reduction = "pca.full",
  sketched.assay = "sketch",
  sketched.reduction = "pca",
  umap.model = "umap",
  dims = 1:50,
  refdata = list(cluster_full = "seurat_clusters")
)
# now that we have projected the full dataset, switch back to analyzing all cells
DefaultAssay(obj) <- "RNA"
```

Example 41 (unknown):
```unknown
DimPlot(obj, label = T, label.size = 3, reduction = "full.umap", group.by = "cluster_full", alpha = 0.1) + NoLegend()
```

Example 42 (r):
```r
DimPlot(obj, label = T, label.size = 3, reduction = "full.umap", group.by = "cluster_full", alpha = 0.1) + NoLegend()
```

Example 43 (r):
```r
DimPlot(obj, label = T, label.size = 3, reduction = "full.umap", group.by = "cluster_full", alpha = 0.1) + NoLegend()
```

Example 44 (unknown):
```unknown
# visualize gene expression on the sketched cells (fast) and the full dataset (slower)
DefaultAssay(obj) <- "sketch"
x1 <- FeaturePlot(obj, "C1qa")
DefaultAssay(obj) <- "RNA"
x2 <- FeaturePlot(obj, "C1qa")
x1 | x2
```

Example 45 (r):
```r
# visualize gene expression on the sketched cells (fast) and the full dataset (slower)
DefaultAssay(obj) <- "sketch"
x1 <- FeaturePlot(obj, "C1qa")
DefaultAssay(obj) <- "RNA"
x2 <- FeaturePlot(obj, "C1qa")
x1 | x2
```

Example 46 (r):
```r
# visualize gene expression on the sketched cells (fast) and the full dataset (slower)
DefaultAssay(obj) <- "sketch"
x1 <- FeaturePlot(obj, "C1qa")
DefaultAssay(obj) <- "RNA"
x2 <- FeaturePlot(obj, "C1qa")
x1 | x2
```

Example 47 (unknown):
```unknown
DefaultAssay(obj) <- "sketch"
VlnPlot(obj, "Dlx2")
```

Example 48 (r):
```r
DefaultAssay(obj) <- "sketch"
VlnPlot(obj, "Dlx2")
```

Example 49 (r):
```r
DefaultAssay(obj) <- "sketch"
VlnPlot(obj, "Dlx2")
```

Example 50 (unknown):
```unknown
# subset cells in these clusters. Note that the data remains on-disk after subsetting
obj.sub <- subset(obj, subset = cluster_full %in% c(2, 15, 18, 28, 40))
DefaultAssay(obj.sub) <- "RNA"

# now convert the RNA assay (previously on-disk) into an in-memory representation (sparse Matrix)
# we only convert the data layer, and keep the counts on-disk
obj.sub[["RNA"]]$data <- as(obj.sub[["RNA"]]$data, Class = "dgCMatrix")

# recluster the cells
obj.sub <- FindVariableFeatures(obj.sub)
obj.sub <- ScaleData(obj.sub)
obj.sub <- RunPCA(obj.sub)
obj.sub <- RunUMAP(obj.sub, dims = 1:30)
obj.sub <- FindNeighbors(obj.sub, dims = 1:30)
obj.sub <- FindClusters(obj.sub)
```

Example 51 (r):
```r
# subset cells in these clusters. Note that the data remains on-disk after subsetting
obj.sub <- subset(obj, subset = cluster_full %in% c(2, 15, 18, 28, 40))
DefaultAssay(obj.sub) <- "RNA"

# now convert the RNA assay (previously on-disk) into an in-memory representation (sparse Matrix)
# we only convert the data layer, and keep the counts on-disk
obj.sub[["RNA"]]$data <- as(obj.sub[["RNA"]]$data, Class = "dgCMatrix")

# recluster the cells
obj.sub <- FindVariableFeatures(obj.sub)
obj.sub <- ScaleData(obj.sub)
obj.sub <- RunPCA(obj.sub)
obj.sub <- RunUMAP(obj.sub, dims = 1:30)
obj.sub <- FindNeighbors(obj.sub, dims = 1:30)
obj.sub <- FindClusters(obj.sub)
```

Example 52 (r):
```r
# subset cells in these clusters. Note that the data remains on-disk after subsetting
obj.sub <- subset(obj, subset = cluster_full %in% c(2, 15, 18, 28, 40))
DefaultAssay(obj.sub) <- "RNA"

# now convert the RNA assay (previously on-disk) into an in-memory representation (sparse Matrix)
# we only convert the data layer, and keep the counts on-disk
obj.sub[["RNA"]]$data <- as(obj.sub[["RNA"]]$data, Class = "dgCMatrix")

# recluster the cells
obj.sub <- FindVariableFeatures(obj.sub)
obj.sub <- ScaleData(obj.sub)
obj.sub <- RunPCA(obj.sub)
obj.sub <- RunUMAP(obj.sub, dims = 1:30)
obj.sub <- FindNeighbors(obj.sub, dims = 1:30)
obj.sub <- FindClusters(obj.sub)
```

Example 53 (unknown):
```unknown
## Modularity Optimizer version 1.3.0 by Ludo Waltman and Nees Jan van Eck
## 
## Number of nodes: 236276
## Number of edges: 5470656
## 
## Running Louvain algorithm...
## Maximum modularity in 10 random starts: 0.8577
## Number of communities: 28
## Elapsed time: 191 seconds
```

Example 54 (unknown):
```unknown
## Modularity Optimizer version 1.3.0 by Ludo Waltman and Nees Jan van Eck
## 
## Number of nodes: 236276
## Number of edges: 5470656
## 
## Running Louvain algorithm...
## Maximum modularity in 10 random starts: 0.8577
## Number of communities: 28
## Elapsed time: 191 seconds
```

Example 55 (unknown):
```unknown
DimPlot(obj.sub, label = T, label.size = 3) + NoLegend()
```

Example 56 (r):
```r
DimPlot(obj.sub, label = T, label.size = 3) + NoLegend()
```

Example 57 (r):
```r
DimPlot(obj.sub, label = T, label.size = 3) + NoLegend()
```

Example 58 (unknown):
```unknown
FeaturePlot(
  object = obj.sub,
  features = c(
    "Dlx2", "Gad2", "Lhx6", "Nr2f2", "Sst",
    "Mef2c", "Meis2", "Id2", "Dlx6os1"
  ),
  ncol = 3
)
```

Example 59 (r):
```r
FeaturePlot(
  object = obj.sub,
  features = c(
    "Dlx2", "Gad2", "Lhx6", "Nr2f2", "Sst",
    "Mef2c", "Meis2", "Id2", "Dlx6os1"
  ),
  ncol = 3
)
```

Example 60 (r):
```r
FeaturePlot(
  object = obj.sub,
  features = c(
    "Dlx2", "Gad2", "Lhx6", "Nr2f2", "Sst",
    "Mef2c", "Meis2", "Id2", "Dlx6os1"
  ),
  ncol = 3
)
```

Example 61 (unknown):
```unknown
sessionInfo()
```

Example 62 (r):
```r
sessionInfo()
```

Example 63 (r):
```r
sessionInfo()
```

Example 64 (unknown):
```unknown
## R version 4.2.2 Patched (2022-11-10 r83330)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.6 LTS
## 
## Matrix products: default
## BLAS:   /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.9.0
## LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.9.0
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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       
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
## [1] ggplot2_3.4.4      BPCells_0.1.0      Seurat_5.0.0       SeuratObject_5.0.0
## [5] sp_2.1-1          
## 
## loaded via a namespace (and not attached):
##   [1] spam_2.10-0            systemfonts_1.0.4      plyr_1.8.9            
##   [4] igraph_1.5.1           lazyeval_0.2.2         splines_4.2.2         
##   [7] RcppHNSW_0.5.0         listenv_0.9.0          scattermore_1.2       
##  [10] GenomeInfoDb_1.34.9    digest_0.6.33          htmltools_0.5.6.1     
##  [13] fansi_1.0.5            magrittr_2.0.3         memoise_2.0.1         
##  [16] tensor_1.5             cluster_2.1.4          ROCR_1.0-11           
##  [19] globals_0.16.2         matrixStats_1.0.0      R.utils_2.12.2        
##  [22] pkgdown_2.0.7          spatstat.sparse_3.0-3  colorspace_2.1-0      
##  [25] ggrepel_0.9.4          textshaping_0.3.6      xfun_0.40             
##  [28] dplyr_1.1.3            RCurl_1.98-1.12        jsonlite_1.8.7        
##  [31] progressr_0.14.0       spatstat.data_3.0-3    survival_3.5-7        
##  [34] zoo_1.8-12             glue_1.6.2             polyclip_1.10-6       
##  [37] gtable_0.3.4           zlibbioc_1.44.0        XVector_0.38.0        
##  [40] leiden_0.4.3           R.cache_0.16.0         future.apply_1.11.0   
##  [43] BiocGenerics_0.44.0    abind_1.4-5            scales_1.2.1          
##  [46] spatstat.random_3.2-1  miniUI_0.1.1.1         Rcpp_1.0.11           
##  [49] viridisLite_0.4.2      xtable_1.8-4           reticulate_1.34.0     
##  [52] dotCall64_1.1-0        stats4_4.2.2           htmlwidgets_1.6.2     
##  [55] httr_1.4.7             RColorBrewer_1.1-3     ellipsis_0.3.2        
##  [58] ica_1.0-3              farver_2.1.1           pkgconfig_2.0.3       
##  [61] R.methodsS3_1.8.2      sass_0.4.7             uwot_0.1.16           
##  [64] deldir_1.0-9           utf8_1.2.4             labeling_0.4.3        
##  [67] tidyselect_1.2.0       rlang_1.1.1            reshape2_1.4.4        
##  [70] later_1.3.1            munsell_0.5.0          tools_4.2.2           
##  [73] cachem_1.0.8           cli_3.6.1              generics_0.1.3        
##  [76] ggridges_0.5.4         evaluate_0.22          stringr_1.5.0         
##  [79] fastmap_1.1.1          yaml_2.3.7             ragg_1.2.5            
##  [82] goftest_1.2-3          knitr_1.45             fs_1.6.3              
##  [85] fitdistrplus_1.1-11    purrr_1.0.2            RANN_2.6.1            
##  [88] pbapply_1.7-2          future_1.33.0          nlme_3.1-162          
##  [91] mime_0.12              ggrastr_1.0.1          R.oo_1.25.0           
##  [94] compiler_4.2.2         beeswarm_0.4.0         plotly_4.10.3         
##  [97] png_0.1-8              spatstat.utils_3.0-4   tibble_3.2.1          
## [100] bslib_0.5.1            stringi_1.7.12         highr_0.10            
## [103] desc_1.4.2             RSpectra_0.16-1        lattice_0.21-9        
## [106] Matrix_1.6-1.1         styler_1.10.2          vctrs_0.6.4           
## [109] pillar_1.9.0           lifecycle_1.0.3        spatstat.geom_3.2-7   
## [112] lmtest_0.9-40          jquerylib_0.1.4        RcppAnnoy_0.0.21      
## [115] bitops_1.0-7           data.table_1.14.8      cowplot_1.1.1         
## [118] irlba_2.3.5.1          httpuv_1.6.12          patchwork_1.1.3       
## [121] GenomicRanges_1.50.2   R6_2.5.1               promises_1.2.1        
## [124] KernSmooth_2.23-22     gridExtra_2.3          vipor_0.4.5           
## [127] IRanges_2.32.0         parallelly_1.36.0      codetools_0.2-19      
## [130] fastDummies_1.7.3      MASS_7.3-58.2          rprojroot_2.0.3       
## [133] withr_2.5.2            sctransform_0.4.1      GenomeInfoDbData_1.2.9
## [136] S4Vectors_0.36.2       parallel_4.2.2         grid_4.2.2            
## [139] tidyr_1.3.0            rmarkdown_2.25         Rtsne_0.16            
## [142] spatstat.explore_3.2-5 shiny_1.7.5.1          ggbeeswarm_0.7.1
```

Example 65 (unknown):
```unknown
## R version 4.2.2 Patched (2022-11-10 r83330)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.6 LTS
## 
## Matrix products: default
## BLAS:   /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.9.0
## LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.9.0
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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       
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
## [1] ggplot2_3.4.4      BPCells_0.1.0      Seurat_5.0.0       SeuratObject_5.0.0
## [5] sp_2.1-1          
## 
## loaded via a namespace (and not attached):
##   [1] spam_2.10-0            systemfonts_1.0.4      plyr_1.8.9            
##   [4] igraph_1.5.1           lazyeval_0.2.2         splines_4.2.2         
##   [7] RcppHNSW_0.5.0         listenv_0.9.0          scattermore_1.2       
##  [10] GenomeInfoDb_1.34.9    digest_0.6.33          htmltools_0.5.6.1     
##  [13] fansi_1.0.5            magrittr_2.0.3         memoise_2.0.1         
##  [16] tensor_1.5             cluster_2.1.4          ROCR_1.0-11           
##  [19] globals_0.16.2         matrixStats_1.0.0      R.utils_2.12.2        
##  [22] pkgdown_2.0.7          spatstat.sparse_3.0-3  colorspace_2.1-0      
##  [25] ggrepel_0.9.4          textshaping_0.3.6      xfun_0.40             
##  [28] dplyr_1.1.3            RCurl_1.98-1.12        jsonlite_1.8.7        
##  [31] progressr_0.14.0       spatstat.data_3.0-3    survival_3.5-7        
##  [34] zoo_1.8-12             glue_1.6.2             polyclip_1.10-6       
##  [37] gtable_0.3.4           zlibbioc_1.44.0        XVector_0.38.0        
##  [40] leiden_0.4.3           R.cache_0.16.0         future.apply_1.11.0   
##  [43] BiocGenerics_0.44.0    abind_1.4-5            scales_1.2.1          
##  [46] spatstat.random_3.2-1  miniUI_0.1.1.1         Rcpp_1.0.11           
##  [49] viridisLite_0.4.2      xtable_1.8-4           reticulate_1.34.0     
##  [52] dotCall64_1.1-0        stats4_4.2.2           htmlwidgets_1.6.2     
##  [55] httr_1.4.7             RColorBrewer_1.1-3     ellipsis_0.3.2        
##  [58] ica_1.0-3              farver_2.1.1           pkgconfig_2.0.3       
##  [61] R.methodsS3_1.8.2      sass_0.4.7             uwot_0.1.16           
##  [64] deldir_1.0-9           utf8_1.2.4             labeling_0.4.3        
##  [67] tidyselect_1.2.0       rlang_1.1.1            reshape2_1.4.4        
##  [70] later_1.3.1            munsell_0.5.0          tools_4.2.2           
##  [73] cachem_1.0.8           cli_3.6.1              generics_0.1.3        
##  [76] ggridges_0.5.4         evaluate_0.22          stringr_1.5.0         
##  [79] fastmap_1.1.1          yaml_2.3.7             ragg_1.2.5            
##  [82] goftest_1.2-3          knitr_1.45             fs_1.6.3              
##  [85] fitdistrplus_1.1-11    purrr_1.0.2            RANN_2.6.1            
##  [88] pbapply_1.7-2          future_1.33.0          nlme_3.1-162          
##  [91] mime_0.12              ggrastr_1.0.1          R.oo_1.25.0           
##  [94] compiler_4.2.2         beeswarm_0.4.0         plotly_4.10.3         
##  [97] png_0.1-8              spatstat.utils_3.0-4   tibble_3.2.1          
## [100] bslib_0.5.1            stringi_1.7.12         highr_0.10            
## [103] desc_1.4.2             RSpectra_0.16-1        lattice_0.21-9        
## [106] Matrix_1.6-1.1         styler_1.10.2          vctrs_0.6.4           
## [109] pillar_1.9.0           lifecycle_1.0.3        spatstat.geom_3.2-7   
## [112] lmtest_0.9-40          jquerylib_0.1.4        RcppAnnoy_0.0.21      
## [115] bitops_1.0-7           data.table_1.14.8      cowplot_1.1.1         
## [118] irlba_2.3.5.1          httpuv_1.6.12          patchwork_1.1.3       
## [121] GenomicRanges_1.50.2   R6_2.5.1               promises_1.2.1        
## [124] KernSmooth_2.23-22     gridExtra_2.3          vipor_0.4.5           
## [127] IRanges_2.32.0         parallelly_1.36.0      codetools_0.2-19      
## [130] fastDummies_1.7.3      MASS_7.3-58.2          rprojroot_2.0.3       
## [133] withr_2.5.2            sctransform_0.4.1      GenomeInfoDbData_1.2.9
## [136] S4Vectors_0.36.2       parallel_4.2.2         grid_4.2.2            
## [139] tidyr_1.3.0            rmarkdown_2.25         Rtsne_0.16            
## [142] spatstat.explore_3.2-5 shiny_1.7.5.1          ggbeeswarm_0.7.1
```

---

## Analysis, visualization, and integration of Visium HD spatial datasets with Seurat • Seurat

**URL:** http://127.0.0.1:9173/seurat/articles/get_started/index.html

**Contents:**
- Getting Started with Seurat v4
- Introductory Vignettes
- Data Integration
- Additional New Methods
- Other
- SeuratWrappers
- Contents

We provide a series of vignettes, tutorials, and analysis walkthroughs to help users get started with Seurat. You can also check out our Reference page which contains a full list of functions available to users.

For new users of Seurat, we suggest starting with a guided walk through of a dataset of 2,700 Peripheral Blood Mononuclear Cells (PBMCs) made publicly available by 10X Genomics. This tutorial implements the major components of a standard unsupervised clustering workflow including QC and data filtration, calculation of high-variance genes, dimensional reduction, graph-based clustering, and the identification of cluster markers.

We provide additional introductory vignettes for users who are interested in analyzing multimodal single-cell datasets (e.g. from CITE-seq, or the 10x multiome kit), or spatial datasets (e.g. 10x Visium or Vizgen MERFISH).

Recently, we have developed computational methods for integrated analysis of single-cell datasets generated across different conditions, technologies, or species. As an example, we provide a guided walk through for integrating and comparing PBMC datasets generated under different stimulation conditions. We provide additional vignettes demonstrating how to leverage an annotated scRNA-seq reference to map and label cells from a query, and to efficiently integrate large datasets.

Seurat also offers additional novel statistical methods for analyzing single-cell data. These include:

Here we provide a series of short vignettes to demonstrate a number of features that are commonly used in Seurat. We’ve focused the vignettes around questions that we frequently receive from users. Click on a vignette to get started.

In order to facilitate the use of community tools with Seurat, we provide the Seurat Wrappers package, which contains code to run other analysis tools on Seurat objects. For the initial release, we provide wrappers for a few packages in the table below but would encourage other package developers interested in interfacing with Seurat to check out our contributor guide here.

Developed by Rahul Satija, Satija Lab and Collaborators.

Site built with pkgdown 2.0.7.

**Examples:**

Example 1 (unknown):
```unknown
vignettes/get_started.Rmd
```

Example 2 (unknown):
```unknown
get_started.Rmd
```

---

## New data visualization methods in v3.0

**URL:** http://127.0.0.1:9173/seurat/archive/v3.0/visualization_vignette/index.html

**Contents:**
- New data visualization methods in v3.0
    - Compiled: 2019-06-24
  - Five visualizations of marker feature expression
  - New additions to FeaturePlot
  - Updated and expanded visualization functions
  - Applying themes to plots
  - Interactive plotting features
  - Plotting Accessories

We’ll demonstrate visualization techniques in Seurat using our previously computed Seurat object from the 2,700 PBMC tutorial. You can download that here

In addition to changes to FeaturePlot, several other plotting functions have been updated and expanded with new features and taking over the role of now-deprecated functions

With Seurat v3.0, all plotting functions return ggplot2-based plots by default, allowing one to easily capture and manipulate plots just like any other ggplot2-based plot.

Seurat utilizes R’s plotly graphing library to create interactive plots. This interactive plotting feature works with any ggplot2-based scatter plots (requires a geom_point layer). To use, simply make a ggplot2-based scatter plot (such as DimPlot or FeaturePlot) and pass the resulting plot to HoverLocator

Another interactive feature provided by Seurat is being able to manually select cells for further investigation. We have found this particularly useful for small clusters that do not always separate using unbiased clustering, but which look tantalizingly distinct. You can now select these cells by creating a ggplot2-based scatter plot (such as with DimPlot or FeaturePlot, and passing the returned plot to CellSelector. CellSelector will return a vector with the names of the points selected, so that you can then set them to a new identity class and perform differential expression.

For example, lets pretend that DCs had merged with monocytes in the clustering, but we wanted to see what was unique about them based on their position in the tSNE plot.

We can then use SetIdent to turn these cells into their own mini-cluster.

Using CellSelector to Automatically Assign Cell Identities

In addition to returning a vector of cell names, CellSelector can also take the selected cells and assign a new identity to them, returning a Seurat object with the identity classes already set. This is done by passing the Seurat object used to make the plot into CellSelector, as well as an identity class. As an example, we’re going to select the same set of cells as before, and set their identity class to “selected”

Along with new functions add interactive functionality to plots, Seurat provides new accessory functions for manipulating and combining plots.

**Examples:**

Example 1 (r):
```r
library(Seurat)
library(ggplot2)
pbmc <- readRDS(file = "../data/pbmc3k_final.rds")
pbmc$groups <- sample(c("group1", "group2"), size = ncol(pbmc), replace = TRUE)
features <- c("LYZ", "CCL5", "IL32", "PTPRCAP", "FCGR3A", "PF4")
pbmc
```

Example 2 (r):
```r
library(Seurat)
library(ggplot2)
pbmc <- readRDS(file = "../data/pbmc3k_final.rds")
pbmc$groups <- sample(c("group1", "group2"), size = ncol(pbmc), replace = TRUE)
features <- c("LYZ", "CCL5", "IL32", "PTPRCAP", "FCGR3A", "PF4")
pbmc
```

Example 3 (python):
```python
## An object of class Seurat 
## 13714 features across 2638 samples within 1 assay 
## Active assay: RNA (13714 features)
##  2 dimensional reductions calculated: pca, umap
```

Example 4 (python):
```python
## An object of class Seurat 
## 13714 features across 2638 samples within 1 assay 
## Active assay: RNA (13714 features)
##  2 dimensional reductions calculated: pca, umap
```

Example 5 (r):
```r
# Ridge plots - from ggridges. Visualize single cell expression distributions in each cluster
RidgePlot(pbmc, features = features, ncol = 2)
```

Example 6 (r):
```r
# Ridge plots - from ggridges. Visualize single cell expression distributions in each cluster
RidgePlot(pbmc, features = features, ncol = 2)
```

Example 7 (r):
```r
# Violin plot - Visualize single cell expression distributions in each cluster
VlnPlot(pbmc, features = features)
```

Example 8 (r):
```r
# Violin plot - Visualize single cell expression distributions in each cluster
VlnPlot(pbmc, features = features)
```

Example 9 (r):
```r
# Feature plot - visualize feature expression in low-dimensional space
FeaturePlot(pbmc, features = features)
```

Example 10 (r):
```r
# Feature plot - visualize feature expression in low-dimensional space
FeaturePlot(pbmc, features = features)
```

Example 11 (r):
```r
# Dot plots - the size of the dot corresponds to the percentage of cells expressing the feature
# in each cluster. The color represents the average expression level
DotPlot(pbmc, features = features) + RotatedAxis()
```

Example 12 (r):
```r
# Dot plots - the size of the dot corresponds to the percentage of cells expressing the feature
# in each cluster. The color represents the average expression level
DotPlot(pbmc, features = features) + RotatedAxis()
```

Example 13 (r):
```r
# Single cell heatmap of feature expression
DoHeatmap(subset(pbmc, downsample = 100), features = features, size = 3)
```

Example 14 (r):
```r
# Single cell heatmap of feature expression
DoHeatmap(subset(pbmc, downsample = 100), features = features, size = 3)
```

Example 15 (unknown):
```unknown
FeaturePlot
```

Example 16 (r):
```r
# Plot a legend to map colors to expression levels
FeaturePlot(pbmc, features = "MS4A1")
```

Example 17 (r):
```r
# Plot a legend to map colors to expression levels
FeaturePlot(pbmc, features = "MS4A1")
```

Example 18 (r):
```r
# Adjust the contrast in the plot
FeaturePlot(pbmc, features = "MS4A1", min.cutoff = 1, max.cutoff = 3)
```

Example 19 (r):
```r
# Adjust the contrast in the plot
FeaturePlot(pbmc, features = "MS4A1", min.cutoff = 1, max.cutoff = 3)
```

Example 20 (r):
```r
# Calculate feature-specific contrast levels based on quantiles of non-zero expression.
# Particularly useful when plotting multiple markers
FeaturePlot(pbmc, features = c("MS4A1", "PTPRCAP"), min.cutoff = "q10", max.cutoff = "q90")
```

Example 21 (r):
```r
# Calculate feature-specific contrast levels based on quantiles of non-zero expression.
# Particularly useful when plotting multiple markers
FeaturePlot(pbmc, features = c("MS4A1", "PTPRCAP"), min.cutoff = "q10", max.cutoff = "q90")
```

Example 22 (r):
```r
# Visualize co-expression of two features simultaneously
FeaturePlot(pbmc, features = c("MS4A1", "CD79A"), blend = TRUE)
```

Example 23 (r):
```r
# Visualize co-expression of two features simultaneously
FeaturePlot(pbmc, features = c("MS4A1", "CD79A"), blend = TRUE)
```

Example 24 (r):
```r
# Split visualization to view expression by groups (replaces FeatureHeatmap)
FeaturePlot(pbmc, features = c("MS4A1", "CD79A"), split.by = "groups")
```

Example 25 (r):
```r
# Split visualization to view expression by groups (replaces FeatureHeatmap)
FeaturePlot(pbmc, features = c("MS4A1", "CD79A"), split.by = "groups")
```

Example 26 (unknown):
```unknown
FeaturePlot
```

Example 27 (r):
```r
# Violin plots can also be split on some variable. Simply add the splitting variable to object
# metadata and pass it to the split.by argument
VlnPlot(pbmc, features = "percent.mt", split.by = "groups")
```

Example 28 (r):
```r
# Violin plots can also be split on some variable. Simply add the splitting variable to object
# metadata and pass it to the split.by argument
VlnPlot(pbmc, features = "percent.mt", split.by = "groups")
```

Example 29 (r):
```r
# SplitDotPlotGG has been replaced with the `split.by` parameter for DotPlot
DotPlot(pbmc, features = features, split.by = "groups") + RotatedAxis()
```

Example 30 (r):
```r
# SplitDotPlotGG has been replaced with the `split.by` parameter for DotPlot
DotPlot(pbmc, features = features, split.by = "groups") + RotatedAxis()
```

Example 31 (r):
```r
# DimPlot replaces TSNEPlot, PCAPlot, etc. In addition, it will plot either 'umap', 'tsne', or
# 'pca' by default, in that order
DimPlot(pbmc)
```

Example 32 (r):
```r
# DimPlot replaces TSNEPlot, PCAPlot, etc. In addition, it will plot either 'umap', 'tsne', or
# 'pca' by default, in that order
DimPlot(pbmc)
```

Example 33 (r):
```r
pbmc.no.umap <- pbmc
pbmc.no.umap[["umap"]] <- NULL
DimPlot(pbmc.no.umap) + RotatedAxis()
```

Example 34 (r):
```r
pbmc.no.umap <- pbmc
pbmc.no.umap[["umap"]] <- NULL
DimPlot(pbmc.no.umap) + RotatedAxis()
```

Example 35 (r):
```r
# DoHeatmap now shows a grouping bar, splitting the heatmap into groups or clusters. This can be
# changed with the `group.by` parameter
DoHeatmap(pbmc, features = VariableFeatures(pbmc)[1:100], cells = 1:500, size = 4, angle = 90) + 
    NoLegend()
```

Example 36 (r):
```r
# DoHeatmap now shows a grouping bar, splitting the heatmap into groups or clusters. This can be
# changed with the `group.by` parameter
DoHeatmap(pbmc, features = VariableFeatures(pbmc)[1:100], cells = 1:500, size = 4, angle = 90) + 
    NoLegend()
```

Example 37 (r):
```r
baseplot <- DimPlot(pbmc, reduction = "umap")
# Add custom labels and titles
baseplot + labs(title = "Clustering of 2,700 PBMCs")
```

Example 38 (r):
```r
baseplot <- DimPlot(pbmc, reduction = "umap")
# Add custom labels and titles
baseplot + labs(title = "Clustering of 2,700 PBMCs")
```

Example 39 (r):
```r
# Use community-created themes, overwriting the default Seurat-applied theme Install ggmin with
# devtools::install_github('sjessa/ggmin')
baseplot + ggmin::theme_powerpoint()
```

Example 40 (r):
```r
# Use community-created themes, overwriting the default Seurat-applied theme Install ggmin with
# devtools::install_github('sjessa/ggmin')
baseplot + ggmin::theme_powerpoint()
```

Example 41 (r):
```r
# Seurat also provides several built-in themes, such as DarkTheme; for more details see
# ?SeuratTheme
baseplot + DarkTheme()
```

Example 42 (r):
```r
# Seurat also provides several built-in themes, such as DarkTheme; for more details see
# ?SeuratTheme
baseplot + DarkTheme()
```

Example 43 (r):
```r
# Chain themes together
baseplot + FontSize(x.title = 20, y.title = 20) + NoLegend()
```

Example 44 (r):
```r
# Chain themes together
baseplot + FontSize(x.title = 20, y.title = 20) + NoLegend()
```

Example 45 (unknown):
```unknown
FeaturePlot
```

Example 46 (unknown):
```unknown
HoverLocator
```

Example 47 (r):
```r
# Include additional data to display alongside cell names by passing in a data frame of
# information Works well when using FetchData
plot <- FeaturePlot(pbmc, features = "MS4A1")
HoverLocator(plot = plot, information = FetchData(pbmc, vars = c("ident", "PC_1", "nFeature_RNA")))
```

Example 48 (r):
```r
# Include additional data to display alongside cell names by passing in a data frame of
# information Works well when using FetchData
plot <- FeaturePlot(pbmc, features = "MS4A1")
HoverLocator(plot = plot, information = FetchData(pbmc, vars = c("ident", "PC_1", "nFeature_RNA")))
```

Example 49 (unknown):
```unknown
FeaturePlot
```

Example 50 (unknown):
```unknown
CellSelector
```

Example 51 (unknown):
```unknown
CellSelector
```

Example 52 (r):
```r
pbmc <- RenameIdents(pbmc, DC = "CD14+ Mono")
plot <- DimPlot(pbmc, reduction = "umap")
select.cells <- CellSelector(plot = plot)
```

Example 53 (r):
```r
pbmc <- RenameIdents(pbmc, DC = "CD14+ Mono")
plot <- DimPlot(pbmc, reduction = "umap")
select.cells <- CellSelector(plot = plot)
```

Example 54 (r):
```r
head(select.cells)
```

Example 55 (r):
```r
head(select.cells)
```

Example 56 (unknown):
```unknown
## [1] "AAGATTACCGCCTT" "AAGCCATGAACTGC" "AATTACGAATTCCT" "ACCCGTTGCTTCTA"
## [5] "ACGAGGGACAGGAG" "ACGTGATGCCATGA"
```

Example 57 (unknown):
```unknown
## [1] "AAGATTACCGCCTT" "AAGCCATGAACTGC" "AATTACGAATTCCT" "ACCCGTTGCTTCTA"
## [5] "ACGAGGGACAGGAG" "ACGTGATGCCATGA"
```

Example 58 (r):
```r
Idents(pbmc, cells = select.cells) <- "NewCells"

# Now, we find markers that are specific to the new cells, and find clear DC markers
newcells.markers <- FindMarkers(pbmc, ident.1 = "NewCells", ident.2 = "CD14+ Mono", min.diff.pct = 0.3, 
    only.pos = TRUE)
head(newcells.markers)
```

Example 59 (r):
```r
Idents(pbmc, cells = select.cells) <- "NewCells"

# Now, we find markers that are specific to the new cells, and find clear DC markers
newcells.markers <- FindMarkers(pbmc, ident.1 = "NewCells", ident.2 = "CD14+ Mono", min.diff.pct = 0.3, 
    only.pos = TRUE)
head(newcells.markers)
```

Example 60 (unknown):
```unknown
CellSelector
```

Example 61 (unknown):
```unknown
CellSelector
```

Example 62 (unknown):
```unknown
CellSelector
```

Example 63 (r):
```r
pbmc <- CellSelector(plot = plot, object = pbmc, ident = "selected")
```

Example 64 (r):
```r
pbmc <- CellSelector(plot = plot, object = pbmc, ident = "selected")
```

Example 65 (r):
```r
levels(pbmc)
```

Example 66 (r):
```r
levels(pbmc)
```

Example 67 (unknown):
```unknown
## [1] "selected"     "Naive CD4 T"  "Memory CD4 T" "CD14+ Mono"  
## [5] "B"            "CD8 T"        "FCGR3A+ Mono" "NK"          
## [9] "Platelet"
```

Example 68 (unknown):
```unknown
## [1] "selected"     "Naive CD4 T"  "Memory CD4 T" "CD14+ Mono"  
## [5] "B"            "CD8 T"        "FCGR3A+ Mono" "NK"          
## [9] "Platelet"
```

Example 69 (r):
```r
# LabelClusters and LabelPoints will label clusters (a coloring variable) or individual points
# on a ggplot2-based scatter plot
plot <- DimPlot(pbmc, reduction = "pca") + NoLegend()
LabelClusters(plot = plot, id = "ident")
```

Example 70 (r):
```r
# LabelClusters and LabelPoints will label clusters (a coloring variable) or individual points
# on a ggplot2-based scatter plot
plot <- DimPlot(pbmc, reduction = "pca") + NoLegend()
LabelClusters(plot = plot, id = "ident")
```

Example 71 (r):
```r
# Both functions support `repel`, which will intelligently stagger labels and draw connecting
# lines from the labels to the points or clusters
LabelPoints(plot = plot, points = TopCells(object = pbmc[["pca"]]), repel = TRUE)
```

Example 72 (r):
```r
# Both functions support `repel`, which will intelligently stagger labels and draw connecting
# lines from the labels to the points or clusters
LabelPoints(plot = plot, points = TopCells(object = pbmc[["pca"]]), repel = TRUE)
```

Example 73 (r):
```r
# Plotting multiple plots at once is easy with CombinePlots
plot1 <- DimPlot(pbmc)
plot2 <- FeatureScatter(pbmc, feature1 = "LYZ", feature2 = "CCL5")
# CombinePlots takes a list of ggplot2-based plots
CombinePlots(plots = list(plot1, plot2))
```

Example 74 (r):
```r
# Plotting multiple plots at once is easy with CombinePlots
plot1 <- DimPlot(pbmc)
plot2 <- FeatureScatter(pbmc, feature1 = "LYZ", feature2 = "CCL5")
# CombinePlots takes a list of ggplot2-based plots
CombinePlots(plots = list(plot1, plot2))
```

Example 75 (r):
```r
# CombinePlots can also easily remove the legend from the plots by passing `legend = 'none'`;
# legends can also be combined with `legend = 'right'`
CombinePlots(plots = list(plot1, plot2), legend = "none")
```

Example 76 (r):
```r
# CombinePlots can also easily remove the legend from the plots by passing `legend = 'none'`;
# legends can also be combined with `legend = 'right'`
CombinePlots(plots = list(plot1, plot2), legend = "none")
```

Example 77 (r):
```r
# CombinePlots used cowplot:plot_grid under the hood, and will pass on additional arguments to
# cowplot::plot_grid
```

Example 78 (r):
```r
# CombinePlots used cowplot:plot_grid under the hood, and will pass on additional arguments to
# cowplot::plot_grid
```

---

## Using Seurat with multi-modal data

**URL:** http://127.0.0.1:9173/seurat/archive/v3.2/multimodal_vignette/index.html

**Contents:**
- Using Seurat with multi-modal data
    - Compiled: 2020-10-02
  - Load in the data
  - Setup a Seurat object, and cluster cells based on RNA expression
  - Add the protein expression levels to the Seurat object
  - Visualize protein levels on RNA clusters
  - Identify differentially expressed proteins between clusters
  - Cluster directly on protein levels
  - Loading data from 10X multi-modal experiments

This vignette demonstrates new features that allow users to analyze and explore multi-modal data with Seurat. While this represents an initial release, we are excited to release significant new functionality for multi-modal datasets in the future.

Here, we analyze a dataset of 8,617 cord blood mononuclear cells (CBMCs), produced with CITE-seq, where we simultaneously measure the single cell transcriptomes alongside the expression of 11 surface proteins, whose levels are quantified with DNA-barcoded antibodies. First, we load in two count matrices : one for the RNA measurements, and one for the antibody-derived tags (ADT). You can download the ADT file here and the RNA file here

The steps below represent a quick clustering of the PBMCs based on the scRNA-seq data. For more detail on individual steps or more advanced options, see our PBMC clustering guided tutorial here

Seurat v3.0 allows you to store information from multiple assays in the same object, as long as the data is multi-modal (collected on the same set of cells). You can use the SetAssayData and GetAssayData accessor functions to add and fetch data from additional assays.

You can use the names of any ADT markers, (i.e. "adt_CD4"), in FetchData, FeaturePlot, RidgePlot, FeatureScatter, DoHeatmap, or any other visualization features

If you look a bit more closely, you'll see that our CD8 T cell cluster is enriched for CD8 T cells, but still contains many CD4+ CD8- T cells. This is because Naive CD4 and CD8 T cells are quite similar transcriptomically, and the RNA dropout levels for CD4 and CD8 are quite high. This demonstrates the challenge of defining subtle immune cell differences from scRNA-seq data alone.

You can also run dimensional reduction and graph-based clustering directly on CITE-seq data

The ADT-based clustering yields similar results, but with a few differences

Seurat is also able to analyze data from multi-modal 10X experiments processed using CellRanger v3; as an example, we recreate the plots above using a dataset of 7,900 peripheral blood mononuclear cells (PBMC), freely available from 10X Genomics here.

**Examples:**

Example 1 (r):
```r
library(Seurat)
library(ggplot2)
library(patchwork)
```

Example 2 (r):
```r
library(Seurat)
library(ggplot2)
library(patchwork)
```

Example 3 (r):
```r
# Load in the RNA UMI matrix

# Note that this dataset also contains ~5% of mouse cells, which we can use as negative controls
# for the protein measurements. For this reason, the gene expression matrix has HUMAN_ or MOUSE_
# appended to the beginning of each gene.
cbmc.rna <- as.sparse(read.csv(file = "../data/GSE100866_CBMC_8K_13AB_10X-RNA_umi.csv.gz", sep = ",", 
    header = TRUE, row.names = 1))

# To make life a bit easier going forward, we're going to discard all but the top 100 most
# highly expressed mouse genes, and remove the 'HUMAN_' from the CITE-seq prefix
cbmc.rna <- CollapseSpeciesExpressionMatrix(cbmc.rna)

# Load in the ADT UMI matrix
cbmc.adt <- as.sparse(read.csv(file = "../data/GSE100866_CBMC_8K_13AB_10X-ADT_umi.csv.gz", sep = ",", 
    header = TRUE, row.names = 1))

# When adding multimodal data to Seurat, it's okay to have duplicate feature names. Each set of
# modal data (eg. RNA, ADT, etc.) is stored in its own Assay object.  One of these Assay objects
# is called the 'default assay', meaning it's used for all analyses and visualization.  To pull
# data from an assay that isn't the default, you can specify a key that's linked to an assay for
# feature pulling.  To see all keys for all objects, use the Key function.  Lastly, we observed
# poor enrichments for CCR5, CCR7, and CD10 - and therefore remove them from the matrix
# (optional)
cbmc.adt <- cbmc.adt[setdiff(rownames(x = cbmc.adt), c("CCR5", "CCR7", "CD10")), ]
```

Example 4 (r):
```r
# Load in the RNA UMI matrix

# Note that this dataset also contains ~5% of mouse cells, which we can use as negative controls
# for the protein measurements. For this reason, the gene expression matrix has HUMAN_ or MOUSE_
# appended to the beginning of each gene.
cbmc.rna <- as.sparse(read.csv(file = "../data/GSE100866_CBMC_8K_13AB_10X-RNA_umi.csv.gz", sep = ",", 
    header = TRUE, row.names = 1))

# To make life a bit easier going forward, we're going to discard all but the top 100 most
# highly expressed mouse genes, and remove the 'HUMAN_' from the CITE-seq prefix
cbmc.rna <- CollapseSpeciesExpressionMatrix(cbmc.rna)

# Load in the ADT UMI matrix
cbmc.adt <- as.sparse(read.csv(file = "../data/GSE100866_CBMC_8K_13AB_10X-ADT_umi.csv.gz", sep = ",", 
    header = TRUE, row.names = 1))

# When adding multimodal data to Seurat, it's okay to have duplicate feature names. Each set of
# modal data (eg. RNA, ADT, etc.) is stored in its own Assay object.  One of these Assay objects
# is called the 'default assay', meaning it's used for all analyses and visualization.  To pull
# data from an assay that isn't the default, you can specify a key that's linked to an assay for
# feature pulling.  To see all keys for all objects, use the Key function.  Lastly, we observed
# poor enrichments for CCR5, CCR7, and CD10 - and therefore remove them from the matrix
# (optional)
cbmc.adt <- cbmc.adt[setdiff(rownames(x = cbmc.adt), c("CCR5", "CCR7", "CD10")), ]
```

Example 5 (r):
```r
cbmc <- CreateSeuratObject(counts = cbmc.rna)

# standard log-normalization
cbmc <- NormalizeData(cbmc)

# choose ~1k variable features
cbmc <- FindVariableFeatures(cbmc)

# standard scaling (no regression)
cbmc <- ScaleData(cbmc)

# Run PCA, select 13 PCs for tSNE visualization and graph-based clustering
cbmc <- RunPCA(cbmc, verbose = FALSE)
ElbowPlot(cbmc, ndims = 50)
```

Example 6 (r):
```r
cbmc <- CreateSeuratObject(counts = cbmc.rna)

# standard log-normalization
cbmc <- NormalizeData(cbmc)

# choose ~1k variable features
cbmc <- FindVariableFeatures(cbmc)

# standard scaling (no regression)
cbmc <- ScaleData(cbmc)

# Run PCA, select 13 PCs for tSNE visualization and graph-based clustering
cbmc <- RunPCA(cbmc, verbose = FALSE)
ElbowPlot(cbmc, ndims = 50)
```

Example 7 (r):
```r
cbmc <- FindNeighbors(cbmc, dims = 1:25)
cbmc <- FindClusters(cbmc, resolution = 0.8)
cbmc <- RunTSNE(cbmc, dims = 1:25, method = "FIt-SNE")

# Find the markers that define each cluster, and use these to annotate the clusters, we use
# max.cells.per.ident to speed up the process
cbmc.rna.markers <- FindAllMarkers(cbmc, max.cells.per.ident = 100, min.diff.pct = 0.3, only.pos = TRUE)
```

Example 8 (r):
```r
cbmc <- FindNeighbors(cbmc, dims = 1:25)
cbmc <- FindClusters(cbmc, resolution = 0.8)
cbmc <- RunTSNE(cbmc, dims = 1:25, method = "FIt-SNE")

# Find the markers that define each cluster, and use these to annotate the clusters, we use
# max.cells.per.ident to speed up the process
cbmc.rna.markers <- FindAllMarkers(cbmc, max.cells.per.ident = 100, min.diff.pct = 0.3, only.pos = TRUE)
```

Example 9 (r):
```r
# Note, for simplicity we are merging two CD14+ Monocyte clusters (that differ in expression of
# HLA-DR genes) and NK clusters (that differ in cell cycle stage)
new.cluster.ids <- c("Memory CD4 T", "CD14+ Mono", "Naive CD4 T", "NK", "CD14+ Mono", "Mouse", "B", 
    "CD8 T", "CD16+ Mono", "T/Mono doublets", "NK", "CD34+", "Multiplets", "Mouse", "Eryth", "Mk", 
    "Mouse", "DC", "pDCs")
names(new.cluster.ids) <- levels(cbmc)
cbmc <- RenameIdents(cbmc, new.cluster.ids)
```

Example 10 (r):
```r
# Note, for simplicity we are merging two CD14+ Monocyte clusters (that differ in expression of
# HLA-DR genes) and NK clusters (that differ in cell cycle stage)
new.cluster.ids <- c("Memory CD4 T", "CD14+ Mono", "Naive CD4 T", "NK", "CD14+ Mono", "Mouse", "B", 
    "CD8 T", "CD16+ Mono", "T/Mono doublets", "NK", "CD34+", "Multiplets", "Mouse", "Eryth", "Mk", 
    "Mouse", "DC", "pDCs")
names(new.cluster.ids) <- levels(cbmc)
cbmc <- RenameIdents(cbmc, new.cluster.ids)
```

Example 11 (r):
```r
DimPlot(cbmc, label = TRUE) + NoLegend()
```

Example 12 (r):
```r
DimPlot(cbmc, label = TRUE) + NoLegend()
```

Example 13 (unknown):
```unknown
SetAssayData
```

Example 14 (unknown):
```unknown
GetAssayData
```

Example 15 (r):
```r
# We will define an ADT assay, and store raw counts for it

# If you are interested in how these data are internally stored, you can check out the Assay
# class, which is defined in objects.R; note that all single-cell expression data, including RNA
# data, are still stored in Assay objects, and can also be accessed using GetAssayData
cbmc[["ADT"]] <- CreateAssayObject(counts = cbmc.adt)

# Now we can repeat the preprocessing (normalization and scaling) steps that we typically run
# with RNA, but modifying the 'assay' argument.  For CITE-seq data, we do not recommend typical
# LogNormalization. Instead, we use a centered log-ratio (CLR) normalization, computed
# independently for each feature.  This is a slightly improved procedure from the original
# publication, and we will release more advanced versions of CITE-seq normalizations soon.
cbmc <- NormalizeData(cbmc, assay = "ADT", normalization.method = "CLR")
cbmc <- ScaleData(cbmc, assay = "ADT")
```

Example 16 (r):
```r
# We will define an ADT assay, and store raw counts for it

# If you are interested in how these data are internally stored, you can check out the Assay
# class, which is defined in objects.R; note that all single-cell expression data, including RNA
# data, are still stored in Assay objects, and can also be accessed using GetAssayData
cbmc[["ADT"]] <- CreateAssayObject(counts = cbmc.adt)

# Now we can repeat the preprocessing (normalization and scaling) steps that we typically run
# with RNA, but modifying the 'assay' argument.  For CITE-seq data, we do not recommend typical
# LogNormalization. Instead, we use a centered log-ratio (CLR) normalization, computed
# independently for each feature.  This is a slightly improved procedure from the original
# publication, and we will release more advanced versions of CITE-seq normalizations soon.
cbmc <- NormalizeData(cbmc, assay = "ADT", normalization.method = "CLR")
cbmc <- ScaleData(cbmc, assay = "ADT")
```

Example 17 (r):
```r
# in this plot, protein (ADT) levels are on top, and RNA levels are on the bottom
FeaturePlot(cbmc, features = c("adt_CD3", "adt_CD11c", "adt_CD8", "adt_CD16", "CD3E", "ITGAX", "CD8A", 
    "FCGR3A"), min.cutoff = "q05", max.cutoff = "q95", ncol = 4)
```

Example 18 (r):
```r
# in this plot, protein (ADT) levels are on top, and RNA levels are on the bottom
FeaturePlot(cbmc, features = c("adt_CD3", "adt_CD11c", "adt_CD8", "adt_CD16", "CD3E", "ITGAX", "CD8A", 
    "FCGR3A"), min.cutoff = "q05", max.cutoff = "q95", ncol = 4)
```

Example 19 (r):
```r
RidgePlot(cbmc, features = c("adt_CD3", "adt_CD11c", "adt_CD8", "adt_CD16"), ncol = 2)
```

Example 20 (r):
```r
RidgePlot(cbmc, features = c("adt_CD3", "adt_CD11c", "adt_CD8", "adt_CD16"), ncol = 2)
```

Example 21 (r):
```r
# Draw ADT scatter plots (like biaxial plots for FACS). Note that you can even 'gate' cells if
# desired by using HoverLocator and FeatureLocator
FeatureScatter(cbmc, feature1 = "adt_CD19", feature2 = "adt_CD3")
```

Example 22 (r):
```r
# Draw ADT scatter plots (like biaxial plots for FACS). Note that you can even 'gate' cells if
# desired by using HoverLocator and FeatureLocator
FeatureScatter(cbmc, feature1 = "adt_CD19", feature2 = "adt_CD3")
```

Example 23 (r):
```r
# view relationship between protein and RNA
FeatureScatter(cbmc, feature1 = "adt_CD3", feature2 = "CD3E")
```

Example 24 (r):
```r
# view relationship between protein and RNA
FeatureScatter(cbmc, feature1 = "adt_CD3", feature2 = "CD3E")
```

Example 25 (r):
```r
# Let's plot CD4 vs CD8 levels in T cells
tcells <- subset(cbmc, idents = c("Naive CD4 T", "Memory CD4 T", "CD8 T"))
FeatureScatter(tcells, feature1 = "adt_CD4", feature2 = "adt_CD8")
```

Example 26 (r):
```r
# Let's plot CD4 vs CD8 levels in T cells
tcells <- subset(cbmc, idents = c("Naive CD4 T", "Memory CD4 T", "CD8 T"))
FeatureScatter(tcells, feature1 = "adt_CD4", feature2 = "adt_CD8")
```

Example 27 (r):
```r
# # Let's look at the raw (non-normalized) ADT counts. You can see the values are quite high,
# particularly in comparison to RNA values. This is due to the significantly higher protein copy
# number in cells, which significantly reduces 'drop-out' in ADT data
FeatureScatter(tcells, feature1 = "adt_CD4", feature2 = "adt_CD8", slot = "counts")
```

Example 28 (r):
```r
# # Let's look at the raw (non-normalized) ADT counts. You can see the values are quite high,
# particularly in comparison to RNA values. This is due to the significantly higher protein copy
# number in cells, which significantly reduces 'drop-out' in ADT data
FeatureScatter(tcells, feature1 = "adt_CD4", feature2 = "adt_CD8", slot = "counts")
```

Example 29 (r):
```r
saveRDS(cbmc, file = "../output/cbmc.rds")
```

Example 30 (r):
```r
saveRDS(cbmc, file = "../output/cbmc.rds")
```

Example 31 (r):
```r
# Downsample the clusters to a maximum of 300 cells each (makes the heatmap easier to see for
# small clusters)
cbmc.small <- subset(cbmc, downsample = 300)

# Find protein markers for all clusters, and draw a heatmap
adt.markers <- FindAllMarkers(cbmc.small, assay = "ADT", only.pos = TRUE)
DoHeatmap(cbmc.small, features = unique(adt.markers$gene), assay = "ADT", angle = 90) + NoLegend()
```

Example 32 (r):
```r
# Downsample the clusters to a maximum of 300 cells each (makes the heatmap easier to see for
# small clusters)
cbmc.small <- subset(cbmc, downsample = 300)

# Find protein markers for all clusters, and draw a heatmap
adt.markers <- FindAllMarkers(cbmc.small, assay = "ADT", only.pos = TRUE)
DoHeatmap(cbmc.small, features = unique(adt.markers$gene), assay = "ADT", angle = 90) + NoLegend()
```

Example 33 (r):
```r
# You can see that our unknown cells co-express both myeloid and lymphoid markers (true at the
# RNA level as well). They are likely cell clumps (multiplets) that should be discarded. We'll
# remove the mouse cells now as well
cbmc <- subset(cbmc, idents = c("Multiplets", "Mouse"), invert = TRUE)
```

Example 34 (r):
```r
# You can see that our unknown cells co-express both myeloid and lymphoid markers (true at the
# RNA level as well). They are likely cell clumps (multiplets) that should be discarded. We'll
# remove the mouse cells now as well
cbmc <- subset(cbmc, idents = c("Multiplets", "Mouse"), invert = TRUE)
```

Example 35 (r):
```r
# Because we're going to be working with the ADT data extensively, we're going to switch the
# default assay to the 'ADT' assay.  This will cause all functions to use ADT data by default,
# rather than requiring us to specify it each time
DefaultAssay(cbmc) <- "ADT"
cbmc <- RunPCA(cbmc, features = rownames(cbmc), reduction.name = "pca_adt", reduction.key = "pca_adt_", 
    verbose = FALSE)
DimPlot(cbmc, reduction = "pca_adt")
```

Example 36 (r):
```r
# Because we're going to be working with the ADT data extensively, we're going to switch the
# default assay to the 'ADT' assay.  This will cause all functions to use ADT data by default,
# rather than requiring us to specify it each time
DefaultAssay(cbmc) <- "ADT"
cbmc <- RunPCA(cbmc, features = rownames(cbmc), reduction.name = "pca_adt", reduction.key = "pca_adt_", 
    verbose = FALSE)
DimPlot(cbmc, reduction = "pca_adt")
```

Example 37 (r):
```r
# Before we recluster the data on ADT levels, we'll stash the RNA cluster IDs for later
cbmc[["rnaClusterID"]] <- Idents(cbmc)

# Now, we rerun tSNE using the PCA only on ADT (protein) levels.
cbmc <- RunTSNE(cbmc, dims = 1:10, reduction = "pca_adt", reduction.key = "adtTSNE_", reduction.name = "tsne_adt")
cbmc <- FindNeighbors(cbmc, features = rownames(cbmc), dims = NULL)
cbmc <- FindClusters(cbmc, resolution = 0.2, graph.name = "ADT_snn")

# We can compare the RNA and protein clustering, and use this to annotate the protein clustering
# (we could also of course use FindMarkers)
clustering.table <- table(Idents(cbmc), cbmc$rnaClusterID)
clustering.table
```

Example 38 (r):
```r
# Before we recluster the data on ADT levels, we'll stash the RNA cluster IDs for later
cbmc[["rnaClusterID"]] <- Idents(cbmc)

# Now, we rerun tSNE using the PCA only on ADT (protein) levels.
cbmc <- RunTSNE(cbmc, dims = 1:10, reduction = "pca_adt", reduction.key = "adtTSNE_", reduction.name = "tsne_adt")
cbmc <- FindNeighbors(cbmc, features = rownames(cbmc), dims = NULL)
cbmc <- FindClusters(cbmc, resolution = 0.2, graph.name = "ADT_snn")

# We can compare the RNA and protein clustering, and use this to annotate the protein clustering
# (we could also of course use FindMarkers)
clustering.table <- table(Idents(cbmc), cbmc$rnaClusterID)
clustering.table
```

Example 39 (r):
```r
new.cluster.ids <- c("CD4 T", "CD14+ Mono", "NK", "B", "CD8 T", "NK", "CD34+", "T/Mono doublets", 
    "CD16+ Mono", "pDCs", "B")
names(new.cluster.ids) <- levels(cbmc)
cbmc <- RenameIdents(cbmc, new.cluster.ids)

tsne_rnaClusters <- DimPlot(cbmc, reduction = "tsne_adt", group.by = "rnaClusterID") + NoLegend()
tsne_rnaClusters <- tsne_rnaClusters + ggtitle("Clustering based on scRNA-seq") + theme(plot.title = element_text(hjust = 0.5))
tsne_rnaClusters <- LabelClusters(plot = tsne_rnaClusters, id = "rnaClusterID", size = 4)

tsne_adtClusters <- DimPlot(cbmc, reduction = "tsne_adt", pt.size = 0.5) + NoLegend()
tsne_adtClusters <- tsne_adtClusters + ggtitle("Clustering based on ADT signal") + theme(plot.title = element_text(hjust = 0.5))
tsne_adtClusters <- LabelClusters(plot = tsne_adtClusters, id = "ident", size = 4)

# Note: for this comparison, both the RNA and protein clustering are visualized on a tSNE
# generated using the ADT distance matrix.
wrap_plots(list(tsne_rnaClusters, tsne_adtClusters), ncol = 2)
```

Example 40 (r):
```r
new.cluster.ids <- c("CD4 T", "CD14+ Mono", "NK", "B", "CD8 T", "NK", "CD34+", "T/Mono doublets", 
    "CD16+ Mono", "pDCs", "B")
names(new.cluster.ids) <- levels(cbmc)
cbmc <- RenameIdents(cbmc, new.cluster.ids)

tsne_rnaClusters <- DimPlot(cbmc, reduction = "tsne_adt", group.by = "rnaClusterID") + NoLegend()
tsne_rnaClusters <- tsne_rnaClusters + ggtitle("Clustering based on scRNA-seq") + theme(plot.title = element_text(hjust = 0.5))
tsne_rnaClusters <- LabelClusters(plot = tsne_rnaClusters, id = "rnaClusterID", size = 4)

tsne_adtClusters <- DimPlot(cbmc, reduction = "tsne_adt", pt.size = 0.5) + NoLegend()
tsne_adtClusters <- tsne_adtClusters + ggtitle("Clustering based on ADT signal") + theme(plot.title = element_text(hjust = 0.5))
tsne_adtClusters <- LabelClusters(plot = tsne_adtClusters, id = "ident", size = 4)

# Note: for this comparison, both the RNA and protein clustering are visualized on a tSNE
# generated using the ADT distance matrix.
wrap_plots(list(tsne_rnaClusters, tsne_adtClusters), ncol = 2)
```

Example 41 (r):
```r
tcells <- subset(cbmc, idents = c("CD4 T", "CD8 T"))
FeatureScatter(tcells, feature1 = "CD4", feature2 = "CD8")
```

Example 42 (r):
```r
tcells <- subset(cbmc, idents = c("CD4 T", "CD8 T"))
FeatureScatter(tcells, feature1 = "CD4", feature2 = "CD8")
```

Example 43 (r):
```r
RidgePlot(cbmc, features = c("adt_CD11c", "adt_CD8", "adt_CD16", "adt_CD4", "adt_CD19", "adt_CD14"), 
    ncol = 2)
```

Example 44 (r):
```r
RidgePlot(cbmc, features = c("adt_CD11c", "adt_CD8", "adt_CD16", "adt_CD4", "adt_CD19", "adt_CD14"), 
    ncol = 2)
```

Example 45 (r):
```r
saveRDS(cbmc, file = "../output/cbmc_multimodal.rds")
```

Example 46 (r):
```r
saveRDS(cbmc, file = "../output/cbmc_multimodal.rds")
```

Example 47 (r):
```r
pbmc10k.data <- Read10X(data.dir = "../data/pbmc10k/filtered_feature_bc_matrix/")
rownames(x = pbmc10k.data[["Antibody Capture"]]) <- gsub(pattern = "_[control_]*TotalSeqB", replacement = "", 
    x = rownames(x = pbmc10k.data[["Antibody Capture"]]))

pbmc10k <- CreateSeuratObject(counts = pbmc10k.data[["Gene Expression"]], min.cells = 3, min.features = 200)
pbmc10k <- NormalizeData(pbmc10k)
pbmc10k[["ADT"]] <- CreateAssayObject(pbmc10k.data[["Antibody Capture"]][, colnames(x = pbmc10k)])
pbmc10k <- NormalizeData(pbmc10k, assay = "ADT", normalization.method = "CLR")

plot1 <- FeatureScatter(pbmc10k, feature1 = "adt_CD19", feature2 = "adt_CD3", pt.size = 1)
plot2 <- FeatureScatter(pbmc10k, feature1 = "adt_CD4", feature2 = "adt_CD8a", pt.size = 1)
plot3 <- FeatureScatter(pbmc10k, feature1 = "adt_CD3", feature2 = "CD3E", pt.size = 1)
(plot1 + plot2 + plot3) & NoLegend()
```

Example 48 (r):
```r
pbmc10k.data <- Read10X(data.dir = "../data/pbmc10k/filtered_feature_bc_matrix/")
rownames(x = pbmc10k.data[["Antibody Capture"]]) <- gsub(pattern = "_[control_]*TotalSeqB", replacement = "", 
    x = rownames(x = pbmc10k.data[["Antibody Capture"]]))

pbmc10k <- CreateSeuratObject(counts = pbmc10k.data[["Gene Expression"]], min.cells = 3, min.features = 200)
pbmc10k <- NormalizeData(pbmc10k)
pbmc10k[["ADT"]] <- CreateAssayObject(pbmc10k.data[["Antibody Capture"]][, colnames(x = pbmc10k)])
pbmc10k <- NormalizeData(pbmc10k, assay = "ADT", normalization.method = "CLR")

plot1 <- FeatureScatter(pbmc10k, feature1 = "adt_CD19", feature2 = "adt_CD3", pt.size = 1)
plot2 <- FeatureScatter(pbmc10k, feature1 = "adt_CD4", feature2 = "adt_CD8a", pt.size = 1)
plot3 <- FeatureScatter(pbmc10k, feature1 = "adt_CD3", feature2 = "CD3E", pt.size = 1)
(plot1 + plot2 + plot3) & NoLegend()
```

---

## Analysis, visualization, and integration of Visium HD spatial datasets with Seurat • Seurat

**URL:** http://127.0.0.1:9173/seurat/articles/integration_introduction/index.html

**Contents:**
- Introduction to scRNA-seq integration
    - Compiled: November 16, 2023
- Introduction to scRNA-seq integration
- Integration goals
- Setup the Seurat objects
- Perform analysis without integration
- Perform integration
- Identify conserved cell type markers
- Identify differential expressed genes across conditions
- Perform integration with SCTransform-normalized datasets
- Contents

Integration of single-cell sequencing datasets, for example across experimental batches, donors, or conditions, is often an important step in scRNA-seq workflows. Integrative analysis can help to match shared cell types and states across datasets, which can boost statistical power, and most importantly, facilitate accurate comparative analysis across datasets. In previous versions of Seurat we introduced methods for integrative analysis, including our ‘anchor-based’ integration workflow. Many labs have also published powerful and pioneering methods, including Harmony and scVI, for integrative analysis. Please see our Integrating scRNA-seq data with multiple tools vignette.

The following tutorial is designed to give you an overview of the kinds of comparative analyses on complex cell types that are possible using the Seurat integration procedure. Here, we address a few key goals:

For convenience, we distribute this dataset through our SeuratData package.

The object contains data from human PBMC from two conditions, interferon-stimulated and control cells (stored in the stim column in the object metadata). We will aim to integrate the two conditions together, so that we can jointly identify cell subpopulations across datasets, and then explore how each group differs across conditions

In previous versions of Seurat, we would require the data to be represented as two different Seurat objects. In Seurat v5, we keep all the data in one object, but simply split it into multiple ‘layers’. To learn more about layers, check out our Seurat object interaction vignette.

We can first analyze the dataset without integration. The resulting clusters are defined both by cell type and stimulation condition, which creates challenges for downstream analysis.

We now aim to integrate data from the two conditions, so that cells from the same cell type/subpopulation will cluster together.

We often refer to this procedure as intergration/alignment. When aligning two genome sequences together, identification of shared/homologous regions can help to interpret differences between the sequences as well. Similarly for scRNA-seq integration, our goal is not to remove biological differences across conditions, but to learn shared cell types/states in an initial step - specifically because that will enable us to compare control stimulated and control profiles for these individual cell types.

The Seurat v5 integration procedure aims to return a single dimensional reduction that captures the shared sources of variance across multiple layers, so that cells in a similar biological state will cluster. The method returns a dimensional reduction (i.e. integrated.cca) which can be used for visualization and unsupervised clustering analysis. For evaluating performance, we can use cell type labels that are pre-loaded in the seurat_annotations metadata column.

To visualize the two conditions side-by-side, we can use the split.by argument to show each condition colored by cluster.

To identify canonical cell type marker genes that are conserved across conditions, we provide the FindConservedMarkers() function. This function performs differential gene expression testing for each dataset/group and combines the p-values using meta-analysis methods from the MetaDE R package. For example, we can calculated the genes that are conserved markers irrespective of stimulation condition in cluster 6 (NK cells).

You can perform these same analysis on the unsupervised clustering results (stored in seurat_clusters), and use these conserved markers to annotate cell types in your dataset.

The DotPlot() function with the split.by parameter can be useful for viewing conserved cell type markers across conditions, showing both the expression level and the percentage of cells in a cluster expressing any given gene. Here we plot 2-3 strong marker genes for each of our 14 clusters.

Now that we’ve aligned the stimulated and control cells, we can start to do comparative analyses and look at the differences induced by stimulation.

We can aggregate cells of a similar type and condition together to create “pseudobulk” profiles using the AggregateExpression command. As an initial exploratory analysis, we can compare pseudobulk profiles of two cell types (naive CD4 T cells, and CD14 monocytes), and compare their gene expression profiles before and after stimulation. We highlight genes that exhibit dramatic responses to interferon stimulation. As you can see, many of the same genes are upregulated in both of these cell types and likely represent a conserved interferon response pathway, though CD14 monocytes exhibit a stronger transcriptional response.

We can now ask what genes change in different conditions for cells of the same type. First, we create a column in the meta.data slot to hold both the cell type and stimulation information and switch the current ident to that column. Then we use FindMarkers() to find the genes that are different between stimulated and control B cells. Notice that many of the top genes that show up here are the same as the ones we plotted earlier as core interferon response genes. Additionally, genes like CXCL10 which we saw were specific to monocyte and B cell interferon response show up as highly significant in this list as well.

Please note that p-values obtained from this analysis should be interpreted with caution, as these tests treat each cell as an independent replicate, and ignore inherent correlations between cells originating from the same sample. As discussed here, DE tests across multiple conditions should expressly utilize multiple samples/replicates, and can be performed after aggregating (‘pseudobulking’) cells from the same sample and subpopulation together. We do not perform this analysis here, as there is a single replicate in the data, but please see our vignette comparing healthy and diabetic samples as an example for how to perform DE analysis across conditions.

Another useful way to visualize these changes in gene expression is with the split.by option to the FeaturePlot() or VlnPlot() function. This will display FeaturePlots of the list of given genes, split by a grouping variable (stimulation condition here). Genes such as CD3D and GNLY are canonical cell type markers (for T cells and NK/CD8 T cells) that are virtually unaffected by interferon stimulation and display similar gene expression patterns in the control and stimulated group. IFI6 and ISG15, on the other hand, are core interferon response genes and are upregulated accordingly in all cell types. Finally, CD14 and CXCL10 are genes that show a cell type specific interferon response. CD14 expression decreases after stimulation in CD14 monocytes, which could lead to misclassification in a supervised analysis framework, underscoring the value of integrated analysis. CXCL10 shows a distinct upregulation in monocytes and B cells after interferon stimulation but not in other cell types.

As an alternative to log-normalization, Seurat also includes support for preprocessing of scRNA-seq using the sctransform workflow. The IntegrateLayers function also supports SCTransform-normalized data, by setting the normalization.method parameter, as shown below.

Developed by Rahul Satija, Satija Lab and Collaborators.

Site built with pkgdown 2.0.7.

**Examples:**

Example 1 (unknown):
```unknown
vignettes/integration_introduction.Rmd
```

Example 2 (unknown):
```unknown
integration_introduction.Rmd
```

Example 3 (unknown):
```unknown
library(Seurat)
library(SeuratData)
library(patchwork)
```

Example 4 (r):
```r
library(Seurat)
library(SeuratData)
library(patchwork)
```

Example 5 (r):
```r
library(Seurat)
library(SeuratData)
library(patchwork)
```

Example 6 (unknown):
```unknown
# install dataset
InstallData("ifnb")
```

Example 7 (r):
```r
# install dataset
InstallData("ifnb")
```

Example 8 (r):
```r
# install dataset
InstallData("ifnb")
```

Example 9 (unknown):
```unknown
# load dataset
ifnb <- LoadData("ifnb")
# split the RNA measurements into two layers one for control cells, one for stimulated cells

ifnb[["RNA"]] <- split(ifnb[["RNA"]], f = ifnb$stim)
ifnb
```

Example 10 (r):
```r
# load dataset
ifnb <- LoadData("ifnb")
# split the RNA measurements into two layers one for control cells, one for stimulated cells

ifnb[["RNA"]] <- split(ifnb[["RNA"]], f = ifnb$stim)
ifnb
```

Example 11 (r):
```r
# load dataset
ifnb <- LoadData("ifnb")
# split the RNA measurements into two layers one for control cells, one for stimulated cells

ifnb[["RNA"]] <- split(ifnb[["RNA"]], f = ifnb$stim)
ifnb
```

Example 12 (unknown):
```unknown
# run standard anlaysis workflow
ifnb <- NormalizeData(ifnb)
ifnb <- FindVariableFeatures(ifnb)
ifnb <- ScaleData(ifnb)
ifnb <- RunPCA(ifnb)
```

Example 13 (r):
```r
# run standard anlaysis workflow
ifnb <- NormalizeData(ifnb)
ifnb <- FindVariableFeatures(ifnb)
ifnb <- ScaleData(ifnb)
ifnb <- RunPCA(ifnb)
```

Example 14 (r):
```r
# run standard anlaysis workflow
ifnb <- NormalizeData(ifnb)
ifnb <- FindVariableFeatures(ifnb)
ifnb <- ScaleData(ifnb)
ifnb <- RunPCA(ifnb)
```

Example 15 (unknown):
```unknown
ifnb <- FindNeighbors(ifnb, dims = 1:30, reduction = "pca")
ifnb <- FindClusters(ifnb, resolution = 2, cluster.name = "unintegrated_clusters")
```

Example 16 (r):
```r
ifnb <- FindNeighbors(ifnb, dims = 1:30, reduction = "pca")
ifnb <- FindClusters(ifnb, resolution = 2, cluster.name = "unintegrated_clusters")
```

Example 17 (r):
```r
ifnb <- FindNeighbors(ifnb, dims = 1:30, reduction = "pca")
ifnb <- FindClusters(ifnb, resolution = 2, cluster.name = "unintegrated_clusters")
```

Example 18 (unknown):
```unknown
## Modularity Optimizer version 1.3.0 by Ludo Waltman and Nees Jan van Eck
## 
## Number of nodes: 13999
## Number of edges: 555146
## 
## Running Louvain algorithm...
## Maximum modularity in 10 random starts: 0.8153
## Number of communities: 26
## Elapsed time: 23 seconds
```

Example 19 (unknown):
```unknown
## Modularity Optimizer version 1.3.0 by Ludo Waltman and Nees Jan van Eck
## 
## Number of nodes: 13999
## Number of edges: 555146
## 
## Running Louvain algorithm...
## Maximum modularity in 10 random starts: 0.8153
## Number of communities: 26
## Elapsed time: 23 seconds
```

Example 20 (unknown):
```unknown
ifnb <- RunUMAP(ifnb, dims = 1:30, reduction = "pca", reduction.name = "umap.unintegrated")
DimPlot(ifnb, reduction = "umap.unintegrated", group.by = c("stim", "seurat_clusters"))
```

Example 21 (r):
```r
ifnb <- RunUMAP(ifnb, dims = 1:30, reduction = "pca", reduction.name = "umap.unintegrated")
DimPlot(ifnb, reduction = "umap.unintegrated", group.by = c("stim", "seurat_clusters"))
```

Example 22 (r):
```r
ifnb <- RunUMAP(ifnb, dims = 1:30, reduction = "pca", reduction.name = "umap.unintegrated")
DimPlot(ifnb, reduction = "umap.unintegrated", group.by = c("stim", "seurat_clusters"))
```

Example 23 (unknown):
```unknown
integrated.cca
```

Example 24 (unknown):
```unknown
seurat_annotations
```

Example 25 (unknown):
```unknown
ifnb <- IntegrateLayers(object = ifnb, method = CCAIntegration, orig.reduction = "pca", new.reduction = "integrated.cca",
    verbose = FALSE)

# re-join layers after integration
ifnb[["RNA"]] <- JoinLayers(ifnb[["RNA"]])

ifnb <- FindNeighbors(ifnb, reduction = "integrated.cca", dims = 1:30)
ifnb <- FindClusters(ifnb, resolution = 1)
```

Example 26 (r):
```r
ifnb <- IntegrateLayers(object = ifnb, method = CCAIntegration, orig.reduction = "pca", new.reduction = "integrated.cca",
    verbose = FALSE)

# re-join layers after integration
ifnb[["RNA"]] <- JoinLayers(ifnb[["RNA"]])

ifnb <- FindNeighbors(ifnb, reduction = "integrated.cca", dims = 1:30)
ifnb <- FindClusters(ifnb, resolution = 1)
```

Example 27 (r):
```r
ifnb <- IntegrateLayers(object = ifnb, method = CCAIntegration, orig.reduction = "pca", new.reduction = "integrated.cca",
    verbose = FALSE)

# re-join layers after integration
ifnb[["RNA"]] <- JoinLayers(ifnb[["RNA"]])

ifnb <- FindNeighbors(ifnb, reduction = "integrated.cca", dims = 1:30)
ifnb <- FindClusters(ifnb, resolution = 1)
```

Example 28 (unknown):
```unknown
## Modularity Optimizer version 1.3.0 by Ludo Waltman and Nees Jan van Eck
## 
## Number of nodes: 13999
## Number of edges: 588593
## 
## Running Louvain algorithm...
## Maximum modularity in 10 random starts: 0.8454
## Number of communities: 17
## Elapsed time: 26 seconds
```

Example 29 (unknown):
```unknown
## Modularity Optimizer version 1.3.0 by Ludo Waltman and Nees Jan van Eck
## 
## Number of nodes: 13999
## Number of edges: 588593
## 
## Running Louvain algorithm...
## Maximum modularity in 10 random starts: 0.8454
## Number of communities: 17
## Elapsed time: 26 seconds
```

Example 30 (unknown):
```unknown
ifnb <- RunUMAP(ifnb, dims = 1:30, reduction = "integrated.cca")
```

Example 31 (r):
```r
ifnb <- RunUMAP(ifnb, dims = 1:30, reduction = "integrated.cca")
```

Example 32 (r):
```r
ifnb <- RunUMAP(ifnb, dims = 1:30, reduction = "integrated.cca")
```

Example 33 (unknown):
```unknown
# Visualization
DimPlot(ifnb, reduction = "umap", group.by = c("stim", "seurat_annotations"))
```

Example 34 (r):
```r
# Visualization
DimPlot(ifnb, reduction = "umap", group.by = c("stim", "seurat_annotations"))
```

Example 35 (r):
```r
# Visualization
DimPlot(ifnb, reduction = "umap", group.by = c("stim", "seurat_annotations"))
```

Example 36 (unknown):
```unknown
DimPlot(ifnb, reduction = "umap", split.by = "stim")
```

Example 37 (r):
```r
DimPlot(ifnb, reduction = "umap", split.by = "stim")
```

Example 38 (r):
```r
DimPlot(ifnb, reduction = "umap", split.by = "stim")
```

Example 39 (unknown):
```unknown
FindConservedMarkers()
```

Example 40 (unknown):
```unknown
Idents(ifnb) <- "seurat_annotations"
nk.markers <- FindConservedMarkers(ifnb, ident.1 = "NK", grouping.var = "stim", verbose = FALSE)
head(nk.markers)
```

Example 41 (r):
```r
Idents(ifnb) <- "seurat_annotations"
nk.markers <- FindConservedMarkers(ifnb, ident.1 = "NK", grouping.var = "stim", verbose = FALSE)
head(nk.markers)
```

Example 42 (r):
```r
Idents(ifnb) <- "seurat_annotations"
nk.markers <- FindConservedMarkers(ifnb, ident.1 = "NK", grouping.var = "stim", verbose = FALSE)
head(nk.markers)
```

Example 43 (unknown):
```unknown
##       CTRL_p_val CTRL_avg_log2FC CTRL_pct.1 CTRL_pct.2 CTRL_p_val_adj
## GNLY           0        6.854586      0.943      0.046              0
## NKG7           0        5.358881      0.953      0.085              0
## GZMB           0        5.078135      0.839      0.044              0
## CLIC3          0        5.765314      0.601      0.024              0
## CTSW           0        5.307246      0.537      0.030              0
## KLRD1          0        5.261553      0.507      0.019              0
##       STIM_p_val STIM_avg_log2FC STIM_pct.1 STIM_pct.2 STIM_p_val_adj max_pval
## GNLY           0        6.435910      0.956      0.059              0        0
## NKG7           0        4.971397      0.950      0.081              0        0
## GZMB           0        5.151924      0.897      0.060              0        0
## CLIC3          0        5.505208      0.623      0.031              0        0
## CTSW           0        5.240729      0.592      0.035              0        0
## KLRD1          0        4.852457      0.555      0.027              0        0
##       minimump_p_val
## GNLY               0
## NKG7               0
## GZMB               0
## CLIC3              0
## CTSW               0
## KLRD1              0
```

Example 44 (unknown):
```unknown
##       CTRL_p_val CTRL_avg_log2FC CTRL_pct.1 CTRL_pct.2 CTRL_p_val_adj
## GNLY           0        6.854586      0.943      0.046              0
## NKG7           0        5.358881      0.953      0.085              0
## GZMB           0        5.078135      0.839      0.044              0
## CLIC3          0        5.765314      0.601      0.024              0
## CTSW           0        5.307246      0.537      0.030              0
## KLRD1          0        5.261553      0.507      0.019              0
##       STIM_p_val STIM_avg_log2FC STIM_pct.1 STIM_pct.2 STIM_p_val_adj max_pval
## GNLY           0        6.435910      0.956      0.059              0        0
## NKG7           0        4.971397      0.950      0.081              0        0
## GZMB           0        5.151924      0.897      0.060              0        0
## CLIC3          0        5.505208      0.623      0.031              0        0
## CTSW           0        5.240729      0.592      0.035              0        0
## KLRD1          0        4.852457      0.555      0.027              0        0
##       minimump_p_val
## GNLY               0
## NKG7               0
## GZMB               0
## CLIC3              0
## CTSW               0
## KLRD1              0
```

Example 45 (unknown):
```unknown
seurat_clusters
```

Example 46 (unknown):
```unknown
# NEEDS TO BE FIXED AND SET ORDER CORRECTLY
Idents(ifnb) <- factor(Idents(ifnb), levels = c("pDC", "Eryth", "Mk", "DC", "CD14 Mono", "CD16 Mono",
    "B Activated", "B", "CD8 T", "NK", "T activated", "CD4 Naive T", "CD4 Memory T"))

markers.to.plot <- c("CD3D", "CREM", "HSPH1", "SELL", "GIMAP5", "CACYBP", "GNLY", "NKG7", "CCL5",
    "CD8A", "MS4A1", "CD79A", "MIR155HG", "NME1", "FCGR3A", "VMO1", "CCL2", "S100A9", "HLA-DQA1",
    "GPR183", "PPBP", "GNG11", "HBA2", "HBB", "TSPAN13", "IL3RA", "IGJ", "PRSS57")
DotPlot(ifnb, features = markers.to.plot, cols = c("blue", "red"), dot.scale = 8, split.by = "stim") +
    RotatedAxis()
```

Example 47 (r):
```r
# NEEDS TO BE FIXED AND SET ORDER CORRECTLY
Idents(ifnb) <- factor(Idents(ifnb), levels = c("pDC", "Eryth", "Mk", "DC", "CD14 Mono", "CD16 Mono",
    "B Activated", "B", "CD8 T", "NK", "T activated", "CD4 Naive T", "CD4 Memory T"))

markers.to.plot <- c("CD3D", "CREM", "HSPH1", "SELL", "GIMAP5", "CACYBP", "GNLY", "NKG7", "CCL5",
    "CD8A", "MS4A1", "CD79A", "MIR155HG", "NME1", "FCGR3A", "VMO1", "CCL2", "S100A9", "HLA-DQA1",
    "GPR183", "PPBP", "GNG11", "HBA2", "HBB", "TSPAN13", "IL3RA", "IGJ", "PRSS57")
DotPlot(ifnb, features = markers.to.plot, cols = c("blue", "red"), dot.scale = 8, split.by = "stim") +
    RotatedAxis()
```

Example 48 (r):
```r
# NEEDS TO BE FIXED AND SET ORDER CORRECTLY
Idents(ifnb) <- factor(Idents(ifnb), levels = c("pDC", "Eryth", "Mk", "DC", "CD14 Mono", "CD16 Mono",
    "B Activated", "B", "CD8 T", "NK", "T activated", "CD4 Naive T", "CD4 Memory T"))

markers.to.plot <- c("CD3D", "CREM", "HSPH1", "SELL", "GIMAP5", "CACYBP", "GNLY", "NKG7", "CCL5",
    "CD8A", "MS4A1", "CD79A", "MIR155HG", "NME1", "FCGR3A", "VMO1", "CCL2", "S100A9", "HLA-DQA1",
    "GPR183", "PPBP", "GNG11", "HBA2", "HBB", "TSPAN13", "IL3RA", "IGJ", "PRSS57")
DotPlot(ifnb, features = markers.to.plot, cols = c("blue", "red"), dot.scale = 8, split.by = "stim") +
    RotatedAxis()
```

Example 49 (unknown):
```unknown
AggregateExpression
```

Example 50 (unknown):
```unknown
library(ggplot2)
library(cowplot)
theme_set(theme_cowplot())

aggregate_ifnb <- AggregateExpression(ifnb, group.by = c("seurat_annotations", "stim"), return.seurat = TRUE)
genes.to.label = c("ISG15", "LY6E", "IFI6", "ISG20", "MX1", "IFIT2", "IFIT1", "CXCL10", "CCL8")

p1 <- CellScatter(aggregate_ifnb, "CD14 Mono_CTRL", "CD14 Mono_STIM", highlight = genes.to.label)
p2 <- LabelPoints(plot = p1, points = genes.to.label, repel = TRUE)

p3 <- CellScatter(aggregate_ifnb, "CD4 Naive T_CTRL", "CD4 Naive T_STIM", highlight = genes.to.label)
p4 <- LabelPoints(plot = p3, points = genes.to.label, repel = TRUE)

p2 + p4
```

Example 51 (r):
```r
library(ggplot2)
library(cowplot)
theme_set(theme_cowplot())

aggregate_ifnb <- AggregateExpression(ifnb, group.by = c("seurat_annotations", "stim"), return.seurat = TRUE)
genes.to.label = c("ISG15", "LY6E", "IFI6", "ISG20", "MX1", "IFIT2", "IFIT1", "CXCL10", "CCL8")

p1 <- CellScatter(aggregate_ifnb, "CD14 Mono_CTRL", "CD14 Mono_STIM", highlight = genes.to.label)
p2 <- LabelPoints(plot = p1, points = genes.to.label, repel = TRUE)

p3 <- CellScatter(aggregate_ifnb, "CD4 Naive T_CTRL", "CD4 Naive T_STIM", highlight = genes.to.label)
p4 <- LabelPoints(plot = p3, points = genes.to.label, repel = TRUE)

p2 + p4
```

Example 52 (r):
```r
library(ggplot2)
library(cowplot)
theme_set(theme_cowplot())

aggregate_ifnb <- AggregateExpression(ifnb, group.by = c("seurat_annotations", "stim"), return.seurat = TRUE)
genes.to.label = c("ISG15", "LY6E", "IFI6", "ISG20", "MX1", "IFIT2", "IFIT1", "CXCL10", "CCL8")

p1 <- CellScatter(aggregate_ifnb, "CD14 Mono_CTRL", "CD14 Mono_STIM", highlight = genes.to.label)
p2 <- LabelPoints(plot = p1, points = genes.to.label, repel = TRUE)

p3 <- CellScatter(aggregate_ifnb, "CD4 Naive T_CTRL", "CD4 Naive T_STIM", highlight = genes.to.label)
p4 <- LabelPoints(plot = p3, points = genes.to.label, repel = TRUE)

p2 + p4
```

Example 53 (unknown):
```unknown
FindMarkers()
```

Example 54 (unknown):
```unknown
ifnb$celltype.stim <- paste(ifnb$seurat_annotations, ifnb$stim, sep = "_")
Idents(ifnb) <- "celltype.stim"
b.interferon.response <- FindMarkers(ifnb, ident.1 = "B_STIM", ident.2 = "B_CTRL", verbose = FALSE)
head(b.interferon.response, n = 15)
```

Example 55 (r):
```r
ifnb$celltype.stim <- paste(ifnb$seurat_annotations, ifnb$stim, sep = "_")
Idents(ifnb) <- "celltype.stim"
b.interferon.response <- FindMarkers(ifnb, ident.1 = "B_STIM", ident.2 = "B_CTRL", verbose = FALSE)
head(b.interferon.response, n = 15)
```

Example 56 (r):
```r
ifnb$celltype.stim <- paste(ifnb$seurat_annotations, ifnb$stim, sep = "_")
Idents(ifnb) <- "celltype.stim"
b.interferon.response <- FindMarkers(ifnb, ident.1 = "B_STIM", ident.2 = "B_CTRL", verbose = FALSE)
head(b.interferon.response, n = 15)
```

Example 57 (unknown):
```unknown
##                 p_val avg_log2FC pct.1 pct.2     p_val_adj
## ISG15   5.387767e-159  5.0588481 0.998 0.233 7.571429e-155
## IFIT3   1.945114e-154  6.1124940 0.965 0.052 2.733468e-150
## IFI6    2.503565e-152  5.4933132 0.965 0.076 3.518260e-148
## ISG20   6.492570e-150  3.0549593 1.000 0.668 9.124009e-146
## IFIT1   1.951022e-139  6.2320388 0.907 0.029 2.741772e-135
## MX1     6.897626e-123  3.9798482 0.905 0.115 9.693234e-119
## LY6E    2.825649e-120  3.7907800 0.898 0.150 3.970885e-116
## TNFSF10 4.007285e-112  6.5802175 0.786 0.020 5.631437e-108
## IFIT2   2.672552e-108  5.5525558 0.786 0.037 3.755738e-104
## B2M      5.283684e-98  0.6104044 1.000 1.000  7.425161e-94
## PLSCR1   4.634658e-96  3.8010721 0.793 0.113  6.513085e-92
## IRF7     2.411149e-94  3.1992949 0.835 0.187  3.388388e-90
## CXCL10   3.708508e-86  8.0906108 0.651 0.010  5.211566e-82
## UBE2L6   5.547472e-83  2.5167981 0.851 0.297  7.795863e-79
## PSMB9    1.716262e-77  1.7715351 0.937 0.568  2.411863e-73
```

Example 58 (unknown):
```unknown
##                 p_val avg_log2FC pct.1 pct.2     p_val_adj
## ISG15   5.387767e-159  5.0588481 0.998 0.233 7.571429e-155
## IFIT3   1.945114e-154  6.1124940 0.965 0.052 2.733468e-150
## IFI6    2.503565e-152  5.4933132 0.965 0.076 3.518260e-148
## ISG20   6.492570e-150  3.0549593 1.000 0.668 9.124009e-146
## IFIT1   1.951022e-139  6.2320388 0.907 0.029 2.741772e-135
## MX1     6.897626e-123  3.9798482 0.905 0.115 9.693234e-119
## LY6E    2.825649e-120  3.7907800 0.898 0.150 3.970885e-116
## TNFSF10 4.007285e-112  6.5802175 0.786 0.020 5.631437e-108
## IFIT2   2.672552e-108  5.5525558 0.786 0.037 3.755738e-104
## B2M      5.283684e-98  0.6104044 1.000 1.000  7.425161e-94
## PLSCR1   4.634658e-96  3.8010721 0.793 0.113  6.513085e-92
## IRF7     2.411149e-94  3.1992949 0.835 0.187  3.388388e-90
## CXCL10   3.708508e-86  8.0906108 0.651 0.010  5.211566e-82
## UBE2L6   5.547472e-83  2.5167981 0.851 0.297  7.795863e-79
## PSMB9    1.716262e-77  1.7715351 0.937 0.568  2.411863e-73
```

Example 59 (unknown):
```unknown
FeaturePlot()
```

Example 60 (unknown):
```unknown
FeaturePlot(ifnb, features = c("CD3D", "GNLY", "IFI6"), split.by = "stim", max.cutoff = 3, cols = c("grey",
    "red"), reduction = "umap")
```

Example 61 (r):
```r
FeaturePlot(ifnb, features = c("CD3D", "GNLY", "IFI6"), split.by = "stim", max.cutoff = 3, cols = c("grey",
    "red"), reduction = "umap")
```

Example 62 (r):
```r
FeaturePlot(ifnb, features = c("CD3D", "GNLY", "IFI6"), split.by = "stim", max.cutoff = 3, cols = c("grey",
    "red"), reduction = "umap")
```

Example 63 (unknown):
```unknown
plots <- VlnPlot(ifnb, features = c("LYZ", "ISG15", "CXCL10"), split.by = "stim", group.by = "seurat_annotations",
    pt.size = 0, combine = FALSE)
wrap_plots(plots = plots, ncol = 1)
```

Example 64 (r):
```r
plots <- VlnPlot(ifnb, features = c("LYZ", "ISG15", "CXCL10"), split.by = "stim", group.by = "seurat_annotations",
    pt.size = 0, combine = FALSE)
wrap_plots(plots = plots, ncol = 1)
```

Example 65 (r):
```r
plots <- VlnPlot(ifnb, features = c("LYZ", "ISG15", "CXCL10"), split.by = "stim", group.by = "seurat_annotations",
    pt.size = 0, combine = FALSE)
wrap_plots(plots = plots, ncol = 1)
```

Example 66 (unknown):
```unknown
IntegrateLayers
```

Example 67 (unknown):
```unknown
normalization.method
```

Example 68 (unknown):
```unknown
ifnb <- LoadData("ifnb")

# split datasets and process without integration
ifnb[["RNA"]] <- split(ifnb[["RNA"]], f = ifnb$stim)
ifnb <- SCTransform(ifnb)
ifnb <- RunPCA(ifnb)
ifnb <- RunUMAP(ifnb, dims = 1:30)
DimPlot(ifnb, reduction = "umap", group.by = c("stim", "seurat_annotations"))
```

Example 69 (r):
```r
ifnb <- LoadData("ifnb")

# split datasets and process without integration
ifnb[["RNA"]] <- split(ifnb[["RNA"]], f = ifnb$stim)
ifnb <- SCTransform(ifnb)
ifnb <- RunPCA(ifnb)
ifnb <- RunUMAP(ifnb, dims = 1:30)
DimPlot(ifnb, reduction = "umap", group.by = c("stim", "seurat_annotations"))
```

Example 70 (r):
```r
ifnb <- LoadData("ifnb")

# split datasets and process without integration
ifnb[["RNA"]] <- split(ifnb[["RNA"]], f = ifnb$stim)
ifnb <- SCTransform(ifnb)
ifnb <- RunPCA(ifnb)
ifnb <- RunUMAP(ifnb, dims = 1:30)
DimPlot(ifnb, reduction = "umap", group.by = c("stim", "seurat_annotations"))
```

Example 71 (unknown):
```unknown
# integrate datasets
ifnb <- IntegrateLayers(object = ifnb, method = CCAIntegration, normalization.method = "SCT", verbose = F)
ifnb <- FindNeighbors(ifnb, reduction = "integrated.dr", dims = 1:30)
ifnb <- FindClusters(ifnb, resolution = 0.6)
```

Example 72 (r):
```r
# integrate datasets
ifnb <- IntegrateLayers(object = ifnb, method = CCAIntegration, normalization.method = "SCT", verbose = F)
ifnb <- FindNeighbors(ifnb, reduction = "integrated.dr", dims = 1:30)
ifnb <- FindClusters(ifnb, resolution = 0.6)
```

Example 73 (r):
```r
# integrate datasets
ifnb <- IntegrateLayers(object = ifnb, method = CCAIntegration, normalization.method = "SCT", verbose = F)
ifnb <- FindNeighbors(ifnb, reduction = "integrated.dr", dims = 1:30)
ifnb <- FindClusters(ifnb, resolution = 0.6)
```

Example 74 (unknown):
```unknown
## Modularity Optimizer version 1.3.0 by Ludo Waltman and Nees Jan van Eck
## 
## Number of nodes: 13999
## Number of edges: 528127
## 
## Running Louvain algorithm...
## Maximum modularity in 10 random starts: 0.9060
## Number of communities: 20
## Elapsed time: 21 seconds
```

Example 75 (unknown):
```unknown
## Modularity Optimizer version 1.3.0 by Ludo Waltman and Nees Jan van Eck
## 
## Number of nodes: 13999
## Number of edges: 528127
## 
## Running Louvain algorithm...
## Maximum modularity in 10 random starts: 0.9060
## Number of communities: 20
## Elapsed time: 21 seconds
```

Example 76 (unknown):
```unknown
ifnb <- RunUMAP(ifnb, dims = 1:30, reduction = "integrated.dr")
DimPlot(ifnb, reduction = "umap", group.by = c("stim", "seurat_annotations"))
```

Example 77 (r):
```r
ifnb <- RunUMAP(ifnb, dims = 1:30, reduction = "integrated.dr")
DimPlot(ifnb, reduction = "umap", group.by = c("stim", "seurat_annotations"))
```

Example 78 (r):
```r
ifnb <- RunUMAP(ifnb, dims = 1:30, reduction = "integrated.dr")
DimPlot(ifnb, reduction = "umap", group.by = c("stim", "seurat_annotations"))
```

Example 79 (unknown):
```unknown
# perform differential expression
ifnb <- PrepSCTFindMarkers(ifnb)
ifnb$celltype.stim <- paste(ifnb$seurat_annotations, ifnb$stim, sep = "_")
Idents(ifnb) <- "celltype.stim"
b.interferon.response <- FindMarkers(ifnb, ident.1 = "B_STIM", ident.2 = "B_CTRL", verbose = FALSE)
```

Example 80 (r):
```r
# perform differential expression
ifnb <- PrepSCTFindMarkers(ifnb)
ifnb$celltype.stim <- paste(ifnb$seurat_annotations, ifnb$stim, sep = "_")
Idents(ifnb) <- "celltype.stim"
b.interferon.response <- FindMarkers(ifnb, ident.1 = "B_STIM", ident.2 = "B_CTRL", verbose = FALSE)
```

Example 81 (r):
```r
# perform differential expression
ifnb <- PrepSCTFindMarkers(ifnb)
ifnb$celltype.stim <- paste(ifnb$seurat_annotations, ifnb$stim, sep = "_")
Idents(ifnb) <- "celltype.stim"
b.interferon.response <- FindMarkers(ifnb, ident.1 = "B_STIM", ident.2 = "B_CTRL", verbose = FALSE)
```

Example 82 (unknown):
```unknown
sessionInfo()
```

Example 83 (r):
```r
sessionInfo()
```

Example 84 (r):
```r
sessionInfo()
```

Example 85 (unknown):
```unknown
## R version 4.2.2 Patched (2022-11-10 r83330)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.6 LTS
## 
## Matrix products: default
## BLAS:   /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.9.0
## LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.9.0
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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       
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
##  [1] cowplot_1.1.1                  ggplot2_3.4.4                 
##  [3] patchwork_1.1.3                thp1.eccite.SeuratData_3.1.5  
##  [5] stxBrain.SeuratData_0.1.1      ssHippo.SeuratData_3.1.4      
##  [7] pbmcsca.SeuratData_3.0.0       pbmcref.SeuratData_1.0.0      
##  [9] pbmcMultiome.SeuratData_0.1.4  pbmc3k.SeuratData_3.1.4       
## [11] panc8.SeuratData_3.0.2         ifnb.SeuratData_3.0.0         
## [13] hcabm40k.SeuratData_3.0.0      cbmc.SeuratData_3.1.4         
## [15] bonemarrowref.SeuratData_1.0.0 bmcite.SeuratData_0.3.0       
## [17] SeuratData_0.2.2.9001          Seurat_5.0.1             
## [19] testthat_3.2.0                 SeuratObject_5.0.1            
## [21] sp_2.1-1                      
## 
## loaded via a namespace (and not attached):
##   [1] utf8_1.2.4                  spatstat.explore_3.2-5     
##   [3] reticulate_1.34.0           tidyselect_1.2.0           
##   [5] htmlwidgets_1.6.2           grid_4.2.2                 
##   [7] Rtsne_0.16                  devtools_2.4.5             
##   [9] munsell_0.5.0               mutoss_0.1-13              
##  [11] codetools_0.2-19            ragg_1.2.5                 
##  [13] ica_1.0-3                   future_1.33.0              
##  [15] miniUI_0.1.1.1              withr_2.5.2                
##  [17] spatstat.random_3.2-1       colorspace_2.1-0           
##  [19] progressr_0.14.0            Biobase_2.58.0             
##  [21] highr_0.10                  knitr_1.45                 
##  [23] rstudioapi_0.14             stats4_4.2.2               
##  [25] ROCR_1.0-11                 tensor_1.5                 
##  [27] listenv_0.9.0               MatrixGenerics_1.10.0      
##  [29] Rdpack_2.5                  labeling_0.4.3             
##  [31] GenomeInfoDbData_1.2.9      mnormt_2.1.1               
##  [33] polyclip_1.10-6             farver_2.1.1               
##  [35] rprojroot_2.0.4             TH.data_1.1-2              
##  [37] parallelly_1.36.0           vctrs_0.6.4                
##  [39] generics_0.1.3              xfun_0.40                  
##  [41] GenomeInfoDb_1.34.9         R6_2.5.1                   
##  [43] ggbeeswarm_0.7.1            DelayedArray_0.24.0        
##  [45] bitops_1.0-7                spatstat.utils_3.0-4       
##  [47] cachem_1.0.8                promises_1.2.1             
##  [49] scales_1.2.1                multcomp_1.4-25            
##  [51] beeswarm_0.4.0              gtable_0.3.4               
##  [53] globals_0.16.2              processx_3.8.2             
##  [55] goftest_1.2-3               spam_2.10-0                
##  [57] sandwich_3.0-2              rlang_1.1.1                
##  [59] systemfonts_1.0.4           splines_4.2.2              
##  [61] lazyeval_0.2.2              spatstat.geom_3.2-7        
##  [63] yaml_2.3.7                  reshape2_1.4.4             
##  [65] abind_1.4-5                 httpuv_1.6.12              
##  [67] tools_4.2.2                 usethis_2.1.6              
##  [69] ellipsis_0.3.2              jquerylib_0.1.4            
##  [71] RColorBrewer_1.1-3          BiocGenerics_0.44.0        
##  [73] sessioninfo_1.2.2           ggridges_0.5.4             
##  [75] TFisher_0.2.0               Rcpp_1.0.11                
##  [77] plyr_1.8.9                  sparseMatrixStats_1.10.0   
##  [79] zlibbioc_1.44.0             RCurl_1.98-1.12            
##  [81] purrr_1.0.2                 ps_1.7.5                   
##  [83] prettyunits_1.2.0           deldir_1.0-9               
##  [85] pbapply_1.7-2               urlchecker_1.0.1           
##  [87] S4Vectors_0.36.2            zoo_1.8-12                 
##  [89] SummarizedExperiment_1.28.0 ggrepel_0.9.4              
##  [91] cluster_2.1.4               fs_1.6.3                   
##  [93] magrittr_2.0.3              glmGamPoi_1.10.2           
##  [95] data.table_1.14.8           RSpectra_0.16-1            
##  [97] scattermore_1.2             lmtest_0.9-40              
##  [99] RANN_2.6.1                  mvtnorm_1.2-3              
## [101] fitdistrplus_1.1-11         matrixStats_1.0.0          
## [103] pkgload_1.3.3               mime_0.12                  
## [105] evaluate_0.22               xtable_1.8-4               
## [107] IRanges_2.32.0              fastDummies_1.7.3          
## [109] gridExtra_2.3               compiler_4.2.2             
## [111] tibble_3.2.1                KernSmooth_2.23-22         
## [113] crayon_1.5.2                htmltools_0.5.6.1          
## [115] later_1.3.1                 tidyr_1.3.0                
## [117] formatR_1.14                MASS_7.3-58.2              
## [119] rappdirs_0.3.3              Matrix_1.6-1.1             
## [121] brio_1.1.3                  cli_3.6.1                  
## [123] rbibutils_2.2.15            qqconf_1.3.2               
## [125] parallel_4.2.2              dotCall64_1.1-0            
## [127] metap_1.9                   igraph_1.5.1               
## [129] GenomicRanges_1.50.2        pkgconfig_2.0.3            
## [131] sn_2.1.1                    pkgdown_2.0.7              
## [133] numDeriv_2016.8-1.1         plotly_4.10.3              
## [135] spatstat.sparse_3.0-3       vipor_0.4.5                
## [137] bslib_0.5.1                 XVector_0.38.0             
## [139] multtest_2.54.0             stringr_1.5.0              
## [141] callr_3.7.3                 digest_0.6.33              
## [143] sctransform_0.4.1           RcppAnnoy_0.0.21           
## [145] spatstat.data_3.0-3         rmarkdown_2.25             
## [147] leiden_0.4.3                uwot_0.1.16                
## [149] DelayedMatrixStats_1.20.0   shiny_1.7.5.1              
## [151] lifecycle_1.0.4             nlme_3.1-162               
## [153] jsonlite_1.8.7              limma_3.54.1               
## [155] desc_1.4.2                  viridisLite_0.4.2          
## [157] fansi_1.0.5                 pillar_1.9.0               
## [159] lattice_0.21-9              ggrastr_1.0.1              
## [161] plotrix_3.8-2               fastmap_1.1.1              
## [163] httr_1.4.7                  pkgbuild_1.4.2             
## [165] survival_3.5-7              glue_1.6.2                 
## [167] remotes_2.4.2.1             png_0.1-8                  
## [169] presto_1.0.0                stringi_1.7.12             
## [171] sass_0.4.7                  profvis_0.3.7              
## [173] textshaping_0.3.6           RcppHNSW_0.5.0             
## [175] memoise_2.0.1               mathjaxr_1.6-0             
## [177] dplyr_1.1.3                 irlba_2.3.5.1              
## [179] future.apply_1.11.0
```

Example 86 (unknown):
```unknown
## R version 4.2.2 Patched (2022-11-10 r83330)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.6 LTS
## 
## Matrix products: default
## BLAS:   /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.9.0
## LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.9.0
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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       
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
##  [1] cowplot_1.1.1                  ggplot2_3.4.4                 
##  [3] patchwork_1.1.3                thp1.eccite.SeuratData_3.1.5  
##  [5] stxBrain.SeuratData_0.1.1      ssHippo.SeuratData_3.1.4      
##  [7] pbmcsca.SeuratData_3.0.0       pbmcref.SeuratData_1.0.0      
##  [9] pbmcMultiome.SeuratData_0.1.4  pbmc3k.SeuratData_3.1.4       
## [11] panc8.SeuratData_3.0.2         ifnb.SeuratData_3.0.0         
## [13] hcabm40k.SeuratData_3.0.0      cbmc.SeuratData_3.1.4         
## [15] bonemarrowref.SeuratData_1.0.0 bmcite.SeuratData_0.3.0       
## [17] SeuratData_0.2.2.9001          Seurat_5.0.1             
## [19] testthat_3.2.0                 SeuratObject_5.0.1            
## [21] sp_2.1-1                      
## 
## loaded via a namespace (and not attached):
##   [1] utf8_1.2.4                  spatstat.explore_3.2-5     
##   [3] reticulate_1.34.0           tidyselect_1.2.0           
##   [5] htmlwidgets_1.6.2           grid_4.2.2                 
##   [7] Rtsne_0.16                  devtools_2.4.5             
##   [9] munsell_0.5.0               mutoss_0.1-13              
##  [11] codetools_0.2-19            ragg_1.2.5                 
##  [13] ica_1.0-3                   future_1.33.0              
##  [15] miniUI_0.1.1.1              withr_2.5.2                
##  [17] spatstat.random_3.2-1       colorspace_2.1-0           
##  [19] progressr_0.14.0            Biobase_2.58.0             
##  [21] highr_0.10                  knitr_1.45                 
##  [23] rstudioapi_0.14             stats4_4.2.2               
##  [25] ROCR_1.0-11                 tensor_1.5                 
##  [27] listenv_0.9.0               MatrixGenerics_1.10.0      
##  [29] Rdpack_2.5                  labeling_0.4.3             
##  [31] GenomeInfoDbData_1.2.9      mnormt_2.1.1               
##  [33] polyclip_1.10-6             farver_2.1.1               
##  [35] rprojroot_2.0.4             TH.data_1.1-2              
##  [37] parallelly_1.36.0           vctrs_0.6.4                
##  [39] generics_0.1.3              xfun_0.40                  
##  [41] GenomeInfoDb_1.34.9         R6_2.5.1                   
##  [43] ggbeeswarm_0.7.1            DelayedArray_0.24.0        
##  [45] bitops_1.0-7                spatstat.utils_3.0-4       
##  [47] cachem_1.0.8                promises_1.2.1             
##  [49] scales_1.2.1                multcomp_1.4-25            
##  [51] beeswarm_0.4.0              gtable_0.3.4               
##  [53] globals_0.16.2              processx_3.8.2             
##  [55] goftest_1.2-3               spam_2.10-0                
##  [57] sandwich_3.0-2              rlang_1.1.1                
##  [59] systemfonts_1.0.4           splines_4.2.2              
##  [61] lazyeval_0.2.2              spatstat.geom_3.2-7        
##  [63] yaml_2.3.7                  reshape2_1.4.4             
##  [65] abind_1.4-5                 httpuv_1.6.12              
##  [67] tools_4.2.2                 usethis_2.1.6              
##  [69] ellipsis_0.3.2              jquerylib_0.1.4            
##  [71] RColorBrewer_1.1-3          BiocGenerics_0.44.0        
##  [73] sessioninfo_1.2.2           ggridges_0.5.4             
##  [75] TFisher_0.2.0               Rcpp_1.0.11                
##  [77] plyr_1.8.9                  sparseMatrixStats_1.10.0   
##  [79] zlibbioc_1.44.0             RCurl_1.98-1.12            
##  [81] purrr_1.0.2                 ps_1.7.5                   
##  [83] prettyunits_1.2.0           deldir_1.0-9               
##  [85] pbapply_1.7-2               urlchecker_1.0.1           
##  [87] S4Vectors_0.36.2            zoo_1.8-12                 
##  [89] SummarizedExperiment_1.28.0 ggrepel_0.9.4              
##  [91] cluster_2.1.4               fs_1.6.3                   
##  [93] magrittr_2.0.3              glmGamPoi_1.10.2           
##  [95] data.table_1.14.8           RSpectra_0.16-1            
##  [97] scattermore_1.2             lmtest_0.9-40              
##  [99] RANN_2.6.1                  mvtnorm_1.2-3              
## [101] fitdistrplus_1.1-11         matrixStats_1.0.0          
## [103] pkgload_1.3.3               mime_0.12                  
## [105] evaluate_0.22               xtable_1.8-4               
## [107] IRanges_2.32.0              fastDummies_1.7.3          
## [109] gridExtra_2.3               compiler_4.2.2             
## [111] tibble_3.2.1                KernSmooth_2.23-22         
## [113] crayon_1.5.2                htmltools_0.5.6.1          
## [115] later_1.3.1                 tidyr_1.3.0                
## [117] formatR_1.14                MASS_7.3-58.2              
## [119] rappdirs_0.3.3              Matrix_1.6-1.1             
## [121] brio_1.1.3                  cli_3.6.1                  
## [123] rbibutils_2.2.15            qqconf_1.3.2               
## [125] parallel_4.2.2              dotCall64_1.1-0            
## [127] metap_1.9                   igraph_1.5.1               
## [129] GenomicRanges_1.50.2        pkgconfig_2.0.3            
## [131] sn_2.1.1                    pkgdown_2.0.7              
## [133] numDeriv_2016.8-1.1         plotly_4.10.3              
## [135] spatstat.sparse_3.0-3       vipor_0.4.5                
## [137] bslib_0.5.1                 XVector_0.38.0             
## [139] multtest_2.54.0             stringr_1.5.0              
## [141] callr_3.7.3                 digest_0.6.33              
## [143] sctransform_0.4.1           RcppAnnoy_0.0.21           
## [145] spatstat.data_3.0-3         rmarkdown_2.25             
## [147] leiden_0.4.3                uwot_0.1.16                
## [149] DelayedMatrixStats_1.20.0   shiny_1.7.5.1              
## [151] lifecycle_1.0.4             nlme_3.1-162               
## [153] jsonlite_1.8.7              limma_3.54.1               
## [155] desc_1.4.2                  viridisLite_0.4.2          
## [157] fansi_1.0.5                 pillar_1.9.0               
## [159] lattice_0.21-9              ggrastr_1.0.1              
## [161] plotrix_3.8-2               fastmap_1.1.1              
## [163] httr_1.4.7                  pkgbuild_1.4.2             
## [165] survival_3.5-7              glue_1.6.2                 
## [167] remotes_2.4.2.1             png_0.1-8                  
## [169] presto_1.0.0                stringi_1.7.12             
## [171] sass_0.4.7                  profvis_0.3.7              
## [173] textshaping_0.3.6           RcppHNSW_0.5.0             
## [175] memoise_2.0.1               mathjaxr_1.6-0             
## [177] dplyr_1.1.3                 irlba_2.3.5.1              
## [179] future.apply_1.11.0
```

---

## Analysis, visualization, and integration of Visium HD spatial datasets with Seurat • Seurat

**URL:** http://127.0.0.1:9173/articles_integration_introduction.html

**Contents:**
- Introduction to scRNA-seq integration
    - Compiled: November 16, 2023
- Introduction to scRNA-seq integration
- Integration goals
- Setup the Seurat objects
- Perform analysis without integration
- Perform integration
- Identify conserved cell type markers
- Identify differential expressed genes across conditions
- Perform integration with SCTransform-normalized datasets
- Contents

Integration of single-cell sequencing datasets, for example across experimental batches, donors, or conditions, is often an important step in scRNA-seq workflows. Integrative analysis can help to match shared cell types and states across datasets, which can boost statistical power, and most importantly, facilitate accurate comparative analysis across datasets. In previous versions of Seurat we introduced methods for integrative analysis, including our ‘anchor-based’ integration workflow. Many labs have also published powerful and pioneering methods, including Harmony and scVI, for integrative analysis. Please see our Integrating scRNA-seq data with multiple tools vignette.

The following tutorial is designed to give you an overview of the kinds of comparative analyses on complex cell types that are possible using the Seurat integration procedure. Here, we address a few key goals:

For convenience, we distribute this dataset through our SeuratData package.

The object contains data from human PBMC from two conditions, interferon-stimulated and control cells (stored in the stim column in the object metadata). We will aim to integrate the two conditions together, so that we can jointly identify cell subpopulations across datasets, and then explore how each group differs across conditions

In previous versions of Seurat, we would require the data to be represented as two different Seurat objects. In Seurat v5, we keep all the data in one object, but simply split it into multiple ‘layers’. To learn more about layers, check out our Seurat object interaction vignette.

We can first analyze the dataset without integration. The resulting clusters are defined both by cell type and stimulation condition, which creates challenges for downstream analysis.

We now aim to integrate data from the two conditions, so that cells from the same cell type/subpopulation will cluster together.

We often refer to this procedure as intergration/alignment. When aligning two genome sequences together, identification of shared/homologous regions can help to interpret differences between the sequences as well. Similarly for scRNA-seq integration, our goal is not to remove biological differences across conditions, but to learn shared cell types/states in an initial step - specifically because that will enable us to compare control stimulated and control profiles for these individual cell types.

The Seurat v5 integration procedure aims to return a single dimensional reduction that captures the shared sources of variance across multiple layers, so that cells in a similar biological state will cluster. The method returns a dimensional reduction (i.e. integrated.cca) which can be used for visualization and unsupervised clustering analysis. For evaluating performance, we can use cell type labels that are pre-loaded in the seurat_annotations metadata column.

To visualize the two conditions side-by-side, we can use the split.by argument to show each condition colored by cluster.

To identify canonical cell type marker genes that are conserved across conditions, we provide the FindConservedMarkers() function. This function performs differential gene expression testing for each dataset/group and combines the p-values using meta-analysis methods from the MetaDE R package. For example, we can calculated the genes that are conserved markers irrespective of stimulation condition in cluster 6 (NK cells).

You can perform these same analysis on the unsupervised clustering results (stored in seurat_clusters), and use these conserved markers to annotate cell types in your dataset.

The DotPlot() function with the split.by parameter can be useful for viewing conserved cell type markers across conditions, showing both the expression level and the percentage of cells in a cluster expressing any given gene. Here we plot 2-3 strong marker genes for each of our 14 clusters.

Now that we’ve aligned the stimulated and control cells, we can start to do comparative analyses and look at the differences induced by stimulation.

We can aggregate cells of a similar type and condition together to create “pseudobulk” profiles using the AggregateExpression command. As an initial exploratory analysis, we can compare pseudobulk profiles of two cell types (naive CD4 T cells, and CD14 monocytes), and compare their gene expression profiles before and after stimulation. We highlight genes that exhibit dramatic responses to interferon stimulation. As you can see, many of the same genes are upregulated in both of these cell types and likely represent a conserved interferon response pathway, though CD14 monocytes exhibit a stronger transcriptional response.

We can now ask what genes change in different conditions for cells of the same type. First, we create a column in the meta.data slot to hold both the cell type and stimulation information and switch the current ident to that column. Then we use FindMarkers() to find the genes that are different between stimulated and control B cells. Notice that many of the top genes that show up here are the same as the ones we plotted earlier as core interferon response genes. Additionally, genes like CXCL10 which we saw were specific to monocyte and B cell interferon response show up as highly significant in this list as well.

Please note that p-values obtained from this analysis should be interpreted with caution, as these tests treat each cell as an independent replicate, and ignore inherent correlations between cells originating from the same sample. As discussed here, DE tests across multiple conditions should expressly utilize multiple samples/replicates, and can be performed after aggregating (‘pseudobulking’) cells from the same sample and subpopulation together. We do not perform this analysis here, as there is a single replicate in the data, but please see our vignette comparing healthy and diabetic samples as an example for how to perform DE analysis across conditions.

Another useful way to visualize these changes in gene expression is with the split.by option to the FeaturePlot() or VlnPlot() function. This will display FeaturePlots of the list of given genes, split by a grouping variable (stimulation condition here). Genes such as CD3D and GNLY are canonical cell type markers (for T cells and NK/CD8 T cells) that are virtually unaffected by interferon stimulation and display similar gene expression patterns in the control and stimulated group. IFI6 and ISG15, on the other hand, are core interferon response genes and are upregulated accordingly in all cell types. Finally, CD14 and CXCL10 are genes that show a cell type specific interferon response. CD14 expression decreases after stimulation in CD14 monocytes, which could lead to misclassification in a supervised analysis framework, underscoring the value of integrated analysis. CXCL10 shows a distinct upregulation in monocytes and B cells after interferon stimulation but not in other cell types.

As an alternative to log-normalization, Seurat also includes support for preprocessing of scRNA-seq using the sctransform workflow. The IntegrateLayers function also supports SCTransform-normalized data, by setting the normalization.method parameter, as shown below.

Developed by Rahul Satija, Satija Lab and Collaborators.

Site built with pkgdown 2.0.7.

**Examples:**

Example 1 (unknown):
```unknown
vignettes/integration_introduction.Rmd
```

Example 2 (unknown):
```unknown
integration_introduction.Rmd
```

Example 3 (unknown):
```unknown
library(Seurat)
library(SeuratData)
library(patchwork)
```

Example 4 (r):
```r
library(Seurat)
library(SeuratData)
library(patchwork)
```

Example 5 (r):
```r
library(Seurat)
library(SeuratData)
library(patchwork)
```

Example 6 (unknown):
```unknown
# install dataset
InstallData("ifnb")
```

Example 7 (r):
```r
# install dataset
InstallData("ifnb")
```

Example 8 (r):
```r
# install dataset
InstallData("ifnb")
```

Example 9 (unknown):
```unknown
# load dataset
ifnb <- LoadData("ifnb")
# split the RNA measurements into two layers one for control cells, one for stimulated cells

ifnb[["RNA"]] <- split(ifnb[["RNA"]], f = ifnb$stim)
ifnb
```

Example 10 (r):
```r
# load dataset
ifnb <- LoadData("ifnb")
# split the RNA measurements into two layers one for control cells, one for stimulated cells

ifnb[["RNA"]] <- split(ifnb[["RNA"]], f = ifnb$stim)
ifnb
```

Example 11 (r):
```r
# load dataset
ifnb <- LoadData("ifnb")
# split the RNA measurements into two layers one for control cells, one for stimulated cells

ifnb[["RNA"]] <- split(ifnb[["RNA"]], f = ifnb$stim)
ifnb
```

Example 12 (unknown):
```unknown
# run standard anlaysis workflow
ifnb <- NormalizeData(ifnb)
ifnb <- FindVariableFeatures(ifnb)
ifnb <- ScaleData(ifnb)
ifnb <- RunPCA(ifnb)
```

Example 13 (r):
```r
# run standard anlaysis workflow
ifnb <- NormalizeData(ifnb)
ifnb <- FindVariableFeatures(ifnb)
ifnb <- ScaleData(ifnb)
ifnb <- RunPCA(ifnb)
```

Example 14 (r):
```r
# run standard anlaysis workflow
ifnb <- NormalizeData(ifnb)
ifnb <- FindVariableFeatures(ifnb)
ifnb <- ScaleData(ifnb)
ifnb <- RunPCA(ifnb)
```

Example 15 (unknown):
```unknown
ifnb <- FindNeighbors(ifnb, dims = 1:30, reduction = "pca")
ifnb <- FindClusters(ifnb, resolution = 2, cluster.name = "unintegrated_clusters")
```

Example 16 (r):
```r
ifnb <- FindNeighbors(ifnb, dims = 1:30, reduction = "pca")
ifnb <- FindClusters(ifnb, resolution = 2, cluster.name = "unintegrated_clusters")
```

Example 17 (r):
```r
ifnb <- FindNeighbors(ifnb, dims = 1:30, reduction = "pca")
ifnb <- FindClusters(ifnb, resolution = 2, cluster.name = "unintegrated_clusters")
```

Example 18 (unknown):
```unknown
## Modularity Optimizer version 1.3.0 by Ludo Waltman and Nees Jan van Eck
## 
## Number of nodes: 13999
## Number of edges: 555146
## 
## Running Louvain algorithm...
## Maximum modularity in 10 random starts: 0.8153
## Number of communities: 26
## Elapsed time: 23 seconds
```

Example 19 (unknown):
```unknown
## Modularity Optimizer version 1.3.0 by Ludo Waltman and Nees Jan van Eck
## 
## Number of nodes: 13999
## Number of edges: 555146
## 
## Running Louvain algorithm...
## Maximum modularity in 10 random starts: 0.8153
## Number of communities: 26
## Elapsed time: 23 seconds
```

Example 20 (unknown):
```unknown
ifnb <- RunUMAP(ifnb, dims = 1:30, reduction = "pca", reduction.name = "umap.unintegrated")
DimPlot(ifnb, reduction = "umap.unintegrated", group.by = c("stim", "seurat_clusters"))
```

Example 21 (r):
```r
ifnb <- RunUMAP(ifnb, dims = 1:30, reduction = "pca", reduction.name = "umap.unintegrated")
DimPlot(ifnb, reduction = "umap.unintegrated", group.by = c("stim", "seurat_clusters"))
```

Example 22 (r):
```r
ifnb <- RunUMAP(ifnb, dims = 1:30, reduction = "pca", reduction.name = "umap.unintegrated")
DimPlot(ifnb, reduction = "umap.unintegrated", group.by = c("stim", "seurat_clusters"))
```

Example 23 (unknown):
```unknown
integrated.cca
```

Example 24 (unknown):
```unknown
seurat_annotations
```

Example 25 (unknown):
```unknown
ifnb <- IntegrateLayers(object = ifnb, method = CCAIntegration, orig.reduction = "pca", new.reduction = "integrated.cca",
    verbose = FALSE)

# re-join layers after integration
ifnb[["RNA"]] <- JoinLayers(ifnb[["RNA"]])

ifnb <- FindNeighbors(ifnb, reduction = "integrated.cca", dims = 1:30)
ifnb <- FindClusters(ifnb, resolution = 1)
```

Example 26 (r):
```r
ifnb <- IntegrateLayers(object = ifnb, method = CCAIntegration, orig.reduction = "pca", new.reduction = "integrated.cca",
    verbose = FALSE)

# re-join layers after integration
ifnb[["RNA"]] <- JoinLayers(ifnb[["RNA"]])

ifnb <- FindNeighbors(ifnb, reduction = "integrated.cca", dims = 1:30)
ifnb <- FindClusters(ifnb, resolution = 1)
```

Example 27 (r):
```r
ifnb <- IntegrateLayers(object = ifnb, method = CCAIntegration, orig.reduction = "pca", new.reduction = "integrated.cca",
    verbose = FALSE)

# re-join layers after integration
ifnb[["RNA"]] <- JoinLayers(ifnb[["RNA"]])

ifnb <- FindNeighbors(ifnb, reduction = "integrated.cca", dims = 1:30)
ifnb <- FindClusters(ifnb, resolution = 1)
```

Example 28 (unknown):
```unknown
## Modularity Optimizer version 1.3.0 by Ludo Waltman and Nees Jan van Eck
## 
## Number of nodes: 13999
## Number of edges: 588593
## 
## Running Louvain algorithm...
## Maximum modularity in 10 random starts: 0.8454
## Number of communities: 17
## Elapsed time: 26 seconds
```

Example 29 (unknown):
```unknown
## Modularity Optimizer version 1.3.0 by Ludo Waltman and Nees Jan van Eck
## 
## Number of nodes: 13999
## Number of edges: 588593
## 
## Running Louvain algorithm...
## Maximum modularity in 10 random starts: 0.8454
## Number of communities: 17
## Elapsed time: 26 seconds
```

Example 30 (unknown):
```unknown
ifnb <- RunUMAP(ifnb, dims = 1:30, reduction = "integrated.cca")
```

Example 31 (r):
```r
ifnb <- RunUMAP(ifnb, dims = 1:30, reduction = "integrated.cca")
```

Example 32 (r):
```r
ifnb <- RunUMAP(ifnb, dims = 1:30, reduction = "integrated.cca")
```

Example 33 (unknown):
```unknown
# Visualization
DimPlot(ifnb, reduction = "umap", group.by = c("stim", "seurat_annotations"))
```

Example 34 (r):
```r
# Visualization
DimPlot(ifnb, reduction = "umap", group.by = c("stim", "seurat_annotations"))
```

Example 35 (r):
```r
# Visualization
DimPlot(ifnb, reduction = "umap", group.by = c("stim", "seurat_annotations"))
```

Example 36 (unknown):
```unknown
DimPlot(ifnb, reduction = "umap", split.by = "stim")
```

Example 37 (r):
```r
DimPlot(ifnb, reduction = "umap", split.by = "stim")
```

Example 38 (r):
```r
DimPlot(ifnb, reduction = "umap", split.by = "stim")
```

Example 39 (unknown):
```unknown
FindConservedMarkers()
```

Example 40 (unknown):
```unknown
Idents(ifnb) <- "seurat_annotations"
nk.markers <- FindConservedMarkers(ifnb, ident.1 = "NK", grouping.var = "stim", verbose = FALSE)
head(nk.markers)
```

Example 41 (r):
```r
Idents(ifnb) <- "seurat_annotations"
nk.markers <- FindConservedMarkers(ifnb, ident.1 = "NK", grouping.var = "stim", verbose = FALSE)
head(nk.markers)
```

Example 42 (r):
```r
Idents(ifnb) <- "seurat_annotations"
nk.markers <- FindConservedMarkers(ifnb, ident.1 = "NK", grouping.var = "stim", verbose = FALSE)
head(nk.markers)
```

Example 43 (unknown):
```unknown
##       CTRL_p_val CTRL_avg_log2FC CTRL_pct.1 CTRL_pct.2 CTRL_p_val_adj
## GNLY           0        6.854586      0.943      0.046              0
## NKG7           0        5.358881      0.953      0.085              0
## GZMB           0        5.078135      0.839      0.044              0
## CLIC3          0        5.765314      0.601      0.024              0
## CTSW           0        5.307246      0.537      0.030              0
## KLRD1          0        5.261553      0.507      0.019              0
##       STIM_p_val STIM_avg_log2FC STIM_pct.1 STIM_pct.2 STIM_p_val_adj max_pval
## GNLY           0        6.435910      0.956      0.059              0        0
## NKG7           0        4.971397      0.950      0.081              0        0
## GZMB           0        5.151924      0.897      0.060              0        0
## CLIC3          0        5.505208      0.623      0.031              0        0
## CTSW           0        5.240729      0.592      0.035              0        0
## KLRD1          0        4.852457      0.555      0.027              0        0
##       minimump_p_val
## GNLY               0
## NKG7               0
## GZMB               0
## CLIC3              0
## CTSW               0
## KLRD1              0
```

Example 44 (unknown):
```unknown
##       CTRL_p_val CTRL_avg_log2FC CTRL_pct.1 CTRL_pct.2 CTRL_p_val_adj
## GNLY           0        6.854586      0.943      0.046              0
## NKG7           0        5.358881      0.953      0.085              0
## GZMB           0        5.078135      0.839      0.044              0
## CLIC3          0        5.765314      0.601      0.024              0
## CTSW           0        5.307246      0.537      0.030              0
## KLRD1          0        5.261553      0.507      0.019              0
##       STIM_p_val STIM_avg_log2FC STIM_pct.1 STIM_pct.2 STIM_p_val_adj max_pval
## GNLY           0        6.435910      0.956      0.059              0        0
## NKG7           0        4.971397      0.950      0.081              0        0
## GZMB           0        5.151924      0.897      0.060              0        0
## CLIC3          0        5.505208      0.623      0.031              0        0
## CTSW           0        5.240729      0.592      0.035              0        0
## KLRD1          0        4.852457      0.555      0.027              0        0
##       minimump_p_val
## GNLY               0
## NKG7               0
## GZMB               0
## CLIC3              0
## CTSW               0
## KLRD1              0
```

Example 45 (unknown):
```unknown
seurat_clusters
```

Example 46 (unknown):
```unknown
# NEEDS TO BE FIXED AND SET ORDER CORRECTLY
Idents(ifnb) <- factor(Idents(ifnb), levels = c("pDC", "Eryth", "Mk", "DC", "CD14 Mono", "CD16 Mono",
    "B Activated", "B", "CD8 T", "NK", "T activated", "CD4 Naive T", "CD4 Memory T"))

markers.to.plot <- c("CD3D", "CREM", "HSPH1", "SELL", "GIMAP5", "CACYBP", "GNLY", "NKG7", "CCL5",
    "CD8A", "MS4A1", "CD79A", "MIR155HG", "NME1", "FCGR3A", "VMO1", "CCL2", "S100A9", "HLA-DQA1",
    "GPR183", "PPBP", "GNG11", "HBA2", "HBB", "TSPAN13", "IL3RA", "IGJ", "PRSS57")
DotPlot(ifnb, features = markers.to.plot, cols = c("blue", "red"), dot.scale = 8, split.by = "stim") +
    RotatedAxis()
```

Example 47 (r):
```r
# NEEDS TO BE FIXED AND SET ORDER CORRECTLY
Idents(ifnb) <- factor(Idents(ifnb), levels = c("pDC", "Eryth", "Mk", "DC", "CD14 Mono", "CD16 Mono",
    "B Activated", "B", "CD8 T", "NK", "T activated", "CD4 Naive T", "CD4 Memory T"))

markers.to.plot <- c("CD3D", "CREM", "HSPH1", "SELL", "GIMAP5", "CACYBP", "GNLY", "NKG7", "CCL5",
    "CD8A", "MS4A1", "CD79A", "MIR155HG", "NME1", "FCGR3A", "VMO1", "CCL2", "S100A9", "HLA-DQA1",
    "GPR183", "PPBP", "GNG11", "HBA2", "HBB", "TSPAN13", "IL3RA", "IGJ", "PRSS57")
DotPlot(ifnb, features = markers.to.plot, cols = c("blue", "red"), dot.scale = 8, split.by = "stim") +
    RotatedAxis()
```

Example 48 (r):
```r
# NEEDS TO BE FIXED AND SET ORDER CORRECTLY
Idents(ifnb) <- factor(Idents(ifnb), levels = c("pDC", "Eryth", "Mk", "DC", "CD14 Mono", "CD16 Mono",
    "B Activated", "B", "CD8 T", "NK", "T activated", "CD4 Naive T", "CD4 Memory T"))

markers.to.plot <- c("CD3D", "CREM", "HSPH1", "SELL", "GIMAP5", "CACYBP", "GNLY", "NKG7", "CCL5",
    "CD8A", "MS4A1", "CD79A", "MIR155HG", "NME1", "FCGR3A", "VMO1", "CCL2", "S100A9", "HLA-DQA1",
    "GPR183", "PPBP", "GNG11", "HBA2", "HBB", "TSPAN13", "IL3RA", "IGJ", "PRSS57")
DotPlot(ifnb, features = markers.to.plot, cols = c("blue", "red"), dot.scale = 8, split.by = "stim") +
    RotatedAxis()
```

Example 49 (unknown):
```unknown
AggregateExpression
```

Example 50 (unknown):
```unknown
library(ggplot2)
library(cowplot)
theme_set(theme_cowplot())

aggregate_ifnb <- AggregateExpression(ifnb, group.by = c("seurat_annotations", "stim"), return.seurat = TRUE)
genes.to.label = c("ISG15", "LY6E", "IFI6", "ISG20", "MX1", "IFIT2", "IFIT1", "CXCL10", "CCL8")

p1 <- CellScatter(aggregate_ifnb, "CD14 Mono_CTRL", "CD14 Mono_STIM", highlight = genes.to.label)
p2 <- LabelPoints(plot = p1, points = genes.to.label, repel = TRUE)

p3 <- CellScatter(aggregate_ifnb, "CD4 Naive T_CTRL", "CD4 Naive T_STIM", highlight = genes.to.label)
p4 <- LabelPoints(plot = p3, points = genes.to.label, repel = TRUE)

p2 + p4
```

Example 51 (r):
```r
library(ggplot2)
library(cowplot)
theme_set(theme_cowplot())

aggregate_ifnb <- AggregateExpression(ifnb, group.by = c("seurat_annotations", "stim"), return.seurat = TRUE)
genes.to.label = c("ISG15", "LY6E", "IFI6", "ISG20", "MX1", "IFIT2", "IFIT1", "CXCL10", "CCL8")

p1 <- CellScatter(aggregate_ifnb, "CD14 Mono_CTRL", "CD14 Mono_STIM", highlight = genes.to.label)
p2 <- LabelPoints(plot = p1, points = genes.to.label, repel = TRUE)

p3 <- CellScatter(aggregate_ifnb, "CD4 Naive T_CTRL", "CD4 Naive T_STIM", highlight = genes.to.label)
p4 <- LabelPoints(plot = p3, points = genes.to.label, repel = TRUE)

p2 + p4
```

Example 52 (r):
```r
library(ggplot2)
library(cowplot)
theme_set(theme_cowplot())

aggregate_ifnb <- AggregateExpression(ifnb, group.by = c("seurat_annotations", "stim"), return.seurat = TRUE)
genes.to.label = c("ISG15", "LY6E", "IFI6", "ISG20", "MX1", "IFIT2", "IFIT1", "CXCL10", "CCL8")

p1 <- CellScatter(aggregate_ifnb, "CD14 Mono_CTRL", "CD14 Mono_STIM", highlight = genes.to.label)
p2 <- LabelPoints(plot = p1, points = genes.to.label, repel = TRUE)

p3 <- CellScatter(aggregate_ifnb, "CD4 Naive T_CTRL", "CD4 Naive T_STIM", highlight = genes.to.label)
p4 <- LabelPoints(plot = p3, points = genes.to.label, repel = TRUE)

p2 + p4
```

Example 53 (unknown):
```unknown
FindMarkers()
```

Example 54 (unknown):
```unknown
ifnb$celltype.stim <- paste(ifnb$seurat_annotations, ifnb$stim, sep = "_")
Idents(ifnb) <- "celltype.stim"
b.interferon.response <- FindMarkers(ifnb, ident.1 = "B_STIM", ident.2 = "B_CTRL", verbose = FALSE)
head(b.interferon.response, n = 15)
```

Example 55 (r):
```r
ifnb$celltype.stim <- paste(ifnb$seurat_annotations, ifnb$stim, sep = "_")
Idents(ifnb) <- "celltype.stim"
b.interferon.response <- FindMarkers(ifnb, ident.1 = "B_STIM", ident.2 = "B_CTRL", verbose = FALSE)
head(b.interferon.response, n = 15)
```

Example 56 (r):
```r
ifnb$celltype.stim <- paste(ifnb$seurat_annotations, ifnb$stim, sep = "_")
Idents(ifnb) <- "celltype.stim"
b.interferon.response <- FindMarkers(ifnb, ident.1 = "B_STIM", ident.2 = "B_CTRL", verbose = FALSE)
head(b.interferon.response, n = 15)
```

Example 57 (unknown):
```unknown
##                 p_val avg_log2FC pct.1 pct.2     p_val_adj
## ISG15   5.387767e-159  5.0588481 0.998 0.233 7.571429e-155
## IFIT3   1.945114e-154  6.1124940 0.965 0.052 2.733468e-150
## IFI6    2.503565e-152  5.4933132 0.965 0.076 3.518260e-148
## ISG20   6.492570e-150  3.0549593 1.000 0.668 9.124009e-146
## IFIT1   1.951022e-139  6.2320388 0.907 0.029 2.741772e-135
## MX1     6.897626e-123  3.9798482 0.905 0.115 9.693234e-119
## LY6E    2.825649e-120  3.7907800 0.898 0.150 3.970885e-116
## TNFSF10 4.007285e-112  6.5802175 0.786 0.020 5.631437e-108
## IFIT2   2.672552e-108  5.5525558 0.786 0.037 3.755738e-104
## B2M      5.283684e-98  0.6104044 1.000 1.000  7.425161e-94
## PLSCR1   4.634658e-96  3.8010721 0.793 0.113  6.513085e-92
## IRF7     2.411149e-94  3.1992949 0.835 0.187  3.388388e-90
## CXCL10   3.708508e-86  8.0906108 0.651 0.010  5.211566e-82
## UBE2L6   5.547472e-83  2.5167981 0.851 0.297  7.795863e-79
## PSMB9    1.716262e-77  1.7715351 0.937 0.568  2.411863e-73
```

Example 58 (unknown):
```unknown
##                 p_val avg_log2FC pct.1 pct.2     p_val_adj
## ISG15   5.387767e-159  5.0588481 0.998 0.233 7.571429e-155
## IFIT3   1.945114e-154  6.1124940 0.965 0.052 2.733468e-150
## IFI6    2.503565e-152  5.4933132 0.965 0.076 3.518260e-148
## ISG20   6.492570e-150  3.0549593 1.000 0.668 9.124009e-146
## IFIT1   1.951022e-139  6.2320388 0.907 0.029 2.741772e-135
## MX1     6.897626e-123  3.9798482 0.905 0.115 9.693234e-119
## LY6E    2.825649e-120  3.7907800 0.898 0.150 3.970885e-116
## TNFSF10 4.007285e-112  6.5802175 0.786 0.020 5.631437e-108
## IFIT2   2.672552e-108  5.5525558 0.786 0.037 3.755738e-104
## B2M      5.283684e-98  0.6104044 1.000 1.000  7.425161e-94
## PLSCR1   4.634658e-96  3.8010721 0.793 0.113  6.513085e-92
## IRF7     2.411149e-94  3.1992949 0.835 0.187  3.388388e-90
## CXCL10   3.708508e-86  8.0906108 0.651 0.010  5.211566e-82
## UBE2L6   5.547472e-83  2.5167981 0.851 0.297  7.795863e-79
## PSMB9    1.716262e-77  1.7715351 0.937 0.568  2.411863e-73
```

Example 59 (unknown):
```unknown
FeaturePlot()
```

Example 60 (unknown):
```unknown
FeaturePlot(ifnb, features = c("CD3D", "GNLY", "IFI6"), split.by = "stim", max.cutoff = 3, cols = c("grey",
    "red"), reduction = "umap")
```

Example 61 (r):
```r
FeaturePlot(ifnb, features = c("CD3D", "GNLY", "IFI6"), split.by = "stim", max.cutoff = 3, cols = c("grey",
    "red"), reduction = "umap")
```

Example 62 (r):
```r
FeaturePlot(ifnb, features = c("CD3D", "GNLY", "IFI6"), split.by = "stim", max.cutoff = 3, cols = c("grey",
    "red"), reduction = "umap")
```

Example 63 (unknown):
```unknown
plots <- VlnPlot(ifnb, features = c("LYZ", "ISG15", "CXCL10"), split.by = "stim", group.by = "seurat_annotations",
    pt.size = 0, combine = FALSE)
wrap_plots(plots = plots, ncol = 1)
```

Example 64 (r):
```r
plots <- VlnPlot(ifnb, features = c("LYZ", "ISG15", "CXCL10"), split.by = "stim", group.by = "seurat_annotations",
    pt.size = 0, combine = FALSE)
wrap_plots(plots = plots, ncol = 1)
```

Example 65 (r):
```r
plots <- VlnPlot(ifnb, features = c("LYZ", "ISG15", "CXCL10"), split.by = "stim", group.by = "seurat_annotations",
    pt.size = 0, combine = FALSE)
wrap_plots(plots = plots, ncol = 1)
```

Example 66 (unknown):
```unknown
IntegrateLayers
```

Example 67 (unknown):
```unknown
normalization.method
```

Example 68 (unknown):
```unknown
ifnb <- LoadData("ifnb")

# split datasets and process without integration
ifnb[["RNA"]] <- split(ifnb[["RNA"]], f = ifnb$stim)
ifnb <- SCTransform(ifnb)
ifnb <- RunPCA(ifnb)
ifnb <- RunUMAP(ifnb, dims = 1:30)
DimPlot(ifnb, reduction = "umap", group.by = c("stim", "seurat_annotations"))
```

Example 69 (r):
```r
ifnb <- LoadData("ifnb")

# split datasets and process without integration
ifnb[["RNA"]] <- split(ifnb[["RNA"]], f = ifnb$stim)
ifnb <- SCTransform(ifnb)
ifnb <- RunPCA(ifnb)
ifnb <- RunUMAP(ifnb, dims = 1:30)
DimPlot(ifnb, reduction = "umap", group.by = c("stim", "seurat_annotations"))
```

Example 70 (r):
```r
ifnb <- LoadData("ifnb")

# split datasets and process without integration
ifnb[["RNA"]] <- split(ifnb[["RNA"]], f = ifnb$stim)
ifnb <- SCTransform(ifnb)
ifnb <- RunPCA(ifnb)
ifnb <- RunUMAP(ifnb, dims = 1:30)
DimPlot(ifnb, reduction = "umap", group.by = c("stim", "seurat_annotations"))
```

Example 71 (unknown):
```unknown
# integrate datasets
ifnb <- IntegrateLayers(object = ifnb, method = CCAIntegration, normalization.method = "SCT", verbose = F)
ifnb <- FindNeighbors(ifnb, reduction = "integrated.dr", dims = 1:30)
ifnb <- FindClusters(ifnb, resolution = 0.6)
```

Example 72 (r):
```r
# integrate datasets
ifnb <- IntegrateLayers(object = ifnb, method = CCAIntegration, normalization.method = "SCT", verbose = F)
ifnb <- FindNeighbors(ifnb, reduction = "integrated.dr", dims = 1:30)
ifnb <- FindClusters(ifnb, resolution = 0.6)
```

Example 73 (r):
```r
# integrate datasets
ifnb <- IntegrateLayers(object = ifnb, method = CCAIntegration, normalization.method = "SCT", verbose = F)
ifnb <- FindNeighbors(ifnb, reduction = "integrated.dr", dims = 1:30)
ifnb <- FindClusters(ifnb, resolution = 0.6)
```

Example 74 (unknown):
```unknown
## Modularity Optimizer version 1.3.0 by Ludo Waltman and Nees Jan van Eck
## 
## Number of nodes: 13999
## Number of edges: 528127
## 
## Running Louvain algorithm...
## Maximum modularity in 10 random starts: 0.9060
## Number of communities: 20
## Elapsed time: 21 seconds
```

Example 75 (unknown):
```unknown
## Modularity Optimizer version 1.3.0 by Ludo Waltman and Nees Jan van Eck
## 
## Number of nodes: 13999
## Number of edges: 528127
## 
## Running Louvain algorithm...
## Maximum modularity in 10 random starts: 0.9060
## Number of communities: 20
## Elapsed time: 21 seconds
```

Example 76 (unknown):
```unknown
ifnb <- RunUMAP(ifnb, dims = 1:30, reduction = "integrated.dr")
DimPlot(ifnb, reduction = "umap", group.by = c("stim", "seurat_annotations"))
```

Example 77 (r):
```r
ifnb <- RunUMAP(ifnb, dims = 1:30, reduction = "integrated.dr")
DimPlot(ifnb, reduction = "umap", group.by = c("stim", "seurat_annotations"))
```

Example 78 (r):
```r
ifnb <- RunUMAP(ifnb, dims = 1:30, reduction = "integrated.dr")
DimPlot(ifnb, reduction = "umap", group.by = c("stim", "seurat_annotations"))
```

Example 79 (unknown):
```unknown
# perform differential expression
ifnb <- PrepSCTFindMarkers(ifnb)
ifnb$celltype.stim <- paste(ifnb$seurat_annotations, ifnb$stim, sep = "_")
Idents(ifnb) <- "celltype.stim"
b.interferon.response <- FindMarkers(ifnb, ident.1 = "B_STIM", ident.2 = "B_CTRL", verbose = FALSE)
```

Example 80 (r):
```r
# perform differential expression
ifnb <- PrepSCTFindMarkers(ifnb)
ifnb$celltype.stim <- paste(ifnb$seurat_annotations, ifnb$stim, sep = "_")
Idents(ifnb) <- "celltype.stim"
b.interferon.response <- FindMarkers(ifnb, ident.1 = "B_STIM", ident.2 = "B_CTRL", verbose = FALSE)
```

Example 81 (r):
```r
# perform differential expression
ifnb <- PrepSCTFindMarkers(ifnb)
ifnb$celltype.stim <- paste(ifnb$seurat_annotations, ifnb$stim, sep = "_")
Idents(ifnb) <- "celltype.stim"
b.interferon.response <- FindMarkers(ifnb, ident.1 = "B_STIM", ident.2 = "B_CTRL", verbose = FALSE)
```

Example 82 (unknown):
```unknown
sessionInfo()
```

Example 83 (r):
```r
sessionInfo()
```

Example 84 (r):
```r
sessionInfo()
```

Example 85 (unknown):
```unknown
## R version 4.2.2 Patched (2022-11-10 r83330)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.6 LTS
## 
## Matrix products: default
## BLAS:   /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.9.0
## LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.9.0
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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       
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
##  [1] cowplot_1.1.1                  ggplot2_3.4.4                 
##  [3] patchwork_1.1.3                thp1.eccite.SeuratData_3.1.5  
##  [5] stxBrain.SeuratData_0.1.1      ssHippo.SeuratData_3.1.4      
##  [7] pbmcsca.SeuratData_3.0.0       pbmcref.SeuratData_1.0.0      
##  [9] pbmcMultiome.SeuratData_0.1.4  pbmc3k.SeuratData_3.1.4       
## [11] panc8.SeuratData_3.0.2         ifnb.SeuratData_3.0.0         
## [13] hcabm40k.SeuratData_3.0.0      cbmc.SeuratData_3.1.4         
## [15] bonemarrowref.SeuratData_1.0.0 bmcite.SeuratData_0.3.0       
## [17] SeuratData_0.2.2.9001          Seurat_5.0.1             
## [19] testthat_3.2.0                 SeuratObject_5.0.1            
## [21] sp_2.1-1                      
## 
## loaded via a namespace (and not attached):
##   [1] utf8_1.2.4                  spatstat.explore_3.2-5     
##   [3] reticulate_1.34.0           tidyselect_1.2.0           
##   [5] htmlwidgets_1.6.2           grid_4.2.2                 
##   [7] Rtsne_0.16                  devtools_2.4.5             
##   [9] munsell_0.5.0               mutoss_0.1-13              
##  [11] codetools_0.2-19            ragg_1.2.5                 
##  [13] ica_1.0-3                   future_1.33.0              
##  [15] miniUI_0.1.1.1              withr_2.5.2                
##  [17] spatstat.random_3.2-1       colorspace_2.1-0           
##  [19] progressr_0.14.0            Biobase_2.58.0             
##  [21] highr_0.10                  knitr_1.45                 
##  [23] rstudioapi_0.14             stats4_4.2.2               
##  [25] ROCR_1.0-11                 tensor_1.5                 
##  [27] listenv_0.9.0               MatrixGenerics_1.10.0      
##  [29] Rdpack_2.5                  labeling_0.4.3             
##  [31] GenomeInfoDbData_1.2.9      mnormt_2.1.1               
##  [33] polyclip_1.10-6             farver_2.1.1               
##  [35] rprojroot_2.0.4             TH.data_1.1-2              
##  [37] parallelly_1.36.0           vctrs_0.6.4                
##  [39] generics_0.1.3              xfun_0.40                  
##  [41] GenomeInfoDb_1.34.9         R6_2.5.1                   
##  [43] ggbeeswarm_0.7.1            DelayedArray_0.24.0        
##  [45] bitops_1.0-7                spatstat.utils_3.0-4       
##  [47] cachem_1.0.8                promises_1.2.1             
##  [49] scales_1.2.1                multcomp_1.4-25            
##  [51] beeswarm_0.4.0              gtable_0.3.4               
##  [53] globals_0.16.2              processx_3.8.2             
##  [55] goftest_1.2-3               spam_2.10-0                
##  [57] sandwich_3.0-2              rlang_1.1.1                
##  [59] systemfonts_1.0.4           splines_4.2.2              
##  [61] lazyeval_0.2.2              spatstat.geom_3.2-7        
##  [63] yaml_2.3.7                  reshape2_1.4.4             
##  [65] abind_1.4-5                 httpuv_1.6.12              
##  [67] tools_4.2.2                 usethis_2.1.6              
##  [69] ellipsis_0.3.2              jquerylib_0.1.4            
##  [71] RColorBrewer_1.1-3          BiocGenerics_0.44.0        
##  [73] sessioninfo_1.2.2           ggridges_0.5.4             
##  [75] TFisher_0.2.0               Rcpp_1.0.11                
##  [77] plyr_1.8.9                  sparseMatrixStats_1.10.0   
##  [79] zlibbioc_1.44.0             RCurl_1.98-1.12            
##  [81] purrr_1.0.2                 ps_1.7.5                   
##  [83] prettyunits_1.2.0           deldir_1.0-9               
##  [85] pbapply_1.7-2               urlchecker_1.0.1           
##  [87] S4Vectors_0.36.2            zoo_1.8-12                 
##  [89] SummarizedExperiment_1.28.0 ggrepel_0.9.4              
##  [91] cluster_2.1.4               fs_1.6.3                   
##  [93] magrittr_2.0.3              glmGamPoi_1.10.2           
##  [95] data.table_1.14.8           RSpectra_0.16-1            
##  [97] scattermore_1.2             lmtest_0.9-40              
##  [99] RANN_2.6.1                  mvtnorm_1.2-3              
## [101] fitdistrplus_1.1-11         matrixStats_1.0.0          
## [103] pkgload_1.3.3               mime_0.12                  
## [105] evaluate_0.22               xtable_1.8-4               
## [107] IRanges_2.32.0              fastDummies_1.7.3          
## [109] gridExtra_2.3               compiler_4.2.2             
## [111] tibble_3.2.1                KernSmooth_2.23-22         
## [113] crayon_1.5.2                htmltools_0.5.6.1          
## [115] later_1.3.1                 tidyr_1.3.0                
## [117] formatR_1.14                MASS_7.3-58.2              
## [119] rappdirs_0.3.3              Matrix_1.6-1.1             
## [121] brio_1.1.3                  cli_3.6.1                  
## [123] rbibutils_2.2.15            qqconf_1.3.2               
## [125] parallel_4.2.2              dotCall64_1.1-0            
## [127] metap_1.9                   igraph_1.5.1               
## [129] GenomicRanges_1.50.2        pkgconfig_2.0.3            
## [131] sn_2.1.1                    pkgdown_2.0.7              
## [133] numDeriv_2016.8-1.1         plotly_4.10.3              
## [135] spatstat.sparse_3.0-3       vipor_0.4.5                
## [137] bslib_0.5.1                 XVector_0.38.0             
## [139] multtest_2.54.0             stringr_1.5.0              
## [141] callr_3.7.3                 digest_0.6.33              
## [143] sctransform_0.4.1           RcppAnnoy_0.0.21           
## [145] spatstat.data_3.0-3         rmarkdown_2.25             
## [147] leiden_0.4.3                uwot_0.1.16                
## [149] DelayedMatrixStats_1.20.0   shiny_1.7.5.1              
## [151] lifecycle_1.0.4             nlme_3.1-162               
## [153] jsonlite_1.8.7              limma_3.54.1               
## [155] desc_1.4.2                  viridisLite_0.4.2          
## [157] fansi_1.0.5                 pillar_1.9.0               
## [159] lattice_0.21-9              ggrastr_1.0.1              
## [161] plotrix_3.8-2               fastmap_1.1.1              
## [163] httr_1.4.7                  pkgbuild_1.4.2             
## [165] survival_3.5-7              glue_1.6.2                 
## [167] remotes_2.4.2.1             png_0.1-8                  
## [169] presto_1.0.0                stringi_1.7.12             
## [171] sass_0.4.7                  profvis_0.3.7              
## [173] textshaping_0.3.6           RcppHNSW_0.5.0             
## [175] memoise_2.0.1               mathjaxr_1.6-0             
## [177] dplyr_1.1.3                 irlba_2.3.5.1              
## [179] future.apply_1.11.0
```

Example 86 (unknown):
```unknown
## R version 4.2.2 Patched (2022-11-10 r83330)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.6 LTS
## 
## Matrix products: default
## BLAS:   /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.9.0
## LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.9.0
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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       
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
##  [1] cowplot_1.1.1                  ggplot2_3.4.4                 
##  [3] patchwork_1.1.3                thp1.eccite.SeuratData_3.1.5  
##  [5] stxBrain.SeuratData_0.1.1      ssHippo.SeuratData_3.1.4      
##  [7] pbmcsca.SeuratData_3.0.0       pbmcref.SeuratData_1.0.0      
##  [9] pbmcMultiome.SeuratData_0.1.4  pbmc3k.SeuratData_3.1.4       
## [11] panc8.SeuratData_3.0.2         ifnb.SeuratData_3.0.0         
## [13] hcabm40k.SeuratData_3.0.0      cbmc.SeuratData_3.1.4         
## [15] bonemarrowref.SeuratData_1.0.0 bmcite.SeuratData_0.3.0       
## [17] SeuratData_0.2.2.9001          Seurat_5.0.1             
## [19] testthat_3.2.0                 SeuratObject_5.0.1            
## [21] sp_2.1-1                      
## 
## loaded via a namespace (and not attached):
##   [1] utf8_1.2.4                  spatstat.explore_3.2-5     
##   [3] reticulate_1.34.0           tidyselect_1.2.0           
##   [5] htmlwidgets_1.6.2           grid_4.2.2                 
##   [7] Rtsne_0.16                  devtools_2.4.5             
##   [9] munsell_0.5.0               mutoss_0.1-13              
##  [11] codetools_0.2-19            ragg_1.2.5                 
##  [13] ica_1.0-3                   future_1.33.0              
##  [15] miniUI_0.1.1.1              withr_2.5.2                
##  [17] spatstat.random_3.2-1       colorspace_2.1-0           
##  [19] progressr_0.14.0            Biobase_2.58.0             
##  [21] highr_0.10                  knitr_1.45                 
##  [23] rstudioapi_0.14             stats4_4.2.2               
##  [25] ROCR_1.0-11                 tensor_1.5                 
##  [27] listenv_0.9.0               MatrixGenerics_1.10.0      
##  [29] Rdpack_2.5                  labeling_0.4.3             
##  [31] GenomeInfoDbData_1.2.9      mnormt_2.1.1               
##  [33] polyclip_1.10-6             farver_2.1.1               
##  [35] rprojroot_2.0.4             TH.data_1.1-2              
##  [37] parallelly_1.36.0           vctrs_0.6.4                
##  [39] generics_0.1.3              xfun_0.40                  
##  [41] GenomeInfoDb_1.34.9         R6_2.5.1                   
##  [43] ggbeeswarm_0.7.1            DelayedArray_0.24.0        
##  [45] bitops_1.0-7                spatstat.utils_3.0-4       
##  [47] cachem_1.0.8                promises_1.2.1             
##  [49] scales_1.2.1                multcomp_1.4-25            
##  [51] beeswarm_0.4.0              gtable_0.3.4               
##  [53] globals_0.16.2              processx_3.8.2             
##  [55] goftest_1.2-3               spam_2.10-0                
##  [57] sandwich_3.0-2              rlang_1.1.1                
##  [59] systemfonts_1.0.4           splines_4.2.2              
##  [61] lazyeval_0.2.2              spatstat.geom_3.2-7        
##  [63] yaml_2.3.7                  reshape2_1.4.4             
##  [65] abind_1.4-5                 httpuv_1.6.12              
##  [67] tools_4.2.2                 usethis_2.1.6              
##  [69] ellipsis_0.3.2              jquerylib_0.1.4            
##  [71] RColorBrewer_1.1-3          BiocGenerics_0.44.0        
##  [73] sessioninfo_1.2.2           ggridges_0.5.4             
##  [75] TFisher_0.2.0               Rcpp_1.0.11                
##  [77] plyr_1.8.9                  sparseMatrixStats_1.10.0   
##  [79] zlibbioc_1.44.0             RCurl_1.98-1.12            
##  [81] purrr_1.0.2                 ps_1.7.5                   
##  [83] prettyunits_1.2.0           deldir_1.0-9               
##  [85] pbapply_1.7-2               urlchecker_1.0.1           
##  [87] S4Vectors_0.36.2            zoo_1.8-12                 
##  [89] SummarizedExperiment_1.28.0 ggrepel_0.9.4              
##  [91] cluster_2.1.4               fs_1.6.3                   
##  [93] magrittr_2.0.3              glmGamPoi_1.10.2           
##  [95] data.table_1.14.8           RSpectra_0.16-1            
##  [97] scattermore_1.2             lmtest_0.9-40              
##  [99] RANN_2.6.1                  mvtnorm_1.2-3              
## [101] fitdistrplus_1.1-11         matrixStats_1.0.0          
## [103] pkgload_1.3.3               mime_0.12                  
## [105] evaluate_0.22               xtable_1.8-4               
## [107] IRanges_2.32.0              fastDummies_1.7.3          
## [109] gridExtra_2.3               compiler_4.2.2             
## [111] tibble_3.2.1                KernSmooth_2.23-22         
## [113] crayon_1.5.2                htmltools_0.5.6.1          
## [115] later_1.3.1                 tidyr_1.3.0                
## [117] formatR_1.14                MASS_7.3-58.2              
## [119] rappdirs_0.3.3              Matrix_1.6-1.1             
## [121] brio_1.1.3                  cli_3.6.1                  
## [123] rbibutils_2.2.15            qqconf_1.3.2               
## [125] parallel_4.2.2              dotCall64_1.1-0            
## [127] metap_1.9                   igraph_1.5.1               
## [129] GenomicRanges_1.50.2        pkgconfig_2.0.3            
## [131] sn_2.1.1                    pkgdown_2.0.7              
## [133] numDeriv_2016.8-1.1         plotly_4.10.3              
## [135] spatstat.sparse_3.0-3       vipor_0.4.5                
## [137] bslib_0.5.1                 XVector_0.38.0             
## [139] multtest_2.54.0             stringr_1.5.0              
## [141] callr_3.7.3                 digest_0.6.33              
## [143] sctransform_0.4.1           RcppAnnoy_0.0.21           
## [145] spatstat.data_3.0-3         rmarkdown_2.25             
## [147] leiden_0.4.3                uwot_0.1.16                
## [149] DelayedMatrixStats_1.20.0   shiny_1.7.5.1              
## [151] lifecycle_1.0.4             nlme_3.1-162               
## [153] jsonlite_1.8.7              limma_3.54.1               
## [155] desc_1.4.2                  viridisLite_0.4.2          
## [157] fansi_1.0.5                 pillar_1.9.0               
## [159] lattice_0.21-9              ggrastr_1.0.1              
## [161] plotrix_3.8-2               fastmap_1.1.1              
## [163] httr_1.4.7                  pkgbuild_1.4.2             
## [165] survival_3.5-7              glue_1.6.2                 
## [167] remotes_2.4.2.1             png_0.1-8                  
## [169] presto_1.0.0                stringi_1.7.12             
## [171] sass_0.4.7                  profvis_0.3.7              
## [173] textshaping_0.3.6           RcppHNSW_0.5.0             
## [175] memoise_2.0.1               mathjaxr_1.6-0             
## [177] dplyr_1.1.3                 irlba_2.3.5.1              
## [179] future.apply_1.11.0
```

---

## Differential expression testing

**URL:** http://127.0.0.1:9173/seurat/archive/v3.1/de_vignette/index.html

**Contents:**
- Differential expression testing
    - Compiled: 2020-04-17
  - Load in the data
  - Perform default differential expression tests
  - Prefilter features or cells to increase the speed of DE testing
  - Perform DE analysis using alternative tests
  - Acknowledgements

This vignette highlights some example workflows for performing differential expression in Seurat. For demonstration purposes, we will be using the 2,700 PBMC object that is created in the first guided tutorial. You can download the pre-computed object here.

The bulk of Seurat’s differential expression features can be accessed through the FindMarkers function. As a default, Seurat performs differential expression based on the non-parameteric Wilcoxon rank sum test. This replaces the previous default test (‘bimod’). To test for differential expression between two specific groups of cells, specify the ident.1 and ident.2 parameters.

The results data frame has the following columns :

If the ident.2 parameter is omitted or set to NULL, FindMarkers will test for differentially expressed features between the group specified by ident.1 and all other cells.

To increase the speed of marker discovery, particularly for large datasets, Seurat allows for pre-filtering of features or cells. For example, features that are very infrequently detected in either group of cells, or features that are expressed at similar average levels, are unlikely to be differentially expressed. Example use cases of the min.pct, logfc.threshold, min.diff.pct, and max.cells.per.ident parameters are demonstrated below.

The following differential expression tests are currently supported:

For MAST and DESeq2 please ensure that these packages are installed separately in order to use them as part of Seurat. Once installed, use the test.use parameter can be used to specify which DE test to use.

We thank the authors of the MAST and DESeq2 packages for their kind assistance and advice. We also point users to the following study by Charlotte Soneson and Mark Robinson, which performs careful and extensive evaluation of methods for single cell differential expression testing.

**Examples:**

Example 1 (r):
```r
library(Seurat)
pbmc <- readRDS(file = "../data/pbmc3k_final.rds")
```

Example 2 (r):
```r
library(Seurat)
pbmc <- readRDS(file = "../data/pbmc3k_final.rds")
```

Example 3 (unknown):
```unknown
FindMarkers
```

Example 4 (r):
```r
# list options for groups to perform differential expression on
levels(pbmc)
```

Example 5 (r):
```r
# list options for groups to perform differential expression on
levels(pbmc)
```

Example 6 (unknown):
```unknown
## [1] "Naive CD4 T"  "Memory CD4 T" "CD14+ Mono"   "B"            "CD8 T"       
## [6] "FCGR3A+ Mono" "NK"           "DC"           "Platelet"
```

Example 7 (unknown):
```unknown
## [1] "Naive CD4 T"  "Memory CD4 T" "CD14+ Mono"   "B"            "CD8 T"       
## [6] "FCGR3A+ Mono" "NK"           "DC"           "Platelet"
```

Example 8 (r):
```r
# Find differentially expressed features between CD14+ and FCGR3A+ Monocytes
monocyte.de.markers <- FindMarkers(pbmc, ident.1 = "CD14+ Mono", ident.2 = "FCGR3A+ Mono")
# view results
head(monocyte.de.markers)
```

Example 9 (r):
```r
# Find differentially expressed features between CD14+ and FCGR3A+ Monocytes
monocyte.de.markers <- FindMarkers(pbmc, ident.1 = "CD14+ Mono", ident.2 = "FCGR3A+ Mono")
# view results
head(monocyte.de.markers)
```

Example 10 (unknown):
```unknown
FindMarkers
```

Example 11 (r):
```r
# Find differentially expressed features between CD14+ Monocytes and all other cells, only
# search for positive markers
monocyte.de.markers <- FindMarkers(pbmc, ident.1 = "CD14+ Mono", ident.2 = NULL, only.pos = TRUE)
# view results
head(monocyte.de.markers)
```

Example 12 (r):
```r
# Find differentially expressed features between CD14+ Monocytes and all other cells, only
# search for positive markers
monocyte.de.markers <- FindMarkers(pbmc, ident.1 = "CD14+ Mono", ident.2 = NULL, only.pos = TRUE)
# view results
head(monocyte.de.markers)
```

Example 13 (unknown):
```unknown
logfc.threshold
```

Example 14 (unknown):
```unknown
min.diff.pct
```

Example 15 (unknown):
```unknown
max.cells.per.ident
```

Example 16 (r):
```r
# Pre-filter features that are detected at <50% frequency in either CD14+ Monocytes or FCGR3A+
# Monocytes
head(FindMarkers(pbmc, ident.1 = "CD14+ Mono", ident.2 = "FCGR3A+ Mono", min.pct = 0.5))
```

Example 17 (r):
```r
# Pre-filter features that are detected at <50% frequency in either CD14+ Monocytes or FCGR3A+
# Monocytes
head(FindMarkers(pbmc, ident.1 = "CD14+ Mono", ident.2 = "FCGR3A+ Mono", min.pct = 0.5))
```

Example 18 (r):
```r
# Pre-filter features that have less than a two-fold change between the average expression of
# CD14+ Monocytes vs FCGR3A+ Monocytes
head(FindMarkers(pbmc, ident.1 = "CD14+ Mono", ident.2 = "FCGR3A+ Mono", logfc.threshold = log(2)))
```

Example 19 (r):
```r
# Pre-filter features that have less than a two-fold change between the average expression of
# CD14+ Monocytes vs FCGR3A+ Monocytes
head(FindMarkers(pbmc, ident.1 = "CD14+ Mono", ident.2 = "FCGR3A+ Mono", logfc.threshold = log(2)))
```

Example 20 (r):
```r
# Pre-filter features whose detection percentages across the two groups are similar (within
# 0.25)
head(FindMarkers(pbmc, ident.1 = "CD14+ Mono", ident.2 = "FCGR3A+ Mono", min.diff.pct = 0.25))
```

Example 21 (r):
```r
# Pre-filter features whose detection percentages across the two groups are similar (within
# 0.25)
head(FindMarkers(pbmc, ident.1 = "CD14+ Mono", ident.2 = "FCGR3A+ Mono", min.diff.pct = 0.25))
```

Example 22 (r):
```r
# Increasing min.pct, logfc.threshold, and min.diff.pct, will increase the speed of DE testing,
# but could also miss features that are prefiltered

# Subsample each group to a maximum of 200 cells. Can be very useful for large clusters, or
# computationally-intensive DE tests
head(FindMarkers(pbmc, ident.1 = "CD14+ Mono", ident.2 = "FCGR3A+ Mono", max.cells.per.ident = 200))
```

Example 23 (r):
```r
# Increasing min.pct, logfc.threshold, and min.diff.pct, will increase the speed of DE testing,
# but could also miss features that are prefiltered

# Subsample each group to a maximum of 200 cells. Can be very useful for large clusters, or
# computationally-intensive DE tests
head(FindMarkers(pbmc, ident.1 = "CD14+ Mono", ident.2 = "FCGR3A+ Mono", max.cells.per.ident = 200))
```

Example 24 (r):
```r
# Test for DE features using the MAST package
head(FindMarkers(pbmc, ident.1 = "CD14+ Mono", ident.2 = "FCGR3A+ Mono", test.use = "MAST"))
```

Example 25 (r):
```r
# Test for DE features using the MAST package
head(FindMarkers(pbmc, ident.1 = "CD14+ Mono", ident.2 = "FCGR3A+ Mono", test.use = "MAST"))
```

Example 26 (r):
```r
# Test for DE features using the DESeq2 package. Throws an error if DESeq2 has not already been
# installed Note that the DESeq2 workflows can be computationally intensive for large datasets,
# but are incompatible with some feature pre-filtering options We therefore suggest initially
# limiting the number of cells used for testing
head(FindMarkers(pbmc, ident.1 = "CD14+ Mono", ident.2 = "FCGR3A+ Mono", test.use = "DESeq2", max.cells.per.ident = 50))
```

Example 27 (r):
```r
# Test for DE features using the DESeq2 package. Throws an error if DESeq2 has not already been
# installed Note that the DESeq2 workflows can be computationally intensive for large datasets,
# but are incompatible with some feature pre-filtering options We therefore suggest initially
# limiting the number of cells used for testing
head(FindMarkers(pbmc, ident.1 = "CD14+ Mono", ident.2 = "FCGR3A+ Mono", test.use = "DESeq2", max.cells.per.ident = 50))
```

---

## Seurat - Dimensional Reduction Vignette

**URL:** http://127.0.0.1:9173/seurat/archive/v3.2/dim_reduction_vignette/index.html

**Contents:**
- Seurat - Dimensional Reduction Vignette
    - Compiled: October 02, 2020
  - Load in the data
  - Explore the new dimensional reduction structure
  - Storing a custom dimensional reduction calculation

This vignette demonstrates how to store and interact with dimensional reduction information (such as the output from RunPCA) in Seurat v3.0. For demonstration purposes, we will be using the 2,700 PBMC object that is created in the first guided tutorial. You can download the pre-computed object here.

In Seurat v3.0, storing and interacting with dimensional reduction information has been generalized and formalized into the DimReduc object. Each dimensional reduction procedure is stored as a DimReduc object in the object@reductions slot as an element of a named list. Accessing these reductions can be done with the [[ operator, calling the name of the reduction desired. For example, after running a principle component analysis with RunPCA, object[['pca']] will contain the results of the PCA. By adding new elements to the list, users can add additional, and custom, dimensional reductions. Each stored dimensional reduction contains the following slots:

To access these slots, we provide the Embeddings,Loadings, and Stdev functions

Seurat provides RunPCA (pca), and RunTSNE (tsne), and representing dimensional reduction techniques commonly applied to scRNA-seq data. When using these functions, all slots are filled automatically.

We also allow users to add the results of a custom dimensional reduction technique (for example, multi-dimensional scaling (MDS), or zero-inflated factor analysis), that is computed separately. All you need is a matrix with each cell's coordinates in low-dimensional space, as shown below.

Though not incorporated as part of the Seurat package, its easy to run multidimensional scaling (MDS) in R. If you were interested in running MDS and storing the output in your Seurat object:

**Examples:**

Example 1 (r):
```r
library(Seurat)
pbmc <- readRDS(file = "../data/pbmc3k_final.rds")
```

Example 2 (r):
```r
library(Seurat)
pbmc <- readRDS(file = "../data/pbmc3k_final.rds")
```

Example 3 (unknown):
```unknown
object@reductions
```

Example 4 (unknown):
```unknown
object[['pca']]
```

Example 5 (r):
```r
pbmc[["pca"]]
```

Example 6 (r):
```r
pbmc[["pca"]]
```

Example 7 (unknown):
```unknown
## A dimensional reduction object with key PC_ 
##  Number of dimensions: 50 
##  Projected dimensional reduction calculated:  FALSE 
##  Jackstraw run: TRUE 
##  Computed using assay: RNA
```

Example 8 (unknown):
```unknown
## A dimensional reduction object with key PC_ 
##  Number of dimensions: 50 
##  Projected dimensional reduction calculated:  FALSE 
##  Jackstraw run: TRUE 
##  Computed using assay: RNA
```

Example 9 (r):
```r
head(Embeddings(pbmc, reduction = "pca")[, 1:5])
```

Example 10 (r):
```r
head(Embeddings(pbmc, reduction = "pca")[, 1:5])
```

Example 11 (unknown):
```unknown
##                        PC_1       PC_2       PC_3       PC_4        PC_5
## AAACATACAACCAC-1 -4.7296855 -0.5184265 -0.7623220 -2.3156790 -0.07160006
## AAACATTGAGCTAC-1 -0.5174029  4.5918957  5.9091921  6.9118856 -1.96243034
## AAACATTGATCAGC-1 -3.1891063 -3.4695154 -0.8313710 -2.0019985 -5.10442765
## AAACCGTGCTTCCG-1 12.7933021  0.1007166  0.6310221 -0.3687338  0.21838204
## AAACCGTGTATGCG-1 -3.1288078 -6.3481412  1.2507776  3.0191026  7.84739502
## AAACGCACTGGTAC-1 -3.1088963  0.9262125 -0.6482331 -2.3244378 -2.00526763
```

Example 12 (unknown):
```unknown
##                        PC_1       PC_2       PC_3       PC_4        PC_5
## AAACATACAACCAC-1 -4.7296855 -0.5184265 -0.7623220 -2.3156790 -0.07160006
## AAACATTGAGCTAC-1 -0.5174029  4.5918957  5.9091921  6.9118856 -1.96243034
## AAACATTGATCAGC-1 -3.1891063 -3.4695154 -0.8313710 -2.0019985 -5.10442765
## AAACCGTGCTTCCG-1 12.7933021  0.1007166  0.6310221 -0.3687338  0.21838204
## AAACCGTGTATGCG-1 -3.1288078 -6.3481412  1.2507776  3.0191026  7.84739502
## AAACGCACTGGTAC-1 -3.1088963  0.9262125 -0.6482331 -2.3244378 -2.00526763
```

Example 13 (r):
```r
head(Loadings(pbmc, reduction = "pca")[, 1:5])
```

Example 14 (r):
```r
head(Loadings(pbmc, reduction = "pca")[, 1:5])
```

Example 15 (unknown):
```unknown
##                PC_1        PC_2        PC_3        PC_4        PC_5
## PPBP    0.010990202  0.01148426 -0.15176092  0.10403737 0.003299077
## LYZ     0.116231706  0.01472515 -0.01280613 -0.04414540 0.049906881
## S100A9  0.115414362  0.01895146 -0.02368853 -0.05787777 0.085382309
## IGLL5  -0.007987473  0.05454239  0.04901533  0.06694722 0.004603231
## GNLY   -0.015238762 -0.13375626  0.04101340  0.06912322 0.104558611
## FTL     0.118292572  0.01871142 -0.00984755 -0.01555269 0.038743505
```

Example 16 (unknown):
```unknown
##                PC_1        PC_2        PC_3        PC_4        PC_5
## PPBP    0.010990202  0.01148426 -0.15176092  0.10403737 0.003299077
## LYZ     0.116231706  0.01472515 -0.01280613 -0.04414540 0.049906881
## S100A9  0.115414362  0.01895146 -0.02368853 -0.05787777 0.085382309
## IGLL5  -0.007987473  0.05454239  0.04901533  0.06694722 0.004603231
## GNLY   -0.015238762 -0.13375626  0.04101340  0.06912322 0.104558611
## FTL     0.118292572  0.01871142 -0.00984755 -0.01555269 0.038743505
```

Example 17 (r):
```r
head(Stdev(pbmc, reduction = "pca"))
```

Example 18 (r):
```r
head(Stdev(pbmc, reduction = "pca"))
```

Example 19 (unknown):
```unknown
## [1] 7.098420 4.495493 3.872592 3.748859 3.171755 2.545292
```

Example 20 (unknown):
```unknown
## [1] 7.098420 4.495493 3.872592 3.748859 3.171755 2.545292
```

Example 21 (r):
```r
# Before running MDS, we first calculate a distance matrix between all pairs of cells.  Here we
# use a simple euclidean distance metric on all genes, using scale.data as input
d <- dist(t(GetAssayData(pbmc, slot = "scale.data")))
# Run the MDS procedure, k determines the number of dimensions
mds <- cmdscale(d = d, k = 2)
# cmdscale returns the cell embeddings, we first label the columns to ensure downstream
# consistency
colnames(mds) <- paste0("MDS_", 1:2)
# We will now store this as a custom dimensional reduction called 'mds'
pbmc[["mds"]] <- CreateDimReducObject(embeddings = mds, key = "MDS_", assay = DefaultAssay(pbmc))

# We can now use this as you would any other dimensional reduction in all downstream functions
DimPlot(pbmc, reduction = "mds", pt.size = 0.5)
```

Example 22 (r):
```r
# Before running MDS, we first calculate a distance matrix between all pairs of cells.  Here we
# use a simple euclidean distance metric on all genes, using scale.data as input
d <- dist(t(GetAssayData(pbmc, slot = "scale.data")))
# Run the MDS procedure, k determines the number of dimensions
mds <- cmdscale(d = d, k = 2)
# cmdscale returns the cell embeddings, we first label the columns to ensure downstream
# consistency
colnames(mds) <- paste0("MDS_", 1:2)
# We will now store this as a custom dimensional reduction called 'mds'
pbmc[["mds"]] <- CreateDimReducObject(embeddings = mds, key = "MDS_", assay = DefaultAssay(pbmc))

# We can now use this as you would any other dimensional reduction in all downstream functions
DimPlot(pbmc, reduction = "mds", pt.size = 0.5)
```

Example 23 (r):
```r
# If you wold like to observe genes that are strongly correlated with the first MDS coordinate
pbmc <- ProjectDim(pbmc, reduction = "mds")
```

Example 24 (r):
```r
# If you wold like to observe genes that are strongly correlated with the first MDS coordinate
pbmc <- ProjectDim(pbmc, reduction = "mds")
```

Example 25 (unknown):
```unknown
## MDS_ 1 
## Positive:  CST3, TYROBP, FCER1G, LST1, FTL, AIF1, FTH1, TYMP, FCN1, LYZ 
##     LGALS1, S100A9, CFD, CD68, SERPINA1, CTSS, IFITM3, SPI1, S100A8, LGALS2 
## Negative:  MALAT1, RPS27A, RPS27, RPL3, RPL23A, RPL21, RPL13A, RPS6, RPS3A, RPS3 
##     RPL9, LTB, RPSA, CD3D, RPS25, RPS18, PTPRCAP, RPS12, RPL30, RPL31 
## MDS_ 2 
## Positive:  NKG7, PRF1, CST7, GZMA, GZMB, B2M, FGFBP2, CTSW, GNLY, HLA-C 
##     GZMH, SPON2, CD247, FCGR3A, CCL5, HLA-A, CCL4, GZMM, KLRD1, CLIC3 
## Negative:  RPL32, RPL18A, HLA-DRA, CD79A, RPL13, MS4A1, RPL11, TCL1A, RPS9, RPL12 
##     LINC00926, HLA-DQB1, HLA-DQA1, HLA-DRB1, RPL28, RPS2, S100A8, HLA-DMA, RPL8, RPLP1
```

Example 26 (unknown):
```unknown
## MDS_ 1 
## Positive:  CST3, TYROBP, FCER1G, LST1, FTL, AIF1, FTH1, TYMP, FCN1, LYZ 
##     LGALS1, S100A9, CFD, CD68, SERPINA1, CTSS, IFITM3, SPI1, S100A8, LGALS2 
## Negative:  MALAT1, RPS27A, RPS27, RPL3, RPL23A, RPL21, RPL13A, RPS6, RPS3A, RPS3 
##     RPL9, LTB, RPSA, CD3D, RPS25, RPS18, PTPRCAP, RPS12, RPL30, RPL31 
## MDS_ 2 
## Positive:  NKG7, PRF1, CST7, GZMA, GZMB, B2M, FGFBP2, CTSW, GNLY, HLA-C 
##     GZMH, SPON2, CD247, FCGR3A, CCL5, HLA-A, CCL4, GZMM, KLRD1, CLIC3 
## Negative:  RPL32, RPL18A, HLA-DRA, CD79A, RPL13, MS4A1, RPL11, TCL1A, RPS9, RPL12 
##     LINC00926, HLA-DQB1, HLA-DQA1, HLA-DRB1, RPL28, RPS2, S100A8, HLA-DMA, RPL8, RPLP1
```

Example 27 (r):
```r
# Display the results as a heatmap
DimHeatmap(pbmc, reduction = "mds", dims = 1, cells = 500, projected = TRUE, balanced = TRUE)
```

Example 28 (r):
```r
# Display the results as a heatmap
DimHeatmap(pbmc, reduction = "mds", dims = 1, cells = 500, projected = TRUE, balanced = TRUE)
```

Example 29 (r):
```r
# Explore how the first MDS dimension is distributed across clusters
VlnPlot(pbmc, features = "MDS_1")
```

Example 30 (r):
```r
# Explore how the first MDS dimension is distributed across clusters
VlnPlot(pbmc, features = "MDS_1")
```

Example 31 (r):
```r
# See how the first MDS dimension is correlated with the first PC dimension
FeatureScatter(pbmc, feature1 = "MDS_1", feature2 = "PC_1")
```

Example 32 (r):
```r
# See how the first MDS dimension is correlated with the first PC dimension
FeatureScatter(pbmc, feature1 = "MDS_1", feature2 = "PC_1")
```

---

## Using sctransform in Seurat

**URL:** http://127.0.0.1:9173/seurat/archive/v3.1/sctransform_vignette/index.html

**Contents:**
- Using sctransform in Seurat
    - Christoph Hafemeister & Rahul Satija
    - Compiled: 2020-04-17

This vignette shows how to use the sctransform wrapper in Seurat.

Install sctransform and Seurat v3.

Load data and create Seurat object

Apply sctransform normalization

Perform dimensionality reduction by PCA and UMAP embedding

Why can we choose more PCs when using sctransform?

In the standard Seurat workflow we focus on 10 PCs for this dataset, though we highlight that the results are similar with higher settings for this parameter. Interestingtly, we’ve found that when using sctransform, we often benefit by pushing this parameter even higher. We believe this is because the sctransform workflow performs more effective normalization, strongly removing technical effects from the data.

Even after standard log-normalization, variation in sequencing depth is still a confounding factor (see Figure 1), and this effect can subtly influence higher PCs. In sctransform, this effect is substantially mitigated (see Figure 3). This means that higher PCs are more likely to represent subtle, but biologically relevant, sources of heterogeneity – so including them may improve downstream analysis.

In addition, sctransform returns 3,000 variable features by default, instead of 2,000. The rationale is similar, the additional variable features are less likely to be driven by technical differences across cells, and instead may represent more subtle biological fluctuations. In general, we find that results produced with sctransform are less dependent on these parameters (indeed, we achieve nearly identical results when using all genes in the transcriptome, though this does reduce computational efficiency). This can help users generate more robust results, and in addition, enables the application of standard anlaysis pipelines with identical parameter settings that can quickly be applied to new datasets:

For example, the following code replicates the full end-to-end workflow, in a single command:

Where are normalized values stored for sctransform?

As described in our preprint, sctransform calculates a model of technical noise in scRNA-seq data using ‘regularized negative binomial regression’. The residuals for this model are normalized values, and can be positive or negative. Positive residuals for a given gene in a given cell indicate that we observed more UMIs than expected given the gene’s average expression in the population and cellular sequencing depth, while negative residuals indicate the converse.

The results of sctransfrom are stored in the “SCT” assay. You can learn more about multi-assay data and commands in Seurat in our vignette, command cheat sheet, or developer guide.

Users can individually annotate clusters based on canonical markers. However, the sctransform normalization reveals sharper biological distinctions compared to the standard Seurat workflow, in a few ways:

**Examples:**

Example 1 (r):
```r
install.packages("Seurat")
```

Example 2 (r):
```r
install.packages("Seurat")
```

Example 3 (r):
```r
library(Seurat)
library(ggplot2)
library(sctransform)
```

Example 4 (r):
```r
library(Seurat)
library(ggplot2)
library(sctransform)
```

Example 5 (r):
```r
pbmc_data <- Read10X(data.dir = "../data/pbmc3k/filtered_gene_bc_matrices/hg19/")
pbmc <- CreateSeuratObject(counts = pbmc_data)
```

Example 6 (r):
```r
pbmc_data <- Read10X(data.dir = "../data/pbmc3k/filtered_gene_bc_matrices/hg19/")
pbmc <- CreateSeuratObject(counts = pbmc_data)
```

Example 7 (unknown):
```unknown
NormalizeData
```

Example 8 (unknown):
```unknown
FindVariableFeatures
```

Example 9 (r):
```r
# store mitochondrial percentage in object meta data
pbmc <- PercentageFeatureSet(pbmc, pattern = "^MT-", col.name = "percent.mt")

# run sctransform
pbmc <- SCTransform(pbmc, vars.to.regress = "percent.mt", verbose = FALSE)
```

Example 10 (r):
```r
# store mitochondrial percentage in object meta data
pbmc <- PercentageFeatureSet(pbmc, pattern = "^MT-", col.name = "percent.mt")

# run sctransform
pbmc <- SCTransform(pbmc, vars.to.regress = "percent.mt", verbose = FALSE)
```

Example 11 (r):
```r
# These are now standard steps in the Seurat workflow for visualization and clustering
pbmc <- RunPCA(pbmc, verbose = FALSE)
pbmc <- RunUMAP(pbmc, dims = 1:30, verbose = FALSE)

pbmc <- FindNeighbors(pbmc, dims = 1:30, verbose = FALSE)
pbmc <- FindClusters(pbmc, verbose = FALSE)
DimPlot(pbmc, label = TRUE) + NoLegend()
```

Example 12 (r):
```r
# These are now standard steps in the Seurat workflow for visualization and clustering
pbmc <- RunPCA(pbmc, verbose = FALSE)
pbmc <- RunUMAP(pbmc, dims = 1:30, verbose = FALSE)

pbmc <- FindNeighbors(pbmc, dims = 1:30, verbose = FALSE)
pbmc <- FindClusters(pbmc, verbose = FALSE)
DimPlot(pbmc, label = TRUE) + NoLegend()
```

Example 13 (r):
```r
pbmc <- CreateSeuratObject(pbmc_data) %>% PercentageFeatureSet(pattern = "^MT-", col.name = "percent.mt") %>% 
    SCTransform(vars.to.regress = "percent.mt") %>% RunPCA() %>% FindNeighbors(dims = 1:30) %>% 
    RunUMAP(dims = 1:30) %>% FindClusters()
```

Example 14 (r):
```r
pbmc <- CreateSeuratObject(pbmc_data) %>% PercentageFeatureSet(pattern = "^MT-", col.name = "percent.mt") %>% 
    SCTransform(vars.to.regress = "percent.mt") %>% RunPCA() %>% FindNeighbors(dims = 1:30) %>% 
    RunUMAP(dims = 1:30) %>% FindClusters()
```

Example 15 (unknown):
```unknown
pbmc[["SCT"]]@scale.data
```

Example 16 (unknown):
```unknown
SCTransform
```

Example 17 (unknown):
```unknown
pbmc[["SCT"]]@counts
```

Example 18 (unknown):
```unknown
pbmc[["SCT"]]@data
```

Example 19 (r):
```r
# These are now standard steps in the Seurat workflow for visualization and clustering Visualize
# canonical marker genes as violin plots.
VlnPlot(pbmc, features = c("CD8A", "GZMK", "CCL5", "S100A4", "ANXA1", "CCR7", "ISG15", "CD3D"), 
    pt.size = 0.2, ncol = 4)
```

Example 20 (r):
```r
# These are now standard steps in the Seurat workflow for visualization and clustering Visualize
# canonical marker genes as violin plots.
VlnPlot(pbmc, features = c("CD8A", "GZMK", "CCL5", "S100A4", "ANXA1", "CCR7", "ISG15", "CD3D"), 
    pt.size = 0.2, ncol = 4)
```

Example 21 (r):
```r
# Visualize canonical marker genes on the sctransform embedding.
FeaturePlot(pbmc, features = c("CD8A", "GZMK", "CCL5", "S100A4", "ANXA1", "CCR7"), pt.size = 0.2, 
    ncol = 3)
```

Example 22 (r):
```r
# Visualize canonical marker genes on the sctransform embedding.
FeaturePlot(pbmc, features = c("CD8A", "GZMK", "CCL5", "S100A4", "ANXA1", "CCR7"), pt.size = 0.2, 
    ncol = 3)
```

Example 23 (r):
```r
FeaturePlot(pbmc, features = c("CD3D", "ISG15", "TCL1A", "FCER2", "XCL1", "FCGR3A"), pt.size = 0.2, 
    ncol = 3)
```

Example 24 (r):
```r
FeaturePlot(pbmc, features = c("CD3D", "ISG15", "TCL1A", "FCER2", "XCL1", "FCGR3A"), pt.size = 0.2, 
    ncol = 3)
```

---

## Using sctransform in Seurat • Seurat

**URL:** http://127.0.0.1:9173/seurat/archive/v4.3/sctransform_vignette/index.html

**Contents:**
- Using sctransform in Seurat
    - Christoph Hafemeister & Rahul Satija
    - Compiled: 2023-03-27

Biological heterogeneity in single-cell RNA-seq data is often confounded by technical factors including sequencing depth. The number of molecules detected in each cell can vary significantly between cells, even within the same celltype. Interpretation of scRNA-seq data requires effective pre-processing and normalization to remove this technical variability. In Hafemeister and Satija, 2019 we introduce a modeling framework for the normalization and variance stabilization of molecular count data from scRNA-seq experiment. This procedure omits the need for heuristic steps including pseudocount addition or log-transformation and improves common downstream analytical tasks such as variable gene selection, dimensional reduction, and differential expression.In this vignette, we demonstrate how using sctransform based normalization enables recovering sharper biological distinction compared to log-normalization. library(Seurat) library(ggplot2) library(sctransform)Load data and create Seurat object pbmc_data <- Read10X(data.dir = "../data/pbmc3k/filtered_gene_bc_matrices/hg19/") pbmc <- CreateSeuratObject(counts = pbmc_data)Apply sctransform normalizationNote that this single command replaces NormalizeData(), ScaleData(), and FindVariableFeatures().Transformed data will be available in the SCT assay, which is set as the default after running sctransformDuring normalization, we can also remove confounding sources of variation, for example, mitochondrial mapping percentage # store mitochondrial percentage in object meta data pbmc <- PercentageFeatureSet(pbmc, pattern = "^MT-", col.name = "percent.mt") # run sctransform pbmc <- SCTransform(pbmc, vars.to.regress = "percent.mt", verbose = FALSE)The latest version of sctransform also supports using glmGamPoi package which substantially improves the speed of the learning procedure. It can be invoked by specifying method="glmGamPoi". if (!requireNamespace("BiocManager", quietly = TRUE)) install.packages("BiocManager") BiocManager::install("glmGamPoi") pbmc <- SCTransform(pbmc, method = "glmGamPoi", vars.to.regress = "percent.mt", verbose = FALSE)Perform dimensionality reduction by PCA and UMAP embedding # These are now standard steps in the Seurat workflow for visualization and clustering pbmc <- RunPCA(pbmc, verbose = FALSE) pbmc <- RunUMAP(pbmc, dims = 1:30, verbose = FALSE) pbmc <- FindNeighbors(pbmc, dims = 1:30, verbose = FALSE) pbmc <- FindClusters(pbmc, verbose = FALSE) DimPlot(pbmc, label = TRUE) + NoLegend()Why can we choose more PCs when using sctransform?In the standard Seurat workflow we focus on 10 PCs for this dataset, though we highlight that the results are similar with higher settings for this parameter. Interestingly, we’ve found that when using sctransform, we often benefit by pushing this parameter even higher. We believe this is because the sctransform workflow performs more effective normalization, strongly removing technical effects from the data.Even after standard log-normalization, variation in sequencing depth is still a confounding factor (see Figure 1), and this effect can subtly influence higher PCs. In sctransform, this effect is substantially mitigated (see Figure 3). This means that higher PCs are more likely to represent subtle, but biologically relevant, sources of heterogeneity – so including them may improve downstream analysis.In addition, sctransform returns 3,000 variable features by default, instead of 2,000. The rationale is similar, the additional variable features are less likely to be driven by technical differences across cells, and instead may represent more subtle biological fluctuations. In general, we find that results produced with sctransform are less dependent on these parameters (indeed, we achieve nearly identical results when using all genes in the transcriptome, though this does reduce computational efficiency). This can help users generate more robust results, and in addition, enables the application of standard analysis pipelines with identical parameter settings that can quickly be applied to new datasets:For example, the following code replicates the full end-to-end workflow, in a single command: pbmc <- CreateSeuratObject(pbmc_data) %>% PercentageFeatureSet(pattern = "^MT-", col.name = "percent.mt") %>% SCTransform(vars.to.regress = "percent.mt") %>% RunPCA() %>% FindNeighbors(dims = 1:30) %>% RunUMAP(dims = 1:30) %>% FindClusters()Where are normalized values stored for sctransform?As described in our paper, sctransform calculates a model of technical noise in scRNA-seq data using ‘regularized negative binomial regression’. The residuals for this model are normalized values, and can be positive or negative. Positive residuals for a given gene in a given cell indicate that we observed more UMIs than expected given the gene’s average expression in the population and cellular sequencing depth, while negative residuals indicate the converse.The results of sctransfrom are stored in the “SCT” assay. You can learn more about multi-assay data and commands in Seurat in our vignette, command cheat sheet, or developer guide.pbmc[["SCT"]]@scale.data contains the residuals (normalized values), and is used directly as input to PCA. Please note that this matrix is non-sparse, and can therefore take up a lot of memory if stored for all genes. To save memory, we store these values only for variable genes, by setting the return.only.var.genes = TRUE by default in the SCTransform() function call.To assist with visualization and interpretation. we also convert Pearson residuals back to ‘corrected’ UMI counts. You can interpret these as the UMI counts we would expect to observe if all cells were sequenced to the same depth. If you want to see exactly how we do this, please look at the correct function here.The ‘corrected’ UMI counts are stored in pbmc[["SCT"]]@counts. We store log-normalized versions of these corrected counts in pbmc[["SCT"]]@data, which are very helpful for visualization.You can use the corrected log-normalized counts for differential expression and integration. However, in principle, it would be most optimal to perform these calculations directly on the residuals (stored in the scale.data slot) themselves. This is not currently supported in Seurat v3, but will be soon.Users can individually annotate clusters based on canonical markers. However, the sctransform normalization reveals sharper biological distinctions compared to the standard Seurat workflow, in a few ways:Clear separation of at least 3 CD8 T cell populations (naive, memory, effector), based on CD8A, GZMK, CCL5, GZMK expressionClear separation of three CD4 T cell populations (naive, memory, IFN-activated) based on S100A4, CCR7, IL32, and ISG15Additional developmental sub-structure in B cell cluster, based on TCL1A, FCER2Additional separation of NK cells into CD56dim vs. bright clusters, based on XCL1 and FCGR3A # These are now standard steps in the Seurat workflow for visualization and clustering # Visualize canonical marker genes as violin plots. VlnPlot(pbmc, features = c("CD8A", "GZMK", "CCL5", "S100A4", "ANXA1", "CCR7", "ISG15", "CD3D"), pt.size = 0.2, ncol = 4) # Visualize canonical marker genes on the sctransform embedding. FeaturePlot(pbmc, features = c("CD8A", "GZMK", "CCL5", "S100A4", "ANXA1", "CCR7"), pt.size = 0.2, ncol = 3) FeaturePlot(pbmc, features = c("CD3D", "ISG15", "TCL1A", "FCER2", "XCL1", "FCGR3A"), pt.size = 0.2, ncol = 3)Session Info sessionInfo()## R version 4.2.0 (2022-04-22) ## Platform: x86_64-pc-linux-gnu (64-bit) ## Running under: Ubuntu 20.04.5 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/liblapack.so.3 ## ## locale: ## [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C ## [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8 ## [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 ## ## attached base packages: ## [1] stats graphics grDevices utils datasets methods base ## ## other attached packages: ## [1] sctransform_0.3.5 ggplot2_3.4.1 SeuratObject_4.1.3 Seurat_4.3.0 ## ## loaded via a namespace (and not attached): ## [1] Rtsne_0.16 colorspace_2.1-0 deldir_1.0-6 ## [4] ellipsis_0.3.2 ggridges_0.5.4 rprojroot_2.0.3 ## [7] fs_1.6.1 spatstat.data_3.0-0 farver_2.1.1 ## [10] leiden_0.4.3 listenv_0.9.0 ggrepel_0.9.3 ## [13] fansi_1.0.4 R.methodsS3_1.8.2 codetools_0.2-18 ## [16] splines_4.2.0 cachem_1.0.7 knitr_1.42 ## [19] polyclip_1.10-4 jsonlite_1.8.4 ica_1.0-3 ## [22] cluster_2.1.3 R.oo_1.25.0 png_0.1-8 ## [25] uwot_0.1.14 spatstat.sparse_3.0-0 shiny_1.7.4 ## [28] compiler_4.2.0 httr_1.4.5 Matrix_1.5-3 ## [31] fastmap_1.1.1 lazyeval_0.2.2 cli_3.6.0 ## [34] later_1.3.0 formatR_1.14 htmltools_0.5.4 ## [37] tools_4.2.0 igraph_1.4.1 gtable_0.3.1 ## [40] glue_1.6.2 RANN_2.6.1 reshape2_1.4.4 ## [43] dplyr_1.1.0 Rcpp_1.0.10 scattermore_0.8 ## [46] jquerylib_0.1.4 pkgdown_2.0.7 vctrs_0.5.2 ## [49] nlme_3.1-157 spatstat.explore_3.0-6 progressr_0.13.0 ## [52] lmtest_0.9-40 spatstat.random_3.1-3 xfun_0.37 ## [55] stringr_1.5.0 globals_0.16.2 mime_0.12 ## [58] miniUI_0.1.1.1 lifecycle_1.0.3 irlba_2.3.5.1 ## [61] goftest_1.2-3 future_1.31.0 MASS_7.3-56 ## [64] zoo_1.8-11 scales_1.2.1 ragg_1.2.5 ## [67] promises_1.2.0.1 spatstat.utils_3.0-1 parallel_4.2.0 ## [70] RColorBrewer_1.1-3 yaml_2.3.7 memoise_2.0.1 ## [73] reticulate_1.28 pbapply_1.7-0 gridExtra_2.3 ## [76] sass_0.4.5 stringi_1.7.12 highr_0.10 ## [79] desc_1.4.2 rlang_1.0.6 pkgconfig_2.0.3 ## [82] systemfonts_1.0.4 matrixStats_0.63.0 evaluate_0.20 ## [85] lattice_0.20-45 tensor_1.5 ROCR_1.0-11 ## [88] purrr_1.0.1 labeling_0.4.2 patchwork_1.1.2 ## [91] htmlwidgets_1.6.1 cowplot_1.1.1 tidyselect_1.2.0 ## [94] parallelly_1.34.0 RcppAnnoy_0.0.20 plyr_1.8.8 ## [97] magrittr_2.0.3 R6_2.5.1 generics_0.1.3 ## [100] withr_2.5.0 pillar_1.8.1 fitdistrplus_1.1-8 ## [103] abind_1.4-5 survival_3.3-1 sp_1.6-0 ## [106] tibble_3.1.8 future.apply_1.10.0 KernSmooth_2.23-20 ## [109] utf8_1.2.3 spatstat.geom_3.0-6 plotly_4.10.1 ## [112] rmarkdown_2.20 grid_4.2.0 data.table_1.14.8 ## [115] digest_0.6.31 xtable_1.8-4 tidyr_1.3.0 ## [118] httpuv_1.6.9 R.utils_2.12.2 textshaping_0.3.6 ## [121] munsell_0.5.0 viridisLite_0.4.1 bslib_0.4.2

In this vignette, we demonstrate how using sctransform based normalization enables recovering sharper biological distinction compared to log-normalization. library(Seurat) library(ggplot2) library(sctransform)Load data and create Seurat object pbmc_data <- Read10X(data.dir = "../data/pbmc3k/filtered_gene_bc_matrices/hg19/") pbmc <- CreateSeuratObject(counts = pbmc_data)Apply sctransform normalizationNote that this single command replaces NormalizeData(), ScaleData(), and FindVariableFeatures().Transformed data will be available in the SCT assay, which is set as the default after running sctransformDuring normalization, we can also remove confounding sources of variation, for example, mitochondrial mapping percentage # store mitochondrial percentage in object meta data pbmc <- PercentageFeatureSet(pbmc, pattern = "^MT-", col.name = "percent.mt") # run sctransform pbmc <- SCTransform(pbmc, vars.to.regress = "percent.mt", verbose = FALSE)The latest version of sctransform also supports using glmGamPoi package which substantially improves the speed of the learning procedure. It can be invoked by specifying method="glmGamPoi". if (!requireNamespace("BiocManager", quietly = TRUE)) install.packages("BiocManager") BiocManager::install("glmGamPoi") pbmc <- SCTransform(pbmc, method = "glmGamPoi", vars.to.regress = "percent.mt", verbose = FALSE)Perform dimensionality reduction by PCA and UMAP embedding # These are now standard steps in the Seurat workflow for visualization and clustering pbmc <- RunPCA(pbmc, verbose = FALSE) pbmc <- RunUMAP(pbmc, dims = 1:30, verbose = FALSE) pbmc <- FindNeighbors(pbmc, dims = 1:30, verbose = FALSE) pbmc <- FindClusters(pbmc, verbose = FALSE) DimPlot(pbmc, label = TRUE) + NoLegend()Why can we choose more PCs when using sctransform?In the standard Seurat workflow we focus on 10 PCs for this dataset, though we highlight that the results are similar with higher settings for this parameter. Interestingly, we’ve found that when using sctransform, we often benefit by pushing this parameter even higher. We believe this is because the sctransform workflow performs more effective normalization, strongly removing technical effects from the data.Even after standard log-normalization, variation in sequencing depth is still a confounding factor (see Figure 1), and this effect can subtly influence higher PCs. In sctransform, this effect is substantially mitigated (see Figure 3). This means that higher PCs are more likely to represent subtle, but biologically relevant, sources of heterogeneity – so including them may improve downstream analysis.In addition, sctransform returns 3,000 variable features by default, instead of 2,000. The rationale is similar, the additional variable features are less likely to be driven by technical differences across cells, and instead may represent more subtle biological fluctuations. In general, we find that results produced with sctransform are less dependent on these parameters (indeed, we achieve nearly identical results when using all genes in the transcriptome, though this does reduce computational efficiency). This can help users generate more robust results, and in addition, enables the application of standard analysis pipelines with identical parameter settings that can quickly be applied to new datasets:For example, the following code replicates the full end-to-end workflow, in a single command: pbmc <- CreateSeuratObject(pbmc_data) %>% PercentageFeatureSet(pattern = "^MT-", col.name = "percent.mt") %>% SCTransform(vars.to.regress = "percent.mt") %>% RunPCA() %>% FindNeighbors(dims = 1:30) %>% RunUMAP(dims = 1:30) %>% FindClusters()Where are normalized values stored for sctransform?As described in our paper, sctransform calculates a model of technical noise in scRNA-seq data using ‘regularized negative binomial regression’. The residuals for this model are normalized values, and can be positive or negative. Positive residuals for a given gene in a given cell indicate that we observed more UMIs than expected given the gene’s average expression in the population and cellular sequencing depth, while negative residuals indicate the converse.The results of sctransfrom are stored in the “SCT” assay. You can learn more about multi-assay data and commands in Seurat in our vignette, command cheat sheet, or developer guide.pbmc[["SCT"]]@scale.data contains the residuals (normalized values), and is used directly as input to PCA. Please note that this matrix is non-sparse, and can therefore take up a lot of memory if stored for all genes. To save memory, we store these values only for variable genes, by setting the return.only.var.genes = TRUE by default in the SCTransform() function call.To assist with visualization and interpretation. we also convert Pearson residuals back to ‘corrected’ UMI counts. You can interpret these as the UMI counts we would expect to observe if all cells were sequenced to the same depth. If you want to see exactly how we do this, please look at the correct function here.The ‘corrected’ UMI counts are stored in pbmc[["SCT"]]@counts. We store log-normalized versions of these corrected counts in pbmc[["SCT"]]@data, which are very helpful for visualization.You can use the corrected log-normalized counts for differential expression and integration. However, in principle, it would be most optimal to perform these calculations directly on the residuals (stored in the scale.data slot) themselves. This is not currently supported in Seurat v3, but will be soon.Users can individually annotate clusters based on canonical markers. However, the sctransform normalization reveals sharper biological distinctions compared to the standard Seurat workflow, in a few ways:Clear separation of at least 3 CD8 T cell populations (naive, memory, effector), based on CD8A, GZMK, CCL5, GZMK expressionClear separation of three CD4 T cell populations (naive, memory, IFN-activated) based on S100A4, CCR7, IL32, and ISG15Additional developmental sub-structure in B cell cluster, based on TCL1A, FCER2Additional separation of NK cells into CD56dim vs. bright clusters, based on XCL1 and FCGR3A # These are now standard steps in the Seurat workflow for visualization and clustering # Visualize canonical marker genes as violin plots. VlnPlot(pbmc, features = c("CD8A", "GZMK", "CCL5", "S100A4", "ANXA1", "CCR7", "ISG15", "CD3D"), pt.size = 0.2, ncol = 4) # Visualize canonical marker genes on the sctransform embedding. FeaturePlot(pbmc, features = c("CD8A", "GZMK", "CCL5", "S100A4", "ANXA1", "CCR7"), pt.size = 0.2, ncol = 3) FeaturePlot(pbmc, features = c("CD3D", "ISG15", "TCL1A", "FCER2", "XCL1", "FCGR3A"), pt.size = 0.2, ncol = 3)Session Info sessionInfo()## R version 4.2.0 (2022-04-22) ## Platform: x86_64-pc-linux-gnu (64-bit) ## Running under: Ubuntu 20.04.5 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/liblapack.so.3 ## ## locale: ## [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C ## [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8 ## [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 ## ## attached base packages: ## [1] stats graphics grDevices utils datasets methods base ## ## other attached packages: ## [1] sctransform_0.3.5 ggplot2_3.4.1 SeuratObject_4.1.3 Seurat_4.3.0 ## ## loaded via a namespace (and not attached): ## [1] Rtsne_0.16 colorspace_2.1-0 deldir_1.0-6 ## [4] ellipsis_0.3.2 ggridges_0.5.4 rprojroot_2.0.3 ## [7] fs_1.6.1 spatstat.data_3.0-0 farver_2.1.1 ## [10] leiden_0.4.3 listenv_0.9.0 ggrepel_0.9.3 ## [13] fansi_1.0.4 R.methodsS3_1.8.2 codetools_0.2-18 ## [16] splines_4.2.0 cachem_1.0.7 knitr_1.42 ## [19] polyclip_1.10-4 jsonlite_1.8.4 ica_1.0-3 ## [22] cluster_2.1.3 R.oo_1.25.0 png_0.1-8 ## [25] uwot_0.1.14 spatstat.sparse_3.0-0 shiny_1.7.4 ## [28] compiler_4.2.0 httr_1.4.5 Matrix_1.5-3 ## [31] fastmap_1.1.1 lazyeval_0.2.2 cli_3.6.0 ## [34] later_1.3.0 formatR_1.14 htmltools_0.5.4 ## [37] tools_4.2.0 igraph_1.4.1 gtable_0.3.1 ## [40] glue_1.6.2 RANN_2.6.1 reshape2_1.4.4 ## [43] dplyr_1.1.0 Rcpp_1.0.10 scattermore_0.8 ## [46] jquerylib_0.1.4 pkgdown_2.0.7 vctrs_0.5.2 ## [49] nlme_3.1-157 spatstat.explore_3.0-6 progressr_0.13.0 ## [52] lmtest_0.9-40 spatstat.random_3.1-3 xfun_0.37 ## [55] stringr_1.5.0 globals_0.16.2 mime_0.12 ## [58] miniUI_0.1.1.1 lifecycle_1.0.3 irlba_2.3.5.1 ## [61] goftest_1.2-3 future_1.31.0 MASS_7.3-56 ## [64] zoo_1.8-11 scales_1.2.1 ragg_1.2.5 ## [67] promises_1.2.0.1 spatstat.utils_3.0-1 parallel_4.2.0 ## [70] RColorBrewer_1.1-3 yaml_2.3.7 memoise_2.0.1 ## [73] reticulate_1.28 pbapply_1.7-0 gridExtra_2.3 ## [76] sass_0.4.5 stringi_1.7.12 highr_0.10 ## [79] desc_1.4.2 rlang_1.0.6 pkgconfig_2.0.3 ## [82] systemfonts_1.0.4 matrixStats_0.63.0 evaluate_0.20 ## [85] lattice_0.20-45 tensor_1.5 ROCR_1.0-11 ## [88] purrr_1.0.1 labeling_0.4.2 patchwork_1.1.2 ## [91] htmlwidgets_1.6.1 cowplot_1.1.1 tidyselect_1.2.0 ## [94] parallelly_1.34.0 RcppAnnoy_0.0.20 plyr_1.8.8 ## [97] magrittr_2.0.3 R6_2.5.1 generics_0.1.3 ## [100] withr_2.5.0 pillar_1.8.1 fitdistrplus_1.1-8 ## [103] abind_1.4-5 survival_3.3-1 sp_1.6-0 ## [106] tibble_3.1.8 future.apply_1.10.0 KernSmooth_2.23-20 ## [109] utf8_1.2.3 spatstat.geom_3.0-6 plotly_4.10.1 ## [112] rmarkdown_2.20 grid_4.2.0 data.table_1.14.8 ## [115] digest_0.6.31 xtable_1.8-4 tidyr_1.3.0 ## [118] httpuv_1.6.9 R.utils_2.12.2 textshaping_0.3.6 ## [121] munsell_0.5.0 viridisLite_0.4.1 bslib_0.4.2

Load data and create Seurat object pbmc_data <- Read10X(data.dir = "../data/pbmc3k/filtered_gene_bc_matrices/hg19/") pbmc <- CreateSeuratObject(counts = pbmc_data)Apply sctransform normalizationNote that this single command replaces NormalizeData(), ScaleData(), and FindVariableFeatures().Transformed data will be available in the SCT assay, which is set as the default after running sctransformDuring normalization, we can also remove confounding sources of variation, for example, mitochondrial mapping percentage # store mitochondrial percentage in object meta data pbmc <- PercentageFeatureSet(pbmc, pattern = "^MT-", col.name = "percent.mt") # run sctransform pbmc <- SCTransform(pbmc, vars.to.regress = "percent.mt", verbose = FALSE)The latest version of sctransform also supports using glmGamPoi package which substantially improves the speed of the learning procedure. It can be invoked by specifying method="glmGamPoi". if (!requireNamespace("BiocManager", quietly = TRUE)) install.packages("BiocManager") BiocManager::install("glmGamPoi") pbmc <- SCTransform(pbmc, method = "glmGamPoi", vars.to.regress = "percent.mt", verbose = FALSE)Perform dimensionality reduction by PCA and UMAP embedding # These are now standard steps in the Seurat workflow for visualization and clustering pbmc <- RunPCA(pbmc, verbose = FALSE) pbmc <- RunUMAP(pbmc, dims = 1:30, verbose = FALSE) pbmc <- FindNeighbors(pbmc, dims = 1:30, verbose = FALSE) pbmc <- FindClusters(pbmc, verbose = FALSE) DimPlot(pbmc, label = TRUE) + NoLegend()Why can we choose more PCs when using sctransform?In the standard Seurat workflow we focus on 10 PCs for this dataset, though we highlight that the results are similar with higher settings for this parameter. Interestingly, we’ve found that when using sctransform, we often benefit by pushing this parameter even higher. We believe this is because the sctransform workflow performs more effective normalization, strongly removing technical effects from the data.Even after standard log-normalization, variation in sequencing depth is still a confounding factor (see Figure 1), and this effect can subtly influence higher PCs. In sctransform, this effect is substantially mitigated (see Figure 3). This means that higher PCs are more likely to represent subtle, but biologically relevant, sources of heterogeneity – so including them may improve downstream analysis.In addition, sctransform returns 3,000 variable features by default, instead of 2,000. The rationale is similar, the additional variable features are less likely to be driven by technical differences across cells, and instead may represent more subtle biological fluctuations. In general, we find that results produced with sctransform are less dependent on these parameters (indeed, we achieve nearly identical results when using all genes in the transcriptome, though this does reduce computational efficiency). This can help users generate more robust results, and in addition, enables the application of standard analysis pipelines with identical parameter settings that can quickly be applied to new datasets:For example, the following code replicates the full end-to-end workflow, in a single command: pbmc <- CreateSeuratObject(pbmc_data) %>% PercentageFeatureSet(pattern = "^MT-", col.name = "percent.mt") %>% SCTransform(vars.to.regress = "percent.mt") %>% RunPCA() %>% FindNeighbors(dims = 1:30) %>% RunUMAP(dims = 1:30) %>% FindClusters()Where are normalized values stored for sctransform?As described in our paper, sctransform calculates a model of technical noise in scRNA-seq data using ‘regularized negative binomial regression’. The residuals for this model are normalized values, and can be positive or negative. Positive residuals for a given gene in a given cell indicate that we observed more UMIs than expected given the gene’s average expression in the population and cellular sequencing depth, while negative residuals indicate the converse.The results of sctransfrom are stored in the “SCT” assay. You can learn more about multi-assay data and commands in Seurat in our vignette, command cheat sheet, or developer guide.pbmc[["SCT"]]@scale.data contains the residuals (normalized values), and is used directly as input to PCA. Please note that this matrix is non-sparse, and can therefore take up a lot of memory if stored for all genes. To save memory, we store these values only for variable genes, by setting the return.only.var.genes = TRUE by default in the SCTransform() function call.To assist with visualization and interpretation. we also convert Pearson residuals back to ‘corrected’ UMI counts. You can interpret these as the UMI counts we would expect to observe if all cells were sequenced to the same depth. If you want to see exactly how we do this, please look at the correct function here.The ‘corrected’ UMI counts are stored in pbmc[["SCT"]]@counts. We store log-normalized versions of these corrected counts in pbmc[["SCT"]]@data, which are very helpful for visualization.You can use the corrected log-normalized counts for differential expression and integration. However, in principle, it would be most optimal to perform these calculations directly on the residuals (stored in the scale.data slot) themselves. This is not currently supported in Seurat v3, but will be soon.Users can individually annotate clusters based on canonical markers. However, the sctransform normalization reveals sharper biological distinctions compared to the standard Seurat workflow, in a few ways:Clear separation of at least 3 CD8 T cell populations (naive, memory, effector), based on CD8A, GZMK, CCL5, GZMK expressionClear separation of three CD4 T cell populations (naive, memory, IFN-activated) based on S100A4, CCR7, IL32, and ISG15Additional developmental sub-structure in B cell cluster, based on TCL1A, FCER2Additional separation of NK cells into CD56dim vs. bright clusters, based on XCL1 and FCGR3A # These are now standard steps in the Seurat workflow for visualization and clustering # Visualize canonical marker genes as violin plots. VlnPlot(pbmc, features = c("CD8A", "GZMK", "CCL5", "S100A4", "ANXA1", "CCR7", "ISG15", "CD3D"), pt.size = 0.2, ncol = 4) # Visualize canonical marker genes on the sctransform embedding. FeaturePlot(pbmc, features = c("CD8A", "GZMK", "CCL5", "S100A4", "ANXA1", "CCR7"), pt.size = 0.2, ncol = 3) FeaturePlot(pbmc, features = c("CD3D", "ISG15", "TCL1A", "FCER2", "XCL1", "FCGR3A"), pt.size = 0.2, ncol = 3)Session Info sessionInfo()## R version 4.2.0 (2022-04-22) ## Platform: x86_64-pc-linux-gnu (64-bit) ## Running under: Ubuntu 20.04.5 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/liblapack.so.3 ## ## locale: ## [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C ## [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8 ## [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 ## ## attached base packages: ## [1] stats graphics grDevices utils datasets methods base ## ## other attached packages: ## [1] sctransform_0.3.5 ggplot2_3.4.1 SeuratObject_4.1.3 Seurat_4.3.0 ## ## loaded via a namespace (and not attached): ## [1] Rtsne_0.16 colorspace_2.1-0 deldir_1.0-6 ## [4] ellipsis_0.3.2 ggridges_0.5.4 rprojroot_2.0.3 ## [7] fs_1.6.1 spatstat.data_3.0-0 farver_2.1.1 ## [10] leiden_0.4.3 listenv_0.9.0 ggrepel_0.9.3 ## [13] fansi_1.0.4 R.methodsS3_1.8.2 codetools_0.2-18 ## [16] splines_4.2.0 cachem_1.0.7 knitr_1.42 ## [19] polyclip_1.10-4 jsonlite_1.8.4 ica_1.0-3 ## [22] cluster_2.1.3 R.oo_1.25.0 png_0.1-8 ## [25] uwot_0.1.14 spatstat.sparse_3.0-0 shiny_1.7.4 ## [28] compiler_4.2.0 httr_1.4.5 Matrix_1.5-3 ## [31] fastmap_1.1.1 lazyeval_0.2.2 cli_3.6.0 ## [34] later_1.3.0 formatR_1.14 htmltools_0.5.4 ## [37] tools_4.2.0 igraph_1.4.1 gtable_0.3.1 ## [40] glue_1.6.2 RANN_2.6.1 reshape2_1.4.4 ## [43] dplyr_1.1.0 Rcpp_1.0.10 scattermore_0.8 ## [46] jquerylib_0.1.4 pkgdown_2.0.7 vctrs_0.5.2 ## [49] nlme_3.1-157 spatstat.explore_3.0-6 progressr_0.13.0 ## [52] lmtest_0.9-40 spatstat.random_3.1-3 xfun_0.37 ## [55] stringr_1.5.0 globals_0.16.2 mime_0.12 ## [58] miniUI_0.1.1.1 lifecycle_1.0.3 irlba_2.3.5.1 ## [61] goftest_1.2-3 future_1.31.0 MASS_7.3-56 ## [64] zoo_1.8-11 scales_1.2.1 ragg_1.2.5 ## [67] promises_1.2.0.1 spatstat.utils_3.0-1 parallel_4.2.0 ## [70] RColorBrewer_1.1-3 yaml_2.3.7 memoise_2.0.1 ## [73] reticulate_1.28 pbapply_1.7-0 gridExtra_2.3 ## [76] sass_0.4.5 stringi_1.7.12 highr_0.10 ## [79] desc_1.4.2 rlang_1.0.6 pkgconfig_2.0.3 ## [82] systemfonts_1.0.4 matrixStats_0.63.0 evaluate_0.20 ## [85] lattice_0.20-45 tensor_1.5 ROCR_1.0-11 ## [88] purrr_1.0.1 labeling_0.4.2 patchwork_1.1.2 ## [91] htmlwidgets_1.6.1 cowplot_1.1.1 tidyselect_1.2.0 ## [94] parallelly_1.34.0 RcppAnnoy_0.0.20 plyr_1.8.8 ## [97] magrittr_2.0.3 R6_2.5.1 generics_0.1.3 ## [100] withr_2.5.0 pillar_1.8.1 fitdistrplus_1.1-8 ## [103] abind_1.4-5 survival_3.3-1 sp_1.6-0 ## [106] tibble_3.1.8 future.apply_1.10.0 KernSmooth_2.23-20 ## [109] utf8_1.2.3 spatstat.geom_3.0-6 plotly_4.10.1 ## [112] rmarkdown_2.20 grid_4.2.0 data.table_1.14.8 ## [115] digest_0.6.31 xtable_1.8-4 tidyr_1.3.0 ## [118] httpuv_1.6.9 R.utils_2.12.2 textshaping_0.3.6 ## [121] munsell_0.5.0 viridisLite_0.4.1 bslib_0.4.2

Apply sctransform normalizationNote that this single command replaces NormalizeData(), ScaleData(), and FindVariableFeatures().Transformed data will be available in the SCT assay, which is set as the default after running sctransformDuring normalization, we can also remove confounding sources of variation, for example, mitochondrial mapping percentage # store mitochondrial percentage in object meta data pbmc <- PercentageFeatureSet(pbmc, pattern = "^MT-", col.name = "percent.mt") # run sctransform pbmc <- SCTransform(pbmc, vars.to.regress = "percent.mt", verbose = FALSE)The latest version of sctransform also supports using glmGamPoi package which substantially improves the speed of the learning procedure. It can be invoked by specifying method="glmGamPoi". if (!requireNamespace("BiocManager", quietly = TRUE)) install.packages("BiocManager") BiocManager::install("glmGamPoi") pbmc <- SCTransform(pbmc, method = "glmGamPoi", vars.to.regress = "percent.mt", verbose = FALSE)Perform dimensionality reduction by PCA and UMAP embedding # These are now standard steps in the Seurat workflow for visualization and clustering pbmc <- RunPCA(pbmc, verbose = FALSE) pbmc <- RunUMAP(pbmc, dims = 1:30, verbose = FALSE) pbmc <- FindNeighbors(pbmc, dims = 1:30, verbose = FALSE) pbmc <- FindClusters(pbmc, verbose = FALSE) DimPlot(pbmc, label = TRUE) + NoLegend()Why can we choose more PCs when using sctransform?In the standard Seurat workflow we focus on 10 PCs for this dataset, though we highlight that the results are similar with higher settings for this parameter. Interestingly, we’ve found that when using sctransform, we often benefit by pushing this parameter even higher. We believe this is because the sctransform workflow performs more effective normalization, strongly removing technical effects from the data.Even after standard log-normalization, variation in sequencing depth is still a confounding factor (see Figure 1), and this effect can subtly influence higher PCs. In sctransform, this effect is substantially mitigated (see Figure 3). This means that higher PCs are more likely to represent subtle, but biologically relevant, sources of heterogeneity – so including them may improve downstream analysis.In addition, sctransform returns 3,000 variable features by default, instead of 2,000. The rationale is similar, the additional variable features are less likely to be driven by technical differences across cells, and instead may represent more subtle biological fluctuations. In general, we find that results produced with sctransform are less dependent on these parameters (indeed, we achieve nearly identical results when using all genes in the transcriptome, though this does reduce computational efficiency). This can help users generate more robust results, and in addition, enables the application of standard analysis pipelines with identical parameter settings that can quickly be applied to new datasets:For example, the following code replicates the full end-to-end workflow, in a single command: pbmc <- CreateSeuratObject(pbmc_data) %>% PercentageFeatureSet(pattern = "^MT-", col.name = "percent.mt") %>% SCTransform(vars.to.regress = "percent.mt") %>% RunPCA() %>% FindNeighbors(dims = 1:30) %>% RunUMAP(dims = 1:30) %>% FindClusters()Where are normalized values stored for sctransform?As described in our paper, sctransform calculates a model of technical noise in scRNA-seq data using ‘regularized negative binomial regression’. The residuals for this model are normalized values, and can be positive or negative. Positive residuals for a given gene in a given cell indicate that we observed more UMIs than expected given the gene’s average expression in the population and cellular sequencing depth, while negative residuals indicate the converse.The results of sctransfrom are stored in the “SCT” assay. You can learn more about multi-assay data and commands in Seurat in our vignette, command cheat sheet, or developer guide.pbmc[["SCT"]]@scale.data contains the residuals (normalized values), and is used directly as input to PCA. Please note that this matrix is non-sparse, and can therefore take up a lot of memory if stored for all genes. To save memory, we store these values only for variable genes, by setting the return.only.var.genes = TRUE by default in the SCTransform() function call.To assist with visualization and interpretation. we also convert Pearson residuals back to ‘corrected’ UMI counts. You can interpret these as the UMI counts we would expect to observe if all cells were sequenced to the same depth. If you want to see exactly how we do this, please look at the correct function here.The ‘corrected’ UMI counts are stored in pbmc[["SCT"]]@counts. We store log-normalized versions of these corrected counts in pbmc[["SCT"]]@data, which are very helpful for visualization.You can use the corrected log-normalized counts for differential expression and integration. However, in principle, it would be most optimal to perform these calculations directly on the residuals (stored in the scale.data slot) themselves. This is not currently supported in Seurat v3, but will be soon.Users can individually annotate clusters based on canonical markers. However, the sctransform normalization reveals sharper biological distinctions compared to the standard Seurat workflow, in a few ways:Clear separation of at least 3 CD8 T cell populations (naive, memory, effector), based on CD8A, GZMK, CCL5, GZMK expressionClear separation of three CD4 T cell populations (naive, memory, IFN-activated) based on S100A4, CCR7, IL32, and ISG15Additional developmental sub-structure in B cell cluster, based on TCL1A, FCER2Additional separation of NK cells into CD56dim vs. bright clusters, based on XCL1 and FCGR3A # These are now standard steps in the Seurat workflow for visualization and clustering # Visualize canonical marker genes as violin plots. VlnPlot(pbmc, features = c("CD8A", "GZMK", "CCL5", "S100A4", "ANXA1", "CCR7", "ISG15", "CD3D"), pt.size = 0.2, ncol = 4) # Visualize canonical marker genes on the sctransform embedding. FeaturePlot(pbmc, features = c("CD8A", "GZMK", "CCL5", "S100A4", "ANXA1", "CCR7"), pt.size = 0.2, ncol = 3) FeaturePlot(pbmc, features = c("CD3D", "ISG15", "TCL1A", "FCER2", "XCL1", "FCGR3A"), pt.size = 0.2, ncol = 3)Session Info sessionInfo()## R version 4.2.0 (2022-04-22) ## Platform: x86_64-pc-linux-gnu (64-bit) ## Running under: Ubuntu 20.04.5 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/liblapack.so.3 ## ## locale: ## [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C ## [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8 ## [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 ## ## attached base packages: ## [1] stats graphics grDevices utils datasets methods base ## ## other attached packages: ## [1] sctransform_0.3.5 ggplot2_3.4.1 SeuratObject_4.1.3 Seurat_4.3.0 ## ## loaded via a namespace (and not attached): ## [1] Rtsne_0.16 colorspace_2.1-0 deldir_1.0-6 ## [4] ellipsis_0.3.2 ggridges_0.5.4 rprojroot_2.0.3 ## [7] fs_1.6.1 spatstat.data_3.0-0 farver_2.1.1 ## [10] leiden_0.4.3 listenv_0.9.0 ggrepel_0.9.3 ## [13] fansi_1.0.4 R.methodsS3_1.8.2 codetools_0.2-18 ## [16] splines_4.2.0 cachem_1.0.7 knitr_1.42 ## [19] polyclip_1.10-4 jsonlite_1.8.4 ica_1.0-3 ## [22] cluster_2.1.3 R.oo_1.25.0 png_0.1-8 ## [25] uwot_0.1.14 spatstat.sparse_3.0-0 shiny_1.7.4 ## [28] compiler_4.2.0 httr_1.4.5 Matrix_1.5-3 ## [31] fastmap_1.1.1 lazyeval_0.2.2 cli_3.6.0 ## [34] later_1.3.0 formatR_1.14 htmltools_0.5.4 ## [37] tools_4.2.0 igraph_1.4.1 gtable_0.3.1 ## [40] glue_1.6.2 RANN_2.6.1 reshape2_1.4.4 ## [43] dplyr_1.1.0 Rcpp_1.0.10 scattermore_0.8 ## [46] jquerylib_0.1.4 pkgdown_2.0.7 vctrs_0.5.2 ## [49] nlme_3.1-157 spatstat.explore_3.0-6 progressr_0.13.0 ## [52] lmtest_0.9-40 spatstat.random_3.1-3 xfun_0.37 ## [55] stringr_1.5.0 globals_0.16.2 mime_0.12 ## [58] miniUI_0.1.1.1 lifecycle_1.0.3 irlba_2.3.5.1 ## [61] goftest_1.2-3 future_1.31.0 MASS_7.3-56 ## [64] zoo_1.8-11 scales_1.2.1 ragg_1.2.5 ## [67] promises_1.2.0.1 spatstat.utils_3.0-1 parallel_4.2.0 ## [70] RColorBrewer_1.1-3 yaml_2.3.7 memoise_2.0.1 ## [73] reticulate_1.28 pbapply_1.7-0 gridExtra_2.3 ## [76] sass_0.4.5 stringi_1.7.12 highr_0.10 ## [79] desc_1.4.2 rlang_1.0.6 pkgconfig_2.0.3 ## [82] systemfonts_1.0.4 matrixStats_0.63.0 evaluate_0.20 ## [85] lattice_0.20-45 tensor_1.5 ROCR_1.0-11 ## [88] purrr_1.0.1 labeling_0.4.2 patchwork_1.1.2 ## [91] htmlwidgets_1.6.1 cowplot_1.1.1 tidyselect_1.2.0 ## [94] parallelly_1.34.0 RcppAnnoy_0.0.20 plyr_1.8.8 ## [97] magrittr_2.0.3 R6_2.5.1 generics_0.1.3 ## [100] withr_2.5.0 pillar_1.8.1 fitdistrplus_1.1-8 ## [103] abind_1.4-5 survival_3.3-1 sp_1.6-0 ## [106] tibble_3.1.8 future.apply_1.10.0 KernSmooth_2.23-20 ## [109] utf8_1.2.3 spatstat.geom_3.0-6 plotly_4.10.1 ## [112] rmarkdown_2.20 grid_4.2.0 data.table_1.14.8 ## [115] digest_0.6.31 xtable_1.8-4 tidyr_1.3.0 ## [118] httpuv_1.6.9 R.utils_2.12.2 textshaping_0.3.6 ## [121] munsell_0.5.0 viridisLite_0.4.1 bslib_0.4.2

The latest version of sctransform also supports using glmGamPoi package which substantially improves the speed of the learning procedure. It can be invoked by specifying method="glmGamPoi". if (!requireNamespace("BiocManager", quietly = TRUE)) install.packages("BiocManager") BiocManager::install("glmGamPoi") pbmc <- SCTransform(pbmc, method = "glmGamPoi", vars.to.regress = "percent.mt", verbose = FALSE)Perform dimensionality reduction by PCA and UMAP embedding # These are now standard steps in the Seurat workflow for visualization and clustering pbmc <- RunPCA(pbmc, verbose = FALSE) pbmc <- RunUMAP(pbmc, dims = 1:30, verbose = FALSE) pbmc <- FindNeighbors(pbmc, dims = 1:30, verbose = FALSE) pbmc <- FindClusters(pbmc, verbose = FALSE) DimPlot(pbmc, label = TRUE) + NoLegend()Why can we choose more PCs when using sctransform?In the standard Seurat workflow we focus on 10 PCs for this dataset, though we highlight that the results are similar with higher settings for this parameter. Interestingly, we’ve found that when using sctransform, we often benefit by pushing this parameter even higher. We believe this is because the sctransform workflow performs more effective normalization, strongly removing technical effects from the data.Even after standard log-normalization, variation in sequencing depth is still a confounding factor (see Figure 1), and this effect can subtly influence higher PCs. In sctransform, this effect is substantially mitigated (see Figure 3). This means that higher PCs are more likely to represent subtle, but biologically relevant, sources of heterogeneity – so including them may improve downstream analysis.In addition, sctransform returns 3,000 variable features by default, instead of 2,000. The rationale is similar, the additional variable features are less likely to be driven by technical differences across cells, and instead may represent more subtle biological fluctuations. In general, we find that results produced with sctransform are less dependent on these parameters (indeed, we achieve nearly identical results when using all genes in the transcriptome, though this does reduce computational efficiency). This can help users generate more robust results, and in addition, enables the application of standard analysis pipelines with identical parameter settings that can quickly be applied to new datasets:For example, the following code replicates the full end-to-end workflow, in a single command: pbmc <- CreateSeuratObject(pbmc_data) %>% PercentageFeatureSet(pattern = "^MT-", col.name = "percent.mt") %>% SCTransform(vars.to.regress = "percent.mt") %>% RunPCA() %>% FindNeighbors(dims = 1:30) %>% RunUMAP(dims = 1:30) %>% FindClusters()Where are normalized values stored for sctransform?As described in our paper, sctransform calculates a model of technical noise in scRNA-seq data using ‘regularized negative binomial regression’. The residuals for this model are normalized values, and can be positive or negative. Positive residuals for a given gene in a given cell indicate that we observed more UMIs than expected given the gene’s average expression in the population and cellular sequencing depth, while negative residuals indicate the converse.The results of sctransfrom are stored in the “SCT” assay. You can learn more about multi-assay data and commands in Seurat in our vignette, command cheat sheet, or developer guide.pbmc[["SCT"]]@scale.data contains the residuals (normalized values), and is used directly as input to PCA. Please note that this matrix is non-sparse, and can therefore take up a lot of memory if stored for all genes. To save memory, we store these values only for variable genes, by setting the return.only.var.genes = TRUE by default in the SCTransform() function call.To assist with visualization and interpretation. we also convert Pearson residuals back to ‘corrected’ UMI counts. You can interpret these as the UMI counts we would expect to observe if all cells were sequenced to the same depth. If you want to see exactly how we do this, please look at the correct function here.The ‘corrected’ UMI counts are stored in pbmc[["SCT"]]@counts. We store log-normalized versions of these corrected counts in pbmc[["SCT"]]@data, which are very helpful for visualization.You can use the corrected log-normalized counts for differential expression and integration. However, in principle, it would be most optimal to perform these calculations directly on the residuals (stored in the scale.data slot) themselves. This is not currently supported in Seurat v3, but will be soon.Users can individually annotate clusters based on canonical markers. However, the sctransform normalization reveals sharper biological distinctions compared to the standard Seurat workflow, in a few ways:Clear separation of at least 3 CD8 T cell populations (naive, memory, effector), based on CD8A, GZMK, CCL5, GZMK expressionClear separation of three CD4 T cell populations (naive, memory, IFN-activated) based on S100A4, CCR7, IL32, and ISG15Additional developmental sub-structure in B cell cluster, based on TCL1A, FCER2Additional separation of NK cells into CD56dim vs. bright clusters, based on XCL1 and FCGR3A # These are now standard steps in the Seurat workflow for visualization and clustering # Visualize canonical marker genes as violin plots. VlnPlot(pbmc, features = c("CD8A", "GZMK", "CCL5", "S100A4", "ANXA1", "CCR7", "ISG15", "CD3D"), pt.size = 0.2, ncol = 4) # Visualize canonical marker genes on the sctransform embedding. FeaturePlot(pbmc, features = c("CD8A", "GZMK", "CCL5", "S100A4", "ANXA1", "CCR7"), pt.size = 0.2, ncol = 3) FeaturePlot(pbmc, features = c("CD3D", "ISG15", "TCL1A", "FCER2", "XCL1", "FCGR3A"), pt.size = 0.2, ncol = 3)Session Info sessionInfo()## R version 4.2.0 (2022-04-22) ## Platform: x86_64-pc-linux-gnu (64-bit) ## Running under: Ubuntu 20.04.5 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/liblapack.so.3 ## ## locale: ## [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C ## [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8 ## [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 ## ## attached base packages: ## [1] stats graphics grDevices utils datasets methods base ## ## other attached packages: ## [1] sctransform_0.3.5 ggplot2_3.4.1 SeuratObject_4.1.3 Seurat_4.3.0 ## ## loaded via a namespace (and not attached): ## [1] Rtsne_0.16 colorspace_2.1-0 deldir_1.0-6 ## [4] ellipsis_0.3.2 ggridges_0.5.4 rprojroot_2.0.3 ## [7] fs_1.6.1 spatstat.data_3.0-0 farver_2.1.1 ## [10] leiden_0.4.3 listenv_0.9.0 ggrepel_0.9.3 ## [13] fansi_1.0.4 R.methodsS3_1.8.2 codetools_0.2-18 ## [16] splines_4.2.0 cachem_1.0.7 knitr_1.42 ## [19] polyclip_1.10-4 jsonlite_1.8.4 ica_1.0-3 ## [22] cluster_2.1.3 R.oo_1.25.0 png_0.1-8 ## [25] uwot_0.1.14 spatstat.sparse_3.0-0 shiny_1.7.4 ## [28] compiler_4.2.0 httr_1.4.5 Matrix_1.5-3 ## [31] fastmap_1.1.1 lazyeval_0.2.2 cli_3.6.0 ## [34] later_1.3.0 formatR_1.14 htmltools_0.5.4 ## [37] tools_4.2.0 igraph_1.4.1 gtable_0.3.1 ## [40] glue_1.6.2 RANN_2.6.1 reshape2_1.4.4 ## [43] dplyr_1.1.0 Rcpp_1.0.10 scattermore_0.8 ## [46] jquerylib_0.1.4 pkgdown_2.0.7 vctrs_0.5.2 ## [49] nlme_3.1-157 spatstat.explore_3.0-6 progressr_0.13.0 ## [52] lmtest_0.9-40 spatstat.random_3.1-3 xfun_0.37 ## [55] stringr_1.5.0 globals_0.16.2 mime_0.12 ## [58] miniUI_0.1.1.1 lifecycle_1.0.3 irlba_2.3.5.1 ## [61] goftest_1.2-3 future_1.31.0 MASS_7.3-56 ## [64] zoo_1.8-11 scales_1.2.1 ragg_1.2.5 ## [67] promises_1.2.0.1 spatstat.utils_3.0-1 parallel_4.2.0 ## [70] RColorBrewer_1.1-3 yaml_2.3.7 memoise_2.0.1 ## [73] reticulate_1.28 pbapply_1.7-0 gridExtra_2.3 ## [76] sass_0.4.5 stringi_1.7.12 highr_0.10 ## [79] desc_1.4.2 rlang_1.0.6 pkgconfig_2.0.3 ## [82] systemfonts_1.0.4 matrixStats_0.63.0 evaluate_0.20 ## [85] lattice_0.20-45 tensor_1.5 ROCR_1.0-11 ## [88] purrr_1.0.1 labeling_0.4.2 patchwork_1.1.2 ## [91] htmlwidgets_1.6.1 cowplot_1.1.1 tidyselect_1.2.0 ## [94] parallelly_1.34.0 RcppAnnoy_0.0.20 plyr_1.8.8 ## [97] magrittr_2.0.3 R6_2.5.1 generics_0.1.3 ## [100] withr_2.5.0 pillar_1.8.1 fitdistrplus_1.1-8 ## [103] abind_1.4-5 survival_3.3-1 sp_1.6-0 ## [106] tibble_3.1.8 future.apply_1.10.0 KernSmooth_2.23-20 ## [109] utf8_1.2.3 spatstat.geom_3.0-6 plotly_4.10.1 ## [112] rmarkdown_2.20 grid_4.2.0 data.table_1.14.8 ## [115] digest_0.6.31 xtable_1.8-4 tidyr_1.3.0 ## [118] httpuv_1.6.9 R.utils_2.12.2 textshaping_0.3.6 ## [121] munsell_0.5.0 viridisLite_0.4.1 bslib_0.4.2

Perform dimensionality reduction by PCA and UMAP embedding # These are now standard steps in the Seurat workflow for visualization and clustering pbmc <- RunPCA(pbmc, verbose = FALSE) pbmc <- RunUMAP(pbmc, dims = 1:30, verbose = FALSE) pbmc <- FindNeighbors(pbmc, dims = 1:30, verbose = FALSE) pbmc <- FindClusters(pbmc, verbose = FALSE) DimPlot(pbmc, label = TRUE) + NoLegend()Why can we choose more PCs when using sctransform?In the standard Seurat workflow we focus on 10 PCs for this dataset, though we highlight that the results are similar with higher settings for this parameter. Interestingly, we’ve found that when using sctransform, we often benefit by pushing this parameter even higher. We believe this is because the sctransform workflow performs more effective normalization, strongly removing technical effects from the data.Even after standard log-normalization, variation in sequencing depth is still a confounding factor (see Figure 1), and this effect can subtly influence higher PCs. In sctransform, this effect is substantially mitigated (see Figure 3). This means that higher PCs are more likely to represent subtle, but biologically relevant, sources of heterogeneity – so including them may improve downstream analysis.In addition, sctransform returns 3,000 variable features by default, instead of 2,000. The rationale is similar, the additional variable features are less likely to be driven by technical differences across cells, and instead may represent more subtle biological fluctuations. In general, we find that results produced with sctransform are less dependent on these parameters (indeed, we achieve nearly identical results when using all genes in the transcriptome, though this does reduce computational efficiency). This can help users generate more robust results, and in addition, enables the application of standard analysis pipelines with identical parameter settings that can quickly be applied to new datasets:For example, the following code replicates the full end-to-end workflow, in a single command: pbmc <- CreateSeuratObject(pbmc_data) %>% PercentageFeatureSet(pattern = "^MT-", col.name = "percent.mt") %>% SCTransform(vars.to.regress = "percent.mt") %>% RunPCA() %>% FindNeighbors(dims = 1:30) %>% RunUMAP(dims = 1:30) %>% FindClusters()Where are normalized values stored for sctransform?As described in our paper, sctransform calculates a model of technical noise in scRNA-seq data using ‘regularized negative binomial regression’. The residuals for this model are normalized values, and can be positive or negative. Positive residuals for a given gene in a given cell indicate that we observed more UMIs than expected given the gene’s average expression in the population and cellular sequencing depth, while negative residuals indicate the converse.The results of sctransfrom are stored in the “SCT” assay. You can learn more about multi-assay data and commands in Seurat in our vignette, command cheat sheet, or developer guide.pbmc[["SCT"]]@scale.data contains the residuals (normalized values), and is used directly as input to PCA. Please note that this matrix is non-sparse, and can therefore take up a lot of memory if stored for all genes. To save memory, we store these values only for variable genes, by setting the return.only.var.genes = TRUE by default in the SCTransform() function call.To assist with visualization and interpretation. we also convert Pearson residuals back to ‘corrected’ UMI counts. You can interpret these as the UMI counts we would expect to observe if all cells were sequenced to the same depth. If you want to see exactly how we do this, please look at the correct function here.The ‘corrected’ UMI counts are stored in pbmc[["SCT"]]@counts. We store log-normalized versions of these corrected counts in pbmc[["SCT"]]@data, which are very helpful for visualization.You can use the corrected log-normalized counts for differential expression and integration. However, in principle, it would be most optimal to perform these calculations directly on the residuals (stored in the scale.data slot) themselves. This is not currently supported in Seurat v3, but will be soon.Users can individually annotate clusters based on canonical markers. However, the sctransform normalization reveals sharper biological distinctions compared to the standard Seurat workflow, in a few ways:Clear separation of at least 3 CD8 T cell populations (naive, memory, effector), based on CD8A, GZMK, CCL5, GZMK expressionClear separation of three CD4 T cell populations (naive, memory, IFN-activated) based on S100A4, CCR7, IL32, and ISG15Additional developmental sub-structure in B cell cluster, based on TCL1A, FCER2Additional separation of NK cells into CD56dim vs. bright clusters, based on XCL1 and FCGR3A # These are now standard steps in the Seurat workflow for visualization and clustering # Visualize canonical marker genes as violin plots. VlnPlot(pbmc, features = c("CD8A", "GZMK", "CCL5", "S100A4", "ANXA1", "CCR7", "ISG15", "CD3D"), pt.size = 0.2, ncol = 4) # Visualize canonical marker genes on the sctransform embedding. FeaturePlot(pbmc, features = c("CD8A", "GZMK", "CCL5", "S100A4", "ANXA1", "CCR7"), pt.size = 0.2, ncol = 3) FeaturePlot(pbmc, features = c("CD3D", "ISG15", "TCL1A", "FCER2", "XCL1", "FCGR3A"), pt.size = 0.2, ncol = 3)Session Info sessionInfo()## R version 4.2.0 (2022-04-22) ## Platform: x86_64-pc-linux-gnu (64-bit) ## Running under: Ubuntu 20.04.5 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/liblapack.so.3 ## ## locale: ## [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C ## [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8 ## [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 ## ## attached base packages: ## [1] stats graphics grDevices utils datasets methods base ## ## other attached packages: ## [1] sctransform_0.3.5 ggplot2_3.4.1 SeuratObject_4.1.3 Seurat_4.3.0 ## ## loaded via a namespace (and not attached): ## [1] Rtsne_0.16 colorspace_2.1-0 deldir_1.0-6 ## [4] ellipsis_0.3.2 ggridges_0.5.4 rprojroot_2.0.3 ## [7] fs_1.6.1 spatstat.data_3.0-0 farver_2.1.1 ## [10] leiden_0.4.3 listenv_0.9.0 ggrepel_0.9.3 ## [13] fansi_1.0.4 R.methodsS3_1.8.2 codetools_0.2-18 ## [16] splines_4.2.0 cachem_1.0.7 knitr_1.42 ## [19] polyclip_1.10-4 jsonlite_1.8.4 ica_1.0-3 ## [22] cluster_2.1.3 R.oo_1.25.0 png_0.1-8 ## [25] uwot_0.1.14 spatstat.sparse_3.0-0 shiny_1.7.4 ## [28] compiler_4.2.0 httr_1.4.5 Matrix_1.5-3 ## [31] fastmap_1.1.1 lazyeval_0.2.2 cli_3.6.0 ## [34] later_1.3.0 formatR_1.14 htmltools_0.5.4 ## [37] tools_4.2.0 igraph_1.4.1 gtable_0.3.1 ## [40] glue_1.6.2 RANN_2.6.1 reshape2_1.4.4 ## [43] dplyr_1.1.0 Rcpp_1.0.10 scattermore_0.8 ## [46] jquerylib_0.1.4 pkgdown_2.0.7 vctrs_0.5.2 ## [49] nlme_3.1-157 spatstat.explore_3.0-6 progressr_0.13.0 ## [52] lmtest_0.9-40 spatstat.random_3.1-3 xfun_0.37 ## [55] stringr_1.5.0 globals_0.16.2 mime_0.12 ## [58] miniUI_0.1.1.1 lifecycle_1.0.3 irlba_2.3.5.1 ## [61] goftest_1.2-3 future_1.31.0 MASS_7.3-56 ## [64] zoo_1.8-11 scales_1.2.1 ragg_1.2.5 ## [67] promises_1.2.0.1 spatstat.utils_3.0-1 parallel_4.2.0 ## [70] RColorBrewer_1.1-3 yaml_2.3.7 memoise_2.0.1 ## [73] reticulate_1.28 pbapply_1.7-0 gridExtra_2.3 ## [76] sass_0.4.5 stringi_1.7.12 highr_0.10 ## [79] desc_1.4.2 rlang_1.0.6 pkgconfig_2.0.3 ## [82] systemfonts_1.0.4 matrixStats_0.63.0 evaluate_0.20 ## [85] lattice_0.20-45 tensor_1.5 ROCR_1.0-11 ## [88] purrr_1.0.1 labeling_0.4.2 patchwork_1.1.2 ## [91] htmlwidgets_1.6.1 cowplot_1.1.1 tidyselect_1.2.0 ## [94] parallelly_1.34.0 RcppAnnoy_0.0.20 plyr_1.8.8 ## [97] magrittr_2.0.3 R6_2.5.1 generics_0.1.3 ## [100] withr_2.5.0 pillar_1.8.1 fitdistrplus_1.1-8 ## [103] abind_1.4-5 survival_3.3-1 sp_1.6-0 ## [106] tibble_3.1.8 future.apply_1.10.0 KernSmooth_2.23-20 ## [109] utf8_1.2.3 spatstat.geom_3.0-6 plotly_4.10.1 ## [112] rmarkdown_2.20 grid_4.2.0 data.table_1.14.8 ## [115] digest_0.6.31 xtable_1.8-4 tidyr_1.3.0 ## [118] httpuv_1.6.9 R.utils_2.12.2 textshaping_0.3.6 ## [121] munsell_0.5.0 viridisLite_0.4.1 bslib_0.4.2

Why can we choose more PCs when using sctransform?In the standard Seurat workflow we focus on 10 PCs for this dataset, though we highlight that the results are similar with higher settings for this parameter. Interestingly, we’ve found that when using sctransform, we often benefit by pushing this parameter even higher. We believe this is because the sctransform workflow performs more effective normalization, strongly removing technical effects from the data.Even after standard log-normalization, variation in sequencing depth is still a confounding factor (see Figure 1), and this effect can subtly influence higher PCs. In sctransform, this effect is substantially mitigated (see Figure 3). This means that higher PCs are more likely to represent subtle, but biologically relevant, sources of heterogeneity – so including them may improve downstream analysis.In addition, sctransform returns 3,000 variable features by default, instead of 2,000. The rationale is similar, the additional variable features are less likely to be driven by technical differences across cells, and instead may represent more subtle biological fluctuations. In general, we find that results produced with sctransform are less dependent on these parameters (indeed, we achieve nearly identical results when using all genes in the transcriptome, though this does reduce computational efficiency). This can help users generate more robust results, and in addition, enables the application of standard analysis pipelines with identical parameter settings that can quickly be applied to new datasets:For example, the following code replicates the full end-to-end workflow, in a single command: pbmc <- CreateSeuratObject(pbmc_data) %>% PercentageFeatureSet(pattern = "^MT-", col.name = "percent.mt") %>% SCTransform(vars.to.regress = "percent.mt") %>% RunPCA() %>% FindNeighbors(dims = 1:30) %>% RunUMAP(dims = 1:30) %>% FindClusters()Where are normalized values stored for sctransform?As described in our paper, sctransform calculates a model of technical noise in scRNA-seq data using ‘regularized negative binomial regression’. The residuals for this model are normalized values, and can be positive or negative. Positive residuals for a given gene in a given cell indicate that we observed more UMIs than expected given the gene’s average expression in the population and cellular sequencing depth, while negative residuals indicate the converse.The results of sctransfrom are stored in the “SCT” assay. You can learn more about multi-assay data and commands in Seurat in our vignette, command cheat sheet, or developer guide.pbmc[["SCT"]]@scale.data contains the residuals (normalized values), and is used directly as input to PCA. Please note that this matrix is non-sparse, and can therefore take up a lot of memory if stored for all genes. To save memory, we store these values only for variable genes, by setting the return.only.var.genes = TRUE by default in the SCTransform() function call.To assist with visualization and interpretation. we also convert Pearson residuals back to ‘corrected’ UMI counts. You can interpret these as the UMI counts we would expect to observe if all cells were sequenced to the same depth. If you want to see exactly how we do this, please look at the correct function here.The ‘corrected’ UMI counts are stored in pbmc[["SCT"]]@counts. We store log-normalized versions of these corrected counts in pbmc[["SCT"]]@data, which are very helpful for visualization.You can use the corrected log-normalized counts for differential expression and integration. However, in principle, it would be most optimal to perform these calculations directly on the residuals (stored in the scale.data slot) themselves. This is not currently supported in Seurat v3, but will be soon.Users can individually annotate clusters based on canonical markers. However, the sctransform normalization reveals sharper biological distinctions compared to the standard Seurat workflow, in a few ways:Clear separation of at least 3 CD8 T cell populations (naive, memory, effector), based on CD8A, GZMK, CCL5, GZMK expressionClear separation of three CD4 T cell populations (naive, memory, IFN-activated) based on S100A4, CCR7, IL32, and ISG15Additional developmental sub-structure in B cell cluster, based on TCL1A, FCER2Additional separation of NK cells into CD56dim vs. bright clusters, based on XCL1 and FCGR3A # These are now standard steps in the Seurat workflow for visualization and clustering # Visualize canonical marker genes as violin plots. VlnPlot(pbmc, features = c("CD8A", "GZMK", "CCL5", "S100A4", "ANXA1", "CCR7", "ISG15", "CD3D"), pt.size = 0.2, ncol = 4) # Visualize canonical marker genes on the sctransform embedding. FeaturePlot(pbmc, features = c("CD8A", "GZMK", "CCL5", "S100A4", "ANXA1", "CCR7"), pt.size = 0.2, ncol = 3) FeaturePlot(pbmc, features = c("CD3D", "ISG15", "TCL1A", "FCER2", "XCL1", "FCGR3A"), pt.size = 0.2, ncol = 3)Session Info sessionInfo()## R version 4.2.0 (2022-04-22) ## Platform: x86_64-pc-linux-gnu (64-bit) ## Running under: Ubuntu 20.04.5 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/liblapack.so.3 ## ## locale: ## [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C ## [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8 ## [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 ## ## attached base packages: ## [1] stats graphics grDevices utils datasets methods base ## ## other attached packages: ## [1] sctransform_0.3.5 ggplot2_3.4.1 SeuratObject_4.1.3 Seurat_4.3.0 ## ## loaded via a namespace (and not attached): ## [1] Rtsne_0.16 colorspace_2.1-0 deldir_1.0-6 ## [4] ellipsis_0.3.2 ggridges_0.5.4 rprojroot_2.0.3 ## [7] fs_1.6.1 spatstat.data_3.0-0 farver_2.1.1 ## [10] leiden_0.4.3 listenv_0.9.0 ggrepel_0.9.3 ## [13] fansi_1.0.4 R.methodsS3_1.8.2 codetools_0.2-18 ## [16] splines_4.2.0 cachem_1.0.7 knitr_1.42 ## [19] polyclip_1.10-4 jsonlite_1.8.4 ica_1.0-3 ## [22] cluster_2.1.3 R.oo_1.25.0 png_0.1-8 ## [25] uwot_0.1.14 spatstat.sparse_3.0-0 shiny_1.7.4 ## [28] compiler_4.2.0 httr_1.4.5 Matrix_1.5-3 ## [31] fastmap_1.1.1 lazyeval_0.2.2 cli_3.6.0 ## [34] later_1.3.0 formatR_1.14 htmltools_0.5.4 ## [37] tools_4.2.0 igraph_1.4.1 gtable_0.3.1 ## [40] glue_1.6.2 RANN_2.6.1 reshape2_1.4.4 ## [43] dplyr_1.1.0 Rcpp_1.0.10 scattermore_0.8 ## [46] jquerylib_0.1.4 pkgdown_2.0.7 vctrs_0.5.2 ## [49] nlme_3.1-157 spatstat.explore_3.0-6 progressr_0.13.0 ## [52] lmtest_0.9-40 spatstat.random_3.1-3 xfun_0.37 ## [55] stringr_1.5.0 globals_0.16.2 mime_0.12 ## [58] miniUI_0.1.1.1 lifecycle_1.0.3 irlba_2.3.5.1 ## [61] goftest_1.2-3 future_1.31.0 MASS_7.3-56 ## [64] zoo_1.8-11 scales_1.2.1 ragg_1.2.5 ## [67] promises_1.2.0.1 spatstat.utils_3.0-1 parallel_4.2.0 ## [70] RColorBrewer_1.1-3 yaml_2.3.7 memoise_2.0.1 ## [73] reticulate_1.28 pbapply_1.7-0 gridExtra_2.3 ## [76] sass_0.4.5 stringi_1.7.12 highr_0.10 ## [79] desc_1.4.2 rlang_1.0.6 pkgconfig_2.0.3 ## [82] systemfonts_1.0.4 matrixStats_0.63.0 evaluate_0.20 ## [85] lattice_0.20-45 tensor_1.5 ROCR_1.0-11 ## [88] purrr_1.0.1 labeling_0.4.2 patchwork_1.1.2 ## [91] htmlwidgets_1.6.1 cowplot_1.1.1 tidyselect_1.2.0 ## [94] parallelly_1.34.0 RcppAnnoy_0.0.20 plyr_1.8.8 ## [97] magrittr_2.0.3 R6_2.5.1 generics_0.1.3 ## [100] withr_2.5.0 pillar_1.8.1 fitdistrplus_1.1-8 ## [103] abind_1.4-5 survival_3.3-1 sp_1.6-0 ## [106] tibble_3.1.8 future.apply_1.10.0 KernSmooth_2.23-20 ## [109] utf8_1.2.3 spatstat.geom_3.0-6 plotly_4.10.1 ## [112] rmarkdown_2.20 grid_4.2.0 data.table_1.14.8 ## [115] digest_0.6.31 xtable_1.8-4 tidyr_1.3.0 ## [118] httpuv_1.6.9 R.utils_2.12.2 textshaping_0.3.6 ## [121] munsell_0.5.0 viridisLite_0.4.1 bslib_0.4.2

In the standard Seurat workflow we focus on 10 PCs for this dataset, though we highlight that the results are similar with higher settings for this parameter. Interestingly, we’ve found that when using sctransform, we often benefit by pushing this parameter even higher. We believe this is because the sctransform workflow performs more effective normalization, strongly removing technical effects from the data.Even after standard log-normalization, variation in sequencing depth is still a confounding factor (see Figure 1), and this effect can subtly influence higher PCs. In sctransform, this effect is substantially mitigated (see Figure 3). This means that higher PCs are more likely to represent subtle, but biologically relevant, sources of heterogeneity – so including them may improve downstream analysis.In addition, sctransform returns 3,000 variable features by default, instead of 2,000. The rationale is similar, the additional variable features are less likely to be driven by technical differences across cells, and instead may represent more subtle biological fluctuations. In general, we find that results produced with sctransform are less dependent on these parameters (indeed, we achieve nearly identical results when using all genes in the transcriptome, though this does reduce computational efficiency). This can help users generate more robust results, and in addition, enables the application of standard analysis pipelines with identical parameter settings that can quickly be applied to new datasets:For example, the following code replicates the full end-to-end workflow, in a single command: pbmc <- CreateSeuratObject(pbmc_data) %>% PercentageFeatureSet(pattern = "^MT-", col.name = "percent.mt") %>% SCTransform(vars.to.regress = "percent.mt") %>% RunPCA() %>% FindNeighbors(dims = 1:30) %>% RunUMAP(dims = 1:30) %>% FindClusters()

In the standard Seurat workflow we focus on 10 PCs for this dataset, though we highlight that the results are similar with higher settings for this parameter. Interestingly, we’ve found that when using sctransform, we often benefit by pushing this parameter even higher. We believe this is because the sctransform workflow performs more effective normalization, strongly removing technical effects from the data.Even after standard log-normalization, variation in sequencing depth is still a confounding factor (see Figure 1), and this effect can subtly influence higher PCs. In sctransform, this effect is substantially mitigated (see Figure 3). This means that higher PCs are more likely to represent subtle, but biologically relevant, sources of heterogeneity – so including them may improve downstream analysis.In addition, sctransform returns 3,000 variable features by default, instead of 2,000. The rationale is similar, the additional variable features are less likely to be driven by technical differences across cells, and instead may represent more subtle biological fluctuations. In general, we find that results produced with sctransform are less dependent on these parameters (indeed, we achieve nearly identical results when using all genes in the transcriptome, though this does reduce computational efficiency). This can help users generate more robust results, and in addition, enables the application of standard analysis pipelines with identical parameter settings that can quickly be applied to new datasets:For example, the following code replicates the full end-to-end workflow, in a single command: pbmc <- CreateSeuratObject(pbmc_data) %>% PercentageFeatureSet(pattern = "^MT-", col.name = "percent.mt") %>% SCTransform(vars.to.regress = "percent.mt") %>% RunPCA() %>% FindNeighbors(dims = 1:30) %>% RunUMAP(dims = 1:30) %>% FindClusters()

Even after standard log-normalization, variation in sequencing depth is still a confounding factor (see Figure 1), and this effect can subtly influence higher PCs. In sctransform, this effect is substantially mitigated (see Figure 3). This means that higher PCs are more likely to represent subtle, but biologically relevant, sources of heterogeneity – so including them may improve downstream analysis.In addition, sctransform returns 3,000 variable features by default, instead of 2,000. The rationale is similar, the additional variable features are less likely to be driven by technical differences across cells, and instead may represent more subtle biological fluctuations. In general, we find that results produced with sctransform are less dependent on these parameters (indeed, we achieve nearly identical results when using all genes in the transcriptome, though this does reduce computational efficiency). This can help users generate more robust results, and in addition, enables the application of standard analysis pipelines with identical parameter settings that can quickly be applied to new datasets:For example, the following code replicates the full end-to-end workflow, in a single command: pbmc <- CreateSeuratObject(pbmc_data) %>% PercentageFeatureSet(pattern = "^MT-", col.name = "percent.mt") %>% SCTransform(vars.to.regress = "percent.mt") %>% RunPCA() %>% FindNeighbors(dims = 1:30) %>% RunUMAP(dims = 1:30) %>% FindClusters()

In addition, sctransform returns 3,000 variable features by default, instead of 2,000. The rationale is similar, the additional variable features are less likely to be driven by technical differences across cells, and instead may represent more subtle biological fluctuations. In general, we find that results produced with sctransform are less dependent on these parameters (indeed, we achieve nearly identical results when using all genes in the transcriptome, though this does reduce computational efficiency). This can help users generate more robust results, and in addition, enables the application of standard analysis pipelines with identical parameter settings that can quickly be applied to new datasets:For example, the following code replicates the full end-to-end workflow, in a single command: pbmc <- CreateSeuratObject(pbmc_data) %>% PercentageFeatureSet(pattern = "^MT-", col.name = "percent.mt") %>% SCTransform(vars.to.regress = "percent.mt") %>% RunPCA() %>% FindNeighbors(dims = 1:30) %>% RunUMAP(dims = 1:30) %>% FindClusters()

For example, the following code replicates the full end-to-end workflow, in a single command: pbmc <- CreateSeuratObject(pbmc_data) %>% PercentageFeatureSet(pattern = "^MT-", col.name = "percent.mt") %>% SCTransform(vars.to.regress = "percent.mt") %>% RunPCA() %>% FindNeighbors(dims = 1:30) %>% RunUMAP(dims = 1:30) %>% FindClusters()

As described in our paper, sctransform calculates a model of technical noise in scRNA-seq data using ‘regularized negative binomial regression’. The residuals for this model are normalized values, and can be positive or negative. Positive residuals for a given gene in a given cell indicate that we observed more UMIs than expected given the gene’s average expression in the population and cellular sequencing depth, while negative residuals indicate the converse.The results of sctransfrom are stored in the “SCT” assay. You can learn more about multi-assay data and commands in Seurat in our vignette, command cheat sheet, or developer guide.pbmc[["SCT"]]@scale.data contains the residuals (normalized values), and is used directly as input to PCA. Please note that this matrix is non-sparse, and can therefore take up a lot of memory if stored for all genes. To save memory, we store these values only for variable genes, by setting the return.only.var.genes = TRUE by default in the SCTransform() function call.To assist with visualization and interpretation. we also convert Pearson residuals back to ‘corrected’ UMI counts. You can interpret these as the UMI counts we would expect to observe if all cells were sequenced to the same depth. If you want to see exactly how we do this, please look at the correct function here.The ‘corrected’ UMI counts are stored in pbmc[["SCT"]]@counts. We store log-normalized versions of these corrected counts in pbmc[["SCT"]]@data, which are very helpful for visualization.You can use the corrected log-normalized counts for differential expression and integration. However, in principle, it would be most optimal to perform these calculations directly on the residuals (stored in the scale.data slot) themselves. This is not currently supported in Seurat v3, but will be soon.

As described in our paper, sctransform calculates a model of technical noise in scRNA-seq data using ‘regularized negative binomial regression’. The residuals for this model are normalized values, and can be positive or negative. Positive residuals for a given gene in a given cell indicate that we observed more UMIs than expected given the gene’s average expression in the population and cellular sequencing depth, while negative residuals indicate the converse.The results of sctransfrom are stored in the “SCT” assay. You can learn more about multi-assay data and commands in Seurat in our vignette, command cheat sheet, or developer guide.pbmc[["SCT"]]@scale.data contains the residuals (normalized values), and is used directly as input to PCA. Please note that this matrix is non-sparse, and can therefore take up a lot of memory if stored for all genes. To save memory, we store these values only for variable genes, by setting the return.only.var.genes = TRUE by default in the SCTransform() function call.To assist with visualization and interpretation. we also convert Pearson residuals back to ‘corrected’ UMI counts. You can interpret these as the UMI counts we would expect to observe if all cells were sequenced to the same depth. If you want to see exactly how we do this, please look at the correct function here.The ‘corrected’ UMI counts are stored in pbmc[["SCT"]]@counts. We store log-normalized versions of these corrected counts in pbmc[["SCT"]]@data, which are very helpful for visualization.You can use the corrected log-normalized counts for differential expression and integration. However, in principle, it would be most optimal to perform these calculations directly on the residuals (stored in the scale.data slot) themselves. This is not currently supported in Seurat v3, but will be soon.

The results of sctransfrom are stored in the “SCT” assay. You can learn more about multi-assay data and commands in Seurat in our vignette, command cheat sheet, or developer guide.pbmc[["SCT"]]@scale.data contains the residuals (normalized values), and is used directly as input to PCA. Please note that this matrix is non-sparse, and can therefore take up a lot of memory if stored for all genes. To save memory, we store these values only for variable genes, by setting the return.only.var.genes = TRUE by default in the SCTransform() function call.To assist with visualization and interpretation. we also convert Pearson residuals back to ‘corrected’ UMI counts. You can interpret these as the UMI counts we would expect to observe if all cells were sequenced to the same depth. If you want to see exactly how we do this, please look at the correct function here.The ‘corrected’ UMI counts are stored in pbmc[["SCT"]]@counts. We store log-normalized versions of these corrected counts in pbmc[["SCT"]]@data, which are very helpful for visualization.You can use the corrected log-normalized counts for differential expression and integration. However, in principle, it would be most optimal to perform these calculations directly on the residuals (stored in the scale.data slot) themselves. This is not currently supported in Seurat v3, but will be soon.

Users can individually annotate clusters based on canonical markers. However, the sctransform normalization reveals sharper biological distinctions compared to the standard Seurat workflow, in a few ways:Clear separation of at least 3 CD8 T cell populations (naive, memory, effector), based on CD8A, GZMK, CCL5, GZMK expressionClear separation of three CD4 T cell populations (naive, memory, IFN-activated) based on S100A4, CCR7, IL32, and ISG15Additional developmental sub-structure in B cell cluster, based on TCL1A, FCER2Additional separation of NK cells into CD56dim vs. bright clusters, based on XCL1 and FCGR3A # These are now standard steps in the Seurat workflow for visualization and clustering # Visualize canonical marker genes as violin plots. VlnPlot(pbmc, features = c("CD8A", "GZMK", "CCL5", "S100A4", "ANXA1", "CCR7", "ISG15", "CD3D"), pt.size = 0.2, ncol = 4) # Visualize canonical marker genes on the sctransform embedding. FeaturePlot(pbmc, features = c("CD8A", "GZMK", "CCL5", "S100A4", "ANXA1", "CCR7"), pt.size = 0.2, ncol = 3) FeaturePlot(pbmc, features = c("CD3D", "ISG15", "TCL1A", "FCER2", "XCL1", "FCGR3A"), pt.size = 0.2, ncol = 3)Session Info sessionInfo()## R version 4.2.0 (2022-04-22) ## Platform: x86_64-pc-linux-gnu (64-bit) ## Running under: Ubuntu 20.04.5 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/liblapack.so.3 ## ## locale: ## [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C ## [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8 ## [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 ## ## attached base packages: ## [1] stats graphics grDevices utils datasets methods base ## ## other attached packages: ## [1] sctransform_0.3.5 ggplot2_3.4.1 SeuratObject_4.1.3 Seurat_4.3.0 ## ## loaded via a namespace (and not attached): ## [1] Rtsne_0.16 colorspace_2.1-0 deldir_1.0-6 ## [4] ellipsis_0.3.2 ggridges_0.5.4 rprojroot_2.0.3 ## [7] fs_1.6.1 spatstat.data_3.0-0 farver_2.1.1 ## [10] leiden_0.4.3 listenv_0.9.0 ggrepel_0.9.3 ## [13] fansi_1.0.4 R.methodsS3_1.8.2 codetools_0.2-18 ## [16] splines_4.2.0 cachem_1.0.7 knitr_1.42 ## [19] polyclip_1.10-4 jsonlite_1.8.4 ica_1.0-3 ## [22] cluster_2.1.3 R.oo_1.25.0 png_0.1-8 ## [25] uwot_0.1.14 spatstat.sparse_3.0-0 shiny_1.7.4 ## [28] compiler_4.2.0 httr_1.4.5 Matrix_1.5-3 ## [31] fastmap_1.1.1 lazyeval_0.2.2 cli_3.6.0 ## [34] later_1.3.0 formatR_1.14 htmltools_0.5.4 ## [37] tools_4.2.0 igraph_1.4.1 gtable_0.3.1 ## [40] glue_1.6.2 RANN_2.6.1 reshape2_1.4.4 ## [43] dplyr_1.1.0 Rcpp_1.0.10 scattermore_0.8 ## [46] jquerylib_0.1.4 pkgdown_2.0.7 vctrs_0.5.2 ## [49] nlme_3.1-157 spatstat.explore_3.0-6 progressr_0.13.0 ## [52] lmtest_0.9-40 spatstat.random_3.1-3 xfun_0.37 ## [55] stringr_1.5.0 globals_0.16.2 mime_0.12 ## [58] miniUI_0.1.1.1 lifecycle_1.0.3 irlba_2.3.5.1 ## [61] goftest_1.2-3 future_1.31.0 MASS_7.3-56 ## [64] zoo_1.8-11 scales_1.2.1 ragg_1.2.5 ## [67] promises_1.2.0.1 spatstat.utils_3.0-1 parallel_4.2.0 ## [70] RColorBrewer_1.1-3 yaml_2.3.7 memoise_2.0.1 ## [73] reticulate_1.28 pbapply_1.7-0 gridExtra_2.3 ## [76] sass_0.4.5 stringi_1.7.12 highr_0.10 ## [79] desc_1.4.2 rlang_1.0.6 pkgconfig_2.0.3 ## [82] systemfonts_1.0.4 matrixStats_0.63.0 evaluate_0.20 ## [85] lattice_0.20-45 tensor_1.5 ROCR_1.0-11 ## [88] purrr_1.0.1 labeling_0.4.2 patchwork_1.1.2 ## [91] htmlwidgets_1.6.1 cowplot_1.1.1 tidyselect_1.2.0 ## [94] parallelly_1.34.0 RcppAnnoy_0.0.20 plyr_1.8.8 ## [97] magrittr_2.0.3 R6_2.5.1 generics_0.1.3 ## [100] withr_2.5.0 pillar_1.8.1 fitdistrplus_1.1-8 ## [103] abind_1.4-5 survival_3.3-1 sp_1.6-0 ## [106] tibble_3.1.8 future.apply_1.10.0 KernSmooth_2.23-20 ## [109] utf8_1.2.3 spatstat.geom_3.0-6 plotly_4.10.1 ## [112] rmarkdown_2.20 grid_4.2.0 data.table_1.14.8 ## [115] digest_0.6.31 xtable_1.8-4 tidyr_1.3.0 ## [118] httpuv_1.6.9 R.utils_2.12.2 textshaping_0.3.6 ## [121] munsell_0.5.0 viridisLite_0.4.1 bslib_0.4.2

Users can individually annotate clusters based on canonical markers. However, the sctransform normalization reveals sharper biological distinctions compared to the standard Seurat workflow, in a few ways:Clear separation of at least 3 CD8 T cell populations (naive, memory, effector), based on CD8A, GZMK, CCL5, GZMK expressionClear separation of three CD4 T cell populations (naive, memory, IFN-activated) based on S100A4, CCR7, IL32, and ISG15Additional developmental sub-structure in B cell cluster, based on TCL1A, FCER2Additional separation of NK cells into CD56dim vs. bright clusters, based on XCL1 and FCGR3A # These are now standard steps in the Seurat workflow for visualization and clustering # Visualize canonical marker genes as violin plots. VlnPlot(pbmc, features = c("CD8A", "GZMK", "CCL5", "S100A4", "ANXA1", "CCR7", "ISG15", "CD3D"), pt.size = 0.2, ncol = 4) # Visualize canonical marker genes on the sctransform embedding. FeaturePlot(pbmc, features = c("CD8A", "GZMK", "CCL5", "S100A4", "ANXA1", "CCR7"), pt.size = 0.2, ncol = 3) FeaturePlot(pbmc, features = c("CD3D", "ISG15", "TCL1A", "FCER2", "XCL1", "FCGR3A"), pt.size = 0.2, ncol = 3)Session Info sessionInfo()## R version 4.2.0 (2022-04-22) ## Platform: x86_64-pc-linux-gnu (64-bit) ## Running under: Ubuntu 20.04.5 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/liblapack.so.3 ## ## locale: ## [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C ## [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8 ## [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 ## ## attached base packages: ## [1] stats graphics grDevices utils datasets methods base ## ## other attached packages: ## [1] sctransform_0.3.5 ggplot2_3.4.1 SeuratObject_4.1.3 Seurat_4.3.0 ## ## loaded via a namespace (and not attached): ## [1] Rtsne_0.16 colorspace_2.1-0 deldir_1.0-6 ## [4] ellipsis_0.3.2 ggridges_0.5.4 rprojroot_2.0.3 ## [7] fs_1.6.1 spatstat.data_3.0-0 farver_2.1.1 ## [10] leiden_0.4.3 listenv_0.9.0 ggrepel_0.9.3 ## [13] fansi_1.0.4 R.methodsS3_1.8.2 codetools_0.2-18 ## [16] splines_4.2.0 cachem_1.0.7 knitr_1.42 ## [19] polyclip_1.10-4 jsonlite_1.8.4 ica_1.0-3 ## [22] cluster_2.1.3 R.oo_1.25.0 png_0.1-8 ## [25] uwot_0.1.14 spatstat.sparse_3.0-0 shiny_1.7.4 ## [28] compiler_4.2.0 httr_1.4.5 Matrix_1.5-3 ## [31] fastmap_1.1.1 lazyeval_0.2.2 cli_3.6.0 ## [34] later_1.3.0 formatR_1.14 htmltools_0.5.4 ## [37] tools_4.2.0 igraph_1.4.1 gtable_0.3.1 ## [40] glue_1.6.2 RANN_2.6.1 reshape2_1.4.4 ## [43] dplyr_1.1.0 Rcpp_1.0.10 scattermore_0.8 ## [46] jquerylib_0.1.4 pkgdown_2.0.7 vctrs_0.5.2 ## [49] nlme_3.1-157 spatstat.explore_3.0-6 progressr_0.13.0 ## [52] lmtest_0.9-40 spatstat.random_3.1-3 xfun_0.37 ## [55] stringr_1.5.0 globals_0.16.2 mime_0.12 ## [58] miniUI_0.1.1.1 lifecycle_1.0.3 irlba_2.3.5.1 ## [61] goftest_1.2-3 future_1.31.0 MASS_7.3-56 ## [64] zoo_1.8-11 scales_1.2.1 ragg_1.2.5 ## [67] promises_1.2.0.1 spatstat.utils_3.0-1 parallel_4.2.0 ## [70] RColorBrewer_1.1-3 yaml_2.3.7 memoise_2.0.1 ## [73] reticulate_1.28 pbapply_1.7-0 gridExtra_2.3 ## [76] sass_0.4.5 stringi_1.7.12 highr_0.10 ## [79] desc_1.4.2 rlang_1.0.6 pkgconfig_2.0.3 ## [82] systemfonts_1.0.4 matrixStats_0.63.0 evaluate_0.20 ## [85] lattice_0.20-45 tensor_1.5 ROCR_1.0-11 ## [88] purrr_1.0.1 labeling_0.4.2 patchwork_1.1.2 ## [91] htmlwidgets_1.6.1 cowplot_1.1.1 tidyselect_1.2.0 ## [94] parallelly_1.34.0 RcppAnnoy_0.0.20 plyr_1.8.8 ## [97] magrittr_2.0.3 R6_2.5.1 generics_0.1.3 ## [100] withr_2.5.0 pillar_1.8.1 fitdistrplus_1.1-8 ## [103] abind_1.4-5 survival_3.3-1 sp_1.6-0 ## [106] tibble_3.1.8 future.apply_1.10.0 KernSmooth_2.23-20 ## [109] utf8_1.2.3 spatstat.geom_3.0-6 plotly_4.10.1 ## [112] rmarkdown_2.20 grid_4.2.0 data.table_1.14.8 ## [115] digest_0.6.31 xtable_1.8-4 tidyr_1.3.0 ## [118] httpuv_1.6.9 R.utils_2.12.2 textshaping_0.3.6 ## [121] munsell_0.5.0 viridisLite_0.4.1 bslib_0.4.2

# Visualize canonical marker genes on the sctransform embedding. FeaturePlot(pbmc, features = c("CD8A", "GZMK", "CCL5", "S100A4", "ANXA1", "CCR7"), pt.size = 0.2, ncol = 3) FeaturePlot(pbmc, features = c("CD3D", "ISG15", "TCL1A", "FCER2", "XCL1", "FCGR3A"), pt.size = 0.2, ncol = 3)Session Info sessionInfo()## R version 4.2.0 (2022-04-22) ## Platform: x86_64-pc-linux-gnu (64-bit) ## Running under: Ubuntu 20.04.5 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/liblapack.so.3 ## ## locale: ## [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C ## [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8 ## [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 ## ## attached base packages: ## [1] stats graphics grDevices utils datasets methods base ## ## other attached packages: ## [1] sctransform_0.3.5 ggplot2_3.4.1 SeuratObject_4.1.3 Seurat_4.3.0 ## ## loaded via a namespace (and not attached): ## [1] Rtsne_0.16 colorspace_2.1-0 deldir_1.0-6 ## [4] ellipsis_0.3.2 ggridges_0.5.4 rprojroot_2.0.3 ## [7] fs_1.6.1 spatstat.data_3.0-0 farver_2.1.1 ## [10] leiden_0.4.3 listenv_0.9.0 ggrepel_0.9.3 ## [13] fansi_1.0.4 R.methodsS3_1.8.2 codetools_0.2-18 ## [16] splines_4.2.0 cachem_1.0.7 knitr_1.42 ## [19] polyclip_1.10-4 jsonlite_1.8.4 ica_1.0-3 ## [22] cluster_2.1.3 R.oo_1.25.0 png_0.1-8 ## [25] uwot_0.1.14 spatstat.sparse_3.0-0 shiny_1.7.4 ## [28] compiler_4.2.0 httr_1.4.5 Matrix_1.5-3 ## [31] fastmap_1.1.1 lazyeval_0.2.2 cli_3.6.0 ## [34] later_1.3.0 formatR_1.14 htmltools_0.5.4 ## [37] tools_4.2.0 igraph_1.4.1 gtable_0.3.1 ## [40] glue_1.6.2 RANN_2.6.1 reshape2_1.4.4 ## [43] dplyr_1.1.0 Rcpp_1.0.10 scattermore_0.8 ## [46] jquerylib_0.1.4 pkgdown_2.0.7 vctrs_0.5.2 ## [49] nlme_3.1-157 spatstat.explore_3.0-6 progressr_0.13.0 ## [52] lmtest_0.9-40 spatstat.random_3.1-3 xfun_0.37 ## [55] stringr_1.5.0 globals_0.16.2 mime_0.12 ## [58] miniUI_0.1.1.1 lifecycle_1.0.3 irlba_2.3.5.1 ## [61] goftest_1.2-3 future_1.31.0 MASS_7.3-56 ## [64] zoo_1.8-11 scales_1.2.1 ragg_1.2.5 ## [67] promises_1.2.0.1 spatstat.utils_3.0-1 parallel_4.2.0 ## [70] RColorBrewer_1.1-3 yaml_2.3.7 memoise_2.0.1 ## [73] reticulate_1.28 pbapply_1.7-0 gridExtra_2.3 ## [76] sass_0.4.5 stringi_1.7.12 highr_0.10 ## [79] desc_1.4.2 rlang_1.0.6 pkgconfig_2.0.3 ## [82] systemfonts_1.0.4 matrixStats_0.63.0 evaluate_0.20 ## [85] lattice_0.20-45 tensor_1.5 ROCR_1.0-11 ## [88] purrr_1.0.1 labeling_0.4.2 patchwork_1.1.2 ## [91] htmlwidgets_1.6.1 cowplot_1.1.1 tidyselect_1.2.0 ## [94] parallelly_1.34.0 RcppAnnoy_0.0.20 plyr_1.8.8 ## [97] magrittr_2.0.3 R6_2.5.1 generics_0.1.3 ## [100] withr_2.5.0 pillar_1.8.1 fitdistrplus_1.1-8 ## [103] abind_1.4-5 survival_3.3-1 sp_1.6-0 ## [106] tibble_3.1.8 future.apply_1.10.0 KernSmooth_2.23-20 ## [109] utf8_1.2.3 spatstat.geom_3.0-6 plotly_4.10.1 ## [112] rmarkdown_2.20 grid_4.2.0 data.table_1.14.8 ## [115] digest_0.6.31 xtable_1.8-4 tidyr_1.3.0 ## [118] httpuv_1.6.9 R.utils_2.12.2 textshaping_0.3.6 ## [121] munsell_0.5.0 viridisLite_0.4.1 bslib_0.4.2

FeaturePlot(pbmc, features = c("CD3D", "ISG15", "TCL1A", "FCER2", "XCL1", "FCGR3A"), pt.size = 0.2, ncol = 3)Session Info sessionInfo()## R version 4.2.0 (2022-04-22) ## Platform: x86_64-pc-linux-gnu (64-bit) ## Running under: Ubuntu 20.04.5 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/liblapack.so.3 ## ## locale: ## [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C ## [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8 ## [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 ## ## attached base packages: ## [1] stats graphics grDevices utils datasets methods base ## ## other attached packages: ## [1] sctransform_0.3.5 ggplot2_3.4.1 SeuratObject_4.1.3 Seurat_4.3.0 ## ## loaded via a namespace (and not attached): ## [1] Rtsne_0.16 colorspace_2.1-0 deldir_1.0-6 ## [4] ellipsis_0.3.2 ggridges_0.5.4 rprojroot_2.0.3 ## [7] fs_1.6.1 spatstat.data_3.0-0 farver_2.1.1 ## [10] leiden_0.4.3 listenv_0.9.0 ggrepel_0.9.3 ## [13] fansi_1.0.4 R.methodsS3_1.8.2 codetools_0.2-18 ## [16] splines_4.2.0 cachem_1.0.7 knitr_1.42 ## [19] polyclip_1.10-4 jsonlite_1.8.4 ica_1.0-3 ## [22] cluster_2.1.3 R.oo_1.25.0 png_0.1-8 ## [25] uwot_0.1.14 spatstat.sparse_3.0-0 shiny_1.7.4 ## [28] compiler_4.2.0 httr_1.4.5 Matrix_1.5-3 ## [31] fastmap_1.1.1 lazyeval_0.2.2 cli_3.6.0 ## [34] later_1.3.0 formatR_1.14 htmltools_0.5.4 ## [37] tools_4.2.0 igraph_1.4.1 gtable_0.3.1 ## [40] glue_1.6.2 RANN_2.6.1 reshape2_1.4.4 ## [43] dplyr_1.1.0 Rcpp_1.0.10 scattermore_0.8 ## [46] jquerylib_0.1.4 pkgdown_2.0.7 vctrs_0.5.2 ## [49] nlme_3.1-157 spatstat.explore_3.0-6 progressr_0.13.0 ## [52] lmtest_0.9-40 spatstat.random_3.1-3 xfun_0.37 ## [55] stringr_1.5.0 globals_0.16.2 mime_0.12 ## [58] miniUI_0.1.1.1 lifecycle_1.0.3 irlba_2.3.5.1 ## [61] goftest_1.2-3 future_1.31.0 MASS_7.3-56 ## [64] zoo_1.8-11 scales_1.2.1 ragg_1.2.5 ## [67] promises_1.2.0.1 spatstat.utils_3.0-1 parallel_4.2.0 ## [70] RColorBrewer_1.1-3 yaml_2.3.7 memoise_2.0.1 ## [73] reticulate_1.28 pbapply_1.7-0 gridExtra_2.3 ## [76] sass_0.4.5 stringi_1.7.12 highr_0.10 ## [79] desc_1.4.2 rlang_1.0.6 pkgconfig_2.0.3 ## [82] systemfonts_1.0.4 matrixStats_0.63.0 evaluate_0.20 ## [85] lattice_0.20-45 tensor_1.5 ROCR_1.0-11 ## [88] purrr_1.0.1 labeling_0.4.2 patchwork_1.1.2 ## [91] htmlwidgets_1.6.1 cowplot_1.1.1 tidyselect_1.2.0 ## [94] parallelly_1.34.0 RcppAnnoy_0.0.20 plyr_1.8.8 ## [97] magrittr_2.0.3 R6_2.5.1 generics_0.1.3 ## [100] withr_2.5.0 pillar_1.8.1 fitdistrplus_1.1-8 ## [103] abind_1.4-5 survival_3.3-1 sp_1.6-0 ## [106] tibble_3.1.8 future.apply_1.10.0 KernSmooth_2.23-20 ## [109] utf8_1.2.3 spatstat.geom_3.0-6 plotly_4.10.1 ## [112] rmarkdown_2.20 grid_4.2.0 data.table_1.14.8 ## [115] digest_0.6.31 xtable_1.8-4 tidyr_1.3.0 ## [118] httpuv_1.6.9 R.utils_2.12.2 textshaping_0.3.6 ## [121] munsell_0.5.0 viridisLite_0.4.1 bslib_0.4.2

Session Info sessionInfo()## R version 4.2.0 (2022-04-22) ## Platform: x86_64-pc-linux-gnu (64-bit) ## Running under: Ubuntu 20.04.5 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/liblapack.so.3 ## ## locale: ## [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C ## [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8 ## [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 ## ## attached base packages: ## [1] stats graphics grDevices utils datasets methods base ## ## other attached packages: ## [1] sctransform_0.3.5 ggplot2_3.4.1 SeuratObject_4.1.3 Seurat_4.3.0 ## ## loaded via a namespace (and not attached): ## [1] Rtsne_0.16 colorspace_2.1-0 deldir_1.0-6 ## [4] ellipsis_0.3.2 ggridges_0.5.4 rprojroot_2.0.3 ## [7] fs_1.6.1 spatstat.data_3.0-0 farver_2.1.1 ## [10] leiden_0.4.3 listenv_0.9.0 ggrepel_0.9.3 ## [13] fansi_1.0.4 R.methodsS3_1.8.2 codetools_0.2-18 ## [16] splines_4.2.0 cachem_1.0.7 knitr_1.42 ## [19] polyclip_1.10-4 jsonlite_1.8.4 ica_1.0-3 ## [22] cluster_2.1.3 R.oo_1.25.0 png_0.1-8 ## [25] uwot_0.1.14 spatstat.sparse_3.0-0 shiny_1.7.4 ## [28] compiler_4.2.0 httr_1.4.5 Matrix_1.5-3 ## [31] fastmap_1.1.1 lazyeval_0.2.2 cli_3.6.0 ## [34] later_1.3.0 formatR_1.14 htmltools_0.5.4 ## [37] tools_4.2.0 igraph_1.4.1 gtable_0.3.1 ## [40] glue_1.6.2 RANN_2.6.1 reshape2_1.4.4 ## [43] dplyr_1.1.0 Rcpp_1.0.10 scattermore_0.8 ## [46] jquerylib_0.1.4 pkgdown_2.0.7 vctrs_0.5.2 ## [49] nlme_3.1-157 spatstat.explore_3.0-6 progressr_0.13.0 ## [52] lmtest_0.9-40 spatstat.random_3.1-3 xfun_0.37 ## [55] stringr_1.5.0 globals_0.16.2 mime_0.12 ## [58] miniUI_0.1.1.1 lifecycle_1.0.3 irlba_2.3.5.1 ## [61] goftest_1.2-3 future_1.31.0 MASS_7.3-56 ## [64] zoo_1.8-11 scales_1.2.1 ragg_1.2.5 ## [67] promises_1.2.0.1 spatstat.utils_3.0-1 parallel_4.2.0 ## [70] RColorBrewer_1.1-3 yaml_2.3.7 memoise_2.0.1 ## [73] reticulate_1.28 pbapply_1.7-0 gridExtra_2.3 ## [76] sass_0.4.5 stringi_1.7.12 highr_0.10 ## [79] desc_1.4.2 rlang_1.0.6 pkgconfig_2.0.3 ## [82] systemfonts_1.0.4 matrixStats_0.63.0 evaluate_0.20 ## [85] lattice_0.20-45 tensor_1.5 ROCR_1.0-11 ## [88] purrr_1.0.1 labeling_0.4.2 patchwork_1.1.2 ## [91] htmlwidgets_1.6.1 cowplot_1.1.1 tidyselect_1.2.0 ## [94] parallelly_1.34.0 RcppAnnoy_0.0.20 plyr_1.8.8 ## [97] magrittr_2.0.3 R6_2.5.1 generics_0.1.3 ## [100] withr_2.5.0 pillar_1.8.1 fitdistrplus_1.1-8 ## [103] abind_1.4-5 survival_3.3-1 sp_1.6-0 ## [106] tibble_3.1.8 future.apply_1.10.0 KernSmooth_2.23-20 ## [109] utf8_1.2.3 spatstat.geom_3.0-6 plotly_4.10.1 ## [112] rmarkdown_2.20 grid_4.2.0 data.table_1.14.8 ## [115] digest_0.6.31 xtable_1.8-4 tidyr_1.3.0 ## [118] httpuv_1.6.9 R.utils_2.12.2 textshaping_0.3.6 ## [121] munsell_0.5.0 viridisLite_0.4.1 bslib_0.4.2

sessionInfo()## R version 4.2.0 (2022-04-22) ## Platform: x86_64-pc-linux-gnu (64-bit) ## Running under: Ubuntu 20.04.5 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/liblapack.so.3 ## ## locale: ## [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C ## [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8 ## [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 ## ## attached base packages: ## [1] stats graphics grDevices utils datasets methods base ## ## other attached packages: ## [1] sctransform_0.3.5 ggplot2_3.4.1 SeuratObject_4.1.3 Seurat_4.3.0 ## ## loaded via a namespace (and not attached): ## [1] Rtsne_0.16 colorspace_2.1-0 deldir_1.0-6 ## [4] ellipsis_0.3.2 ggridges_0.5.4 rprojroot_2.0.3 ## [7] fs_1.6.1 spatstat.data_3.0-0 farver_2.1.1 ## [10] leiden_0.4.3 listenv_0.9.0 ggrepel_0.9.3 ## [13] fansi_1.0.4 R.methodsS3_1.8.2 codetools_0.2-18 ## [16] splines_4.2.0 cachem_1.0.7 knitr_1.42 ## [19] polyclip_1.10-4 jsonlite_1.8.4 ica_1.0-3 ## [22] cluster_2.1.3 R.oo_1.25.0 png_0.1-8 ## [25] uwot_0.1.14 spatstat.sparse_3.0-0 shiny_1.7.4 ## [28] compiler_4.2.0 httr_1.4.5 Matrix_1.5-3 ## [31] fastmap_1.1.1 lazyeval_0.2.2 cli_3.6.0 ## [34] later_1.3.0 formatR_1.14 htmltools_0.5.4 ## [37] tools_4.2.0 igraph_1.4.1 gtable_0.3.1 ## [40] glue_1.6.2 RANN_2.6.1 reshape2_1.4.4 ## [43] dplyr_1.1.0 Rcpp_1.0.10 scattermore_0.8 ## [46] jquerylib_0.1.4 pkgdown_2.0.7 vctrs_0.5.2 ## [49] nlme_3.1-157 spatstat.explore_3.0-6 progressr_0.13.0 ## [52] lmtest_0.9-40 spatstat.random_3.1-3 xfun_0.37 ## [55] stringr_1.5.0 globals_0.16.2 mime_0.12 ## [58] miniUI_0.1.1.1 lifecycle_1.0.3 irlba_2.3.5.1 ## [61] goftest_1.2-3 future_1.31.0 MASS_7.3-56 ## [64] zoo_1.8-11 scales_1.2.1 ragg_1.2.5 ## [67] promises_1.2.0.1 spatstat.utils_3.0-1 parallel_4.2.0 ## [70] RColorBrewer_1.1-3 yaml_2.3.7 memoise_2.0.1 ## [73] reticulate_1.28 pbapply_1.7-0 gridExtra_2.3 ## [76] sass_0.4.5 stringi_1.7.12 highr_0.10 ## [79] desc_1.4.2 rlang_1.0.6 pkgconfig_2.0.3 ## [82] systemfonts_1.0.4 matrixStats_0.63.0 evaluate_0.20 ## [85] lattice_0.20-45 tensor_1.5 ROCR_1.0-11 ## [88] purrr_1.0.1 labeling_0.4.2 patchwork_1.1.2 ## [91] htmlwidgets_1.6.1 cowplot_1.1.1 tidyselect_1.2.0 ## [94] parallelly_1.34.0 RcppAnnoy_0.0.20 plyr_1.8.8 ## [97] magrittr_2.0.3 R6_2.5.1 generics_0.1.3 ## [100] withr_2.5.0 pillar_1.8.1 fitdistrplus_1.1-8 ## [103] abind_1.4-5 survival_3.3-1 sp_1.6-0 ## [106] tibble_3.1.8 future.apply_1.10.0 KernSmooth_2.23-20 ## [109] utf8_1.2.3 spatstat.geom_3.0-6 plotly_4.10.1 ## [112] rmarkdown_2.20 grid_4.2.0 data.table_1.14.8 ## [115] digest_0.6.31 xtable_1.8-4 tidyr_1.3.0 ## [118] httpuv_1.6.9 R.utils_2.12.2 textshaping_0.3.6 ## [121] munsell_0.5.0 viridisLite_0.4.1 bslib_0.4.2

Developed by Paul Hoffman, Satija Lab and Collaborators.

Developed by Paul Hoffman, Satija Lab and Collaborators.

Site built with pkgdown 2.0.7.

Site built with pkgdown 2.0.7.

**Examples:**

Example 1 (unknown):
```unknown
vignettes/sctransform_vignette.Rmd
```

Example 2 (unknown):
```unknown
sctransform_vignette.Rmd
```

Example 3 (unknown):
```unknown
library(Seurat)
library(ggplot2)
library(sctransform)
```

Example 4 (r):
```r
library(Seurat)
library(ggplot2)
library(sctransform)
```

Example 5 (r):
```r
library(Seurat)
library(ggplot2)
library(sctransform)
```

Example 6 (unknown):
```unknown
pbmc_data <- Read10X(data.dir = "../data/pbmc3k/filtered_gene_bc_matrices/hg19/")
pbmc <- CreateSeuratObject(counts = pbmc_data)
```

Example 7 (r):
```r
pbmc_data <- Read10X(data.dir = "../data/pbmc3k/filtered_gene_bc_matrices/hg19/")
pbmc <- CreateSeuratObject(counts = pbmc_data)
```

Example 8 (r):
```r
pbmc_data <- Read10X(data.dir = "../data/pbmc3k/filtered_gene_bc_matrices/hg19/")
pbmc <- CreateSeuratObject(counts = pbmc_data)
```

Example 9 (unknown):
```unknown
NormalizeData()
```

Example 10 (unknown):
```unknown
ScaleData()
```

Example 11 (unknown):
```unknown
FindVariableFeatures()
```

Example 12 (unknown):
```unknown
# store mitochondrial percentage in object meta data
pbmc <- PercentageFeatureSet(pbmc, pattern = "^MT-", col.name = "percent.mt")

# run sctransform
pbmc <- SCTransform(pbmc, vars.to.regress = "percent.mt", verbose = FALSE)
```

Example 13 (r):
```r
# store mitochondrial percentage in object meta data
pbmc <- PercentageFeatureSet(pbmc, pattern = "^MT-", col.name = "percent.mt")

# run sctransform
pbmc <- SCTransform(pbmc, vars.to.regress = "percent.mt", verbose = FALSE)
```

Example 14 (r):
```r
# store mitochondrial percentage in object meta data
pbmc <- PercentageFeatureSet(pbmc, pattern = "^MT-", col.name = "percent.mt")

# run sctransform
pbmc <- SCTransform(pbmc, vars.to.regress = "percent.mt", verbose = FALSE)
```

Example 15 (unknown):
```unknown
sctransform
```

Example 16 (unknown):
```unknown
method="glmGamPoi"
```

Example 17 (unknown):
```unknown
if (!requireNamespace("BiocManager", quietly = TRUE)) install.packages("BiocManager")

BiocManager::install("glmGamPoi")
pbmc <- SCTransform(pbmc, method = "glmGamPoi", vars.to.regress = "percent.mt", verbose = FALSE)
```

Example 18 (r):
```r
if (!requireNamespace("BiocManager", quietly = TRUE)) install.packages("BiocManager")

BiocManager::install("glmGamPoi")
pbmc <- SCTransform(pbmc, method = "glmGamPoi", vars.to.regress = "percent.mt", verbose = FALSE)
```

Example 19 (r):
```r
if (!requireNamespace("BiocManager", quietly = TRUE)) install.packages("BiocManager")

BiocManager::install("glmGamPoi")
pbmc <- SCTransform(pbmc, method = "glmGamPoi", vars.to.regress = "percent.mt", verbose = FALSE)
```

Example 20 (unknown):
```unknown
# These are now standard steps in the Seurat workflow for visualization and clustering
pbmc <- RunPCA(pbmc, verbose = FALSE)
pbmc <- RunUMAP(pbmc, dims = 1:30, verbose = FALSE)

pbmc <- FindNeighbors(pbmc, dims = 1:30, verbose = FALSE)
pbmc <- FindClusters(pbmc, verbose = FALSE)
DimPlot(pbmc, label = TRUE) + NoLegend()
```

Example 21 (r):
```r
# These are now standard steps in the Seurat workflow for visualization and clustering
pbmc <- RunPCA(pbmc, verbose = FALSE)
pbmc <- RunUMAP(pbmc, dims = 1:30, verbose = FALSE)

pbmc <- FindNeighbors(pbmc, dims = 1:30, verbose = FALSE)
pbmc <- FindClusters(pbmc, verbose = FALSE)
DimPlot(pbmc, label = TRUE) + NoLegend()
```

Example 22 (r):
```r
# These are now standard steps in the Seurat workflow for visualization and clustering
pbmc <- RunPCA(pbmc, verbose = FALSE)
pbmc <- RunUMAP(pbmc, dims = 1:30, verbose = FALSE)

pbmc <- FindNeighbors(pbmc, dims = 1:30, verbose = FALSE)
pbmc <- FindClusters(pbmc, verbose = FALSE)
DimPlot(pbmc, label = TRUE) + NoLegend()
```

Example 23 (unknown):
```unknown
pbmc <- CreateSeuratObject(pbmc_data) %>%
    PercentageFeatureSet(pattern = "^MT-", col.name = "percent.mt") %>%
    SCTransform(vars.to.regress = "percent.mt") %>%
    RunPCA() %>%
    FindNeighbors(dims = 1:30) %>%
    RunUMAP(dims = 1:30) %>%
    FindClusters()
```

Example 24 (r):
```r
pbmc <- CreateSeuratObject(pbmc_data) %>%
    PercentageFeatureSet(pattern = "^MT-", col.name = "percent.mt") %>%
    SCTransform(vars.to.regress = "percent.mt") %>%
    RunPCA() %>%
    FindNeighbors(dims = 1:30) %>%
    RunUMAP(dims = 1:30) %>%
    FindClusters()
```

Example 25 (r):
```r
pbmc <- CreateSeuratObject(pbmc_data) %>%
    PercentageFeatureSet(pattern = "^MT-", col.name = "percent.mt") %>%
    SCTransform(vars.to.regress = "percent.mt") %>%
    RunPCA() %>%
    FindNeighbors(dims = 1:30) %>%
    RunUMAP(dims = 1:30) %>%
    FindClusters()
```

Example 26 (unknown):
```unknown
pbmc[["SCT"]]@scale.data
```

Example 27 (unknown):
```unknown
SCTransform()
```

Example 28 (unknown):
```unknown
pbmc[["SCT"]]@counts
```

Example 29 (unknown):
```unknown
pbmc[["SCT"]]@data
```

Example 30 (unknown):
```unknown
# These are now standard steps in the Seurat workflow for visualization and clustering
# Visualize canonical marker genes as violin plots.
VlnPlot(pbmc, features = c("CD8A", "GZMK", "CCL5", "S100A4", "ANXA1", "CCR7", "ISG15", "CD3D"),
    pt.size = 0.2, ncol = 4)
```

Example 31 (r):
```r
# These are now standard steps in the Seurat workflow for visualization and clustering
# Visualize canonical marker genes as violin plots.
VlnPlot(pbmc, features = c("CD8A", "GZMK", "CCL5", "S100A4", "ANXA1", "CCR7", "ISG15", "CD3D"),
    pt.size = 0.2, ncol = 4)
```

Example 32 (r):
```r
# These are now standard steps in the Seurat workflow for visualization and clustering
# Visualize canonical marker genes as violin plots.
VlnPlot(pbmc, features = c("CD8A", "GZMK", "CCL5", "S100A4", "ANXA1", "CCR7", "ISG15", "CD3D"),
    pt.size = 0.2, ncol = 4)
```

Example 33 (unknown):
```unknown
# Visualize canonical marker genes on the sctransform embedding.
FeaturePlot(pbmc, features = c("CD8A", "GZMK", "CCL5", "S100A4", "ANXA1", "CCR7"), pt.size = 0.2,
    ncol = 3)
```

Example 34 (r):
```r
# Visualize canonical marker genes on the sctransform embedding.
FeaturePlot(pbmc, features = c("CD8A", "GZMK", "CCL5", "S100A4", "ANXA1", "CCR7"), pt.size = 0.2,
    ncol = 3)
```

Example 35 (r):
```r
# Visualize canonical marker genes on the sctransform embedding.
FeaturePlot(pbmc, features = c("CD8A", "GZMK", "CCL5", "S100A4", "ANXA1", "CCR7"), pt.size = 0.2,
    ncol = 3)
```

Example 36 (unknown):
```unknown
FeaturePlot(pbmc, features = c("CD3D", "ISG15", "TCL1A", "FCER2", "XCL1", "FCGR3A"), pt.size = 0.2,
    ncol = 3)
```

Example 37 (r):
```r
FeaturePlot(pbmc, features = c("CD3D", "ISG15", "TCL1A", "FCER2", "XCL1", "FCGR3A"), pt.size = 0.2,
    ncol = 3)
```

Example 38 (r):
```r
FeaturePlot(pbmc, features = c("CD3D", "ISG15", "TCL1A", "FCER2", "XCL1", "FCGR3A"), pt.size = 0.2,
    ncol = 3)
```

Example 39 (unknown):
```unknown
sessionInfo()
```

Example 40 (r):
```r
sessionInfo()
```

Example 41 (r):
```r
sessionInfo()
```

Example 42 (unknown):
```unknown
## R version 4.2.0 (2022-04-22)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.5 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/liblapack.so.3
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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       
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
## [1] sctransform_0.3.5  ggplot2_3.4.1      SeuratObject_4.1.3 Seurat_4.3.0      
## 
## loaded via a namespace (and not attached):
##   [1] Rtsne_0.16             colorspace_2.1-0       deldir_1.0-6          
##   [4] ellipsis_0.3.2         ggridges_0.5.4         rprojroot_2.0.3       
##   [7] fs_1.6.1               spatstat.data_3.0-0    farver_2.1.1          
##  [10] leiden_0.4.3           listenv_0.9.0          ggrepel_0.9.3         
##  [13] fansi_1.0.4            R.methodsS3_1.8.2      codetools_0.2-18      
##  [16] splines_4.2.0          cachem_1.0.7           knitr_1.42            
##  [19] polyclip_1.10-4        jsonlite_1.8.4         ica_1.0-3             
##  [22] cluster_2.1.3          R.oo_1.25.0            png_0.1-8             
##  [25] uwot_0.1.14            spatstat.sparse_3.0-0  shiny_1.7.4           
##  [28] compiler_4.2.0         httr_1.4.5             Matrix_1.5-3          
##  [31] fastmap_1.1.1          lazyeval_0.2.2         cli_3.6.0             
##  [34] later_1.3.0            formatR_1.14           htmltools_0.5.4       
##  [37] tools_4.2.0            igraph_1.4.1           gtable_0.3.1          
##  [40] glue_1.6.2             RANN_2.6.1             reshape2_1.4.4        
##  [43] dplyr_1.1.0            Rcpp_1.0.10            scattermore_0.8       
##  [46] jquerylib_0.1.4        pkgdown_2.0.7          vctrs_0.5.2           
##  [49] nlme_3.1-157           spatstat.explore_3.0-6 progressr_0.13.0      
##  [52] lmtest_0.9-40          spatstat.random_3.1-3  xfun_0.37             
##  [55] stringr_1.5.0          globals_0.16.2         mime_0.12             
##  [58] miniUI_0.1.1.1         lifecycle_1.0.3        irlba_2.3.5.1         
##  [61] goftest_1.2-3          future_1.31.0          MASS_7.3-56           
##  [64] zoo_1.8-11             scales_1.2.1           ragg_1.2.5            
##  [67] promises_1.2.0.1       spatstat.utils_3.0-1   parallel_4.2.0        
##  [70] RColorBrewer_1.1-3     yaml_2.3.7             memoise_2.0.1         
##  [73] reticulate_1.28        pbapply_1.7-0          gridExtra_2.3         
##  [76] sass_0.4.5             stringi_1.7.12         highr_0.10            
##  [79] desc_1.4.2             rlang_1.0.6            pkgconfig_2.0.3       
##  [82] systemfonts_1.0.4      matrixStats_0.63.0     evaluate_0.20         
##  [85] lattice_0.20-45        tensor_1.5             ROCR_1.0-11           
##  [88] purrr_1.0.1            labeling_0.4.2         patchwork_1.1.2       
##  [91] htmlwidgets_1.6.1      cowplot_1.1.1          tidyselect_1.2.0      
##  [94] parallelly_1.34.0      RcppAnnoy_0.0.20       plyr_1.8.8            
##  [97] magrittr_2.0.3         R6_2.5.1               generics_0.1.3        
## [100] withr_2.5.0            pillar_1.8.1           fitdistrplus_1.1-8    
## [103] abind_1.4-5            survival_3.3-1         sp_1.6-0              
## [106] tibble_3.1.8           future.apply_1.10.0    KernSmooth_2.23-20    
## [109] utf8_1.2.3             spatstat.geom_3.0-6    plotly_4.10.1         
## [112] rmarkdown_2.20         grid_4.2.0             data.table_1.14.8     
## [115] digest_0.6.31          xtable_1.8-4           tidyr_1.3.0           
## [118] httpuv_1.6.9           R.utils_2.12.2         textshaping_0.3.6     
## [121] munsell_0.5.0          viridisLite_0.4.1      bslib_0.4.2
```

Example 43 (unknown):
```unknown
## R version 4.2.0 (2022-04-22)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.5 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/liblapack.so.3
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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       
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
## [1] sctransform_0.3.5  ggplot2_3.4.1      SeuratObject_4.1.3 Seurat_4.3.0      
## 
## loaded via a namespace (and not attached):
##   [1] Rtsne_0.16             colorspace_2.1-0       deldir_1.0-6          
##   [4] ellipsis_0.3.2         ggridges_0.5.4         rprojroot_2.0.3       
##   [7] fs_1.6.1               spatstat.data_3.0-0    farver_2.1.1          
##  [10] leiden_0.4.3           listenv_0.9.0          ggrepel_0.9.3         
##  [13] fansi_1.0.4            R.methodsS3_1.8.2      codetools_0.2-18      
##  [16] splines_4.2.0          cachem_1.0.7           knitr_1.42            
##  [19] polyclip_1.10-4        jsonlite_1.8.4         ica_1.0-3             
##  [22] cluster_2.1.3          R.oo_1.25.0            png_0.1-8             
##  [25] uwot_0.1.14            spatstat.sparse_3.0-0  shiny_1.7.4           
##  [28] compiler_4.2.0         httr_1.4.5             Matrix_1.5-3          
##  [31] fastmap_1.1.1          lazyeval_0.2.2         cli_3.6.0             
##  [34] later_1.3.0            formatR_1.14           htmltools_0.5.4       
##  [37] tools_4.2.0            igraph_1.4.1           gtable_0.3.1          
##  [40] glue_1.6.2             RANN_2.6.1             reshape2_1.4.4        
##  [43] dplyr_1.1.0            Rcpp_1.0.10            scattermore_0.8       
##  [46] jquerylib_0.1.4        pkgdown_2.0.7          vctrs_0.5.2           
##  [49] nlme_3.1-157           spatstat.explore_3.0-6 progressr_0.13.0      
##  [52] lmtest_0.9-40          spatstat.random_3.1-3  xfun_0.37             
##  [55] stringr_1.5.0          globals_0.16.2         mime_0.12             
##  [58] miniUI_0.1.1.1         lifecycle_1.0.3        irlba_2.3.5.1         
##  [61] goftest_1.2-3          future_1.31.0          MASS_7.3-56           
##  [64] zoo_1.8-11             scales_1.2.1           ragg_1.2.5            
##  [67] promises_1.2.0.1       spatstat.utils_3.0-1   parallel_4.2.0        
##  [70] RColorBrewer_1.1-3     yaml_2.3.7             memoise_2.0.1         
##  [73] reticulate_1.28        pbapply_1.7-0          gridExtra_2.3         
##  [76] sass_0.4.5             stringi_1.7.12         highr_0.10            
##  [79] desc_1.4.2             rlang_1.0.6            pkgconfig_2.0.3       
##  [82] systemfonts_1.0.4      matrixStats_0.63.0     evaluate_0.20         
##  [85] lattice_0.20-45        tensor_1.5             ROCR_1.0-11           
##  [88] purrr_1.0.1            labeling_0.4.2         patchwork_1.1.2       
##  [91] htmlwidgets_1.6.1      cowplot_1.1.1          tidyselect_1.2.0      
##  [94] parallelly_1.34.0      RcppAnnoy_0.0.20       plyr_1.8.8            
##  [97] magrittr_2.0.3         R6_2.5.1               generics_0.1.3        
## [100] withr_2.5.0            pillar_1.8.1           fitdistrplus_1.1-8    
## [103] abind_1.4-5            survival_3.3-1         sp_1.6-0              
## [106] tibble_3.1.8           future.apply_1.10.0    KernSmooth_2.23-20    
## [109] utf8_1.2.3             spatstat.geom_3.0-6    plotly_4.10.1         
## [112] rmarkdown_2.20         grid_4.2.0             data.table_1.14.8     
## [115] digest_0.6.31          xtable_1.8-4           tidyr_1.3.0           
## [118] httpuv_1.6.9           R.utils_2.12.2         textshaping_0.3.6     
## [121] munsell_0.5.0          viridisLite_0.4.1      bslib_0.4.2
```

---

## Interoperability between Seurat, SingleCellExperiment, and anndata

**URL:** http://127.0.0.1:9173/seurat/archive/v2.4/conversion_vignette/index.html

**Contents:**
- Interoperability between Seurat, SingleCellExperiment, and anndata
  - Converting to/from SingleCellExperiment
  - Converting to/from anndata
  - Acknowledgments

In this vignette, we demonstrate the ability to convert between Seurat objects, SingleCellExperiment objects, and anndata objects.

SingleCellExperiment is a class for storing single-cell experiment data, created by Davide Risso, Aaron Lun, and Keegan Korthauer, and is used by many Bioconductor analysis packages. Here we demonstrate converting the Seurat object produced in our 3k PBMC tutorial to SingleCellExperiment for use with Davis McCarthy’s scater package.

We demonstrate this on some publicly available data downloaded from a repository maintained by Martin Hemberg’s group.

anndata provides a python class, created by Alex Wolf and Philipp Angerer, that can be used to store single-cell data. This data format is also use for storage in their scanpy package for which we now support interoperability. In order to access the conversion function, first read the data into R using the reticulate package to import the anndata module.

We support conversion from Seurat objects to anndata as well.

Many thanks to Davis McCarthy and Alex Wolf for their help in drafting the conversion functions.

**Examples:**

Example 1 (r):
```r
# install scater
# https://bioconductor.org/packages/release/bioc/html/scater.html
library(scater)
library(Seurat)
library(cowplot)
```

Example 2 (r):
```r
# install scater
# https://bioconductor.org/packages/release/bioc/html/scater.html
library(scater)
library(Seurat)
library(cowplot)
```

Example 3 (r):
```r
# download from satija lab
# https://www.dropbox.com/s/kwd3kcxkmpzqg6w/pbmc3k_final.rds?dl=0
pbmc <- readRDS("~/Downloads/pbmc3k_final.rds")
pbmc_sce <- Convert(from = pbmc, to = "sce")
p1 <- plotExpression(object = pbmc_sce, features = "MS4A1", x = "ident") + theme(axis.text.x = element_text(angle = 45, 
    hjust = 1))
p2 <- plotPCA(object = pbmc_sce, colour_by = "ident")
plot_grid(p1, p2)
```

Example 4 (r):
```r
# download from satija lab
# https://www.dropbox.com/s/kwd3kcxkmpzqg6w/pbmc3k_final.rds?dl=0
pbmc <- readRDS("~/Downloads/pbmc3k_final.rds")
pbmc_sce <- Convert(from = pbmc, to = "sce")
p1 <- plotExpression(object = pbmc_sce, features = "MS4A1", x = "ident") + theme(axis.text.x = element_text(angle = 45, 
    hjust = 1))
p2 <- plotPCA(object = pbmc_sce, colour_by = "ident")
plot_grid(p1, p2)
```

Example 5 (r):
```r
# downloaded from hemberg lab
# https://scrnaseq-public-datasets.s3.amazonaws.com/scater-objects/manno_human.rds
manno <- readRDS("~/Downloads/manno_human.rds")
manno <- runPCA(manno)
manno_seurat <- Convert(from = manno, to = "seurat")
manno_seurat <- SetAllIdent(object = manno_seurat, id = "cell_type1")
p1 <- DimPlot(object = manno_seurat, reduction.use = "PCA", dim.1 = 1, dim.2 = 2, 
    group.by = "Source", do.return = TRUE)
p2 <- RidgePlot(object = manno_seurat, features.plot = "ACTB", y.lab.rot = TRUE, 
    group.by = "Source", do.return = TRUE)
plot_grid(p1, p2)
```

Example 6 (r):
```r
# downloaded from hemberg lab
# https://scrnaseq-public-datasets.s3.amazonaws.com/scater-objects/manno_human.rds
manno <- readRDS("~/Downloads/manno_human.rds")
manno <- runPCA(manno)
manno_seurat <- Convert(from = manno, to = "seurat")
manno_seurat <- SetAllIdent(object = manno_seurat, id = "cell_type1")
p1 <- DimPlot(object = manno_seurat, reduction.use = "PCA", dim.1 = 1, dim.2 = 2, 
    group.by = "Source", do.return = TRUE)
p2 <- RidgePlot(object = manno_seurat, features.plot = "ACTB", y.lab.rot = TRUE, 
    group.by = "Source", do.return = TRUE)
plot_grid(p1, p2)
```

Example 7 (r):
```r
# download from satija lab
# https://www.dropbox.com/s/ngs3p8n2i8y33hj/pbmc3k.h5ad?dl=0
library(reticulate)
ad <- import("anndata", convert = FALSE)
pbmc_ad <- ad$read_h5ad("/Users/abutler/Downloads/pbmc3k.h5ad")
pbmc3k <- Convert(pbmc_ad, to = "seurat")
p1 <- TSNEPlot(pbmc3k, group.by = "louvain", do.return = TRUE)
p2 <- VlnPlot(pbmc3k, c("CST3", "NKG7", "PPBP"), group.by = "louvain", do.return = TRUE)
plot_grid(p1, p2)
```

Example 8 (r):
```r
# download from satija lab
# https://www.dropbox.com/s/ngs3p8n2i8y33hj/pbmc3k.h5ad?dl=0
library(reticulate)
ad <- import("anndata", convert = FALSE)
pbmc_ad <- ad$read_h5ad("/Users/abutler/Downloads/pbmc3k.h5ad")
pbmc3k <- Convert(pbmc_ad, to = "seurat")
p1 <- TSNEPlot(pbmc3k, group.by = "louvain", do.return = TRUE)
p2 <- VlnPlot(pbmc3k, c("CST3", "NKG7", "PPBP"), group.by = "louvain", do.return = TRUE)
plot_grid(p1, p2)
```

Example 9 (r):
```r
pbmc_ad <- Convert(from = pbmc, to = "anndata", filename = "/Users/abutler/Projects/test/pbmc3k.h5ad")
pbmc_ad
```

Example 10 (r):
```r
pbmc_ad <- Convert(from = pbmc, to = "anndata", filename = "/Users/abutler/Projects/test/pbmc3k.h5ad")
pbmc_ad
```

Example 11 (unknown):
```unknown
## AnnData object with n_obs × n_vars = 2638 × 13714 
##     obs: 'ClusterNames_0_6', 'n_counts', 'n_genes', 'orig_ident', 'percent_mito', 'res_0_6', 'res_0_8'
##     var: 'gene.dispersion', 'gene.dispersion.scaled', 'gene.mean'
##     obsm: 'X_pca', 'X_tsne'
```

Example 12 (unknown):
```unknown
## AnnData object with n_obs × n_vars = 2638 × 13714 
##     obs: 'ClusterNames_0_6', 'n_counts', 'n_genes', 'orig_ident', 'percent_mito', 'res_0_6', 'res_0_8'
##     var: 'gene.dispersion', 'gene.dispersion.scaled', 'gene.mean'
##     obsm: 'X_pca', 'X_tsne'
```

---

## Using Seurat with multi-modal data

**URL:** http://127.0.0.1:9173/seurat/archive/v3.0/multimodal_vignette/index.html

**Contents:**
- Using Seurat with multi-modal data
    - Compiled: 2019-06-24
  - Load in the data
  - Setup a Seurat object, and cluster cells based on RNA expression
  - Add the protein expression levels to the Seurat object
  - Visualize protein levels on RNA clusters
  - Identify differentially expressed proteins between clusters
  - Cluster directly on protein levels
  - Loading data from 10X multi-modal experiments

This vignette demonstrates new features that allow users to analyze and explore multi-modal data with Seurat. While this represents an initial release, we are excited to release significant new functionality for multi-modal datasets in the future.

Here, we analyze a dataset of 8,617 cord blood mononuclear cells (CBMCs), produced with CITE-seq, where we simultaneously measure the single cell transcriptomes alongside the expression of 11 surface proteins, whose levels are quantified with DNA-barcoded antibodies. First, we load in two count matrices : one for the RNA measurements, and one for the antibody-derived tags (ADT). You can download the ADT file here and the RNA file here

The steps below represent a quick clustering of the PBMCs based on the scRNA-seq data. For more detail on individual steps or more advanced options, see our PBMC clustering guided tutorial here

Seurat v3.0 allows you to store information from multiple assays in the same object, as long as the data is multi-modal (collected on the same set of cells). You can use the SetAssayData and GetAssayData accessor functions to add and fetch data from additional assays.

You can use the names of any ADT markers, (i.e. “adt_CD4”), in FetchData, FeaturePlot, RidgePlot, FeatureScatter, DoHeatmap, or any other visualization features

If you look a bit more closely, you’ll see that our CD8 T cell cluster is enriched for CD8 T cells, but still contains many CD4+ CD8- T cells. This is because Naive CD4 and CD8 T cells are quite similar transcriptomically, and the RNA dropout levels for CD4 and CD8 are quite high. This demonstrates the challenge of defining subtle immune cell differences from scRNA-seq data alone.

You can also run dimensional reduction and graph-based clustering directly on CITE-seq data

The ADT-based clustering yields similar results, but with a few differences

Seurat is also able to analyze data from multi-modal 10X experiments processed using CellRanger v3; as an example, we recreate the plots above using a dataset of 7,900 peripheral blood mononuclear cells (PBMC), freely available from 10X Genomics here.

**Examples:**

Example 1 (r):
```r
library(Seurat)
library(ggplot2)
```

Example 2 (r):
```r
library(Seurat)
library(ggplot2)
```

Example 3 (r):
```r
# Load in the RNA UMI matrix

# Note that this dataset also contains ~5% of mouse cells, which we can use as negative controls
# for the protein measurements. For this reason, the gene expression matrix has HUMAN_ or MOUSE_
# appended to the beginning of each gene.
cbmc.rna <- as.sparse(read.csv(file = "../data/GSE100866_CBMC_8K_13AB_10X-RNA_umi.csv.gz", sep = ",", 
    header = TRUE, row.names = 1))

# To make life a bit easier going forward, we're going to discard all but the top 100 most
# highly expressed mouse genes, and remove the 'HUMAN_' from the CITE-seq prefix
cbmc.rna <- CollapseSpeciesExpressionMatrix(cbmc.rna)

# Load in the ADT UMI matrix
cbmc.adt <- as.sparse(read.csv(file = "../data/GSE100866_CBMC_8K_13AB_10X-ADT_umi.csv.gz", sep = ",", 
    header = TRUE, row.names = 1))

# When adding multimodal data to Seurat, it's okay to have duplicate feature names. Each set of
# modal data (eg. RNA, ADT, etc.) is stored in its own Assay object.  One of these Assay objects
# is called the 'default assay', meaning it's used for all analyses and visualization.  To pull
# data from an assay that isn't the default, you can specify a key that's linked to an assay for
# feature pulling.  To see all keys for all objects, use the Key function.  Lastly, we observed
# poor enrichments for CCR5, CCR7, and CD10 - and therefore remove them from the matrix
# (optional)
cbmc.adt <- cbmc.adt[setdiff(rownames(x = cbmc.adt), c("CCR5", "CCR7", "CD10")), ]
```

Example 4 (r):
```r
# Load in the RNA UMI matrix

# Note that this dataset also contains ~5% of mouse cells, which we can use as negative controls
# for the protein measurements. For this reason, the gene expression matrix has HUMAN_ or MOUSE_
# appended to the beginning of each gene.
cbmc.rna <- as.sparse(read.csv(file = "../data/GSE100866_CBMC_8K_13AB_10X-RNA_umi.csv.gz", sep = ",", 
    header = TRUE, row.names = 1))

# To make life a bit easier going forward, we're going to discard all but the top 100 most
# highly expressed mouse genes, and remove the 'HUMAN_' from the CITE-seq prefix
cbmc.rna <- CollapseSpeciesExpressionMatrix(cbmc.rna)

# Load in the ADT UMI matrix
cbmc.adt <- as.sparse(read.csv(file = "../data/GSE100866_CBMC_8K_13AB_10X-ADT_umi.csv.gz", sep = ",", 
    header = TRUE, row.names = 1))

# When adding multimodal data to Seurat, it's okay to have duplicate feature names. Each set of
# modal data (eg. RNA, ADT, etc.) is stored in its own Assay object.  One of these Assay objects
# is called the 'default assay', meaning it's used for all analyses and visualization.  To pull
# data from an assay that isn't the default, you can specify a key that's linked to an assay for
# feature pulling.  To see all keys for all objects, use the Key function.  Lastly, we observed
# poor enrichments for CCR5, CCR7, and CD10 - and therefore remove them from the matrix
# (optional)
cbmc.adt <- cbmc.adt[setdiff(rownames(x = cbmc.adt), c("CCR5", "CCR7", "CD10")), ]
```

Example 5 (r):
```r
cbmc <- CreateSeuratObject(counts = cbmc.rna)

# standard log-normalization
cbmc <- NormalizeData(cbmc)

# choose ~1k variable features
cbmc <- FindVariableFeatures(cbmc)

# standard scaling (no regression)
cbmc <- ScaleData(cbmc)

# Run PCA, select 13 PCs for tSNE visualization and graph-based clustering
cbmc <- RunPCA(cbmc, verbose = FALSE)
ElbowPlot(cbmc, ndims = 50)
```

Example 6 (r):
```r
cbmc <- CreateSeuratObject(counts = cbmc.rna)

# standard log-normalization
cbmc <- NormalizeData(cbmc)

# choose ~1k variable features
cbmc <- FindVariableFeatures(cbmc)

# standard scaling (no regression)
cbmc <- ScaleData(cbmc)

# Run PCA, select 13 PCs for tSNE visualization and graph-based clustering
cbmc <- RunPCA(cbmc, verbose = FALSE)
ElbowPlot(cbmc, ndims = 50)
```

Example 7 (r):
```r
cbmc <- FindNeighbors(cbmc, dims = 1:25)
cbmc <- FindClusters(cbmc, resolution = 0.8)
cbmc <- RunTSNE(cbmc, dims = 1:25, method = "FIt-SNE")

# Find the markers that define each cluster, and use these to annotate the clusters, we use
# max.cells.per.ident to speed up the process
cbmc.rna.markers <- FindAllMarkers(cbmc, max.cells.per.ident = 100, min.diff.pct = 0.3, only.pos = TRUE)
```

Example 8 (r):
```r
cbmc <- FindNeighbors(cbmc, dims = 1:25)
cbmc <- FindClusters(cbmc, resolution = 0.8)
cbmc <- RunTSNE(cbmc, dims = 1:25, method = "FIt-SNE")

# Find the markers that define each cluster, and use these to annotate the clusters, we use
# max.cells.per.ident to speed up the process
cbmc.rna.markers <- FindAllMarkers(cbmc, max.cells.per.ident = 100, min.diff.pct = 0.3, only.pos = TRUE)
```

Example 9 (r):
```r
# Note, for simplicity we are merging two CD14+ Monocyte clusters (that differ in expression of
# HLA-DR genes) and NK clusters (that differ in cell cycle stage)
new.cluster.ids <- c("Memory CD4 T", "CD14+ Mono", "Naive CD4 T", "NK", "CD14+ Mono", "Mouse", "B", 
    "CD8 T", "CD16+ Mono", "T/Mono doublets", "NK", "CD34+", "Multiplets", "Mouse", "Eryth", "Mk", 
    "Mouse", "DC", "pDCs")
names(new.cluster.ids) <- levels(cbmc)
cbmc <- RenameIdents(cbmc, new.cluster.ids)
```

Example 10 (r):
```r
# Note, for simplicity we are merging two CD14+ Monocyte clusters (that differ in expression of
# HLA-DR genes) and NK clusters (that differ in cell cycle stage)
new.cluster.ids <- c("Memory CD4 T", "CD14+ Mono", "Naive CD4 T", "NK", "CD14+ Mono", "Mouse", "B", 
    "CD8 T", "CD16+ Mono", "T/Mono doublets", "NK", "CD34+", "Multiplets", "Mouse", "Eryth", "Mk", 
    "Mouse", "DC", "pDCs")
names(new.cluster.ids) <- levels(cbmc)
cbmc <- RenameIdents(cbmc, new.cluster.ids)
```

Example 11 (r):
```r
DimPlot(cbmc, label = TRUE) + NoLegend()
```

Example 12 (r):
```r
DimPlot(cbmc, label = TRUE) + NoLegend()
```

Example 13 (unknown):
```unknown
SetAssayData
```

Example 14 (unknown):
```unknown
GetAssayData
```

Example 15 (r):
```r
# We will define an ADT assay, and store raw counts for it

# If you are interested in how these data are internally stored, you can check out the Assay
# class, which is defined in objects.R; note that all single-cell expression data, including RNA
# data, are still stored in Assay objects, and can also be accessed using GetAssayData
cbmc[["ADT"]] <- CreateAssayObject(counts = cbmc.adt)

# Now we can repeat the preprocessing (normalization and scaling) steps that we typically run
# with RNA, but modifying the 'assay' argument.  For CITE-seq data, we do not recommend typical
# LogNormalization. Instead, we use a centered log-ratio (CLR) normalization, computed
# independently for each feature.  This is a slightly improved procedure from the original
# publication, and we will release more advanced versions of CITE-seq normalizations soon.
cbmc <- NormalizeData(cbmc, assay = "ADT", normalization.method = "CLR")
cbmc <- ScaleData(cbmc, assay = "ADT")
```

Example 16 (r):
```r
# We will define an ADT assay, and store raw counts for it

# If you are interested in how these data are internally stored, you can check out the Assay
# class, which is defined in objects.R; note that all single-cell expression data, including RNA
# data, are still stored in Assay objects, and can also be accessed using GetAssayData
cbmc[["ADT"]] <- CreateAssayObject(counts = cbmc.adt)

# Now we can repeat the preprocessing (normalization and scaling) steps that we typically run
# with RNA, but modifying the 'assay' argument.  For CITE-seq data, we do not recommend typical
# LogNormalization. Instead, we use a centered log-ratio (CLR) normalization, computed
# independently for each feature.  This is a slightly improved procedure from the original
# publication, and we will release more advanced versions of CITE-seq normalizations soon.
cbmc <- NormalizeData(cbmc, assay = "ADT", normalization.method = "CLR")
cbmc <- ScaleData(cbmc, assay = "ADT")
```

Example 17 (r):
```r
# in this plot, protein (ADT) levels are on top, and RNA levels are on the bottom
FeaturePlot(cbmc, features = c("adt_CD3", "adt_CD11c", "adt_CD8", "adt_CD16", "CD3E", "ITGAX", "CD8A", 
    "FCGR3A"), min.cutoff = "q05", max.cutoff = "q95", ncol = 4)
```

Example 18 (r):
```r
# in this plot, protein (ADT) levels are on top, and RNA levels are on the bottom
FeaturePlot(cbmc, features = c("adt_CD3", "adt_CD11c", "adt_CD8", "adt_CD16", "CD3E", "ITGAX", "CD8A", 
    "FCGR3A"), min.cutoff = "q05", max.cutoff = "q95", ncol = 4)
```

Example 19 (r):
```r
RidgePlot(cbmc, features = c("adt_CD3", "adt_CD11c", "adt_CD8", "adt_CD16"), ncol = 2)
```

Example 20 (r):
```r
RidgePlot(cbmc, features = c("adt_CD3", "adt_CD11c", "adt_CD8", "adt_CD16"), ncol = 2)
```

Example 21 (r):
```r
# Draw ADT scatter plots (like biaxial plots for FACS). Note that you can even 'gate' cells if
# desired by using HoverLocator and FeatureLocator
FeatureScatter(cbmc, feature1 = "adt_CD19", feature2 = "adt_CD3")
```

Example 22 (r):
```r
# Draw ADT scatter plots (like biaxial plots for FACS). Note that you can even 'gate' cells if
# desired by using HoverLocator and FeatureLocator
FeatureScatter(cbmc, feature1 = "adt_CD19", feature2 = "adt_CD3")
```

Example 23 (r):
```r
# view relationship between protein and RNA
FeatureScatter(cbmc, feature1 = "adt_CD3", feature2 = "CD3E")
```

Example 24 (r):
```r
# view relationship between protein and RNA
FeatureScatter(cbmc, feature1 = "adt_CD3", feature2 = "CD3E")
```

Example 25 (r):
```r
# Let's plot CD4 vs CD8 levels in T cells
tcells <- subset(cbmc, idents = c("Naive CD4 T", "Memory CD4 T", "CD8 T"))
FeatureScatter(tcells, feature1 = "adt_CD4", feature2 = "adt_CD8")
```

Example 26 (r):
```r
# Let's plot CD4 vs CD8 levels in T cells
tcells <- subset(cbmc, idents = c("Naive CD4 T", "Memory CD4 T", "CD8 T"))
FeatureScatter(tcells, feature1 = "adt_CD4", feature2 = "adt_CD8")
```

Example 27 (r):
```r
# # Let's look at the raw (non-normalized) ADT counts. You can see the values are quite high,
# particularly in comparison to RNA values. This is due to the significantly higher protein copy
# number in cells, which significantly reduces 'drop-out' in ADT data
FeatureScatter(tcells, feature1 = "adt_CD4", feature2 = "adt_CD8", slot = "counts")
```

Example 28 (r):
```r
# # Let's look at the raw (non-normalized) ADT counts. You can see the values are quite high,
# particularly in comparison to RNA values. This is due to the significantly higher protein copy
# number in cells, which significantly reduces 'drop-out' in ADT data
FeatureScatter(tcells, feature1 = "adt_CD4", feature2 = "adt_CD8", slot = "counts")
```

Example 29 (r):
```r
saveRDS(cbmc, file = "../output/cbmc.rds")
```

Example 30 (r):
```r
saveRDS(cbmc, file = "../output/cbmc.rds")
```

Example 31 (r):
```r
# Downsample the clusters to a maximum of 300 cells each (makes the heatmap easier to see for
# small clusters)
cbmc.small <- subset(cbmc, downsample = 300)

# Find protein markers for all clusters, and draw a heatmap
adt.markers <- FindAllMarkers(cbmc.small, assay = "ADT", only.pos = TRUE)
DoHeatmap(cbmc.small, features = unique(adt.markers$gene), assay = "ADT", angle = 90) + NoLegend()
```

Example 32 (r):
```r
# Downsample the clusters to a maximum of 300 cells each (makes the heatmap easier to see for
# small clusters)
cbmc.small <- subset(cbmc, downsample = 300)

# Find protein markers for all clusters, and draw a heatmap
adt.markers <- FindAllMarkers(cbmc.small, assay = "ADT", only.pos = TRUE)
DoHeatmap(cbmc.small, features = unique(adt.markers$gene), assay = "ADT", angle = 90) + NoLegend()
```

Example 33 (r):
```r
# You can see that our unknown cells co-express both myeloid and lymphoid markers (true at the
# RNA level as well). They are likely cell clumps (multiplets) that should be discarded. We'll
# remove the mouse cells now as well
cbmc <- subset(cbmc, idents = c("Multiplets", "Mouse"), invert = TRUE)
```

Example 34 (r):
```r
# You can see that our unknown cells co-express both myeloid and lymphoid markers (true at the
# RNA level as well). They are likely cell clumps (multiplets) that should be discarded. We'll
# remove the mouse cells now as well
cbmc <- subset(cbmc, idents = c("Multiplets", "Mouse"), invert = TRUE)
```

Example 35 (r):
```r
# Because we're going to be working with the ADT data extensively, we're going to switch the
# default assay to the 'CITE' assay.  This will cause all functions to use ADT data by default,
# rather than requiring us to specify it each time
DefaultAssay(cbmc) <- "ADT"
cbmc <- RunPCA(cbmc, features = rownames(cbmc), reduction.name = "pca_adt", reduction.key = "pca_adt_", 
    verbose = FALSE)
DimPlot(cbmc, reduction = "pca_adt")
```

Example 36 (r):
```r
# Because we're going to be working with the ADT data extensively, we're going to switch the
# default assay to the 'CITE' assay.  This will cause all functions to use ADT data by default,
# rather than requiring us to specify it each time
DefaultAssay(cbmc) <- "ADT"
cbmc <- RunPCA(cbmc, features = rownames(cbmc), reduction.name = "pca_adt", reduction.key = "pca_adt_", 
    verbose = FALSE)
DimPlot(cbmc, reduction = "pca_adt")
```

Example 37 (r):
```r
# Since we only have 10 markers, instead of doing PCA, we'll just use a standard euclidean
# distance matrix here.  Also, this provides a good opportunity to demonstrate how to do
# visualization and clustering using a custom distance matrix in Seurat
adt.data <- GetAssayData(cbmc, slot = "data")
adt.dist <- dist(t(adt.data))

# Before we recluster the data on ADT levels, we'll stash the RNA cluster IDs for later
cbmc[["rnaClusterID"]] <- Idents(cbmc)

# Now, we rerun tSNE using our distance matrix defined only on ADT (protein) levels.
cbmc[["tsne_adt"]] <- RunTSNE(adt.dist, assay = "ADT", reduction.key = "adtTSNE_")
cbmc[["adt_snn"]] <- FindNeighbors(adt.dist)$snn
cbmc <- FindClusters(cbmc, resolution = 0.2, graph.name = "adt_snn")

# We can compare the RNA and protein clustering, and use this to annotate the protein clustering
# (we could also of course use FindMarkers)
clustering.table <- table(Idents(cbmc), cbmc$rnaClusterID)
clustering.table
```

Example 38 (r):
```r
# Since we only have 10 markers, instead of doing PCA, we'll just use a standard euclidean
# distance matrix here.  Also, this provides a good opportunity to demonstrate how to do
# visualization and clustering using a custom distance matrix in Seurat
adt.data <- GetAssayData(cbmc, slot = "data")
adt.dist <- dist(t(adt.data))

# Before we recluster the data on ADT levels, we'll stash the RNA cluster IDs for later
cbmc[["rnaClusterID"]] <- Idents(cbmc)

# Now, we rerun tSNE using our distance matrix defined only on ADT (protein) levels.
cbmc[["tsne_adt"]] <- RunTSNE(adt.dist, assay = "ADT", reduction.key = "adtTSNE_")
cbmc[["adt_snn"]] <- FindNeighbors(adt.dist)$snn
cbmc <- FindClusters(cbmc, resolution = 0.2, graph.name = "adt_snn")

# We can compare the RNA and protein clustering, and use this to annotate the protein clustering
# (we could also of course use FindMarkers)
clustering.table <- table(Idents(cbmc), cbmc$rnaClusterID)
clustering.table
```

Example 39 (r):
```r
new.cluster.ids <- c("CD4 T", "CD14+ Mono", "NK", "B", "CD8 T", "NK", "CD34+", "T/Mono doublets", 
    "CD16+ Mono", "pDCs", "B")
names(new.cluster.ids) <- levels(cbmc)
cbmc <- RenameIdents(cbmc, new.cluster.ids)

tsne_rnaClusters <- DimPlot(cbmc, reduction = "tsne_adt", group.by = "rnaClusterID") + NoLegend()
tsne_rnaClusters <- tsne_rnaClusters + ggtitle("Clustering based on scRNA-seq") + theme(plot.title = element_text(hjust = 0.5))
tsne_rnaClusters <- LabelClusters(plot = tsne_rnaClusters, id = "rnaClusterID", size = 4)

tsne_adtClusters <- DimPlot(cbmc, reduction = "tsne_adt", pt.size = 0.5) + NoLegend()
tsne_adtClusters <- tsne_adtClusters + ggtitle("Clustering based on ADT signal") + theme(plot.title = element_text(hjust = 0.5))
tsne_adtClusters <- LabelClusters(plot = tsne_adtClusters, id = "ident", size = 4)

# Note: for this comparison, both the RNA and protein clustering are visualized on a tSNE
# generated using the ADT distance matrix.
CombinePlots(plots = list(tsne_rnaClusters, tsne_adtClusters), ncol = 2)
```

Example 40 (r):
```r
new.cluster.ids <- c("CD4 T", "CD14+ Mono", "NK", "B", "CD8 T", "NK", "CD34+", "T/Mono doublets", 
    "CD16+ Mono", "pDCs", "B")
names(new.cluster.ids) <- levels(cbmc)
cbmc <- RenameIdents(cbmc, new.cluster.ids)

tsne_rnaClusters <- DimPlot(cbmc, reduction = "tsne_adt", group.by = "rnaClusterID") + NoLegend()
tsne_rnaClusters <- tsne_rnaClusters + ggtitle("Clustering based on scRNA-seq") + theme(plot.title = element_text(hjust = 0.5))
tsne_rnaClusters <- LabelClusters(plot = tsne_rnaClusters, id = "rnaClusterID", size = 4)

tsne_adtClusters <- DimPlot(cbmc, reduction = "tsne_adt", pt.size = 0.5) + NoLegend()
tsne_adtClusters <- tsne_adtClusters + ggtitle("Clustering based on ADT signal") + theme(plot.title = element_text(hjust = 0.5))
tsne_adtClusters <- LabelClusters(plot = tsne_adtClusters, id = "ident", size = 4)

# Note: for this comparison, both the RNA and protein clustering are visualized on a tSNE
# generated using the ADT distance matrix.
CombinePlots(plots = list(tsne_rnaClusters, tsne_adtClusters), ncol = 2)
```

Example 41 (r):
```r
tcells <- subset(cbmc, idents = c("CD4 T", "CD8 T"))
FeatureScatter(tcells, feature1 = "CD4", feature2 = "CD8")
```

Example 42 (r):
```r
tcells <- subset(cbmc, idents = c("CD4 T", "CD8 T"))
FeatureScatter(tcells, feature1 = "CD4", feature2 = "CD8")
```

Example 43 (r):
```r
RidgePlot(cbmc, features = c("adt_CD11c", "adt_CD8", "adt_CD16", "adt_CD4", "adt_CD19", "adt_CD14"), 
    ncol = 2)
```

Example 44 (r):
```r
RidgePlot(cbmc, features = c("adt_CD11c", "adt_CD8", "adt_CD16", "adt_CD4", "adt_CD19", "adt_CD14"), 
    ncol = 2)
```

Example 45 (r):
```r
saveRDS(cbmc, file = "../output/cbmc_multimodal.rds")
```

Example 46 (r):
```r
saveRDS(cbmc, file = "../output/cbmc_multimodal.rds")
```

Example 47 (r):
```r
pbmc10k.data <- Read10X(data.dir = "../data/pbmc10k/filtered_feature_bc_matrix/")
rownames(x = pbmc10k.data[["Antibody Capture"]]) <- gsub(pattern = "_[control_]*TotalSeqB", replacement = "", 
    x = rownames(x = pbmc10k.data[["Antibody Capture"]]))

pbmc10k <- CreateSeuratObject(counts = pbmc10k.data[["Gene Expression"]], min.cells = 3, min.features = 200)
pbmc10k <- NormalizeData(pbmc10k)
pbmc10k[["ADT"]] <- CreateAssayObject(pbmc10k.data[["Antibody Capture"]][, colnames(x = pbmc10k)])
pbmc10k <- NormalizeData(pbmc10k, assay = "ADT", normalization.method = "CLR")

plot1 <- FeatureScatter(pbmc10k, feature1 = "adt_CD19", feature2 = "adt_CD3", pt.size = 1)
plot2 <- FeatureScatter(pbmc10k, feature1 = "adt_CD4", feature2 = "adt_CD8a", pt.size = 1)
plot3 <- FeatureScatter(pbmc10k, feature1 = "adt_CD3", feature2 = "CD3E", pt.size = 1)
CombinePlots(plots = list(plot1, plot2, plot3), ncol = 3, legend = "none")
```

Example 48 (r):
```r
pbmc10k.data <- Read10X(data.dir = "../data/pbmc10k/filtered_feature_bc_matrix/")
rownames(x = pbmc10k.data[["Antibody Capture"]]) <- gsub(pattern = "_[control_]*TotalSeqB", replacement = "", 
    x = rownames(x = pbmc10k.data[["Antibody Capture"]]))

pbmc10k <- CreateSeuratObject(counts = pbmc10k.data[["Gene Expression"]], min.cells = 3, min.features = 200)
pbmc10k <- NormalizeData(pbmc10k)
pbmc10k[["ADT"]] <- CreateAssayObject(pbmc10k.data[["Antibody Capture"]][, colnames(x = pbmc10k)])
pbmc10k <- NormalizeData(pbmc10k, assay = "ADT", normalization.method = "CLR")

plot1 <- FeatureScatter(pbmc10k, feature1 = "adt_CD19", feature2 = "adt_CD3", pt.size = 1)
plot2 <- FeatureScatter(pbmc10k, feature1 = "adt_CD4", feature2 = "adt_CD8a", pt.size = 1)
plot3 <- FeatureScatter(pbmc10k, feature1 = "adt_CD3", feature2 = "CD3E", pt.size = 1)
CombinePlots(plots = list(plot1, plot2, plot3), ncol = 3, legend = "none")
```

---

## Tools for Single Cell Genomics • Seurat

**URL:** http://127.0.0.1:9173/seurat.html

**Contents:**
- Seurat v5
- Changes between v4 and v5
- About Seurat
- Links
- License
- Community
- Citation
- Developers

We are excited to release Seurat v5! To install, please follow the instructions in our install page. This update brings the following new features and functionality:

Integrative multimodal analysis: The cellular transcriptome is just one aspect of cellular identity, and recent technologies enable routine profiling of chromatin accessibility, histone modifications, and protein levels from single cells. In Seurat v5, we introduce ‘bridge integration’, a statistical method to integrate experiments measuring different modalities (i.e. separate scRNA-seq and scATAC-seq datasets), using a separate multiomic dataset as a molecular ‘bridge’. For example, we demonstrate how to map scATAC-seq datasets onto scRNA-seq datasets, to assist users in interpreting and annotating data from new modalities. We recognize that while the goal of matching shared cell types across datasets may be important for many problems, users may also be concerned about which method to use, or that integration could result in a loss of biological resolution. In Seurat v5, we also introduce flexible and streamlined workflows for the integration of multiple scRNA-seq datasets. This makes it easier to explore the results of different integration methods, and to compare these results to a workflow that excludes integration steps.

Flexible, interactive, and highly scalable analsyis: The size and scale of single-cell sequencing datasets is rapidly increasing, outpacing even Moore’s law. In Seurat v5, we introduce new infrastructure and methods to analyze, interpret, and explore exciting datasets spanning millions of cells, even if they cannot be fully loaded into memory. We introduce support for ‘sketch’-based analysis, where representative subsamples of a large dataset are stored in-memory to enable rapid and iterative analysis - while the full dataset remains accessible via on-disk storage. We enable high-performance via the BPCells package, developed by Ben Parks in the Greenleaf Lab. The BPCells package enables high-performance analysis via innovative bit-packing compression techniques, optimized C++ code, and use of streamlined and lazy operations.

Analysis of sequencing and imaging-based spatial datasets: Spatially resolved datasets are redefining our understanding of cellular interactions and the organization of human tissues. Both sequencing-based(i.e. Visium, SLIDE-seq, etc.), and imaging-based (MERFISH/Vizgen, Xenium, CosMX, etc.) technologies have unique advantages, and require tailored analytical methods and software infrastructure. In Seurat v5, we introduce flexible and diverse support for a wide variety of spatially resolved data types, and support for analytical techniqiues for scRNA-seq integration, deconvolution, and niche identification.

Backwards compatibility: While Seurat v5 introduces new functionality, we have ensured that the software is backwards-compatible with previous versions, so that users will continue to be able to re-run existing workflows. Previous versions of Seurat, such as Seurat v4, can also be installed following the instructions in our install page.

We have documented major changes between Seurat v4 and v5 in our News page for reference.

Seurat is an R package designed for QC, analysis, and exploration of single-cell RNA-seq data. Seurat aims to enable users to identify and interpret sources of heterogeneity from single-cell transcriptomic measurements, and to integrate diverse types of single-cell data.

If you use Seurat in your research, please considering citing:

All methods emphasize clear, attractive, and interpretable visualizations, and were designed to be easily used by both dry-lab and wet-lab researchers.

Seurat is developed and maintained by the Satija lab and is released under the MIT license.

Developed by Rahul Satija, Satija Lab and Collaborators.

Site built with pkgdown 2.0.7.

---

## Cell-Cycle Scoring and Regression

**URL:** http://127.0.0.1:9173/seurat/archive/v3.2/cell_cycle_vignette/index.html

**Contents:**
- Cell-Cycle Scoring and Regression
    - Compiled: 2020-10-02
  - Assign Cell-Cycle Scores
  - Regress out cell cycle scores during data scaling
  - Alternate Workflow

We demonstrate how to mitigate the effects of cell cycle heterogeneity in scRNA-seq data by calculating cell cycle phase scores based on canonical markers, and regressing these out of the data during pre-processing. We demonstrate this on a dataset of murine hematopoietic progenitors (Nestorowa et al., Blood 2016.You can download the files needed to run this vignette here.

If we run a PCA on our object, using the variable genes we found in FindVariableFeatures above, we see that while most of the variance can be explained by lineage, PC8 and PC10 are split on cell-cycle genes including TOP2A and MKI67. We will attempt to regress this signal from the data, so that cell-cycle heterogneity does not contribute to PCA or downstream analysis.

First, we assign each cell a score, based on its expression of G2/M and S phase markers. These marker sets should be anticorrelated in their expression levels, and cells expressing neither are likely not cycling and in G1 phase.

We assign scores in the CellCycleScoring function, which stores S and G2/M scores in object meta data, along with the predicted classification of each cell in either G2M, S or G1 phase. CellCycleScoring can also set the identity of the Seurat object to the cell-cycle phase by passing set.ident = TRUE (the original identities are stored as old.ident). Please note that Seurat does not use the discrete classifications (G2M/G1/S) in downstream cell cycle regression. Instead, it uses the quantitative scores for G2M and S phase. However, we provide our predicted classifications in case they are of interest.

We score single cells based on the scoring strategy described in Tirosh et al. 2016. See ?AddModuleScore in Seurat for more information, this function can be used to calculate supervised module scores for any gene list.

We now attempt to subtract ('regress out') this source of heterogeneity from the data. For users of Seurat v1.4, this was implemented in RegressOut. However, as the results of this procedure are stored in the scaled data slot (therefore overwriting the output of ScaleData), we now merge this functionality into the ScaleData function itself.

For each gene, Seurat models the relationship between gene expression and the S and G2M cell cycle scores. The scaled residuals of this model represent a 'corrected' expression matrix, that can be used downstream for dimensional reduction.

As the best cell cycle markers are extremely well conserved across tissues and species, we have found this procedure to work robustly and reliably on diverse datasets.

The procedure above removes all signal associated with cell cycle. In some cases, we’ve found that this can negatively impact downstream analysis, particularly in differentiating processes (like murine hematopoiesis), where stem cells are quiescent and differentiated cells are proliferating (or vice versa). In this case, regressing out all cell cycle effects can blur the distinction between stem and progenitor cells as well.

As an alternative, we suggest regressing out the difference between the G2M and S phase scores. This means that signals separating non-cycling cells and cycling cells will be maintained, but differences in cell cycle phase amongst proliferating cells (which are often uninteresting), will be regressed out of the data

**Examples:**

Example 1 (r):
```r
library(Seurat)

# Read in the expression matrix The first row is a header row, the first column is rownames
exp.mat <- read.table(file = "../data/nestorawa_forcellcycle_expressionMatrix.txt", header = TRUE, 
    as.is = TRUE, row.names = 1)

# A list of cell cycle markers, from Tirosh et al, 2015, is loaded with Seurat.  We can
# segregate this list into markers of G2/M phase and markers of S phase
s.genes <- cc.genes$s.genes
g2m.genes <- cc.genes$g2m.genes

# Create our Seurat object and complete the initalization steps
marrow <- CreateSeuratObject(counts = exp.mat)
marrow <- NormalizeData(marrow)
marrow <- FindVariableFeatures(marrow, selection.method = "vst")
marrow <- ScaleData(marrow, features = rownames(marrow))
```

Example 2 (r):
```r
library(Seurat)

# Read in the expression matrix The first row is a header row, the first column is rownames
exp.mat <- read.table(file = "../data/nestorawa_forcellcycle_expressionMatrix.txt", header = TRUE, 
    as.is = TRUE, row.names = 1)

# A list of cell cycle markers, from Tirosh et al, 2015, is loaded with Seurat.  We can
# segregate this list into markers of G2/M phase and markers of S phase
s.genes <- cc.genes$s.genes
g2m.genes <- cc.genes$g2m.genes

# Create our Seurat object and complete the initalization steps
marrow <- CreateSeuratObject(counts = exp.mat)
marrow <- NormalizeData(marrow)
marrow <- FindVariableFeatures(marrow, selection.method = "vst")
marrow <- ScaleData(marrow, features = rownames(marrow))
```

Example 3 (unknown):
```unknown
FindVariableFeatures
```

Example 4 (r):
```r
marrow <- RunPCA(marrow, features = VariableFeatures(marrow), ndims.print = 6:10, nfeatures.print = 10)
```

Example 5 (r):
```r
marrow <- RunPCA(marrow, features = VariableFeatures(marrow), ndims.print = 6:10, nfeatures.print = 10)
```

Example 6 (unknown):
```unknown
## PC_ 6 
## Positive:  SELL, ARL6IP1, CCL9, CD34, ADGRL4, BPIFC, NUSAP1, FAM64A, CD244, C030034L19RIK 
## Negative:  LY6C2, AA467197, CYBB, MGST2, ITGB2, PF4, CD74, ATP1B1, GP1BB, TREM3 
## PC_ 7 
## Positive:  HDC, CPA3, PGLYRP1, MS4A3, NKG7, UBE2C, CCNB1, NUSAP1, PLK1, FUT8 
## Negative:  F13A1, LY86, CFP, IRF8, CSF1R, TIFAB, IFI209, CCR2, TNS4, MS4A6C 
## PC_ 8 
## Positive:  NUSAP1, UBE2C, KIF23, PLK1, CENPF, FAM64A, CCNB1, H2AFX, ID2, CDC20 
## Negative:  WFDC17, SLC35D3, ADGRL4, VLDLR, CD33, H2AFY, P2RY14, IFI206, CCL9, CD34 
## PC_ 9 
## Positive:  IGKC, JCHAIN, LY6D, MZB1, CD74, IGLC2, FCRLA, IGKV4-50, IGHM, IGHV9-1 
## Negative:  SLC2A6, HBA-A1, HBA-A2, IGHV8-7, FCER1G, F13A1, HBB-BS, PLD4, HBB-BT, IGFBP4 
## PC_ 10 
## Positive:  CTSW, XKRX, PRR5L, RORA, MBOAT4, A630014C17RIK, ZFP105, COL9A3, CLEC2I, TRAT1 
## Negative:  H2AFX, FAM64A, ZFP383, NUSAP1, CDC25B, CENPF, GBP10, TOP2A, GBP6, GFRA1
```

Example 7 (unknown):
```unknown
## PC_ 6 
## Positive:  SELL, ARL6IP1, CCL9, CD34, ADGRL4, BPIFC, NUSAP1, FAM64A, CD244, C030034L19RIK 
## Negative:  LY6C2, AA467197, CYBB, MGST2, ITGB2, PF4, CD74, ATP1B1, GP1BB, TREM3 
## PC_ 7 
## Positive:  HDC, CPA3, PGLYRP1, MS4A3, NKG7, UBE2C, CCNB1, NUSAP1, PLK1, FUT8 
## Negative:  F13A1, LY86, CFP, IRF8, CSF1R, TIFAB, IFI209, CCR2, TNS4, MS4A6C 
## PC_ 8 
## Positive:  NUSAP1, UBE2C, KIF23, PLK1, CENPF, FAM64A, CCNB1, H2AFX, ID2, CDC20 
## Negative:  WFDC17, SLC35D3, ADGRL4, VLDLR, CD33, H2AFY, P2RY14, IFI206, CCL9, CD34 
## PC_ 9 
## Positive:  IGKC, JCHAIN, LY6D, MZB1, CD74, IGLC2, FCRLA, IGKV4-50, IGHM, IGHV9-1 
## Negative:  SLC2A6, HBA-A1, HBA-A2, IGHV8-7, FCER1G, F13A1, HBB-BS, PLD4, HBB-BT, IGFBP4 
## PC_ 10 
## Positive:  CTSW, XKRX, PRR5L, RORA, MBOAT4, A630014C17RIK, ZFP105, COL9A3, CLEC2I, TRAT1 
## Negative:  H2AFX, FAM64A, ZFP383, NUSAP1, CDC25B, CENPF, GBP10, TOP2A, GBP6, GFRA1
```

Example 8 (r):
```r
DimHeatmap(marrow, dims = c(8, 10))
```

Example 9 (r):
```r
DimHeatmap(marrow, dims = c(8, 10))
```

Example 10 (unknown):
```unknown
CellCycleScoring
```

Example 11 (unknown):
```unknown
CellCycleScoring
```

Example 12 (unknown):
```unknown
set.ident = TRUE
```

Example 13 (r):
```r
marrow <- CellCycleScoring(marrow, s.features = s.genes, g2m.features = g2m.genes, set.ident = TRUE)

# view cell cycle scores and phase assignments
head(marrow[[]])
```

Example 14 (r):
```r
marrow <- CellCycleScoring(marrow, s.features = s.genes, g2m.features = g2m.genes, set.ident = TRUE)

# view cell cycle scores and phase assignments
head(marrow[[]])
```

Example 15 (r):
```r
# Visualize the distribution of cell cycle markers across
RidgePlot(marrow, features = c("PCNA", "TOP2A", "MCM6", "MKI67"), ncol = 2)
```

Example 16 (r):
```r
# Visualize the distribution of cell cycle markers across
RidgePlot(marrow, features = c("PCNA", "TOP2A", "MCM6", "MKI67"), ncol = 2)
```

Example 17 (r):
```r
# Running a PCA on cell cycle genes reveals, unsurprisingly, that cells separate entirely by
# phase
marrow <- RunPCA(marrow, features = c(s.genes, g2m.genes))
DimPlot(marrow)
```

Example 18 (r):
```r
# Running a PCA on cell cycle genes reveals, unsurprisingly, that cells separate entirely by
# phase
marrow <- RunPCA(marrow, features = c(s.genes, g2m.genes))
DimPlot(marrow)
```

Example 19 (unknown):
```unknown
?AddModuleScore
```

Example 20 (r):
```r
marrow <- ScaleData(marrow, vars.to.regress = c("S.Score", "G2M.Score"), features = rownames(marrow))
```

Example 21 (r):
```r
marrow <- ScaleData(marrow, vars.to.regress = c("S.Score", "G2M.Score"), features = rownames(marrow))
```

Example 22 (r):
```r
# Now, a PCA on the variable genes no longer returns components associated with cell cycle
marrow <- RunPCA(marrow, features = VariableFeatures(marrow), nfeatures.print = 10)
```

Example 23 (r):
```r
# Now, a PCA on the variable genes no longer returns components associated with cell cycle
marrow <- RunPCA(marrow, features = VariableFeatures(marrow), nfeatures.print = 10)
```

Example 24 (unknown):
```unknown
## PC_ 1 
## Positive:  BLVRB, CAR2, KLF1, AQP1, CES2G, ERMAP, CAR1, FAM132A, RHD, SPHK1 
## Negative:  TMSB4X, H2AFY, CORO1A, PLAC8, EMB, MPO, PRTN3, CD34, LCP1, BC035044 
## PC_ 2 
## Positive:  ANGPT1, ADGRG1, MEIS1, ITGA2B, MPL, DAPP1, APOE, RAB37, GATA2, F2R 
## Negative:  LY6C2, ELANE, HP, IGSF6, ANXA3, CTSG, CLEC12A, TIFAB, SLPI, ALAS1 
## PC_ 3 
## Positive:  APOE, GATA2, NKG7, MUC13, MS4A3, RAB44, HDC, CPA3, FCGR3, TUBA8 
## Negative:  FLT3, DNTT, LSP1, WFDC17, MYL10, GIMAP6, LAX1, GPR171, TBXA2R, SATB1 
## PC_ 4 
## Positive:  CSRP3, ST8SIA6, DNTT, MPEG1, SCIN, LGALS1, CMAH, RGL1, APOE, MFSD2B 
## Negative:  PROCR, MPL, HLF, MMRN1, SERPINA3G, ESAM, GSTM1, D630039A03RIK, MYL10, LY6A 
## PC_ 5 
## Positive:  PF4, GP1BB, SDPR, F2RL2, RAB27B, SLC14A1, TREML1, PBX1, F2R, TUBA8 
## Negative:  CPA3, LMO4, IKZF2, IFITM1, FUT8, MS4A2, SIGLECF, CSRP3, HDC, RAB44
```

Example 25 (unknown):
```unknown
## PC_ 1 
## Positive:  BLVRB, CAR2, KLF1, AQP1, CES2G, ERMAP, CAR1, FAM132A, RHD, SPHK1 
## Negative:  TMSB4X, H2AFY, CORO1A, PLAC8, EMB, MPO, PRTN3, CD34, LCP1, BC035044 
## PC_ 2 
## Positive:  ANGPT1, ADGRG1, MEIS1, ITGA2B, MPL, DAPP1, APOE, RAB37, GATA2, F2R 
## Negative:  LY6C2, ELANE, HP, IGSF6, ANXA3, CTSG, CLEC12A, TIFAB, SLPI, ALAS1 
## PC_ 3 
## Positive:  APOE, GATA2, NKG7, MUC13, MS4A3, RAB44, HDC, CPA3, FCGR3, TUBA8 
## Negative:  FLT3, DNTT, LSP1, WFDC17, MYL10, GIMAP6, LAX1, GPR171, TBXA2R, SATB1 
## PC_ 4 
## Positive:  CSRP3, ST8SIA6, DNTT, MPEG1, SCIN, LGALS1, CMAH, RGL1, APOE, MFSD2B 
## Negative:  PROCR, MPL, HLF, MMRN1, SERPINA3G, ESAM, GSTM1, D630039A03RIK, MYL10, LY6A 
## PC_ 5 
## Positive:  PF4, GP1BB, SDPR, F2RL2, RAB27B, SLC14A1, TREML1, PBX1, F2R, TUBA8 
## Negative:  CPA3, LMO4, IKZF2, IFITM1, FUT8, MS4A2, SIGLECF, CSRP3, HDC, RAB44
```

Example 26 (r):
```r
# When running a PCA on only cell cycle genes, cells no longer separate by cell-cycle phase
marrow <- RunPCA(marrow, features = c(s.genes, g2m.genes))
DimPlot(marrow)
```

Example 27 (r):
```r
# When running a PCA on only cell cycle genes, cells no longer separate by cell-cycle phase
marrow <- RunPCA(marrow, features = c(s.genes, g2m.genes))
DimPlot(marrow)
```

Example 28 (r):
```r
marrow$CC.Difference <- marrow$S.Score - marrow$G2M.Score
marrow <- ScaleData(marrow, vars.to.regress = "CC.Difference", features = rownames(marrow))
```

Example 29 (r):
```r
marrow$CC.Difference <- marrow$S.Score - marrow$G2M.Score
marrow <- ScaleData(marrow, vars.to.regress = "CC.Difference", features = rownames(marrow))
```

Example 30 (r):
```r
# cell cycle effects strongly mitigated in PCA
marrow <- RunPCA(marrow, features = VariableFeatures(marrow), nfeatures.print = 10)
```

Example 31 (r):
```r
# cell cycle effects strongly mitigated in PCA
marrow <- RunPCA(marrow, features = VariableFeatures(marrow), nfeatures.print = 10)
```

Example 32 (unknown):
```unknown
## PC_ 1 
## Positive:  BLVRB, KLF1, ERMAP, FAM132A, CAR2, RHD, CES2G, SPHK1, AQP1, SLC38A5 
## Negative:  TMSB4X, CORO1A, PLAC8, H2AFY, LAPTM5, CD34, LCP1, TMEM176B, IGFBP4, EMB 
## PC_ 2 
## Positive:  APOE, GATA2, RAB37, ANGPT1, ADGRG1, MEIS1, MPL, F2R, PDZK1IP1, DAPP1 
## Negative:  CTSG, ELANE, LY6C2, HP, CLEC12A, ANXA3, IGSF6, TIFAB, SLPI, MPO 
## PC_ 3 
## Positive:  APOE, GATA2, NKG7, MUC13, ITGA2B, TUBA8, CPA3, RAB44, SLC18A2, CD9 
## Negative:  DNTT, FLT3, WFDC17, LSP1, MYL10, LAX1, GIMAP6, IGHM, CD24A, MN1 
## PC_ 4 
## Positive:  CSRP3, ST8SIA6, SCIN, LGALS1, APOE, ITGB7, MFSD2B, RGL1, DNTT, IGHV1-23 
## Negative:  MPL, MMRN1, PROCR, HLF, SERPINA3G, ESAM, PTGS1, D630039A03RIK, NDN, PPIC 
## PC_ 5 
## Positive:  HDC, LMO4, CSRP3, IFITM1, FCGR3, HLF, CPA3, PROCR, PGLYRP1, IKZF2 
## Negative:  GP1BB, PF4, SDPR, F2RL2, TREML1, RAB27B, SLC14A1, PBX1, PLEK, TUBA8
```

Example 33 (unknown):
```unknown
## PC_ 1 
## Positive:  BLVRB, KLF1, ERMAP, FAM132A, CAR2, RHD, CES2G, SPHK1, AQP1, SLC38A5 
## Negative:  TMSB4X, CORO1A, PLAC8, H2AFY, LAPTM5, CD34, LCP1, TMEM176B, IGFBP4, EMB 
## PC_ 2 
## Positive:  APOE, GATA2, RAB37, ANGPT1, ADGRG1, MEIS1, MPL, F2R, PDZK1IP1, DAPP1 
## Negative:  CTSG, ELANE, LY6C2, HP, CLEC12A, ANXA3, IGSF6, TIFAB, SLPI, MPO 
## PC_ 3 
## Positive:  APOE, GATA2, NKG7, MUC13, ITGA2B, TUBA8, CPA3, RAB44, SLC18A2, CD9 
## Negative:  DNTT, FLT3, WFDC17, LSP1, MYL10, LAX1, GIMAP6, IGHM, CD24A, MN1 
## PC_ 4 
## Positive:  CSRP3, ST8SIA6, SCIN, LGALS1, APOE, ITGB7, MFSD2B, RGL1, DNTT, IGHV1-23 
## Negative:  MPL, MMRN1, PROCR, HLF, SERPINA3G, ESAM, PTGS1, D630039A03RIK, NDN, PPIC 
## PC_ 5 
## Positive:  HDC, LMO4, CSRP3, IFITM1, FCGR3, HLF, CPA3, PROCR, PGLYRP1, IKZF2 
## Negative:  GP1BB, PF4, SDPR, F2RL2, TREML1, RAB27B, SLC14A1, PBX1, PLEK, TUBA8
```

Example 34 (r):
```r
# when running a PCA on cell cycle genes, actively proliferating cells remain distinct from G1
# cells however, within actively proliferating cells, G2M and S phase cells group together
marrow <- RunPCA(marrow, features = c(s.genes, g2m.genes))
DimPlot(marrow)
```

Example 35 (r):
```r
# when running a PCA on cell cycle genes, actively proliferating cells remain distinct from G1
# cells however, within actively proliferating cells, G2M and S phase cells group together
marrow <- RunPCA(marrow, features = c(s.genes, g2m.genes))
DimPlot(marrow)
```

---

## Demultiplexing with hashtag oligos (HTOs)

**URL:** http://127.0.0.1:9173/seurat/archive/v3.2/hashing_vignette/index.html

**Contents:**
- Demultiplexing with hashtag oligos (HTOs)
    - Compiled: 2020-10-02
- 8-HTO dataset from human PBMCs
  - Basic setup
  - Adding HTO data as an independent assay
  - Demultiplex cells based on HTO enrichment
  - Visualize demultiplexing results
- 12-HTO dataset from four human cell lines
  - Create Seurat object, add HTO data and perform normalization
  - Demultiplex data
  - Visualize demultiplexing results
  - Visualize RNA clustering

Developed in collaboration with the Technology Innovation Group at NYGC, Cell Hashing uses oligo-tagged antibodies against ubuquitously expressed surface proteins to place a "sample barcode" on each single cell, enabling different samples to be multiplexed together and run in a single experiment. For more information, please refer to this paper.

This vignette will give a brief demonstration on how to work with data produced with Cell Hashing in Seurat. Applied to two datasets, we can successfully demultiplex cells to their the original sample-of-origin, and identify cross-sample doublets.

Setup Seurat object and add in the HTO data

You can read more about working with multi-modal data here

Here we use the Seurat function HTODemux() to assign single cells back to their sample origins.

Output from running HTODemux() is saved in the object metadata. We can visualize how many cells are classified as singlets, doublets and negative/ambiguous cells.

Visualize enrichment for selected HTOs with ridge plots

Visualize pairs of HTO signals to confirm mutual exclusivity in singlets

Compare number of UMIs for singlets, doublets and negative cells

Generate a two dimensional tSNE embedding for HTOs.Here we are grouping cells by singlets and doublets for simplicity.

Create an HTO heatmap, based on Figure 1C in the Cell Hashing paper.

Cluster and visualize cells using the usual scRNA-seq workflow, and examine for the potential presence of batch effects.

Distribution of selected HTOs grouped by classification, displayed by ridge plots

Visualize HTO signals in a heatmap

**Examples:**

Example 1 (r):
```r
library(Seurat)
```

Example 2 (r):
```r
library(Seurat)
```

Example 3 (r):
```r
# Load in the UMI matrix
pbmc.umis <- readRDS("../data/pbmc_umi_mtx.rds")

# For generating a hashtag count matrix from FASTQ files, please refer to
# https://github.com/Hoohm/CITE-seq-Count.  Load in the HTO count matrix
pbmc.htos <- readRDS("../data/pbmc_hto_mtx.rds")

# Select cell barcodes detected by both RNA and HTO In the example datasets we have already
# filtered the cells for you, but perform this step for clarity.
joint.bcs <- intersect(colnames(pbmc.umis), colnames(pbmc.htos))

# Subset RNA and HTO counts by joint cell barcodes
pbmc.umis <- pbmc.umis[, joint.bcs]
pbmc.htos <- as.matrix(pbmc.htos[, joint.bcs])

# Confirm that the HTO have the correct names
rownames(pbmc.htos)
```

Example 4 (r):
```r
# Load in the UMI matrix
pbmc.umis <- readRDS("../data/pbmc_umi_mtx.rds")

# For generating a hashtag count matrix from FASTQ files, please refer to
# https://github.com/Hoohm/CITE-seq-Count.  Load in the HTO count matrix
pbmc.htos <- readRDS("../data/pbmc_hto_mtx.rds")

# Select cell barcodes detected by both RNA and HTO In the example datasets we have already
# filtered the cells for you, but perform this step for clarity.
joint.bcs <- intersect(colnames(pbmc.umis), colnames(pbmc.htos))

# Subset RNA and HTO counts by joint cell barcodes
pbmc.umis <- pbmc.umis[, joint.bcs]
pbmc.htos <- as.matrix(pbmc.htos[, joint.bcs])

# Confirm that the HTO have the correct names
rownames(pbmc.htos)
```

Example 5 (unknown):
```unknown
## [1] "HTO_A" "HTO_B" "HTO_C" "HTO_D" "HTO_E" "HTO_F" "HTO_G" "HTO_H"
```

Example 6 (unknown):
```unknown
## [1] "HTO_A" "HTO_B" "HTO_C" "HTO_D" "HTO_E" "HTO_F" "HTO_G" "HTO_H"
```

Example 7 (r):
```r
# Setup Seurat object
pbmc.hashtag <- CreateSeuratObject(counts = pbmc.umis)

# Normalize RNA data with log normalization
pbmc.hashtag <- NormalizeData(pbmc.hashtag)
# Find and scale variable features
pbmc.hashtag <- FindVariableFeatures(pbmc.hashtag, selection.method = "mean.var.plot")
pbmc.hashtag <- ScaleData(pbmc.hashtag, features = VariableFeatures(pbmc.hashtag))
```

Example 8 (r):
```r
# Setup Seurat object
pbmc.hashtag <- CreateSeuratObject(counts = pbmc.umis)

# Normalize RNA data with log normalization
pbmc.hashtag <- NormalizeData(pbmc.hashtag)
# Find and scale variable features
pbmc.hashtag <- FindVariableFeatures(pbmc.hashtag, selection.method = "mean.var.plot")
pbmc.hashtag <- ScaleData(pbmc.hashtag, features = VariableFeatures(pbmc.hashtag))
```

Example 9 (r):
```r
# Add HTO data as a new assay independent from RNA
pbmc.hashtag[["HTO"]] <- CreateAssayObject(counts = pbmc.htos)
# Normalize HTO data, here we use centered log-ratio (CLR) transformation
pbmc.hashtag <- NormalizeData(pbmc.hashtag, assay = "HTO", normalization.method = "CLR")
```

Example 10 (r):
```r
# Add HTO data as a new assay independent from RNA
pbmc.hashtag[["HTO"]] <- CreateAssayObject(counts = pbmc.htos)
# Normalize HTO data, here we use centered log-ratio (CLR) transformation
pbmc.hashtag <- NormalizeData(pbmc.hashtag, assay = "HTO", normalization.method = "CLR")
```

Example 11 (r):
```r
# If you have a very large dataset we suggest using k_function = 'clara'. This is a k-medoid
# clustering function for large applications You can also play with additional parameters (see
# documentation for HTODemux()) to adjust the threshold for classification Here we are using the
# default settings
pbmc.hashtag <- HTODemux(pbmc.hashtag, assay = "HTO", positive.quantile = 0.99)
```

Example 12 (r):
```r
# If you have a very large dataset we suggest using k_function = 'clara'. This is a k-medoid
# clustering function for large applications You can also play with additional parameters (see
# documentation for HTODemux()) to adjust the threshold for classification Here we are using the
# default settings
pbmc.hashtag <- HTODemux(pbmc.hashtag, assay = "HTO", positive.quantile = 0.99)
```

Example 13 (r):
```r
# Global classification results
table(pbmc.hashtag$HTO_classification.global)
```

Example 14 (r):
```r
# Global classification results
table(pbmc.hashtag$HTO_classification.global)
```

Example 15 (javascript):
```javascript
## 
##  Doublet Negative  Singlet 
##     2598      346    13972
```

Example 16 (javascript):
```javascript
## 
##  Doublet Negative  Singlet 
##     2598      346    13972
```

Example 17 (r):
```r
# Group cells based on the max HTO signal
Idents(pbmc.hashtag) <- "HTO_maxID"
RidgePlot(pbmc.hashtag, assay = "HTO", features = rownames(pbmc.hashtag[["HTO"]])[1:2], ncol = 2)
```

Example 18 (r):
```r
# Group cells based on the max HTO signal
Idents(pbmc.hashtag) <- "HTO_maxID"
RidgePlot(pbmc.hashtag, assay = "HTO", features = rownames(pbmc.hashtag[["HTO"]])[1:2], ncol = 2)
```

Example 19 (r):
```r
FeatureScatter(pbmc.hashtag, feature1 = "hto_HTO-A", feature2 = "hto_HTO-B")
```

Example 20 (r):
```r
FeatureScatter(pbmc.hashtag, feature1 = "hto_HTO-A", feature2 = "hto_HTO-B")
```

Example 21 (r):
```r
Idents(pbmc.hashtag) <- "HTO_classification.global"
VlnPlot(pbmc.hashtag, features = "nCount_RNA", pt.size = 0.1, log = TRUE)
```

Example 22 (r):
```r
Idents(pbmc.hashtag) <- "HTO_classification.global"
VlnPlot(pbmc.hashtag, features = "nCount_RNA", pt.size = 0.1, log = TRUE)
```

Example 23 (r):
```r
# First, we will remove negative cells from the object
pbmc.hashtag.subset <- subset(pbmc.hashtag, idents = "Negative", invert = TRUE)

# Calculate a tSNE embedding of the HTO data
DefaultAssay(pbmc.hashtag.subset) <- "HTO"
pbmc.hashtag.subset <- ScaleData(pbmc.hashtag.subset, features = rownames(pbmc.hashtag.subset), 
    verbose = FALSE)
pbmc.hashtag.subset <- RunPCA(pbmc.hashtag.subset, features = rownames(pbmc.hashtag.subset), approx = FALSE)
pbmc.hashtag.subset <- RunTSNE(pbmc.hashtag.subset, dims = 1:8, perplexity = 100)
DimPlot(pbmc.hashtag.subset)
```

Example 24 (r):
```r
# First, we will remove negative cells from the object
pbmc.hashtag.subset <- subset(pbmc.hashtag, idents = "Negative", invert = TRUE)

# Calculate a tSNE embedding of the HTO data
DefaultAssay(pbmc.hashtag.subset) <- "HTO"
pbmc.hashtag.subset <- ScaleData(pbmc.hashtag.subset, features = rownames(pbmc.hashtag.subset), 
    verbose = FALSE)
pbmc.hashtag.subset <- RunPCA(pbmc.hashtag.subset, features = rownames(pbmc.hashtag.subset), approx = FALSE)
pbmc.hashtag.subset <- RunTSNE(pbmc.hashtag.subset, dims = 1:8, perplexity = 100)
DimPlot(pbmc.hashtag.subset)
```

Example 25 (r):
```r
# You can also visualize the more detailed classification result by running Idents(object) <-
# 'HTO_classification' before plotting. Here, you can see that each of the small clouds on the
# tSNE plot corresponds to one of the 28 possible doublet combinations.
```

Example 26 (r):
```r
# You can also visualize the more detailed classification result by running Idents(object) <-
# 'HTO_classification' before plotting. Here, you can see that each of the small clouds on the
# tSNE plot corresponds to one of the 28 possible doublet combinations.
```

Example 27 (r):
```r
# To increase the efficiency of plotting, you can subsample cells using the num.cells argument
HTOHeatmap(pbmc.hashtag, assay = "HTO", ncells = 5000)
```

Example 28 (r):
```r
# To increase the efficiency of plotting, you can subsample cells using the num.cells argument
HTOHeatmap(pbmc.hashtag, assay = "HTO", ncells = 5000)
```

Example 29 (r):
```r
# Extract the singlets
pbmc.singlet <- subset(pbmc.hashtag, idents = "Singlet")

# Select the top 1000 most variable features
pbmc.singlet <- FindVariableFeatures(pbmc.singlet, selection.method = "mean.var.plot")

# Scaling RNA data, we only scale the variable features here for efficiency
pbmc.singlet <- ScaleData(pbmc.singlet, features = VariableFeatures(pbmc.singlet))

# Run PCA
pbmc.singlet <- RunPCA(pbmc.singlet, features = VariableFeatures(pbmc.singlet))
```

Example 30 (r):
```r
# Extract the singlets
pbmc.singlet <- subset(pbmc.hashtag, idents = "Singlet")

# Select the top 1000 most variable features
pbmc.singlet <- FindVariableFeatures(pbmc.singlet, selection.method = "mean.var.plot")

# Scaling RNA data, we only scale the variable features here for efficiency
pbmc.singlet <- ScaleData(pbmc.singlet, features = VariableFeatures(pbmc.singlet))

# Run PCA
pbmc.singlet <- RunPCA(pbmc.singlet, features = VariableFeatures(pbmc.singlet))
```

Example 31 (r):
```r
# We select the top 10 PCs for clustering and tSNE based on PCElbowPlot
pbmc.singlet <- FindNeighbors(pbmc.singlet, reduction = "pca", dims = 1:10)
pbmc.singlet <- FindClusters(pbmc.singlet, resolution = 0.6, verbose = FALSE)
pbmc.singlet <- RunTSNE(pbmc.singlet, reduction = "pca", dims = 1:10)

# Projecting singlet identities on TSNE visualization
DimPlot(pbmc.singlet, group.by = "HTO_classification")
```

Example 32 (r):
```r
# We select the top 10 PCs for clustering and tSNE based on PCElbowPlot
pbmc.singlet <- FindNeighbors(pbmc.singlet, reduction = "pca", dims = 1:10)
pbmc.singlet <- FindClusters(pbmc.singlet, resolution = 0.6, verbose = FALSE)
pbmc.singlet <- RunTSNE(pbmc.singlet, reduction = "pca", dims = 1:10)

# Projecting singlet identities on TSNE visualization
DimPlot(pbmc.singlet, group.by = "HTO_classification")
```

Example 33 (r):
```r
# Read in UMI count matrix for RNA
hto12.umis <- readRDS("../data/hto12_umi_mtx.rds")

# Read in HTO count matrix
hto12.htos <- readRDS("../data/hto12_hto_mtx.rds")

# Select cell barcodes detected in both RNA and HTO
cells.use <- intersect(rownames(hto12.htos), colnames(hto12.umis))

# Create Seurat object and add HTO data
hto12 <- CreateSeuratObject(counts = hto12.umis[, cells.use], min.features = 300)
hto12[["HTO"]] <- CreateAssayObject(counts = t(x = hto12.htos[colnames(hto12), 1:12]))

# Normalize data
hto12 <- NormalizeData(hto12)
hto12 <- NormalizeData(hto12, assay = "HTO", normalization.method = "CLR")
```

Example 34 (r):
```r
# Read in UMI count matrix for RNA
hto12.umis <- readRDS("../data/hto12_umi_mtx.rds")

# Read in HTO count matrix
hto12.htos <- readRDS("../data/hto12_hto_mtx.rds")

# Select cell barcodes detected in both RNA and HTO
cells.use <- intersect(rownames(hto12.htos), colnames(hto12.umis))

# Create Seurat object and add HTO data
hto12 <- CreateSeuratObject(counts = hto12.umis[, cells.use], min.features = 300)
hto12[["HTO"]] <- CreateAssayObject(counts = t(x = hto12.htos[colnames(hto12), 1:12]))

# Normalize data
hto12 <- NormalizeData(hto12)
hto12 <- NormalizeData(hto12, assay = "HTO", normalization.method = "CLR")
```

Example 35 (r):
```r
hto12 <- HTODemux(hto12, assay = "HTO", positive.quantile = 0.99)
```

Example 36 (r):
```r
hto12 <- HTODemux(hto12, assay = "HTO", positive.quantile = 0.99)
```

Example 37 (r):
```r
RidgePlot(hto12, assay = "HTO", features = c("HEK-A", "K562-B", "KG1-A", "THP1-C"), ncol = 2)
```

Example 38 (r):
```r
RidgePlot(hto12, assay = "HTO", features = c("HEK-A", "K562-B", "KG1-A", "THP1-C"), ncol = 2)
```

Example 39 (r):
```r
HTOHeatmap(hto12, assay = "HTO")
```

Example 40 (r):
```r
HTOHeatmap(hto12, assay = "HTO")
```

Example 41 (r):
```r
# Remove the negative cells
hto12 <- subset(hto12, idents = "Negative", invert = TRUE)

# Run PCA on most variable features
hto12 <- FindVariableFeatures(hto12, selection.method = "mean.var.plot")
hto12 <- ScaleData(hto12, features = VariableFeatures(hto12))
hto12 <- RunPCA(hto12)
hto12 <- RunTSNE(hto12, dims = 1:5, perplexity = 100)
DimPlot(hto12) + NoLegend()
```

Example 42 (r):
```r
# Remove the negative cells
hto12 <- subset(hto12, idents = "Negative", invert = TRUE)

# Run PCA on most variable features
hto12 <- FindVariableFeatures(hto12, selection.method = "mean.var.plot")
hto12 <- ScaleData(hto12, features = VariableFeatures(hto12))
hto12 <- RunPCA(hto12)
hto12 <- RunTSNE(hto12, dims = 1:5, perplexity = 100)
DimPlot(hto12) + NoLegend()
```

---

## Analysis, visualization, and integration of Visium HD spatial datasets with Seurat • Seurat

**URL:** http://127.0.0.1:9173/articles_sctransform_vignette.html

**Contents:**
- Using sctransform in Seurat
    - Saket Choudhary, Christoph Hafemeister & Rahul Satija
    - Compiled: 2023-10-31
- Load data and create Seurat object
- Apply sctransform normalization
- Perform dimensionality reduction by PCA and UMAP embedding
- Contents

Biological heterogeneity in single-cell RNA-seq data is often confounded by technical factors including sequencing depth. The number of molecules detected in each cell can vary significantly between cells, even within the same celltype. Interpretation of scRNA-seq data requires effective pre-processing and normalization to remove this technical variability.

In our manuscript we introduce a modeling framework for the normalization and variance stabilization of molecular count data from scRNA-seq experiments. This procedure omits the need for heuristic steps including pseudocount addition or log-transformation and improves common downstream analytical tasks such as variable gene selection, dimensional reduction, and differential expression. We named this method sctransform.

Inspired by important and rigorous work from Lause et al, we released an updated manuscript and updated the sctransform software to a v2 version, which is now the default in Seurat v5.

Why can we choose more PCs when using sctransform?

In the standard Seurat workflow we focus on 10 PCs for this dataset, though we highlight that the results are similar with higher settings for this parameter. Interestingly, we’ve found that when using sctransform, we often benefit by pushing this parameter even higher. We believe this is because the sctransform workflow performs more effective normalization, strongly removing technical effects from the data.

Even after standard log-normalization, variation in sequencing depth is still a confounding factor (see Figure 1), and this effect can subtly influence higher PCs. In sctransform, this effect is substantially mitigated (see Figure 3). This means that higher PCs are more likely to represent subtle, but biologically relevant, sources of heterogeneity – so including them may improve downstream analysis.

In addition, sctransform returns 3,000 variable features by default, instead of 2,000. The rationale is similar, the additional variable features are less likely to be driven by technical differences across cells, and instead may represent more subtle biological fluctuations. In general, we find that results produced with sctransform are less dependent on these parameters (indeed, we achieve nearly identical results when using all genes in the transcriptome, though this does reduce computational efficiency). This can help users generate more robust results, and in addition, enables the application of standard analysis pipelines with identical parameter settings that can quickly be applied to new datasets:

For example, the following code replicates the full end-to-end workflow, in a single command:

Where are normalized values stored for sctransform?

The results of sctransfrom are stored in the “SCT” assay. You can learn more about multi-assay data and commands in Seurat in our vignette, command cheat sheet, or developer guide.

Users can individually annotate clusters based on canonical markers. However, the sctransform normalization reveals sharper biological distinctions compared to the standard Seurat workflow, in a few ways:

Developed by Rahul Satija, Satija Lab and Collaborators.

Site built with pkgdown 2.0.7.

**Examples:**

Example 1 (unknown):
```unknown
vignettes/sctransform_vignette.Rmd
```

Example 2 (unknown):
```unknown
sctransform_vignette.Rmd
```

Example 3 (unknown):
```unknown
sctransform
```

Example 4 (unknown):
```unknown
library(Seurat)
library(ggplot2)
library(sctransform)
```

Example 5 (r):
```r
library(Seurat)
library(ggplot2)
library(sctransform)
```

Example 6 (r):
```r
library(Seurat)
library(ggplot2)
library(sctransform)
```

Example 7 (unknown):
```unknown
pbmc_data <- Read10X(data.dir = "/brahms/shared/vignette-data/pbmc3k/filtered_gene_bc_matrices/hg19/")
pbmc <- CreateSeuratObject(counts = pbmc_data)
```

Example 8 (r):
```r
pbmc_data <- Read10X(data.dir = "/brahms/shared/vignette-data/pbmc3k/filtered_gene_bc_matrices/hg19/")
pbmc <- CreateSeuratObject(counts = pbmc_data)
```

Example 9 (r):
```r
pbmc_data <- Read10X(data.dir = "/brahms/shared/vignette-data/pbmc3k/filtered_gene_bc_matrices/hg19/")
pbmc <- CreateSeuratObject(counts = pbmc_data)
```

Example 10 (unknown):
```unknown
NormalizeData()
```

Example 11 (unknown):
```unknown
ScaleData()
```

Example 12 (unknown):
```unknown
FindVariableFeatures()
```

Example 13 (unknown):
```unknown
vst.flavor = 'v1'
```

Example 14 (unknown):
```unknown
# store mitochondrial percentage in object meta data
pbmc <- PercentageFeatureSet(pbmc, pattern = "^MT-", col.name = "percent.mt")

# run sctransform
pbmc <- SCTransform(pbmc, vars.to.regress = "percent.mt", verbose = FALSE)
```

Example 15 (r):
```r
# store mitochondrial percentage in object meta data
pbmc <- PercentageFeatureSet(pbmc, pattern = "^MT-", col.name = "percent.mt")

# run sctransform
pbmc <- SCTransform(pbmc, vars.to.regress = "percent.mt", verbose = FALSE)
```

Example 16 (r):
```r
# store mitochondrial percentage in object meta data
pbmc <- PercentageFeatureSet(pbmc, pattern = "^MT-", col.name = "percent.mt")

# run sctransform
pbmc <- SCTransform(pbmc, vars.to.regress = "percent.mt", verbose = FALSE)
```

Example 17 (unknown):
```unknown
# These are now standard steps in the Seurat workflow for visualization and clustering
pbmc <- RunPCA(pbmc, verbose = FALSE)
pbmc <- RunUMAP(pbmc, dims = 1:30, verbose = FALSE)

pbmc <- FindNeighbors(pbmc, dims = 1:30, verbose = FALSE)
pbmc <- FindClusters(pbmc, verbose = FALSE)
DimPlot(pbmc, label = TRUE)
```

Example 18 (r):
```r
# These are now standard steps in the Seurat workflow for visualization and clustering
pbmc <- RunPCA(pbmc, verbose = FALSE)
pbmc <- RunUMAP(pbmc, dims = 1:30, verbose = FALSE)

pbmc <- FindNeighbors(pbmc, dims = 1:30, verbose = FALSE)
pbmc <- FindClusters(pbmc, verbose = FALSE)
DimPlot(pbmc, label = TRUE)
```

Example 19 (r):
```r
# These are now standard steps in the Seurat workflow for visualization and clustering
pbmc <- RunPCA(pbmc, verbose = FALSE)
pbmc <- RunUMAP(pbmc, dims = 1:30, verbose = FALSE)

pbmc <- FindNeighbors(pbmc, dims = 1:30, verbose = FALSE)
pbmc <- FindClusters(pbmc, verbose = FALSE)
DimPlot(pbmc, label = TRUE)
```

Example 20 (unknown):
```unknown
pbmc <- CreateSeuratObject(pbmc_data) %>%
    PercentageFeatureSet(pattern = "^MT-", col.name = "percent.mt") %>%
    SCTransform(vars.to.regress = "percent.mt") %>%
    RunPCA() %>%
    FindNeighbors(dims = 1:30) %>%
    RunUMAP(dims = 1:30) %>%
    FindClusters()
```

Example 21 (r):
```r
pbmc <- CreateSeuratObject(pbmc_data) %>%
    PercentageFeatureSet(pattern = "^MT-", col.name = "percent.mt") %>%
    SCTransform(vars.to.regress = "percent.mt") %>%
    RunPCA() %>%
    FindNeighbors(dims = 1:30) %>%
    RunUMAP(dims = 1:30) %>%
    FindClusters()
```

Example 22 (r):
```r
pbmc <- CreateSeuratObject(pbmc_data) %>%
    PercentageFeatureSet(pattern = "^MT-", col.name = "percent.mt") %>%
    SCTransform(vars.to.regress = "percent.mt") %>%
    RunPCA() %>%
    FindNeighbors(dims = 1:30) %>%
    RunUMAP(dims = 1:30) %>%
    FindClusters()
```

Example 23 (unknown):
```unknown
pbmc[["SCT"]]$scale.data
```

Example 24 (unknown):
```unknown
SCTransform()
```

Example 25 (unknown):
```unknown
pbmc[["SCT"]]$counts
```

Example 26 (unknown):
```unknown
pbmc[["SCT"]]$data
```

Example 27 (unknown):
```unknown
# These are now standard steps in the Seurat workflow for visualization and clustering
# Visualize canonical marker genes as violin plots.
VlnPlot(pbmc, features = c("CD8A", "GZMK", "CCL5", "S100A4", "ANXA1", "CCR7", "ISG15", "CD3D"),
    pt.size = 0.2, ncol = 4)
```

Example 28 (r):
```r
# These are now standard steps in the Seurat workflow for visualization and clustering
# Visualize canonical marker genes as violin plots.
VlnPlot(pbmc, features = c("CD8A", "GZMK", "CCL5", "S100A4", "ANXA1", "CCR7", "ISG15", "CD3D"),
    pt.size = 0.2, ncol = 4)
```

Example 29 (r):
```r
# These are now standard steps in the Seurat workflow for visualization and clustering
# Visualize canonical marker genes as violin plots.
VlnPlot(pbmc, features = c("CD8A", "GZMK", "CCL5", "S100A4", "ANXA1", "CCR7", "ISG15", "CD3D"),
    pt.size = 0.2, ncol = 4)
```

Example 30 (unknown):
```unknown
# Visualize canonical marker genes on the sctransform embedding.
FeaturePlot(pbmc, features = c("CD8A", "GZMK", "CCL5", "S100A4", "ANXA1", "CCR7"), pt.size = 0.2,
    ncol = 3)
```

Example 31 (r):
```r
# Visualize canonical marker genes on the sctransform embedding.
FeaturePlot(pbmc, features = c("CD8A", "GZMK", "CCL5", "S100A4", "ANXA1", "CCR7"), pt.size = 0.2,
    ncol = 3)
```

Example 32 (r):
```r
# Visualize canonical marker genes on the sctransform embedding.
FeaturePlot(pbmc, features = c("CD8A", "GZMK", "CCL5", "S100A4", "ANXA1", "CCR7"), pt.size = 0.2,
    ncol = 3)
```

Example 33 (unknown):
```unknown
FeaturePlot(pbmc, features = c("CD3D", "ISG15", "TCL1A", "FCER2", "XCL1", "FCGR3A"), pt.size = 0.2,
    ncol = 3)
```

Example 34 (r):
```r
FeaturePlot(pbmc, features = c("CD3D", "ISG15", "TCL1A", "FCER2", "XCL1", "FCGR3A"), pt.size = 0.2,
    ncol = 3)
```

Example 35 (r):
```r
FeaturePlot(pbmc, features = c("CD3D", "ISG15", "TCL1A", "FCER2", "XCL1", "FCGR3A"), pt.size = 0.2,
    ncol = 3)
```

Example 36 (unknown):
```unknown
sessionInfo()
```

Example 37 (r):
```r
sessionInfo()
```

Example 38 (r):
```r
sessionInfo()
```

Example 39 (unknown):
```unknown
## R version 4.2.2 Patched (2022-11-10 r83330)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.6 LTS
## 
## Matrix products: default
## BLAS:   /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.9.0
## LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.9.0
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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       
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
## [1] sctransform_0.4.1  ggplot2_3.4.4      Seurat_5.0.0       SeuratObject_5.0.0
## [5] sp_2.1-1          
## 
## loaded via a namespace (and not attached):
##   [1] spam_2.10-0                 systemfonts_1.0.4          
##   [3] plyr_1.8.9                  igraph_1.5.1               
##   [5] lazyeval_0.2.2              splines_4.2.2              
##   [7] RcppHNSW_0.5.0              listenv_0.9.0              
##   [9] scattermore_1.2             GenomeInfoDb_1.34.9        
##  [11] digest_0.6.33               htmltools_0.5.6.1          
##  [13] fansi_1.0.5                 magrittr_2.0.3             
##  [15] memoise_2.0.1               tensor_1.5                 
##  [17] cluster_2.1.4               ROCR_1.0-11                
##  [19] globals_0.16.2              matrixStats_1.0.0          
##  [21] R.utils_2.12.2              pkgdown_2.0.7              
##  [23] spatstat.sparse_3.0-3       colorspace_2.1-0           
##  [25] ggrepel_0.9.4               textshaping_0.3.6          
##  [27] xfun_0.40                   dplyr_1.1.3                
##  [29] RCurl_1.98-1.12             jsonlite_1.8.7             
##  [31] progressr_0.14.0            spatstat.data_3.0-3        
##  [33] survival_3.5-7              zoo_1.8-12                 
##  [35] glue_1.6.2                  polyclip_1.10-6            
##  [37] gtable_0.3.4                zlibbioc_1.44.0            
##  [39] XVector_0.38.0              leiden_0.4.3               
##  [41] DelayedArray_0.24.0         future.apply_1.11.0        
##  [43] BiocGenerics_0.44.0         abind_1.4-5                
##  [45] scales_1.2.1                spatstat.random_3.2-1      
##  [47] miniUI_0.1.1.1              Rcpp_1.0.11                
##  [49] viridisLite_0.4.2           xtable_1.8-4               
##  [51] reticulate_1.34.0           dotCall64_1.1-0            
##  [53] stats4_4.2.2                htmlwidgets_1.6.2          
##  [55] httr_1.4.7                  RColorBrewer_1.1-3         
##  [57] ellipsis_0.3.2              ica_1.0-3                  
##  [59] farver_2.1.1                pkgconfig_2.0.3            
##  [61] R.methodsS3_1.8.2           sass_0.4.7                 
##  [63] uwot_0.1.16                 deldir_1.0-9               
##  [65] utf8_1.2.4                  labeling_0.4.3             
##  [67] tidyselect_1.2.0            rlang_1.1.1                
##  [69] reshape2_1.4.4              later_1.3.1                
##  [71] munsell_0.5.0               tools_4.2.2                
##  [73] cachem_1.0.8                cli_3.6.1                  
##  [75] generics_0.1.3              ggridges_0.5.4             
##  [77] evaluate_0.22               stringr_1.5.0              
##  [79] fastmap_1.1.1               yaml_2.3.7                 
##  [81] ragg_1.2.5                  goftest_1.2-3              
##  [83] knitr_1.45                  fs_1.6.3                   
##  [85] fitdistrplus_1.1-11         purrr_1.0.2                
##  [87] RANN_2.6.1                  sparseMatrixStats_1.10.0   
##  [89] pbapply_1.7-2               future_1.33.0              
##  [91] nlme_3.1-162                mime_0.12                  
##  [93] formatR_1.14                ggrastr_1.0.1              
##  [95] R.oo_1.25.0                 compiler_4.2.2             
##  [97] beeswarm_0.4.0              plotly_4.10.3              
##  [99] png_0.1-8                   spatstat.utils_3.0-4       
## [101] tibble_3.2.1                bslib_0.5.1                
## [103] glmGamPoi_1.10.2            stringi_1.7.12             
## [105] highr_0.10                  desc_1.4.2                 
## [107] RSpectra_0.16-1             lattice_0.21-9             
## [109] Matrix_1.6-1.1              vctrs_0.6.4                
## [111] pillar_1.9.0                lifecycle_1.0.3            
## [113] spatstat.geom_3.2-7         lmtest_0.9-40              
## [115] jquerylib_0.1.4             RcppAnnoy_0.0.21           
## [117] bitops_1.0-7                data.table_1.14.8          
## [119] cowplot_1.1.1               irlba_2.3.5.1              
## [121] GenomicRanges_1.50.2        httpuv_1.6.12              
## [123] patchwork_1.1.3             R6_2.5.1                   
## [125] promises_1.2.1              KernSmooth_2.23-22         
## [127] gridExtra_2.3               vipor_0.4.5                
## [129] IRanges_2.32.0              parallelly_1.36.0          
## [131] codetools_0.2-19            fastDummies_1.7.3          
## [133] MASS_7.3-58.2               SummarizedExperiment_1.28.0
## [135] rprojroot_2.0.3             withr_2.5.2                
## [137] GenomeInfoDbData_1.2.9      S4Vectors_0.36.2           
## [139] parallel_4.2.2              grid_4.2.2                 
## [141] tidyr_1.3.0                 DelayedMatrixStats_1.20.0  
## [143] rmarkdown_2.25              MatrixGenerics_1.10.0      
## [145] Rtsne_0.16                  spatstat.explore_3.2-5     
## [147] Biobase_2.58.0              shiny_1.7.5.1              
## [149] ggbeeswarm_0.7.1
```

Example 40 (unknown):
```unknown
## R version 4.2.2 Patched (2022-11-10 r83330)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.6 LTS
## 
## Matrix products: default
## BLAS:   /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.9.0
## LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.9.0
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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       
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
## [1] sctransform_0.4.1  ggplot2_3.4.4      Seurat_5.0.0       SeuratObject_5.0.0
## [5] sp_2.1-1          
## 
## loaded via a namespace (and not attached):
##   [1] spam_2.10-0                 systemfonts_1.0.4          
##   [3] plyr_1.8.9                  igraph_1.5.1               
##   [5] lazyeval_0.2.2              splines_4.2.2              
##   [7] RcppHNSW_0.5.0              listenv_0.9.0              
##   [9] scattermore_1.2             GenomeInfoDb_1.34.9        
##  [11] digest_0.6.33               htmltools_0.5.6.1          
##  [13] fansi_1.0.5                 magrittr_2.0.3             
##  [15] memoise_2.0.1               tensor_1.5                 
##  [17] cluster_2.1.4               ROCR_1.0-11                
##  [19] globals_0.16.2              matrixStats_1.0.0          
##  [21] R.utils_2.12.2              pkgdown_2.0.7              
##  [23] spatstat.sparse_3.0-3       colorspace_2.1-0           
##  [25] ggrepel_0.9.4               textshaping_0.3.6          
##  [27] xfun_0.40                   dplyr_1.1.3                
##  [29] RCurl_1.98-1.12             jsonlite_1.8.7             
##  [31] progressr_0.14.0            spatstat.data_3.0-3        
##  [33] survival_3.5-7              zoo_1.8-12                 
##  [35] glue_1.6.2                  polyclip_1.10-6            
##  [37] gtable_0.3.4                zlibbioc_1.44.0            
##  [39] XVector_0.38.0              leiden_0.4.3               
##  [41] DelayedArray_0.24.0         future.apply_1.11.0        
##  [43] BiocGenerics_0.44.0         abind_1.4-5                
##  [45] scales_1.2.1                spatstat.random_3.2-1      
##  [47] miniUI_0.1.1.1              Rcpp_1.0.11                
##  [49] viridisLite_0.4.2           xtable_1.8-4               
##  [51] reticulate_1.34.0           dotCall64_1.1-0            
##  [53] stats4_4.2.2                htmlwidgets_1.6.2          
##  [55] httr_1.4.7                  RColorBrewer_1.1-3         
##  [57] ellipsis_0.3.2              ica_1.0-3                  
##  [59] farver_2.1.1                pkgconfig_2.0.3            
##  [61] R.methodsS3_1.8.2           sass_0.4.7                 
##  [63] uwot_0.1.16                 deldir_1.0-9               
##  [65] utf8_1.2.4                  labeling_0.4.3             
##  [67] tidyselect_1.2.0            rlang_1.1.1                
##  [69] reshape2_1.4.4              later_1.3.1                
##  [71] munsell_0.5.0               tools_4.2.2                
##  [73] cachem_1.0.8                cli_3.6.1                  
##  [75] generics_0.1.3              ggridges_0.5.4             
##  [77] evaluate_0.22               stringr_1.5.0              
##  [79] fastmap_1.1.1               yaml_2.3.7                 
##  [81] ragg_1.2.5                  goftest_1.2-3              
##  [83] knitr_1.45                  fs_1.6.3                   
##  [85] fitdistrplus_1.1-11         purrr_1.0.2                
##  [87] RANN_2.6.1                  sparseMatrixStats_1.10.0   
##  [89] pbapply_1.7-2               future_1.33.0              
##  [91] nlme_3.1-162                mime_0.12                  
##  [93] formatR_1.14                ggrastr_1.0.1              
##  [95] R.oo_1.25.0                 compiler_4.2.2             
##  [97] beeswarm_0.4.0              plotly_4.10.3              
##  [99] png_0.1-8                   spatstat.utils_3.0-4       
## [101] tibble_3.2.1                bslib_0.5.1                
## [103] glmGamPoi_1.10.2            stringi_1.7.12             
## [105] highr_0.10                  desc_1.4.2                 
## [107] RSpectra_0.16-1             lattice_0.21-9             
## [109] Matrix_1.6-1.1              vctrs_0.6.4                
## [111] pillar_1.9.0                lifecycle_1.0.3            
## [113] spatstat.geom_3.2-7         lmtest_0.9-40              
## [115] jquerylib_0.1.4             RcppAnnoy_0.0.21           
## [117] bitops_1.0-7                data.table_1.14.8          
## [119] cowplot_1.1.1               irlba_2.3.5.1              
## [121] GenomicRanges_1.50.2        httpuv_1.6.12              
## [123] patchwork_1.1.3             R6_2.5.1                   
## [125] promises_1.2.1              KernSmooth_2.23-22         
## [127] gridExtra_2.3               vipor_0.4.5                
## [129] IRanges_2.32.0              parallelly_1.36.0          
## [131] codetools_0.2-19            fastDummies_1.7.3          
## [133] MASS_7.3-58.2               SummarizedExperiment_1.28.0
## [135] rprojroot_2.0.3             withr_2.5.2                
## [137] GenomeInfoDbData_1.2.9      S4Vectors_0.36.2           
## [139] parallel_4.2.2              grid_4.2.2                 
## [141] tidyr_1.3.0                 DelayedMatrixStats_1.20.0  
## [143] rmarkdown_2.25              MatrixGenerics_1.10.0      
## [145] Rtsne_0.16                  spatstat.explore_3.2-5     
## [147] Biobase_2.58.0              shiny_1.7.5.1              
## [149] ggbeeswarm_0.7.1
```

---

## Analysis, visualization, and integration of Visium HD spatial datasets with Seurat • Seurat

**URL:** http://127.0.0.1:9173/install_v5.html

**Contents:**
- Installation Instructions for Seurat
- Seurat 5: Install from CRAN
- Install previous versions of Seurat
  - Install Seurat v4
  - Older versions of Seurat
- Install the development version of Seurat
- Docker
- Contents

To install Seurat, R version 4.0 or greater is required. We also recommend installing R Studio.

Seurat is available on CRAN for all platforms. To install, run:

Seurat does not require, but makes use of, packages developed by other labs that can substantially enhance speed and performance. These include presto (Korunsky/Raychaudhari labs), BPCells (Greenleaf Lab), and glmGamPoi (Huber Lab). We recommend users install these along with Seurat:

We also recommend installing these additional packages, which are used in our vignettes, and enhance the functionality of Seurat:

Seurat v4.4.0 can be installed with the following commands:

Old versions of Seurat, from Seurat v2.0.1 and up, are hosted in CRAN’s archive. To install an old version of Seurat, run:

For versions of Seurat older than those not hosted on CRAN (versions 1.3.0 and 1.4.0), please download the packaged source code from our releases page and install from the tarball.

Install the development version of Seurat - directly from GitHub.

We provide docker images for Seurat via dockerhub.

To pull the latest image from the command line:

To use as a base image in a new Dockerfile:

Developed by Rahul Satija, Satija Lab and Collaborators.

Site built with pkgdown 2.0.7.

**Examples:**

Example 1 (unknown):
```unknown
vignettes/install_v5.Rmd
```

Example 2 (unknown):
```unknown
install_v5.Rmd
```

Example 3 (unknown):
```unknown
# Enter commands in R (or R studio, if installed)
install.packages('Seurat')
library(Seurat)
```

Example 4 (r):
```r
# Enter commands in R (or R studio, if installed)
install.packages('Seurat')
library(Seurat)
```

Example 5 (r):
```r
# Enter commands in R (or R studio, if installed)
install.packages('Seurat')
library(Seurat)
```

Example 6 (unknown):
```unknown
setRepositories(ind = 1:3, addURLs = c('https://satijalab.r-universe.dev', 'https://bnprks.r-universe.dev/'))
install.packages(c("BPCells", "presto", "glmGamPoi"))
```

Example 7 (r):
```r
setRepositories(ind = 1:3, addURLs = c('https://satijalab.r-universe.dev', 'https://bnprks.r-universe.dev/'))
install.packages(c("BPCells", "presto", "glmGamPoi"))
```

Example 8 (r):
```r
setRepositories(ind = 1:3, addURLs = c('https://satijalab.r-universe.dev', 'https://bnprks.r-universe.dev/'))
install.packages(c("BPCells", "presto", "glmGamPoi"))
```

Example 9 (unknown):
```unknown
# Install the remotes package
if (!requireNamespace("remotes", quietly = TRUE)) {
  install.packages("remotes")
}
install.packages('Signac')
remotes::install_github("satijalab/seurat-data", quiet = TRUE)
remotes::install_github("satijalab/azimuth", quiet = TRUE)
remotes::install_github("satijalab/seurat-wrappers", quiet = TRUE)
```

Example 10 (r):
```r
# Install the remotes package
if (!requireNamespace("remotes", quietly = TRUE)) {
  install.packages("remotes")
}
install.packages('Signac')
remotes::install_github("satijalab/seurat-data", quiet = TRUE)
remotes::install_github("satijalab/azimuth", quiet = TRUE)
remotes::install_github("satijalab/seurat-wrappers", quiet = TRUE)
```

Example 11 (r):
```r
# Install the remotes package
if (!requireNamespace("remotes", quietly = TRUE)) {
  install.packages("remotes")
}
install.packages('Signac')
remotes::install_github("satijalab/seurat-data", quiet = TRUE)
remotes::install_github("satijalab/azimuth", quiet = TRUE)
remotes::install_github("satijalab/seurat-wrappers", quiet = TRUE)
```

Example 12 (unknown):
```unknown
remotes::install_version("SeuratObject", "4.1.4", repos = c("https://satijalab.r-universe.dev", getOption("repos")))
remotes::install_version("Seurat", "4.4.0", repos = c("https://satijalab.r-universe.dev", getOption("repos")))
```

Example 13 (r):
```r
remotes::install_version("SeuratObject", "4.1.4", repos = c("https://satijalab.r-universe.dev", getOption("repos")))
remotes::install_version("Seurat", "4.4.0", repos = c("https://satijalab.r-universe.dev", getOption("repos")))
```

Example 14 (r):
```r
remotes::install_version("SeuratObject", "4.1.4", repos = c("https://satijalab.r-universe.dev", getOption("repos")))
remotes::install_version("Seurat", "4.4.0", repos = c("https://satijalab.r-universe.dev", getOption("repos")))
```

Example 15 (unknown):
```unknown
# Install the remotes package 
install.packages('remotes')
# Replace 'X.X.X' with your desired version
remotes::install_version(package = 'Seurat', version = package_version('X.X.X'))
```

Example 16 (r):
```r
# Install the remotes package 
install.packages('remotes')
# Replace 'X.X.X' with your desired version
remotes::install_version(package = 'Seurat', version = package_version('X.X.X'))
```

Example 17 (r):
```r
# Install the remotes package 
install.packages('remotes')
# Replace 'X.X.X' with your desired version
remotes::install_version(package = 'Seurat', version = package_version('X.X.X'))
```

Example 18 (unknown):
```unknown
# Enter commands in R (or R studio, if installed)
# Install the remotes package
install.packages('remotes')
remotes::install_github(repo = 'satijalab/seurat', ref = 'develop')
library(Seurat)
```

Example 19 (r):
```r
# Enter commands in R (or R studio, if installed)
# Install the remotes package
install.packages('remotes')
remotes::install_github(repo = 'satijalab/seurat', ref = 'develop')
library(Seurat)
```

Example 20 (r):
```r
# Enter commands in R (or R studio, if installed)
# Install the remotes package
install.packages('remotes')
remotes::install_github(repo = 'satijalab/seurat', ref = 'develop')
library(Seurat)
```

Example 21 (unknown):
```unknown
docker pull satijalab/seurat:latest
```

Example 22 (unknown):
```unknown
docker pull satijalab/seurat:latest
```

Example 23 (bash):
```bash
docker pull satijalab/seurat:latest
```

Example 24 (unknown):
```unknown
FROM satijalab/seurat:latest
```

Example 25 (unknown):
```unknown
FROM satijalab/seurat:latest
```

Example 26 (bash):
```bash
FROM satijalab/seurat:latest
```

---

## Analysis, visualization, and integration of Visium HD spatial datasets with Seurat • Seurat

**URL:** http://127.0.0.1:9173/seurat/multimodal_vignette.html

**Contents:**
- Using Seurat with multimodal data
    - Compiled: 2023-11-16
- Load in the data
- Setup a Seurat object, add the RNA and protein data
- Cluster cells on the basis of their scRNA-seq profiles
- Visualize multiple modalities side-by-side
- Identify cell surface markers for scRNA-seq clusters
- Additional visualizations of multimodal data
- Loading data from 10X multi-modal experiments
- Additional functionality for multimodal data in Seurat
- Contents

The ability to make simultaneous measurements of multiple data types from the same cell, known as multimodal analysis, represents a new and exciting frontier for single-cell genomics. For example, CITE-seq enables the simultaneous measurements of transcriptomes and cell-surface proteins from the same cell. Other exciting multimodal technologies, such as the 10x multiome kit allow for the paired measurements of cellular transcriptome and chromatin accessibility (i.e scRNA-seq+scATAC-seq). Other modalities that can be measured alongside cellular transcriptomes include genetic perturbations, cellular methylomes, and hashtag oligos from Cell Hashing. We have designed Seurat to enable for the seamless storage, analysis, and exploration of diverse multimodal single-cell datasets.

In this vignette, we present an introductory workflow for creating a multimodal Seurat object and performing an initial analysis. For example, we demonstrate how to cluster a CITE-seq dataset on the basis of the measured cellular transcriptomes, and subsequently discover cell surface proteins that are enriched in each cluster. We note that Seurat also enables more advanced techniques for the analysis of multimodal data, in particular the application of our Weighted Nearest Neighbors (WNN) approach that enables simultaneous clustering of cells based on a weighted combination of both modalities, and you can explore this functionality here.

Here, we analyze a dataset of 8,617 cord blood mononuclear cells (CBMCs), where transcriptomic measurements are paired with abundance estimates for 11 surface proteins, whose levels are quantified with DNA-barcoded antibodies. First, we load in two count matrices : one for the RNA measurements, and one for the antibody-derived tags (ADT). You can download the ADT file here and the RNA file here

Now we create a Seurat object, and add the ADT data as a second assay

The steps below represent a quick clustering of the PBMCs based on the scRNA-seq data. For more detail on individual steps or more advanced options, see our PBMC clustering guided tutorial here

Now that we have obtained clusters from scRNA-seq profiles, we can visualize the expression of either protein or RNA molecules in our dataset. Importantly, Seurat provides a couple ways to switch between modalities, and specify which modality you are interested in analyzing or visualizing. This is particularly important as, in some cases, the same feature can be present in multiple modalities - for example this dataset contains independent measurements of the B cell marker CD19 (both protein and RNA levels).

We can leverage our paired CITE-seq measurements to help annotate clusters derived from scRNA-seq, and to identify both protein and RNA markers.

Seurat is also able to analyze data from multimodal 10X experiments processed using CellRanger v3; as an example, we recreate the plots above using a dataset of 7,900 peripheral blood mononuclear cells (PBMC), freely available from 10X Genomics here.

Seurat v4 also includes additional functionality for the analysis, visualization, and integration of multimodal datasets. For more information, please explore the resources below:

Developed by Rahul Satija, Satija Lab and Collaborators.

Site built with pkgdown 2.0.7.

**Examples:**

Example 1 (unknown):
```unknown
vignettes/multimodal_vignette.Rmd
```

Example 2 (unknown):
```unknown
multimodal_vignette.Rmd
```

Example 3 (unknown):
```unknown
library(Seurat)
library(ggplot2)
library(patchwork)
```

Example 4 (r):
```r
library(Seurat)
library(ggplot2)
library(patchwork)
```

Example 5 (r):
```r
library(Seurat)
library(ggplot2)
library(patchwork)
```

Example 6 (python):
```python
# Load in the RNA UMI matrix

# Note that this dataset also contains ~5% of mouse cells, which we can use as negative
# controls for the protein measurements. For this reason, the gene expression matrix has
# HUMAN_ or MOUSE_ appended to the beginning of each gene.
cbmc.rna <- as.sparse(read.csv(file = "/brahms/shared/vignette-data/GSE100866_CBMC_8K_13AB_10X-RNA_umi.csv.gz",
    sep = ",", header = TRUE, row.names = 1))

# To make life a bit easier going forward, we're going to discard all but the top 100 most
# highly expressed mouse genes, and remove the 'HUMAN_' from the CITE-seq prefix
cbmc.rna <- CollapseSpeciesExpressionMatrix(cbmc.rna)

# Load in the ADT UMI matrix
cbmc.adt <- as.sparse(read.csv(file = "/brahms/shared/vignette-data/GSE100866_CBMC_8K_13AB_10X-ADT_umi.csv.gz",
    sep = ",", header = TRUE, row.names = 1))

# Note that since measurements were made in the same cells, the two matrices have identical
# column names
all.equal(colnames(cbmc.rna), colnames(cbmc.adt))
```

Example 7 (r):
```r
# Load in the RNA UMI matrix

# Note that this dataset also contains ~5% of mouse cells, which we can use as negative
# controls for the protein measurements. For this reason, the gene expression matrix has
# HUMAN_ or MOUSE_ appended to the beginning of each gene.
cbmc.rna <- as.sparse(read.csv(file = "/brahms/shared/vignette-data/GSE100866_CBMC_8K_13AB_10X-RNA_umi.csv.gz",
    sep = ",", header = TRUE, row.names = 1))

# To make life a bit easier going forward, we're going to discard all but the top 100 most
# highly expressed mouse genes, and remove the 'HUMAN_' from the CITE-seq prefix
cbmc.rna <- CollapseSpeciesExpressionMatrix(cbmc.rna)

# Load in the ADT UMI matrix
cbmc.adt <- as.sparse(read.csv(file = "/brahms/shared/vignette-data/GSE100866_CBMC_8K_13AB_10X-ADT_umi.csv.gz",
    sep = ",", header = TRUE, row.names = 1))

# Note that since measurements were made in the same cells, the two matrices have identical
# column names
all.equal(colnames(cbmc.rna), colnames(cbmc.adt))
```

Example 8 (r):
```r
# Load in the RNA UMI matrix

# Note that this dataset also contains ~5% of mouse cells, which we can use as negative
# controls for the protein measurements. For this reason, the gene expression matrix has
# HUMAN_ or MOUSE_ appended to the beginning of each gene.
cbmc.rna <- as.sparse(read.csv(file = "/brahms/shared/vignette-data/GSE100866_CBMC_8K_13AB_10X-RNA_umi.csv.gz",
    sep = ",", header = TRUE, row.names = 1))

# To make life a bit easier going forward, we're going to discard all but the top 100 most
# highly expressed mouse genes, and remove the 'HUMAN_' from the CITE-seq prefix
cbmc.rna <- CollapseSpeciesExpressionMatrix(cbmc.rna)

# Load in the ADT UMI matrix
cbmc.adt <- as.sparse(read.csv(file = "/brahms/shared/vignette-data/GSE100866_CBMC_8K_13AB_10X-ADT_umi.csv.gz",
    sep = ",", header = TRUE, row.names = 1))

# Note that since measurements were made in the same cells, the two matrices have identical
# column names
all.equal(colnames(cbmc.rna), colnames(cbmc.adt))
```

Example 9 (unknown):
```unknown
## [1] TRUE
```

Example 10 (unknown):
```unknown
## [1] TRUE
```

Example 11 (unknown):
```unknown
# creates a Seurat object based on the scRNA-seq data
cbmc <- CreateSeuratObject(counts = cbmc.rna)

# We can see that by default, the cbmc object contains an assay storing RNA measurement
Assays(cbmc)
```

Example 12 (r):
```r
# creates a Seurat object based on the scRNA-seq data
cbmc <- CreateSeuratObject(counts = cbmc.rna)

# We can see that by default, the cbmc object contains an assay storing RNA measurement
Assays(cbmc)
```

Example 13 (r):
```r
# creates a Seurat object based on the scRNA-seq data
cbmc <- CreateSeuratObject(counts = cbmc.rna)

# We can see that by default, the cbmc object contains an assay storing RNA measurement
Assays(cbmc)
```

Example 14 (unknown):
```unknown
## [1] "RNA"
```

Example 15 (unknown):
```unknown
## [1] "RNA"
```

Example 16 (unknown):
```unknown
# create a new assay to store ADT information
adt_assay <- CreateAssay5Object(counts = cbmc.adt)

# add this assay to the previously created Seurat object
cbmc[["ADT"]] <- adt_assay

# Validate that the object now contains multiple assays
Assays(cbmc)
```

Example 17 (r):
```r
# create a new assay to store ADT information
adt_assay <- CreateAssay5Object(counts = cbmc.adt)

# add this assay to the previously created Seurat object
cbmc[["ADT"]] <- adt_assay

# Validate that the object now contains multiple assays
Assays(cbmc)
```

Example 18 (r):
```r
# create a new assay to store ADT information
adt_assay <- CreateAssay5Object(counts = cbmc.adt)

# add this assay to the previously created Seurat object
cbmc[["ADT"]] <- adt_assay

# Validate that the object now contains multiple assays
Assays(cbmc)
```

Example 19 (unknown):
```unknown
## [1] "RNA" "ADT"
```

Example 20 (unknown):
```unknown
## [1] "RNA" "ADT"
```

Example 21 (unknown):
```unknown
# Extract a list of features measured in the ADT assay
rownames(cbmc[["ADT"]])
```

Example 22 (r):
```r
# Extract a list of features measured in the ADT assay
rownames(cbmc[["ADT"]])
```

Example 23 (r):
```r
# Extract a list of features measured in the ADT assay
rownames(cbmc[["ADT"]])
```

Example 24 (unknown):
```unknown
##  [1] "CD3"    "CD4"    "CD8"    "CD45RA" "CD56"   "CD16"   "CD10"   "CD11c" 
##  [9] "CD14"   "CD19"   "CD34"   "CCR5"   "CCR7"
```

Example 25 (unknown):
```unknown
##  [1] "CD3"    "CD4"    "CD8"    "CD45RA" "CD56"   "CD16"   "CD10"   "CD11c" 
##  [9] "CD14"   "CD19"   "CD34"   "CCR5"   "CCR7"
```

Example 26 (unknown):
```unknown
# Note that we can easily switch back and forth between the two assays to specify the default
# for visualization and analysis

# List the current default assay
DefaultAssay(cbmc)
```

Example 27 (r):
```r
# Note that we can easily switch back and forth between the two assays to specify the default
# for visualization and analysis

# List the current default assay
DefaultAssay(cbmc)
```

Example 28 (r):
```r
# Note that we can easily switch back and forth between the two assays to specify the default
# for visualization and analysis

# List the current default assay
DefaultAssay(cbmc)
```

Example 29 (unknown):
```unknown
## [1] "RNA"
```

Example 30 (unknown):
```unknown
## [1] "RNA"
```

Example 31 (unknown):
```unknown
# Switch the default to ADT
DefaultAssay(cbmc) <- "ADT"
DefaultAssay(cbmc)
```

Example 32 (r):
```r
# Switch the default to ADT
DefaultAssay(cbmc) <- "ADT"
DefaultAssay(cbmc)
```

Example 33 (r):
```r
# Switch the default to ADT
DefaultAssay(cbmc) <- "ADT"
DefaultAssay(cbmc)
```

Example 34 (unknown):
```unknown
## [1] "ADT"
```

Example 35 (unknown):
```unknown
## [1] "ADT"
```

Example 36 (unknown):
```unknown
# Note that all operations below are performed on the RNA assay Set and verify that the
# default assay is RNA
DefaultAssay(cbmc) <- "RNA"
DefaultAssay(cbmc)
```

Example 37 (r):
```r
# Note that all operations below are performed on the RNA assay Set and verify that the
# default assay is RNA
DefaultAssay(cbmc) <- "RNA"
DefaultAssay(cbmc)
```

Example 38 (r):
```r
# Note that all operations below are performed on the RNA assay Set and verify that the
# default assay is RNA
DefaultAssay(cbmc) <- "RNA"
DefaultAssay(cbmc)
```

Example 39 (unknown):
```unknown
## [1] "RNA"
```

Example 40 (unknown):
```unknown
## [1] "RNA"
```

Example 41 (unknown):
```unknown
# perform visualization and clustering steps
cbmc <- NormalizeData(cbmc)
cbmc <- FindVariableFeatures(cbmc)
cbmc <- ScaleData(cbmc)
cbmc <- RunPCA(cbmc, verbose = FALSE)
cbmc <- FindNeighbors(cbmc, dims = 1:30)
cbmc <- FindClusters(cbmc, resolution = 0.8, verbose = FALSE)
cbmc <- RunUMAP(cbmc, dims = 1:30)
DimPlot(cbmc, label = TRUE)
```

Example 42 (r):
```r
# perform visualization and clustering steps
cbmc <- NormalizeData(cbmc)
cbmc <- FindVariableFeatures(cbmc)
cbmc <- ScaleData(cbmc)
cbmc <- RunPCA(cbmc, verbose = FALSE)
cbmc <- FindNeighbors(cbmc, dims = 1:30)
cbmc <- FindClusters(cbmc, resolution = 0.8, verbose = FALSE)
cbmc <- RunUMAP(cbmc, dims = 1:30)
DimPlot(cbmc, label = TRUE)
```

Example 43 (r):
```r
# perform visualization and clustering steps
cbmc <- NormalizeData(cbmc)
cbmc <- FindVariableFeatures(cbmc)
cbmc <- ScaleData(cbmc)
cbmc <- RunPCA(cbmc, verbose = FALSE)
cbmc <- FindNeighbors(cbmc, dims = 1:30)
cbmc <- FindClusters(cbmc, resolution = 0.8, verbose = FALSE)
cbmc <- RunUMAP(cbmc, dims = 1:30)
DimPlot(cbmc, label = TRUE)
```

Example 44 (unknown):
```unknown
# Normalize ADT data,
DefaultAssay(cbmc) <- "ADT"
cbmc <- NormalizeData(cbmc, normalization.method = "CLR", margin = 2)
DefaultAssay(cbmc) <- "RNA"

# Note that the following command is an alternative but returns the same result
cbmc <- NormalizeData(cbmc, normalization.method = "CLR", margin = 2, assay = "ADT")

# Now, we will visualize CD14 levels for RNA and protein By setting the default assay, we can
# visualize one or the other
DefaultAssay(cbmc) <- "ADT"
p1 <- FeaturePlot(cbmc, "CD19", cols = c("lightgrey", "darkgreen")) + ggtitle("CD19 protein")
DefaultAssay(cbmc) <- "RNA"
p2 <- FeaturePlot(cbmc, "CD19") + ggtitle("CD19 RNA")

# place plots side-by-side
p1 | p2
```

Example 45 (r):
```r
# Normalize ADT data,
DefaultAssay(cbmc) <- "ADT"
cbmc <- NormalizeData(cbmc, normalization.method = "CLR", margin = 2)
DefaultAssay(cbmc) <- "RNA"

# Note that the following command is an alternative but returns the same result
cbmc <- NormalizeData(cbmc, normalization.method = "CLR", margin = 2, assay = "ADT")

# Now, we will visualize CD14 levels for RNA and protein By setting the default assay, we can
# visualize one or the other
DefaultAssay(cbmc) <- "ADT"
p1 <- FeaturePlot(cbmc, "CD19", cols = c("lightgrey", "darkgreen")) + ggtitle("CD19 protein")
DefaultAssay(cbmc) <- "RNA"
p2 <- FeaturePlot(cbmc, "CD19") + ggtitle("CD19 RNA")

# place plots side-by-side
p1 | p2
```

Example 46 (r):
```r
# Normalize ADT data,
DefaultAssay(cbmc) <- "ADT"
cbmc <- NormalizeData(cbmc, normalization.method = "CLR", margin = 2)
DefaultAssay(cbmc) <- "RNA"

# Note that the following command is an alternative but returns the same result
cbmc <- NormalizeData(cbmc, normalization.method = "CLR", margin = 2, assay = "ADT")

# Now, we will visualize CD14 levels for RNA and protein By setting the default assay, we can
# visualize one or the other
DefaultAssay(cbmc) <- "ADT"
p1 <- FeaturePlot(cbmc, "CD19", cols = c("lightgrey", "darkgreen")) + ggtitle("CD19 protein")
DefaultAssay(cbmc) <- "RNA"
p2 <- FeaturePlot(cbmc, "CD19") + ggtitle("CD19 RNA")

# place plots side-by-side
p1 | p2
```

Example 47 (unknown):
```unknown
# Alternately, we can use specific assay keys to specify a specific modality Identify the key
# for the RNA and protein assays
Key(cbmc[["RNA"]])
```

Example 48 (r):
```r
# Alternately, we can use specific assay keys to specify a specific modality Identify the key
# for the RNA and protein assays
Key(cbmc[["RNA"]])
```

Example 49 (r):
```r
# Alternately, we can use specific assay keys to specify a specific modality Identify the key
# for the RNA and protein assays
Key(cbmc[["RNA"]])
```

Example 50 (unknown):
```unknown
## [1] "rna_"
```

Example 51 (unknown):
```unknown
## [1] "rna_"
```

Example 52 (unknown):
```unknown
Key(cbmc[["ADT"]])
```

Example 53 (r):
```r
Key(cbmc[["ADT"]])
```

Example 54 (r):
```r
Key(cbmc[["ADT"]])
```

Example 55 (unknown):
```unknown
## [1] "adt_"
```

Example 56 (unknown):
```unknown
## [1] "adt_"
```

Example 57 (unknown):
```unknown
# Now, we can include the key in the feature name, which overrides the default assay
p1 <- FeaturePlot(cbmc, "adt_CD19", cols = c("lightgrey", "darkgreen")) + ggtitle("CD19 protein")
p2 <- FeaturePlot(cbmc, "rna_CD19") + ggtitle("CD19 RNA")
p1 | p2
```

Example 58 (r):
```r
# Now, we can include the key in the feature name, which overrides the default assay
p1 <- FeaturePlot(cbmc, "adt_CD19", cols = c("lightgrey", "darkgreen")) + ggtitle("CD19 protein")
p2 <- FeaturePlot(cbmc, "rna_CD19") + ggtitle("CD19 RNA")
p1 | p2
```

Example 59 (r):
```r
# Now, we can include the key in the feature name, which overrides the default assay
p1 <- FeaturePlot(cbmc, "adt_CD19", cols = c("lightgrey", "darkgreen")) + ggtitle("CD19 protein")
p2 <- FeaturePlot(cbmc, "rna_CD19") + ggtitle("CD19 RNA")
p1 | p2
```

Example 60 (unknown):
```unknown
# as we know that CD19 is a B cell marker, we can identify cluster 6 as expressing CD19 on the
# surface
VlnPlot(cbmc, "adt_CD19")
```

Example 61 (r):
```r
# as we know that CD19 is a B cell marker, we can identify cluster 6 as expressing CD19 on the
# surface
VlnPlot(cbmc, "adt_CD19")
```

Example 62 (r):
```r
# as we know that CD19 is a B cell marker, we can identify cluster 6 as expressing CD19 on the
# surface
VlnPlot(cbmc, "adt_CD19")
```

Example 63 (unknown):
```unknown
# we can also identify alternative protein and RNA markers for this cluster through
# differential expression
adt_markers <- FindMarkers(cbmc, ident.1 = 6, assay = "ADT")
rna_markers <- FindMarkers(cbmc, ident.1 = 6, assay = "RNA")

head(adt_markers)
```

Example 64 (r):
```r
# we can also identify alternative protein and RNA markers for this cluster through
# differential expression
adt_markers <- FindMarkers(cbmc, ident.1 = 6, assay = "ADT")
rna_markers <- FindMarkers(cbmc, ident.1 = 6, assay = "RNA")

head(adt_markers)
```

Example 65 (r):
```r
# we can also identify alternative protein and RNA markers for this cluster through
# differential expression
adt_markers <- FindMarkers(cbmc, ident.1 = 6, assay = "ADT")
rna_markers <- FindMarkers(cbmc, ident.1 = 6, assay = "RNA")

head(adt_markers)
```

Example 66 (unknown):
```unknown
##                p_val avg_log2FC pct.1 pct.2     p_val_adj
## CD19   2.067533e-215  2.5741873     1     1 2.687793e-214
## CD45RA 8.108073e-109  0.5300346     1     1 1.054049e-107
## CD4    1.123162e-107 -1.6707420     1     1 1.460110e-106
## CD14   7.212876e-106 -1.0332070     1     1 9.376739e-105
## CD3     1.639633e-87 -1.5823056     1     1  2.131523e-86
## CCR5    2.552859e-63  0.3753989     1     1  3.318716e-62
```

Example 67 (unknown):
```unknown
##                p_val avg_log2FC pct.1 pct.2     p_val_adj
## CD19   2.067533e-215  2.5741873     1     1 2.687793e-214
## CD45RA 8.108073e-109  0.5300346     1     1 1.054049e-107
## CD4    1.123162e-107 -1.6707420     1     1 1.460110e-106
## CD14   7.212876e-106 -1.0332070     1     1 9.376739e-105
## CD3     1.639633e-87 -1.5823056     1     1  2.131523e-86
## CCR5    2.552859e-63  0.3753989     1     1  3.318716e-62
```

Example 68 (unknown):
```unknown
head(rna_markers)
```

Example 69 (r):
```r
head(rna_markers)
```

Example 70 (r):
```r
head(rna_markers)
```

Example 71 (unknown):
```unknown
##       p_val avg_log2FC pct.1 pct.2 p_val_adj
## IGHM      0   6.660187 0.977 0.044         0
## CD79A     0   6.748356 0.965 0.045         0
## TCL1A     0   7.428099 0.904 0.028         0
## CD79B     0   5.525568 0.944 0.089         0
## IGHD      0   7.811884 0.857 0.015         0
## MS4A1     0   7.523215 0.851 0.016         0
```

Example 72 (unknown):
```unknown
##       p_val avg_log2FC pct.1 pct.2 p_val_adj
## IGHM      0   6.660187 0.977 0.044         0
## CD79A     0   6.748356 0.965 0.045         0
## TCL1A     0   7.428099 0.904 0.028         0
## CD79B     0   5.525568 0.944 0.089         0
## IGHD      0   7.811884 0.857 0.015         0
## MS4A1     0   7.523215 0.851 0.016         0
```

Example 73 (unknown):
```unknown
# Draw ADT scatter plots (like biaxial plots for FACS). Note that you can even 'gate' cells if
# desired by using HoverLocator and FeatureLocator
FeatureScatter(cbmc, feature1 = "adt_CD19", feature2 = "adt_CD3")
```

Example 74 (r):
```r
# Draw ADT scatter plots (like biaxial plots for FACS). Note that you can even 'gate' cells if
# desired by using HoverLocator and FeatureLocator
FeatureScatter(cbmc, feature1 = "adt_CD19", feature2 = "adt_CD3")
```

Example 75 (r):
```r
# Draw ADT scatter plots (like biaxial plots for FACS). Note that you can even 'gate' cells if
# desired by using HoverLocator and FeatureLocator
FeatureScatter(cbmc, feature1 = "adt_CD19", feature2 = "adt_CD3")
```

Example 76 (unknown):
```unknown
# view relationship between protein and RNA
FeatureScatter(cbmc, feature1 = "adt_CD3", feature2 = "rna_CD3E")
```

Example 77 (r):
```r
# view relationship between protein and RNA
FeatureScatter(cbmc, feature1 = "adt_CD3", feature2 = "rna_CD3E")
```

Example 78 (r):
```r
# view relationship between protein and RNA
FeatureScatter(cbmc, feature1 = "adt_CD3", feature2 = "rna_CD3E")
```

Example 79 (unknown):
```unknown
FeatureScatter(cbmc, feature1 = "adt_CD4", feature2 = "adt_CD8")
```

Example 80 (r):
```r
FeatureScatter(cbmc, feature1 = "adt_CD4", feature2 = "adt_CD8")
```

Example 81 (r):
```r
FeatureScatter(cbmc, feature1 = "adt_CD4", feature2 = "adt_CD8")
```

Example 82 (unknown):
```unknown
# Let's look at the raw (non-normalized) ADT counts. You can see the values are quite high,
# particularly in comparison to RNA values. This is due to the significantly higher protein
# copy number in cells, which significantly reduces 'drop-out' in ADT data
FeatureScatter(cbmc, feature1 = "adt_CD4", feature2 = "adt_CD8", slot = "counts")
```

Example 83 (r):
```r
# Let's look at the raw (non-normalized) ADT counts. You can see the values are quite high,
# particularly in comparison to RNA values. This is due to the significantly higher protein
# copy number in cells, which significantly reduces 'drop-out' in ADT data
FeatureScatter(cbmc, feature1 = "adt_CD4", feature2 = "adt_CD8", slot = "counts")
```

Example 84 (r):
```r
# Let's look at the raw (non-normalized) ADT counts. You can see the values are quite high,
# particularly in comparison to RNA values. This is due to the significantly higher protein
# copy number in cells, which significantly reduces 'drop-out' in ADT data
FeatureScatter(cbmc, feature1 = "adt_CD4", feature2 = "adt_CD8", slot = "counts")
```

Example 85 (unknown):
```unknown
pbmc10k.data <- Read10X(data.dir = "/brahms/shared/vignette-data/pbmc10k/filtered_feature_bc_matrix/")
rownames(x = pbmc10k.data[["Antibody Capture"]]) <- gsub(pattern = "_[control_]*TotalSeqB", replacement = "",
    x = rownames(x = pbmc10k.data[["Antibody Capture"]]))

pbmc10k <- CreateSeuratObject(counts = pbmc10k.data[["Gene Expression"]], min.cells = 3, min.features = 200)
pbmc10k <- NormalizeData(pbmc10k)
pbmc10k[["ADT"]] <- CreateAssayObject(pbmc10k.data[["Antibody Capture"]][, colnames(x = pbmc10k)])
pbmc10k <- NormalizeData(pbmc10k, assay = "ADT", normalization.method = "CLR")

plot1 <- FeatureScatter(pbmc10k, feature1 = "adt_CD19", feature2 = "adt_CD3", pt.size = 1)
plot2 <- FeatureScatter(pbmc10k, feature1 = "adt_CD4", feature2 = "adt_CD8a", pt.size = 1)
plot3 <- FeatureScatter(pbmc10k, feature1 = "adt_CD3", feature2 = "CD3E", pt.size = 1)
(plot1 + plot2 + plot3) & NoLegend()
```

Example 86 (r):
```r
pbmc10k.data <- Read10X(data.dir = "/brahms/shared/vignette-data/pbmc10k/filtered_feature_bc_matrix/")
rownames(x = pbmc10k.data[["Antibody Capture"]]) <- gsub(pattern = "_[control_]*TotalSeqB", replacement = "",
    x = rownames(x = pbmc10k.data[["Antibody Capture"]]))

pbmc10k <- CreateSeuratObject(counts = pbmc10k.data[["Gene Expression"]], min.cells = 3, min.features = 200)
pbmc10k <- NormalizeData(pbmc10k)
pbmc10k[["ADT"]] <- CreateAssayObject(pbmc10k.data[["Antibody Capture"]][, colnames(x = pbmc10k)])
pbmc10k <- NormalizeData(pbmc10k, assay = "ADT", normalization.method = "CLR")

plot1 <- FeatureScatter(pbmc10k, feature1 = "adt_CD19", feature2 = "adt_CD3", pt.size = 1)
plot2 <- FeatureScatter(pbmc10k, feature1 = "adt_CD4", feature2 = "adt_CD8a", pt.size = 1)
plot3 <- FeatureScatter(pbmc10k, feature1 = "adt_CD3", feature2 = "CD3E", pt.size = 1)
(plot1 + plot2 + plot3) & NoLegend()
```

Example 87 (r):
```r
pbmc10k.data <- Read10X(data.dir = "/brahms/shared/vignette-data/pbmc10k/filtered_feature_bc_matrix/")
rownames(x = pbmc10k.data[["Antibody Capture"]]) <- gsub(pattern = "_[control_]*TotalSeqB", replacement = "",
    x = rownames(x = pbmc10k.data[["Antibody Capture"]]))

pbmc10k <- CreateSeuratObject(counts = pbmc10k.data[["Gene Expression"]], min.cells = 3, min.features = 200)
pbmc10k <- NormalizeData(pbmc10k)
pbmc10k[["ADT"]] <- CreateAssayObject(pbmc10k.data[["Antibody Capture"]][, colnames(x = pbmc10k)])
pbmc10k <- NormalizeData(pbmc10k, assay = "ADT", normalization.method = "CLR")

plot1 <- FeatureScatter(pbmc10k, feature1 = "adt_CD19", feature2 = "adt_CD3", pt.size = 1)
plot2 <- FeatureScatter(pbmc10k, feature1 = "adt_CD4", feature2 = "adt_CD8a", pt.size = 1)
plot3 <- FeatureScatter(pbmc10k, feature1 = "adt_CD3", feature2 = "CD3E", pt.size = 1)
(plot1 + plot2 + plot3) & NoLegend()
```

Example 88 (unknown):
```unknown
plot <- FeatureScatter(cbmc, feature1 = "adt_CD19", feature2 = "adt_CD3") + NoLegend() + theme(axis.title = element_text(size = 18),
    legend.text = element_text(size = 18))
ggsave(filename = "../output/images/citeseq_plot.jpg", height = 7, width = 12, plot = plot, quality = 50)
```

Example 89 (r):
```r
plot <- FeatureScatter(cbmc, feature1 = "adt_CD19", feature2 = "adt_CD3") + NoLegend() + theme(axis.title = element_text(size = 18),
    legend.text = element_text(size = 18))
ggsave(filename = "../output/images/citeseq_plot.jpg", height = 7, width = 12, plot = plot, quality = 50)
```

Example 90 (r):
```r
plot <- FeatureScatter(cbmc, feature1 = "adt_CD19", feature2 = "adt_CD3") + NoLegend() + theme(axis.title = element_text(size = 18),
    legend.text = element_text(size = 18))
ggsave(filename = "../output/images/citeseq_plot.jpg", height = 7, width = 12, plot = plot, quality = 50)
```

Example 91 (unknown):
```unknown
sessionInfo()
```

Example 92 (r):
```r
sessionInfo()
```

Example 93 (r):
```r
sessionInfo()
```

Example 94 (unknown):
```unknown
## R version 4.2.2 Patched (2022-11-10 r83330)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.6 LTS
## 
## Matrix products: default
## BLAS:   /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.9.0
## LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.9.0
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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       
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
## [1] patchwork_1.1.3    ggplot2_3.4.4      Seurat_5.0.1  testthat_3.2.0    
## [5] SeuratObject_5.0.1 sp_2.1-1          
## 
## loaded via a namespace (and not attached):
##   [1] spam_2.10-0            systemfonts_1.0.4      plyr_1.8.9            
##   [4] igraph_1.5.1           lazyeval_0.2.2         splines_4.2.2         
##   [7] RcppHNSW_0.5.0         listenv_0.9.0          scattermore_1.2       
##  [10] usethis_2.1.6          digest_0.6.33          htmltools_0.5.6.1     
##  [13] fansi_1.0.5            magrittr_2.0.3         memoise_2.0.1         
##  [16] tensor_1.5             cluster_2.1.4          ROCR_1.0-11           
##  [19] limma_3.54.1           remotes_2.4.2.1        globals_0.16.2        
##  [22] matrixStats_1.0.0      R.utils_2.12.2         pkgdown_2.0.7         
##  [25] spatstat.sparse_3.0-3  prettyunits_1.2.0      colorspace_2.1-0      
##  [28] ggrepel_0.9.4          textshaping_0.3.6      xfun_0.40             
##  [31] dplyr_1.1.3            callr_3.7.3            crayon_1.5.2          
##  [34] jsonlite_1.8.7         progressr_0.14.0       spatstat.data_3.0-3   
##  [37] survival_3.5-7         zoo_1.8-12             glue_1.6.2            
##  [40] polyclip_1.10-6        gtable_0.3.4           leiden_0.4.3          
##  [43] pkgbuild_1.4.2         future.apply_1.11.0    abind_1.4-5           
##  [46] scales_1.2.1           spatstat.random_3.2-1  miniUI_0.1.1.1        
##  [49] Rcpp_1.0.11            viridisLite_0.4.2      xtable_1.8-4          
##  [52] reticulate_1.34.0      dotCall64_1.1-0        profvis_0.3.7         
##  [55] htmlwidgets_1.6.2      httr_1.4.7             RColorBrewer_1.1-3    
##  [58] ellipsis_0.3.2         ica_1.0-3              R.methodsS3_1.8.2     
##  [61] farver_2.1.1           urlchecker_1.0.1       pkgconfig_2.0.3       
##  [64] uwot_0.1.16            sass_0.4.7             deldir_1.0-9          
##  [67] utf8_1.2.4             labeling_0.4.3         tidyselect_1.2.0      
##  [70] rlang_1.1.1            reshape2_1.4.4         later_1.3.1           
##  [73] munsell_0.5.0          tools_4.2.2            cachem_1.0.8          
##  [76] cli_3.6.1              generics_0.1.3         devtools_2.4.5        
##  [79] ggridges_0.5.4         evaluate_0.22          stringr_1.5.0         
##  [82] fastmap_1.1.1          goftest_1.2-3          yaml_2.3.7            
##  [85] ragg_1.2.5             processx_3.8.2         knitr_1.45            
##  [88] fs_1.6.3               fitdistrplus_1.1-11    purrr_1.0.2           
##  [91] RANN_2.6.1             nlme_3.1-162           pbapply_1.7-2         
##  [94] future_1.33.0          mime_0.12              formatR_1.14          
##  [97] R.oo_1.25.0            ggrastr_1.0.1          brio_1.1.3            
## [100] compiler_4.2.2         rstudioapi_0.14        beeswarm_0.4.0        
## [103] plotly_4.10.3          png_0.1-8              spatstat.utils_3.0-4  
## [106] tibble_3.2.1           bslib_0.5.1            stringi_1.7.12        
## [109] highr_0.10             ps_1.7.5               desc_1.4.2            
## [112] RSpectra_0.16-1        lattice_0.21-9         Matrix_1.6-1.1        
## [115] vctrs_0.6.4            pillar_1.9.0           lifecycle_1.0.4       
## [118] spatstat.geom_3.2-7    lmtest_0.9-40          jquerylib_0.1.4       
## [121] RcppAnnoy_0.0.21       data.table_1.14.8      cowplot_1.1.1         
## [124] irlba_2.3.5.1          httpuv_1.6.12          R6_2.5.1              
## [127] promises_1.2.1         KernSmooth_2.23-22     gridExtra_2.3         
## [130] vipor_0.4.5            parallelly_1.36.0      sessioninfo_1.2.2     
## [133] codetools_0.2-19       fastDummies_1.7.3      MASS_7.3-58.2         
## [136] pkgload_1.3.3          rprojroot_2.0.4        withr_2.5.2           
## [139] presto_1.0.0           sctransform_0.4.1      parallel_4.2.2        
## [142] grid_4.2.2             tidyr_1.3.0            rmarkdown_2.25        
## [145] Rtsne_0.16             spatstat.explore_3.2-5 shiny_1.7.5.1         
## [148] ggbeeswarm_0.7.1
```

Example 95 (unknown):
```unknown
## R version 4.2.2 Patched (2022-11-10 r83330)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.6 LTS
## 
## Matrix products: default
## BLAS:   /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.9.0
## LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.9.0
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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       
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
## [1] patchwork_1.1.3    ggplot2_3.4.4      Seurat_5.0.1  testthat_3.2.0    
## [5] SeuratObject_5.0.1 sp_2.1-1          
## 
## loaded via a namespace (and not attached):
##   [1] spam_2.10-0            systemfonts_1.0.4      plyr_1.8.9            
##   [4] igraph_1.5.1           lazyeval_0.2.2         splines_4.2.2         
##   [7] RcppHNSW_0.5.0         listenv_0.9.0          scattermore_1.2       
##  [10] usethis_2.1.6          digest_0.6.33          htmltools_0.5.6.1     
##  [13] fansi_1.0.5            magrittr_2.0.3         memoise_2.0.1         
##  [16] tensor_1.5             cluster_2.1.4          ROCR_1.0-11           
##  [19] limma_3.54.1           remotes_2.4.2.1        globals_0.16.2        
##  [22] matrixStats_1.0.0      R.utils_2.12.2         pkgdown_2.0.7         
##  [25] spatstat.sparse_3.0-3  prettyunits_1.2.0      colorspace_2.1-0      
##  [28] ggrepel_0.9.4          textshaping_0.3.6      xfun_0.40             
##  [31] dplyr_1.1.3            callr_3.7.3            crayon_1.5.2          
##  [34] jsonlite_1.8.7         progressr_0.14.0       spatstat.data_3.0-3   
##  [37] survival_3.5-7         zoo_1.8-12             glue_1.6.2            
##  [40] polyclip_1.10-6        gtable_0.3.4           leiden_0.4.3          
##  [43] pkgbuild_1.4.2         future.apply_1.11.0    abind_1.4-5           
##  [46] scales_1.2.1           spatstat.random_3.2-1  miniUI_0.1.1.1        
##  [49] Rcpp_1.0.11            viridisLite_0.4.2      xtable_1.8-4          
##  [52] reticulate_1.34.0      dotCall64_1.1-0        profvis_0.3.7         
##  [55] htmlwidgets_1.6.2      httr_1.4.7             RColorBrewer_1.1-3    
##  [58] ellipsis_0.3.2         ica_1.0-3              R.methodsS3_1.8.2     
##  [61] farver_2.1.1           urlchecker_1.0.1       pkgconfig_2.0.3       
##  [64] uwot_0.1.16            sass_0.4.7             deldir_1.0-9          
##  [67] utf8_1.2.4             labeling_0.4.3         tidyselect_1.2.0      
##  [70] rlang_1.1.1            reshape2_1.4.4         later_1.3.1           
##  [73] munsell_0.5.0          tools_4.2.2            cachem_1.0.8          
##  [76] cli_3.6.1              generics_0.1.3         devtools_2.4.5        
##  [79] ggridges_0.5.4         evaluate_0.22          stringr_1.5.0         
##  [82] fastmap_1.1.1          goftest_1.2-3          yaml_2.3.7            
##  [85] ragg_1.2.5             processx_3.8.2         knitr_1.45            
##  [88] fs_1.6.3               fitdistrplus_1.1-11    purrr_1.0.2           
##  [91] RANN_2.6.1             nlme_3.1-162           pbapply_1.7-2         
##  [94] future_1.33.0          mime_0.12              formatR_1.14          
##  [97] R.oo_1.25.0            ggrastr_1.0.1          brio_1.1.3            
## [100] compiler_4.2.2         rstudioapi_0.14        beeswarm_0.4.0        
## [103] plotly_4.10.3          png_0.1-8              spatstat.utils_3.0-4  
## [106] tibble_3.2.1           bslib_0.5.1            stringi_1.7.12        
## [109] highr_0.10             ps_1.7.5               desc_1.4.2            
## [112] RSpectra_0.16-1        lattice_0.21-9         Matrix_1.6-1.1        
## [115] vctrs_0.6.4            pillar_1.9.0           lifecycle_1.0.4       
## [118] spatstat.geom_3.2-7    lmtest_0.9-40          jquerylib_0.1.4       
## [121] RcppAnnoy_0.0.21       data.table_1.14.8      cowplot_1.1.1         
## [124] irlba_2.3.5.1          httpuv_1.6.12          R6_2.5.1              
## [127] promises_1.2.1         KernSmooth_2.23-22     gridExtra_2.3         
## [130] vipor_0.4.5            parallelly_1.36.0      sessioninfo_1.2.2     
## [133] codetools_0.2-19       fastDummies_1.7.3      MASS_7.3-58.2         
## [136] pkgload_1.3.3          rprojroot_2.0.4        withr_2.5.2           
## [139] presto_1.0.0           sctransform_0.4.1      parallel_4.2.2        
## [142] grid_4.2.2             tidyr_1.3.0            rmarkdown_2.25        
## [145] Rtsne_0.16             spatstat.explore_3.2-5 shiny_1.7.5.1         
## [148] ggbeeswarm_0.7.1
```

---

## Analysis, visualization, and integration of Visium HD spatial datasets with Seurat • Seurat

**URL:** http://127.0.0.1:9173/articles_weighted_nearest_neighbor_analysis.html

**Contents:**
- Weighted Nearest Neighbor Analysis
    - Compiled: October 31, 2023
- WNN analysis of CITE-seq, RNA + ADT
- WNN analysis of 10x Multiome, RNA + ATAC
- Contents

The simultaneous measurement of multiple modalities, known as multimodal analysis, represents an exciting frontier for single-cell genomics and necessitates new computational methods that can define cellular states based on multiple data types. The varying information content of each modality, even across cells in the same dataset, represents a pressing challenge for the analysis and integration of multimodal datasets. In (Hao*, Hao* et al, Cell 2021), we introduce ‘weighted-nearest neighbor’ (WNN) analysis, an unsupervised framework to learn the relative utility of each data type in each cell, enabling an integrative analysis of multiple modalities.

This vignette introduces the WNN workflow for the analysis of multimodal single-cell datasets. The workflow consists of three steps

We demonstrate the use of WNN analysis to two single-cell multimodal technologies: CITE-seq and 10x multiome. We define the cellular states based on both modalities, instead of either individual modality.

We use the CITE-seq dataset from (Stuart*, Butler* et al, Cell 2019), which consists of 30,672 scRNA-seq profiles measured alongside a panel of 25 antibodies from bone marrow. The object contains two assays, RNA and antibody-derived tags (ADT).

To run this vignette please install SeuratData, available on GitHub.

We first perform pre-processing and dimensional reduction on both assays independently. We use standard normalization, but you can also use SCTransform or any alternative method.

For each cell, we calculate its closest neighbors in the dataset based on a weighted combination of RNA and protein similarities. The cell-specific modality weights and multimodal neighbors are calculated in a single function, which takes ~2 minutes to run on this dataset. We specify the dimensionality of each modality (similar to specifying the number of PCs to include in scRNA-seq clustering), but you can vary these settings to see that small changes have minimal effect on the overall results.

We can now use these results for downstream analysis, such as visualization and clustering. For example, we can create a UMAP visualization of the data based on a weighted combination of RNA and protein data We can also perform graph-based clustering and visualize these results on the UMAP, alongside a set of cell annotations.

We can also compute UMAP visualization based on only the RNA and protein data and compare. We find that the RNA analysis is more informative than the ADT analysis in identifying progenitor states (the ADT panel contains markers for differentiated cells), while the converse is true of T cell states (where the ADT analysis outperforms RNA).

We can visualize the expression of canonical marker genes and proteins on the multimodal UMAP, which can assist in verifying the provided annotations:

Finally, we can visualize the modality weights that were learned for each cell. Each of the populations with the highest RNA weights represent progenitor cells, while the populations with the highest protein weights represent T cells. This is in line with our biological expectations, as the antibody panel does not contain markers that can distinguish between different progenitor populations.

Here, we demonstrate the use of WNN analysis to a second multimodal technology, the 10x multiome RNA+ATAC kit. We use a dataset that is publicly available on the 10x website, where paired transcriptomes and ATAC-seq profiles are measured in 10,412 PBMCs.

We use the same WNN methods as we use in the previous tab, where we apply integrated multimodal analysis to a CITE-seq dataset. In this example we will demonstrate how to:

You can download the dataset from the 10x Genomics website here. Please make sure to download the following files:

Finally, in order to run the vignette, make sure the following packages are installed:

We’ll create a Seurat object based on the gene expression data, and then add in the ATAC-seq data as a second assay. You can explore the Signac getting started vignette for more information on the creation and processing of a ChromatinAssay object.

We perform basic QC based on the number of detected molecules for each modality as well as mitochondrial percentage.

We next perform pre-processing and dimensional reduction on both assays independently, using standard approaches for RNA and ATAC-seq data.

We calculate a WNN graph, representing a weighted combination of RNA and ATAC-seq modalities. We use this graph for UMAP visualization and clustering

We annotate the clusters below. Note that you could also annotate the dataset using our supervised mapping pipelines, using either our vignette, or automated web tool, Azimuth.

We can visualize clustering based on gene expression, ATAC-seq, or WNN analysis. The differences are more subtle than in the previous analysis (you can explore the weights, which are more evenly split than in our CITE-seq example), but we find that WNN provides the clearest separation of cell states.

For example, the ATAC-seq data assists in the separation of CD4 and CD8 T cell states. This is due to the presence of multiple loci that exhibit differential accessibility between different T cell subtypes. For example, we can visualize ‘pseudobulk’ tracks of the CD8A locus alongside violin plots of gene expression levels, using tools in the Signac visualization vignette.

Next, we will examine the accessible regions of each cell to determine enriched motifs. As described in the Signac motifs vignette, there are a few ways to do this, but we will use the chromVAR package from the Greenleaf lab. This calculates a per-cell accessibility score for known motifs, and adds these scores as a third assay (chromvar) in the Seurat object.

To continue, please make sure you have the following packages installed.

Install command for all dependencies

Finally, we explore the multimodal dataset to identify key regulators of each cell state. Paired data provides a unique opportunity to identify transcription factors (TFs) that satisfy multiple criteria, helping to narrow down the list of putative regulators to the most likely candidates. We aim to identify TFs whose expression is enriched in multiple cell types in the RNA measurements, but also have enriched accessibility for their motifs in the ATAC measurements.

As an example and positive control, the CCAAT Enhancer Binding Protein (CEBP) family of proteins, including the TF CEBPB, have been repeatedly shown to play important roles in the differentiation and function of myeloid cells including monocytes and dendritic cells. We can see that both the expression of the CEBPB, and the accessibility of the MA0466.2.4 motif (which encodes the binding site for CEBPB), are both enriched in monocytes.

We’d like to quantify this relationship, and search across all cell types to find similar examples. To do so, we will use the presto package to perform fast differential expression. We run two tests: one using gene expression data, and the other using chromVAR motif accessibilities. presto calculates a p-value based on the Wilcox rank sum test, which is also the default test in Seurat, and we restrict our search to TFs that return significant results in both tests.

presto also calculates an “AUC” statistic, which reflects the power of each gene (or motif) to serve as a marker of cell type. A maximum AUC value of 1 indicates a perfect marker. Since the AUC statistic is on the same scale for both genes and motifs, we take the average of the AUC values from the two tests, and use this to rank TFs for each cell type:

We can now compute, and visualize, putative regulators for any cell type. We recover well-established regulators, including TBX21 for NK cells, IRF4 for plasma cells, SOX4 for hematopoietic progenitors, EBF1 and PAX5 for B cells, IRF8 and TCF4 for pDC. We believe that similar strategies can be used to help focus on a set of putative regulators in diverse systems.

Developed by Rahul Satija, Satija Lab and Collaborators.

Site built with pkgdown 2.0.7.

**Examples:**

Example 1 (unknown):
```unknown
vignettes/weighted_nearest_neighbor_analysis.Rmd
```

Example 2 (unknown):
```unknown
weighted_nearest_neighbor_analysis.Rmd
```

Example 3 (unknown):
```unknown
library(Seurat)
library(SeuratData)
library(cowplot)
library(dplyr)
```

Example 4 (r):
```r
library(Seurat)
library(SeuratData)
library(cowplot)
library(dplyr)
```

Example 5 (r):
```r
library(Seurat)
library(SeuratData)
library(cowplot)
library(dplyr)
```

Example 6 (unknown):
```unknown
InstallData("bmcite")
bm <- LoadData(ds = "bmcite")
```

Example 7 (r):
```r
InstallData("bmcite")
bm <- LoadData(ds = "bmcite")
```

Example 8 (r):
```r
InstallData("bmcite")
bm <- LoadData(ds = "bmcite")
```

Example 9 (unknown):
```unknown
DefaultAssay(bm) <- 'RNA'
bm <- NormalizeData(bm) %>% FindVariableFeatures() %>% ScaleData() %>% RunPCA()

DefaultAssay(bm) <- 'ADT'
# we will use all ADT features for dimensional reduction
# we set a dimensional reduction name to avoid overwriting the 
VariableFeatures(bm) <- rownames(bm[["ADT"]])
bm <- NormalizeData(bm, normalization.method = 'CLR', margin = 2) %>% 
  ScaleData() %>% RunPCA(reduction.name = 'apca')
```

Example 10 (r):
```r
DefaultAssay(bm) <- 'RNA'
bm <- NormalizeData(bm) %>% FindVariableFeatures() %>% ScaleData() %>% RunPCA()

DefaultAssay(bm) <- 'ADT'
# we will use all ADT features for dimensional reduction
# we set a dimensional reduction name to avoid overwriting the 
VariableFeatures(bm) <- rownames(bm[["ADT"]])
bm <- NormalizeData(bm, normalization.method = 'CLR', margin = 2) %>% 
  ScaleData() %>% RunPCA(reduction.name = 'apca')
```

Example 11 (r):
```r
DefaultAssay(bm) <- 'RNA'
bm <- NormalizeData(bm) %>% FindVariableFeatures() %>% ScaleData() %>% RunPCA()

DefaultAssay(bm) <- 'ADT'
# we will use all ADT features for dimensional reduction
# we set a dimensional reduction name to avoid overwriting the 
VariableFeatures(bm) <- rownames(bm[["ADT"]])
bm <- NormalizeData(bm, normalization.method = 'CLR', margin = 2) %>% 
  ScaleData() %>% RunPCA(reduction.name = 'apca')
```

Example 12 (unknown):
```unknown
# Identify multimodal neighbors. These will be stored in the neighbors slot, 
# and can be accessed using bm[['weighted.nn']]
# The WNN graph can be accessed at bm[["wknn"]], 
# and the SNN graph used for clustering at bm[["wsnn"]]
# Cell-specific modality weights can be accessed at bm$RNA.weight
bm <- FindMultiModalNeighbors(
  bm, reduction.list = list("pca", "apca"), 
  dims.list = list(1:30, 1:18), modality.weight.name = "RNA.weight"
)
```

Example 13 (r):
```r
# Identify multimodal neighbors. These will be stored in the neighbors slot, 
# and can be accessed using bm[['weighted.nn']]
# The WNN graph can be accessed at bm[["wknn"]], 
# and the SNN graph used for clustering at bm[["wsnn"]]
# Cell-specific modality weights can be accessed at bm$RNA.weight
bm <- FindMultiModalNeighbors(
  bm, reduction.list = list("pca", "apca"), 
  dims.list = list(1:30, 1:18), modality.weight.name = "RNA.weight"
)
```

Example 14 (r):
```r
# Identify multimodal neighbors. These will be stored in the neighbors slot, 
# and can be accessed using bm[['weighted.nn']]
# The WNN graph can be accessed at bm[["wknn"]], 
# and the SNN graph used for clustering at bm[["wsnn"]]
# Cell-specific modality weights can be accessed at bm$RNA.weight
bm <- FindMultiModalNeighbors(
  bm, reduction.list = list("pca", "apca"), 
  dims.list = list(1:30, 1:18), modality.weight.name = "RNA.weight"
)
```

Example 15 (unknown):
```unknown
bm <- RunUMAP(bm, nn.name = "weighted.nn", reduction.name = "wnn.umap", reduction.key = "wnnUMAP_")
bm <- FindClusters(bm, graph.name = "wsnn", algorithm = 3, resolution = 2, verbose = FALSE)
```

Example 16 (r):
```r
bm <- RunUMAP(bm, nn.name = "weighted.nn", reduction.name = "wnn.umap", reduction.key = "wnnUMAP_")
bm <- FindClusters(bm, graph.name = "wsnn", algorithm = 3, resolution = 2, verbose = FALSE)
```

Example 17 (r):
```r
bm <- RunUMAP(bm, nn.name = "weighted.nn", reduction.name = "wnn.umap", reduction.key = "wnnUMAP_")
bm <- FindClusters(bm, graph.name = "wsnn", algorithm = 3, resolution = 2, verbose = FALSE)
```

Example 18 (unknown):
```unknown
p1 <- DimPlot(bm, reduction = 'wnn.umap', label = TRUE, repel = TRUE, label.size = 2.5) + NoLegend()
p2 <- DimPlot(bm, reduction = 'wnn.umap', group.by = 'celltype.l2', label = TRUE, repel = TRUE, label.size = 2.5) + NoLegend()
p1 + p2
```

Example 19 (r):
```r
p1 <- DimPlot(bm, reduction = 'wnn.umap', label = TRUE, repel = TRUE, label.size = 2.5) + NoLegend()
p2 <- DimPlot(bm, reduction = 'wnn.umap', group.by = 'celltype.l2', label = TRUE, repel = TRUE, label.size = 2.5) + NoLegend()
p1 + p2
```

Example 20 (r):
```r
p1 <- DimPlot(bm, reduction = 'wnn.umap', label = TRUE, repel = TRUE, label.size = 2.5) + NoLegend()
p2 <- DimPlot(bm, reduction = 'wnn.umap', group.by = 'celltype.l2', label = TRUE, repel = TRUE, label.size = 2.5) + NoLegend()
p1 + p2
```

Example 21 (unknown):
```unknown
bm <- RunUMAP(bm, reduction = 'pca', dims = 1:30, assay = 'RNA', 
              reduction.name = 'rna.umap', reduction.key = 'rnaUMAP_')
bm <- RunUMAP(bm, reduction = 'apca', dims = 1:18, assay = 'ADT', 
              reduction.name = 'adt.umap', reduction.key = 'adtUMAP_')
```

Example 22 (r):
```r
bm <- RunUMAP(bm, reduction = 'pca', dims = 1:30, assay = 'RNA', 
              reduction.name = 'rna.umap', reduction.key = 'rnaUMAP_')
bm <- RunUMAP(bm, reduction = 'apca', dims = 1:18, assay = 'ADT', 
              reduction.name = 'adt.umap', reduction.key = 'adtUMAP_')
```

Example 23 (r):
```r
bm <- RunUMAP(bm, reduction = 'pca', dims = 1:30, assay = 'RNA', 
              reduction.name = 'rna.umap', reduction.key = 'rnaUMAP_')
bm <- RunUMAP(bm, reduction = 'apca', dims = 1:18, assay = 'ADT', 
              reduction.name = 'adt.umap', reduction.key = 'adtUMAP_')
```

Example 24 (unknown):
```unknown
p3 <- DimPlot(bm, reduction = 'rna.umap', group.by = 'celltype.l2', label = TRUE, 
              repel = TRUE, label.size = 2.5) + NoLegend()
p4 <- DimPlot(bm, reduction = 'adt.umap', group.by = 'celltype.l2', label = TRUE, 
              repel = TRUE, label.size = 2.5) + NoLegend()
p3 + p4
```

Example 25 (r):
```r
p3 <- DimPlot(bm, reduction = 'rna.umap', group.by = 'celltype.l2', label = TRUE, 
              repel = TRUE, label.size = 2.5) + NoLegend()
p4 <- DimPlot(bm, reduction = 'adt.umap', group.by = 'celltype.l2', label = TRUE, 
              repel = TRUE, label.size = 2.5) + NoLegend()
p3 + p4
```

Example 26 (r):
```r
p3 <- DimPlot(bm, reduction = 'rna.umap', group.by = 'celltype.l2', label = TRUE, 
              repel = TRUE, label.size = 2.5) + NoLegend()
p4 <- DimPlot(bm, reduction = 'adt.umap', group.by = 'celltype.l2', label = TRUE, 
              repel = TRUE, label.size = 2.5) + NoLegend()
p3 + p4
```

Example 27 (unknown):
```unknown
p5 <- FeaturePlot(bm, features = c("adt_CD45RA","adt_CD16","adt_CD161"),
                  reduction = 'wnn.umap', max.cutoff = 2, 
                  cols = c("lightgrey","darkgreen"), ncol = 3)
p6 <- FeaturePlot(bm, features = c("rna_TRDC","rna_MPO","rna_AVP"), 
                  reduction = 'wnn.umap', max.cutoff = 3, ncol = 3)
p5 / p6
```

Example 28 (r):
```r
p5 <- FeaturePlot(bm, features = c("adt_CD45RA","adt_CD16","adt_CD161"),
                  reduction = 'wnn.umap', max.cutoff = 2, 
                  cols = c("lightgrey","darkgreen"), ncol = 3)
p6 <- FeaturePlot(bm, features = c("rna_TRDC","rna_MPO","rna_AVP"), 
                  reduction = 'wnn.umap', max.cutoff = 3, ncol = 3)
p5 / p6
```

Example 29 (r):
```r
p5 <- FeaturePlot(bm, features = c("adt_CD45RA","adt_CD16","adt_CD161"),
                  reduction = 'wnn.umap', max.cutoff = 2, 
                  cols = c("lightgrey","darkgreen"), ncol = 3)
p6 <- FeaturePlot(bm, features = c("rna_TRDC","rna_MPO","rna_AVP"), 
                  reduction = 'wnn.umap', max.cutoff = 3, ncol = 3)
p5 / p6
```

Example 30 (unknown):
```unknown
VlnPlot(bm, features = "RNA.weight", group.by = 'celltype.l2', sort = TRUE, pt.size = 0.1) +
  NoLegend()
```

Example 31 (r):
```r
VlnPlot(bm, features = "RNA.weight", group.by = 'celltype.l2', sort = TRUE, pt.size = 0.1) +
  NoLegend()
```

Example 32 (r):
```r
VlnPlot(bm, features = "RNA.weight", group.by = 'celltype.l2', sort = TRUE, pt.size = 0.1) +
  NoLegend()
```

Example 33 (unknown):
```unknown
library(Seurat)
library(Signac)
library(EnsDb.Hsapiens.v86)
library(dplyr)
library(ggplot2)
```

Example 34 (r):
```r
library(Seurat)
library(Signac)
library(EnsDb.Hsapiens.v86)
library(dplyr)
library(ggplot2)
```

Example 35 (r):
```r
library(Seurat)
library(Signac)
library(EnsDb.Hsapiens.v86)
library(dplyr)
library(ggplot2)
```

Example 36 (unknown):
```unknown
# the 10x hdf5 file contains both data types. 
inputdata.10x <- Read10X_h5("../data/pbmc_granulocyte_sorted_10k_filtered_feature_bc_matrix.h5")

# extract RNA and ATAC data
rna_counts <- inputdata.10x$`Gene Expression`
atac_counts <- inputdata.10x$Peaks

# Create Seurat object
pbmc <- CreateSeuratObject(counts = rna_counts)
pbmc[["percent.mt"]] <- PercentageFeatureSet(pbmc, pattern = "^MT-")

# Now add in the ATAC-seq data
# we'll only use peaks in standard chromosomes
grange.counts <- StringToGRanges(rownames(atac_counts), sep = c(":", "-"))
grange.use <- seqnames(grange.counts) %in% standardChromosomes(grange.counts)
atac_counts <- atac_counts[as.vector(grange.use), ]
annotations <- GetGRangesFromEnsDb(ensdb = EnsDb.Hsapiens.v86)
seqlevelsStyle(annotations) <- 'UCSC'
genome(annotations) <- "hg38"

frag.file <- "../data/pbmc_granulocyte_sorted_10k_atac_fragments.tsv.gz"
chrom_assay <- CreateChromatinAssay(
   counts = atac_counts,
   sep = c(":", "-"),
   genome = 'hg38',
   fragments = frag.file,
   min.cells = 10,
   annotation = annotations
 )
pbmc[["ATAC"]] <- chrom_assay
```

Example 37 (r):
```r
# the 10x hdf5 file contains both data types. 
inputdata.10x <- Read10X_h5("../data/pbmc_granulocyte_sorted_10k_filtered_feature_bc_matrix.h5")

# extract RNA and ATAC data
rna_counts <- inputdata.10x$`Gene Expression`
atac_counts <- inputdata.10x$Peaks

# Create Seurat object
pbmc <- CreateSeuratObject(counts = rna_counts)
pbmc[["percent.mt"]] <- PercentageFeatureSet(pbmc, pattern = "^MT-")

# Now add in the ATAC-seq data
# we'll only use peaks in standard chromosomes
grange.counts <- StringToGRanges(rownames(atac_counts), sep = c(":", "-"))
grange.use <- seqnames(grange.counts) %in% standardChromosomes(grange.counts)
atac_counts <- atac_counts[as.vector(grange.use), ]
annotations <- GetGRangesFromEnsDb(ensdb = EnsDb.Hsapiens.v86)
seqlevelsStyle(annotations) <- 'UCSC'
genome(annotations) <- "hg38"

frag.file <- "../data/pbmc_granulocyte_sorted_10k_atac_fragments.tsv.gz"
chrom_assay <- CreateChromatinAssay(
   counts = atac_counts,
   sep = c(":", "-"),
   genome = 'hg38',
   fragments = frag.file,
   min.cells = 10,
   annotation = annotations
 )
pbmc[["ATAC"]] <- chrom_assay
```

Example 38 (r):
```r
# the 10x hdf5 file contains both data types. 
inputdata.10x <- Read10X_h5("../data/pbmc_granulocyte_sorted_10k_filtered_feature_bc_matrix.h5")

# extract RNA and ATAC data
rna_counts <- inputdata.10x$`Gene Expression`
atac_counts <- inputdata.10x$Peaks

# Create Seurat object
pbmc <- CreateSeuratObject(counts = rna_counts)
pbmc[["percent.mt"]] <- PercentageFeatureSet(pbmc, pattern = "^MT-")

# Now add in the ATAC-seq data
# we'll only use peaks in standard chromosomes
grange.counts <- StringToGRanges(rownames(atac_counts), sep = c(":", "-"))
grange.use <- seqnames(grange.counts) %in% standardChromosomes(grange.counts)
atac_counts <- atac_counts[as.vector(grange.use), ]
annotations <- GetGRangesFromEnsDb(ensdb = EnsDb.Hsapiens.v86)
seqlevelsStyle(annotations) <- 'UCSC'
genome(annotations) <- "hg38"

frag.file <- "../data/pbmc_granulocyte_sorted_10k_atac_fragments.tsv.gz"
chrom_assay <- CreateChromatinAssay(
   counts = atac_counts,
   sep = c(":", "-"),
   genome = 'hg38',
   fragments = frag.file,
   min.cells = 10,
   annotation = annotations
 )
pbmc[["ATAC"]] <- chrom_assay
```

Example 39 (unknown):
```unknown
VlnPlot(pbmc, features = c("nCount_ATAC", "nCount_RNA", "percent.mt"), ncol = 3,
  log = TRUE, pt.size = 0) + NoLegend()
```

Example 40 (r):
```r
VlnPlot(pbmc, features = c("nCount_ATAC", "nCount_RNA", "percent.mt"), ncol = 3,
  log = TRUE, pt.size = 0) + NoLegend()
```

Example 41 (r):
```r
VlnPlot(pbmc, features = c("nCount_ATAC", "nCount_RNA", "percent.mt"), ncol = 3,
  log = TRUE, pt.size = 0) + NoLegend()
```

Example 42 (unknown):
```unknown
pbmc <- subset(
  x = pbmc,
  subset = nCount_ATAC < 7e4 &
    nCount_ATAC > 5e3 &
    nCount_RNA < 25000 &
    nCount_RNA > 1000 &
    percent.mt < 20
)
```

Example 43 (r):
```r
pbmc <- subset(
  x = pbmc,
  subset = nCount_ATAC < 7e4 &
    nCount_ATAC > 5e3 &
    nCount_RNA < 25000 &
    nCount_RNA > 1000 &
    percent.mt < 20
)
```

Example 44 (r):
```r
pbmc <- subset(
  x = pbmc,
  subset = nCount_ATAC < 7e4 &
    nCount_ATAC > 5e3 &
    nCount_RNA < 25000 &
    nCount_RNA > 1000 &
    percent.mt < 20
)
```

Example 45 (unknown):
```unknown
# RNA analysis
DefaultAssay(pbmc) <- "RNA"
pbmc <- SCTransform(pbmc, verbose = FALSE) %>% RunPCA() %>% RunUMAP(dims = 1:50, reduction.name = 'umap.rna', reduction.key = 'rnaUMAP_')

# ATAC analysis
# We exclude the first dimension as this is typically correlated with sequencing depth
DefaultAssay(pbmc) <- "ATAC"
pbmc <- RunTFIDF(pbmc)
pbmc <- FindTopFeatures(pbmc, min.cutoff = 'q0')
pbmc <- RunSVD(pbmc)
pbmc <- RunUMAP(pbmc, reduction = 'lsi', dims = 2:50, reduction.name = "umap.atac", reduction.key = "atacUMAP_")
```

Example 46 (r):
```r
# RNA analysis
DefaultAssay(pbmc) <- "RNA"
pbmc <- SCTransform(pbmc, verbose = FALSE) %>% RunPCA() %>% RunUMAP(dims = 1:50, reduction.name = 'umap.rna', reduction.key = 'rnaUMAP_')

# ATAC analysis
# We exclude the first dimension as this is typically correlated with sequencing depth
DefaultAssay(pbmc) <- "ATAC"
pbmc <- RunTFIDF(pbmc)
pbmc <- FindTopFeatures(pbmc, min.cutoff = 'q0')
pbmc <- RunSVD(pbmc)
pbmc <- RunUMAP(pbmc, reduction = 'lsi', dims = 2:50, reduction.name = "umap.atac", reduction.key = "atacUMAP_")
```

Example 47 (r):
```r
# RNA analysis
DefaultAssay(pbmc) <- "RNA"
pbmc <- SCTransform(pbmc, verbose = FALSE) %>% RunPCA() %>% RunUMAP(dims = 1:50, reduction.name = 'umap.rna', reduction.key = 'rnaUMAP_')

# ATAC analysis
# We exclude the first dimension as this is typically correlated with sequencing depth
DefaultAssay(pbmc) <- "ATAC"
pbmc <- RunTFIDF(pbmc)
pbmc <- FindTopFeatures(pbmc, min.cutoff = 'q0')
pbmc <- RunSVD(pbmc)
pbmc <- RunUMAP(pbmc, reduction = 'lsi', dims = 2:50, reduction.name = "umap.atac", reduction.key = "atacUMAP_")
```

Example 48 (unknown):
```unknown
pbmc <- FindMultiModalNeighbors(pbmc, reduction.list = list("pca", "lsi"), dims.list = list(1:50, 2:50))
pbmc <- RunUMAP(pbmc, nn.name = "weighted.nn", reduction.name = "wnn.umap", reduction.key = "wnnUMAP_")
pbmc <- FindClusters(pbmc, graph.name = "wsnn", algorithm = 3, verbose = FALSE)
```

Example 49 (r):
```r
pbmc <- FindMultiModalNeighbors(pbmc, reduction.list = list("pca", "lsi"), dims.list = list(1:50, 2:50))
pbmc <- RunUMAP(pbmc, nn.name = "weighted.nn", reduction.name = "wnn.umap", reduction.key = "wnnUMAP_")
pbmc <- FindClusters(pbmc, graph.name = "wsnn", algorithm = 3, verbose = FALSE)
```

Example 50 (r):
```r
pbmc <- FindMultiModalNeighbors(pbmc, reduction.list = list("pca", "lsi"), dims.list = list(1:50, 2:50))
pbmc <- RunUMAP(pbmc, nn.name = "weighted.nn", reduction.name = "wnn.umap", reduction.key = "wnnUMAP_")
pbmc <- FindClusters(pbmc, graph.name = "wsnn", algorithm = 3, verbose = FALSE)
```

Example 51 (unknown):
```unknown
# perform sub-clustering on cluster 6 to find additional structure
pbmc <- FindSubCluster(pbmc, cluster = 6, graph.name = "wsnn", algorithm = 3)
Idents(pbmc) <- "sub.cluster"
```

Example 52 (r):
```r
# perform sub-clustering on cluster 6 to find additional structure
pbmc <- FindSubCluster(pbmc, cluster = 6, graph.name = "wsnn", algorithm = 3)
Idents(pbmc) <- "sub.cluster"
```

Example 53 (r):
```r
# perform sub-clustering on cluster 6 to find additional structure
pbmc <- FindSubCluster(pbmc, cluster = 6, graph.name = "wsnn", algorithm = 3)
Idents(pbmc) <- "sub.cluster"
```

Example 54 (unknown):
```unknown
# add annotations
pbmc <- RenameIdents(pbmc, '19' = 'pDC','20' = 'HSPC','15' = 'cDC')
pbmc <- RenameIdents(pbmc, '0' = 'CD14 Mono', '9' ='CD14 Mono', '5' = 'CD16 Mono')
pbmc <- RenameIdents(pbmc, '10' = 'Naive B', '11' = 'Intermediate B', '17' = 'Memory B', '21' = 'Plasma')
pbmc <- RenameIdents(pbmc, '7' = 'NK')
pbmc <- RenameIdents(pbmc, '4' = 'CD4 TCM', '13'= "CD4 TEM", '3' = "CD4 TCM", '16' ="Treg", '1' ="CD4 Naive", '14' = "CD4 Naive")
pbmc <- RenameIdents(pbmc, '2' = 'CD8 Naive', '8'= "CD8 Naive", '12' = 'CD8 TEM_1', '6_0' = 'CD8 TEM_2', '6_1' ='CD8 TEM_2', '6_4' ='CD8 TEM_2')
pbmc <- RenameIdents(pbmc, '18' = 'MAIT')
pbmc <- RenameIdents(pbmc, '6_2' ='gdT', '6_3' = 'gdT')
pbmc$celltype <- Idents(pbmc)
```

Example 55 (r):
```r
# add annotations
pbmc <- RenameIdents(pbmc, '19' = 'pDC','20' = 'HSPC','15' = 'cDC')
pbmc <- RenameIdents(pbmc, '0' = 'CD14 Mono', '9' ='CD14 Mono', '5' = 'CD16 Mono')
pbmc <- RenameIdents(pbmc, '10' = 'Naive B', '11' = 'Intermediate B', '17' = 'Memory B', '21' = 'Plasma')
pbmc <- RenameIdents(pbmc, '7' = 'NK')
pbmc <- RenameIdents(pbmc, '4' = 'CD4 TCM', '13'= "CD4 TEM", '3' = "CD4 TCM", '16' ="Treg", '1' ="CD4 Naive", '14' = "CD4 Naive")
pbmc <- RenameIdents(pbmc, '2' = 'CD8 Naive', '8'= "CD8 Naive", '12' = 'CD8 TEM_1', '6_0' = 'CD8 TEM_2', '6_1' ='CD8 TEM_2', '6_4' ='CD8 TEM_2')
pbmc <- RenameIdents(pbmc, '18' = 'MAIT')
pbmc <- RenameIdents(pbmc, '6_2' ='gdT', '6_3' = 'gdT')
pbmc$celltype <- Idents(pbmc)
```

Example 56 (r):
```r
# add annotations
pbmc <- RenameIdents(pbmc, '19' = 'pDC','20' = 'HSPC','15' = 'cDC')
pbmc <- RenameIdents(pbmc, '0' = 'CD14 Mono', '9' ='CD14 Mono', '5' = 'CD16 Mono')
pbmc <- RenameIdents(pbmc, '10' = 'Naive B', '11' = 'Intermediate B', '17' = 'Memory B', '21' = 'Plasma')
pbmc <- RenameIdents(pbmc, '7' = 'NK')
pbmc <- RenameIdents(pbmc, '4' = 'CD4 TCM', '13'= "CD4 TEM", '3' = "CD4 TCM", '16' ="Treg", '1' ="CD4 Naive", '14' = "CD4 Naive")
pbmc <- RenameIdents(pbmc, '2' = 'CD8 Naive', '8'= "CD8 Naive", '12' = 'CD8 TEM_1', '6_0' = 'CD8 TEM_2', '6_1' ='CD8 TEM_2', '6_4' ='CD8 TEM_2')
pbmc <- RenameIdents(pbmc, '18' = 'MAIT')
pbmc <- RenameIdents(pbmc, '6_2' ='gdT', '6_3' = 'gdT')
pbmc$celltype <- Idents(pbmc)
```

Example 57 (unknown):
```unknown
p1 <- DimPlot(pbmc, reduction = "umap.rna", group.by = "celltype", label = TRUE, label.size = 2.5, repel = TRUE) + ggtitle("RNA")
p2 <- DimPlot(pbmc, reduction = "umap.atac", group.by = "celltype", label = TRUE, label.size = 2.5, repel = TRUE) + ggtitle("ATAC")
p3 <- DimPlot(pbmc, reduction = "wnn.umap", group.by = "celltype", label = TRUE, label.size = 2.5, repel = TRUE) + ggtitle("WNN")
p1 + p2 + p3 & NoLegend() & theme(plot.title = element_text(hjust = 0.5))
```

Example 58 (r):
```r
p1 <- DimPlot(pbmc, reduction = "umap.rna", group.by = "celltype", label = TRUE, label.size = 2.5, repel = TRUE) + ggtitle("RNA")
p2 <- DimPlot(pbmc, reduction = "umap.atac", group.by = "celltype", label = TRUE, label.size = 2.5, repel = TRUE) + ggtitle("ATAC")
p3 <- DimPlot(pbmc, reduction = "wnn.umap", group.by = "celltype", label = TRUE, label.size = 2.5, repel = TRUE) + ggtitle("WNN")
p1 + p2 + p3 & NoLegend() & theme(plot.title = element_text(hjust = 0.5))
```

Example 59 (r):
```r
p1 <- DimPlot(pbmc, reduction = "umap.rna", group.by = "celltype", label = TRUE, label.size = 2.5, repel = TRUE) + ggtitle("RNA")
p2 <- DimPlot(pbmc, reduction = "umap.atac", group.by = "celltype", label = TRUE, label.size = 2.5, repel = TRUE) + ggtitle("ATAC")
p3 <- DimPlot(pbmc, reduction = "wnn.umap", group.by = "celltype", label = TRUE, label.size = 2.5, repel = TRUE) + ggtitle("WNN")
p1 + p2 + p3 & NoLegend() & theme(plot.title = element_text(hjust = 0.5))
```

Example 60 (unknown):
```unknown
## to make the visualization easier, subset T cell clusters
celltype.names <- levels(pbmc)
tcell.names <- grep("CD4|CD8|Treg", celltype.names,value = TRUE)
tcells <- subset(pbmc, idents = tcell.names)
CoveragePlot(tcells, region = 'CD8A', features = 'CD8A', assay = 'ATAC', expression.assay = 'SCT', peaks = FALSE)
```

Example 61 (r):
```r
## to make the visualization easier, subset T cell clusters
celltype.names <- levels(pbmc)
tcell.names <- grep("CD4|CD8|Treg", celltype.names,value = TRUE)
tcells <- subset(pbmc, idents = tcell.names)
CoveragePlot(tcells, region = 'CD8A', features = 'CD8A', assay = 'ATAC', expression.assay = 'SCT', peaks = FALSE)
```

Example 62 (r):
```r
## to make the visualization easier, subset T cell clusters
celltype.names <- levels(pbmc)
tcell.names <- grep("CD4|CD8|Treg", celltype.names,value = TRUE)
tcells <- subset(pbmc, idents = tcell.names)
CoveragePlot(tcells, region = 'CD8A', features = 'CD8A', assay = 'ATAC', expression.assay = 'SCT', peaks = FALSE)
```

Example 63 (unknown):
```unknown
remotes::install_github("immunogenomics/presto")
BiocManager::install(c("chromVAR", "TFBSTools", "JASPAR2020", "motifmatchr", "BSgenome.Hsapiens.UCSC.hg38"))
```

Example 64 (r):
```r
remotes::install_github("immunogenomics/presto")
BiocManager::install(c("chromVAR", "TFBSTools", "JASPAR2020", "motifmatchr", "BSgenome.Hsapiens.UCSC.hg38"))
```

Example 65 (r):
```r
remotes::install_github("immunogenomics/presto")
BiocManager::install(c("chromVAR", "TFBSTools", "JASPAR2020", "motifmatchr", "BSgenome.Hsapiens.UCSC.hg38"))
```

Example 66 (unknown):
```unknown
library(chromVAR)
library(JASPAR2020)
library(TFBSTools)
library(motifmatchr)
library(BSgenome.Hsapiens.UCSC.hg38)

# Scan the DNA sequence of each peak for the presence of each motif, and create a Motif object
DefaultAssay(pbmc) <- "ATAC"
pwm_set <- getMatrixSet(x = JASPAR2020, opts = list(species = 9606, all_versions = FALSE))
motif.matrix <- CreateMotifMatrix(features = granges(pbmc), pwm = pwm_set, genome = 'hg38', use.counts = FALSE)
motif.object <- CreateMotifObject(data = motif.matrix, pwm = pwm_set)
pbmc <- SetAssayData(pbmc, assay = 'ATAC', slot = 'motifs', new.data = motif.object)

# Note that this step can take 30-60 minutes 
pbmc <- RunChromVAR(
  object = pbmc,
  genome = BSgenome.Hsapiens.UCSC.hg38
)
```

Example 67 (r):
```r
library(chromVAR)
library(JASPAR2020)
library(TFBSTools)
library(motifmatchr)
library(BSgenome.Hsapiens.UCSC.hg38)

# Scan the DNA sequence of each peak for the presence of each motif, and create a Motif object
DefaultAssay(pbmc) <- "ATAC"
pwm_set <- getMatrixSet(x = JASPAR2020, opts = list(species = 9606, all_versions = FALSE))
motif.matrix <- CreateMotifMatrix(features = granges(pbmc), pwm = pwm_set, genome = 'hg38', use.counts = FALSE)
motif.object <- CreateMotifObject(data = motif.matrix, pwm = pwm_set)
pbmc <- SetAssayData(pbmc, assay = 'ATAC', slot = 'motifs', new.data = motif.object)

# Note that this step can take 30-60 minutes 
pbmc <- RunChromVAR(
  object = pbmc,
  genome = BSgenome.Hsapiens.UCSC.hg38
)
```

Example 68 (r):
```r
library(chromVAR)
library(JASPAR2020)
library(TFBSTools)
library(motifmatchr)
library(BSgenome.Hsapiens.UCSC.hg38)

# Scan the DNA sequence of each peak for the presence of each motif, and create a Motif object
DefaultAssay(pbmc) <- "ATAC"
pwm_set <- getMatrixSet(x = JASPAR2020, opts = list(species = 9606, all_versions = FALSE))
motif.matrix <- CreateMotifMatrix(features = granges(pbmc), pwm = pwm_set, genome = 'hg38', use.counts = FALSE)
motif.object <- CreateMotifObject(data = motif.matrix, pwm = pwm_set)
pbmc <- SetAssayData(pbmc, assay = 'ATAC', slot = 'motifs', new.data = motif.object)

# Note that this step can take 30-60 minutes 
pbmc <- RunChromVAR(
  object = pbmc,
  genome = BSgenome.Hsapiens.UCSC.hg38
)
```

Example 69 (unknown):
```unknown
#returns MA0466.2
motif.name <- ConvertMotifID(pbmc, name = 'CEBPB')
gene_plot <- FeaturePlot(pbmc, features = "sct_CEBPB", reduction = 'wnn.umap')
motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap')
gene_plot | motif_plot
```

Example 70 (r):
```r
#returns MA0466.2
motif.name <- ConvertMotifID(pbmc, name = 'CEBPB')
gene_plot <- FeaturePlot(pbmc, features = "sct_CEBPB", reduction = 'wnn.umap')
motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap')
gene_plot | motif_plot
```

Example 71 (r):
```r
#returns MA0466.2
motif.name <- ConvertMotifID(pbmc, name = 'CEBPB')
gene_plot <- FeaturePlot(pbmc, features = "sct_CEBPB", reduction = 'wnn.umap')
motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap')
gene_plot | motif_plot
```

Example 72 (unknown):
```unknown
markers_rna <- presto:::wilcoxauc.Seurat(X = pbmc, group_by = 'celltype', assay = 'data', seurat_assay = 'SCT')
markers_motifs <- presto:::wilcoxauc.Seurat(X = pbmc, group_by = 'celltype', assay = 'data', seurat_assay = 'chromvar')
motif.names <- markers_motifs$feature
colnames(markers_rna) <- paste0("RNA.", colnames(markers_rna))
colnames(markers_motifs) <- paste0("motif.", colnames(markers_motifs))
markers_rna$gene <- markers_rna$RNA.feature
markers_motifs$gene <- ConvertMotifID(pbmc, id = motif.names)
```

Example 73 (r):
```r
markers_rna <- presto:::wilcoxauc.Seurat(X = pbmc, group_by = 'celltype', assay = 'data', seurat_assay = 'SCT')
markers_motifs <- presto:::wilcoxauc.Seurat(X = pbmc, group_by = 'celltype', assay = 'data', seurat_assay = 'chromvar')
motif.names <- markers_motifs$feature
colnames(markers_rna) <- paste0("RNA.", colnames(markers_rna))
colnames(markers_motifs) <- paste0("motif.", colnames(markers_motifs))
markers_rna$gene <- markers_rna$RNA.feature
markers_motifs$gene <- ConvertMotifID(pbmc, id = motif.names)
```

Example 74 (r):
```r
markers_rna <- presto:::wilcoxauc.Seurat(X = pbmc, group_by = 'celltype', assay = 'data', seurat_assay = 'SCT')
markers_motifs <- presto:::wilcoxauc.Seurat(X = pbmc, group_by = 'celltype', assay = 'data', seurat_assay = 'chromvar')
motif.names <- markers_motifs$feature
colnames(markers_rna) <- paste0("RNA.", colnames(markers_rna))
colnames(markers_motifs) <- paste0("motif.", colnames(markers_motifs))
markers_rna$gene <- markers_rna$RNA.feature
markers_motifs$gene <- ConvertMotifID(pbmc, id = motif.names)
```

Example 75 (javascript):
```javascript
# a simple function to implement the procedure above
topTFs <- function(celltype, padj.cutoff = 1e-2) {
  ctmarkers_rna <- dplyr::filter(
    markers_rna, RNA.group == celltype, RNA.padj < padj.cutoff, RNA.logFC > 0) %>% 
    arrange(-RNA.auc)
  ctmarkers_motif <- dplyr::filter(
    markers_motifs, motif.group == celltype, motif.padj < padj.cutoff, motif.logFC > 0) %>% 
    arrange(-motif.auc)
  top_tfs <- inner_join(
    x = ctmarkers_rna[, c(2, 11, 6, 7)], 
    y = ctmarkers_motif[, c(2, 1, 11, 6, 7)], by = "gene"
  )
  top_tfs$avg_auc <- (top_tfs$RNA.auc + top_tfs$motif.auc) / 2
  top_tfs <- arrange(top_tfs, -avg_auc)
  return(top_tfs)
}
```

Example 76 (r):
```r
# a simple function to implement the procedure above
topTFs <- function(celltype, padj.cutoff = 1e-2) {
  ctmarkers_rna <- dplyr::filter(
    markers_rna, RNA.group == celltype, RNA.padj < padj.cutoff, RNA.logFC > 0) %>% 
    arrange(-RNA.auc)
  ctmarkers_motif <- dplyr::filter(
    markers_motifs, motif.group == celltype, motif.padj < padj.cutoff, motif.logFC > 0) %>% 
    arrange(-motif.auc)
  top_tfs <- inner_join(
    x = ctmarkers_rna[, c(2, 11, 6, 7)], 
    y = ctmarkers_motif[, c(2, 1, 11, 6, 7)], by = "gene"
  )
  top_tfs$avg_auc <- (top_tfs$RNA.auc + top_tfs$motif.auc) / 2
  top_tfs <- arrange(top_tfs, -avg_auc)
  return(top_tfs)
}
```

Example 77 (r):
```r
# a simple function to implement the procedure above
topTFs <- function(celltype, padj.cutoff = 1e-2) {
  ctmarkers_rna <- dplyr::filter(
    markers_rna, RNA.group == celltype, RNA.padj < padj.cutoff, RNA.logFC > 0) %>% 
    arrange(-RNA.auc)
  ctmarkers_motif <- dplyr::filter(
    markers_motifs, motif.group == celltype, motif.padj < padj.cutoff, motif.logFC > 0) %>% 
    arrange(-motif.auc)
  top_tfs <- inner_join(
    x = ctmarkers_rna[, c(2, 11, 6, 7)], 
    y = ctmarkers_motif[, c(2, 1, 11, 6, 7)], by = "gene"
  )
  top_tfs$avg_auc <- (top_tfs$RNA.auc + top_tfs$motif.auc) / 2
  top_tfs <- arrange(top_tfs, -avg_auc)
  return(top_tfs)
}
```

Example 78 (unknown):
```unknown
# identify top markers in NK and visualize
head(topTFs("NK"), 3)
```

Example 79 (r):
```r
# identify top markers in NK and visualize
head(topTFs("NK"), 3)
```

Example 80 (r):
```r
# identify top markers in NK and visualize
head(topTFs("NK"), 3)
```

Example 81 (unknown):
```unknown
##   RNA.group  gene   RNA.auc      RNA.pval motif.group motif.feature motif.auc
## 1        NK TBX21 0.7254543  0.000000e+00          NK      MA0690.1 0.9161365
## 2        NK EOMES 0.5889408  5.394245e-99          NK      MA0800.1 0.9239066
## 3        NK RUNX3 0.7705554 1.256004e-119          NK      MA0684.2 0.6813549
##      motif.pval   avg_auc
## 1 2.177841e-204 0.8207954
## 2 5.165634e-212 0.7564237
## 3  2.486287e-40 0.7259552
```

Example 82 (unknown):
```unknown
##   RNA.group  gene   RNA.auc      RNA.pval motif.group motif.feature motif.auc
## 1        NK TBX21 0.7254543  0.000000e+00          NK      MA0690.1 0.9161365
## 2        NK EOMES 0.5889408  5.394245e-99          NK      MA0800.1 0.9239066
## 3        NK RUNX3 0.7705554 1.256004e-119          NK      MA0684.2 0.6813549
##      motif.pval   avg_auc
## 1 2.177841e-204 0.8207954
## 2 5.165634e-212 0.7564237
## 3  2.486287e-40 0.7259552
```

Example 83 (unknown):
```unknown
motif.name <- ConvertMotifID(pbmc, name = 'TBX21')
gene_plot <- FeaturePlot(pbmc, features = "sct_TBX21", reduction = 'wnn.umap')
motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap')
gene_plot | motif_plot
```

Example 84 (r):
```r
motif.name <- ConvertMotifID(pbmc, name = 'TBX21')
gene_plot <- FeaturePlot(pbmc, features = "sct_TBX21", reduction = 'wnn.umap')
motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap')
gene_plot | motif_plot
```

Example 85 (r):
```r
motif.name <- ConvertMotifID(pbmc, name = 'TBX21')
gene_plot <- FeaturePlot(pbmc, features = "sct_TBX21", reduction = 'wnn.umap')
motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap')
gene_plot | motif_plot
```

Example 86 (unknown):
```unknown
# identify top markers in pDC and visualize
head(topTFs("pDC"), 3)
```

Example 87 (r):
```r
# identify top markers in pDC and visualize
head(topTFs("pDC"), 3)
```

Example 88 (r):
```r
# identify top markers in pDC and visualize
head(topTFs("pDC"), 3)
```

Example 89 (unknown):
```unknown
##   RNA.group gene   RNA.auc      RNA.pval motif.group motif.feature motif.auc
## 1       pDC TCF4 0.9998773 1.881543e-162         pDC      MA0830.2 0.9965481
## 2       pDC IRF8 0.9907541 1.197641e-123         pDC      MA0652.1 0.8833112
## 3       pDC SPIB 0.9113825  0.000000e+00         pDC      MA0081.2 0.9068540
##     motif.pval   avg_auc
## 1 1.785897e-69 0.9982127
## 2 3.982413e-42 0.9370327
## 3 3.083509e-47 0.9091182
```

Example 90 (unknown):
```unknown
##   RNA.group gene   RNA.auc      RNA.pval motif.group motif.feature motif.auc
## 1       pDC TCF4 0.9998773 1.881543e-162         pDC      MA0830.2 0.9965481
## 2       pDC IRF8 0.9907541 1.197641e-123         pDC      MA0652.1 0.8833112
## 3       pDC SPIB 0.9113825  0.000000e+00         pDC      MA0081.2 0.9068540
##     motif.pval   avg_auc
## 1 1.785897e-69 0.9982127
## 2 3.982413e-42 0.9370327
## 3 3.083509e-47 0.9091182
```

Example 91 (unknown):
```unknown
motif.name <- ConvertMotifID(pbmc, name = 'TCF4')
gene_plot <- FeaturePlot(pbmc, features = "sct_TCF4", reduction = 'wnn.umap')
motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap')
gene_plot | motif_plot
```

Example 92 (r):
```r
motif.name <- ConvertMotifID(pbmc, name = 'TCF4')
gene_plot <- FeaturePlot(pbmc, features = "sct_TCF4", reduction = 'wnn.umap')
motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap')
gene_plot | motif_plot
```

Example 93 (r):
```r
motif.name <- ConvertMotifID(pbmc, name = 'TCF4')
gene_plot <- FeaturePlot(pbmc, features = "sct_TCF4", reduction = 'wnn.umap')
motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap')
gene_plot | motif_plot
```

Example 94 (unknown):
```unknown
# identify top markers in HSPC and visualize
head(topTFs("CD16 Mono"),3)
```

Example 95 (r):
```r
# identify top markers in HSPC and visualize
head(topTFs("CD16 Mono"),3)
```

Example 96 (r):
```r
# identify top markers in HSPC and visualize
head(topTFs("CD16 Mono"),3)
```

Example 97 (unknown):
```unknown
##   RNA.group  gene   RNA.auc      RNA.pval motif.group motif.feature motif.auc
## 1 CD16 Mono  TCF7 0.6229004  5.572097e-27   CD16 Mono      MA0769.2 0.6956458
## 2 CD16 Mono  LEF1 0.6244160  1.959810e-27   CD16 Mono      MA0768.1 0.6427922
## 3 CD16 Mono GATA3 0.6853318 1.575081e-132   CD16 Mono      MA0037.3 0.5622475
##     motif.pval   avg_auc
## 1 8.605682e-54 0.6592731
## 2 1.845888e-29 0.6336041
## 3 8.972511e-07 0.6237897
```

Example 98 (unknown):
```unknown
##   RNA.group  gene   RNA.auc      RNA.pval motif.group motif.feature motif.auc
## 1 CD16 Mono  TCF7 0.6229004  5.572097e-27   CD16 Mono      MA0769.2 0.6956458
## 2 CD16 Mono  LEF1 0.6244160  1.959810e-27   CD16 Mono      MA0768.1 0.6427922
## 3 CD16 Mono GATA3 0.6853318 1.575081e-132   CD16 Mono      MA0037.3 0.5622475
##     motif.pval   avg_auc
## 1 8.605682e-54 0.6592731
## 2 1.845888e-29 0.6336041
## 3 8.972511e-07 0.6237897
```

Example 99 (unknown):
```unknown
motif.name <- ConvertMotifID(pbmc, name = 'SPI1')
gene_plot <- FeaturePlot(pbmc, features = "sct_SPI1", reduction = 'wnn.umap')
motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap')
gene_plot | motif_plot
```

Example 100 (r):
```r
motif.name <- ConvertMotifID(pbmc, name = 'SPI1')
gene_plot <- FeaturePlot(pbmc, features = "sct_SPI1", reduction = 'wnn.umap')
motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap')
gene_plot | motif_plot
```

Example 101 (r):
```r
motif.name <- ConvertMotifID(pbmc, name = 'SPI1')
gene_plot <- FeaturePlot(pbmc, features = "sct_SPI1", reduction = 'wnn.umap')
motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap')
gene_plot | motif_plot
```

Example 102 (unknown):
```unknown
# identify top markers in other cell types
head(topTFs("Naive B"), 3)
```

Example 103 (r):
```r
# identify top markers in other cell types
head(topTFs("Naive B"), 3)
```

Example 104 (r):
```r
# identify top markers in other cell types
head(topTFs("Naive B"), 3)
```

Example 105 (unknown):
```unknown
##   RNA.group   gene   RNA.auc      RNA.pval motif.group motif.feature motif.auc
## 1   Naive B   TCF4 0.8350167 8.961289e-239     Naive B      MA0830.2 0.9066328
## 2   Naive B POU2F2 0.6969289  9.622025e-43     Naive B      MA0507.1 0.9740857
## 3   Naive B   EBF1 0.9114260  0.000000e+00     Naive B      MA0154.4 0.7565424
##      motif.pval   avg_auc
## 1 8.987390e-151 0.8708247
## 2 3.336610e-204 0.8355073
## 3  3.662535e-61 0.8339842
```

Example 106 (unknown):
```unknown
##   RNA.group   gene   RNA.auc      RNA.pval motif.group motif.feature motif.auc
## 1   Naive B   TCF4 0.8350167 8.961289e-239     Naive B      MA0830.2 0.9066328
## 2   Naive B POU2F2 0.6969289  9.622025e-43     Naive B      MA0507.1 0.9740857
## 3   Naive B   EBF1 0.9114260  0.000000e+00     Naive B      MA0154.4 0.7565424
##      motif.pval   avg_auc
## 1 8.987390e-151 0.8708247
## 2 3.336610e-204 0.8355073
## 3  3.662535e-61 0.8339842
```

Example 107 (unknown):
```unknown
head(topTFs("HSPC"), 3)
```

Example 108 (r):
```r
head(topTFs("HSPC"), 3)
```

Example 109 (r):
```r
head(topTFs("HSPC"), 3)
```

Example 110 (unknown):
```unknown
##   RNA.group  gene   RNA.auc     RNA.pval motif.group motif.feature motif.auc
## 1      HSPC  SOX4 0.9864425 2.831723e-71        HSPC      MA0867.2 0.6830497
## 2      HSPC GATA2 0.7115385 0.000000e+00        HSPC      MA0036.3 0.8275008
## 3      HSPC MEIS1 0.8254177 0.000000e+00        HSPC      MA0498.2 0.6924225
##     motif.pval   avg_auc
## 1 1.241915e-03 0.8347461
## 2 7.591798e-09 0.7695196
## 3 6.877492e-04 0.7589201
```

Example 111 (unknown):
```unknown
##   RNA.group  gene   RNA.auc     RNA.pval motif.group motif.feature motif.auc
## 1      HSPC  SOX4 0.9864425 2.831723e-71        HSPC      MA0867.2 0.6830497
## 2      HSPC GATA2 0.7115385 0.000000e+00        HSPC      MA0036.3 0.8275008
## 3      HSPC MEIS1 0.8254177 0.000000e+00        HSPC      MA0498.2 0.6924225
##     motif.pval   avg_auc
## 1 1.241915e-03 0.8347461
## 2 7.591798e-09 0.7695196
## 3 6.877492e-04 0.7589201
```

Example 112 (unknown):
```unknown
head(topTFs("Plasma"), 3)
```

Example 113 (r):
```r
head(topTFs("Plasma"), 3)
```

Example 114 (r):
```r
head(topTFs("Plasma"), 3)
```

Example 115 (unknown):
```unknown
##   RNA.group  gene   RNA.auc     RNA.pval motif.group motif.feature motif.auc
## 1    Plasma  IRF4 0.8189420 5.329976e-35      Plasma      MA1419.1 0.9776046
## 2    Plasma MEF2C 0.9108487 3.135227e-12      Plasma      MA0497.1 0.7596637
## 3    Plasma  TCF4 0.8306796 1.041100e-13      Plasma      MA0830.2 0.7840848
##     motif.pval   avg_auc
## 1 2.334627e-12 0.8982733
## 2 1.374353e-04 0.8352562
## 3 3.028306e-05 0.8073822
```

Example 116 (unknown):
```unknown
##   RNA.group  gene   RNA.auc     RNA.pval motif.group motif.feature motif.auc
## 1    Plasma  IRF4 0.8189420 5.329976e-35      Plasma      MA1419.1 0.9776046
## 2    Plasma MEF2C 0.9108487 3.135227e-12      Plasma      MA0497.1 0.7596637
## 3    Plasma  TCF4 0.8306796 1.041100e-13      Plasma      MA0830.2 0.7840848
##     motif.pval   avg_auc
## 1 2.334627e-12 0.8982733
## 2 1.374353e-04 0.8352562
## 3 3.028306e-05 0.8073822
```

Example 117 (unknown):
```unknown
sessionInfo()
```

Example 118 (r):
```r
sessionInfo()
```

Example 119 (r):
```r
sessionInfo()
```

Example 120 (unknown):
```unknown
## R version 4.2.2 Patched (2022-11-10 r83330)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.6 LTS
## 
## Matrix products: default
## BLAS:   /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.9.0
## LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.9.0
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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       
## 
## attached base packages:
## [1] stats4    stats     graphics  grDevices utils     datasets  methods  
## [8] base     
## 
## other attached packages:
##  [1] BSgenome.Hsapiens.UCSC.hg38_1.4.5 BSgenome_1.66.3                  
##  [3] rtracklayer_1.58.0                Biostrings_2.66.0                
##  [5] XVector_0.38.0                    motifmatchr_1.20.0               
##  [7] TFBSTools_1.36.0                  JASPAR2020_0.99.10               
##  [9] chromVAR_1.20.2                   EnsDb.Hsapiens.v86_2.99.0        
## [11] ensembldb_2.22.0                  AnnotationFilter_1.22.0          
## [13] GenomicFeatures_1.50.4            AnnotationDbi_1.60.2             
## [15] Biobase_2.58.0                    GenomicRanges_1.50.2             
## [17] GenomeInfoDb_1.34.9               IRanges_2.32.0                   
## [19] S4Vectors_0.36.2                  BiocGenerics_0.44.0              
## [21] Signac_1.12.9000                  ggplot2_3.4.4                    
## [23] dplyr_1.1.3                       cowplot_1.1.1                    
## [25] thp1.eccite.SeuratData_3.1.5      stxBrain.SeuratData_0.1.1        
## [27] ssHippo.SeuratData_3.1.4          pbmcsca.SeuratData_3.0.0         
## [29] pbmcref.SeuratData_1.0.0          pbmcMultiome.SeuratData_0.1.4    
## [31] pbmc3k.SeuratData_3.1.4           panc8.SeuratData_3.0.2           
## [33] ifnb.SeuratData_3.0.0             hcabm40k.SeuratData_3.0.0        
## [35] cbmc.SeuratData_3.1.4             bmcite.SeuratData_0.3.0          
## [37] SeuratData_0.2.2.9001             Seurat_5.0.0                     
## [39] SeuratObject_5.0.0                sp_2.1-1                         
## 
## loaded via a namespace (and not attached):
##   [1] rappdirs_0.3.3              scattermore_1.2            
##   [3] R.methodsS3_1.8.2           ragg_1.2.5                 
##   [5] nabor_0.5.0                 tidyr_1.3.0                
##   [7] bit64_4.0.5                 knitr_1.45                 
##   [9] R.utils_2.12.2              irlba_2.3.5.1              
##  [11] DelayedArray_0.24.0         rpart_4.1.19               
##  [13] data.table_1.14.8           KEGGREST_1.38.0            
##  [15] RCurl_1.98-1.12             generics_0.1.3             
##  [17] RSQLite_2.3.1               RANN_2.6.1                 
##  [19] future_1.33.0               tzdb_0.4.0                 
##  [21] bit_4.0.5                   spatstat.data_3.0-3        
##  [23] xml2_1.3.5                  httpuv_1.6.12              
##  [25] SummarizedExperiment_1.28.0 DirichletMultinomial_1.40.0
##  [27] xfun_0.40                   hms_1.1.3                  
##  [29] jquerylib_0.1.4             evaluate_0.22              
##  [31] promises_1.2.1              fansi_1.0.5                
##  [33] restfulr_0.0.15             progress_1.2.2             
##  [35] caTools_1.18.2              dbplyr_2.3.4               
##  [37] igraph_1.5.1                DBI_1.1.3                  
##  [39] htmlwidgets_1.6.2           spatstat.geom_3.2-7        
##  [41] purrr_1.0.2                 ellipsis_0.3.2             
##  [43] RSpectra_0.16-1             backports_1.4.1            
##  [45] annotate_1.76.0             sparseMatrixStats_1.10.0   
##  [47] biomaRt_2.54.1              deldir_1.0-9               
##  [49] MatrixGenerics_1.10.0       vctrs_0.6.4                
##  [51] ROCR_1.0-11                 abind_1.4-5                
##  [53] cachem_1.0.8                withr_2.5.2                
##  [55] progressr_0.14.0            presto_1.0.0               
##  [57] checkmate_2.2.0             sctransform_0.4.1          
##  [59] GenomicAlignments_1.34.1    prettyunits_1.1.1          
##  [61] goftest_1.2-3               cluster_2.1.4              
##  [63] seqLogo_1.64.0              dotCall64_1.1-0            
##  [65] lazyeval_0.2.2              crayon_1.5.2               
##  [67] hdf5r_1.3.8                 spatstat.explore_3.2-5     
##  [69] pkgconfig_2.0.3             labeling_0.4.3             
##  [71] nlme_3.1-162                vipor_0.4.5                
##  [73] ProtGenerics_1.30.0         nnet_7.3-18                
##  [75] rlang_1.1.1                 globals_0.16.2             
##  [77] lifecycle_1.0.3             miniUI_0.1.1.1             
##  [79] filelock_1.0.2              fastDummies_1.7.3          
##  [81] BiocFileCache_2.6.1         dichromat_2.0-0.1          
##  [83] ggrastr_1.0.1               rprojroot_2.0.3            
##  [85] polyclip_1.10-6             RcppHNSW_0.5.0             
##  [87] matrixStats_1.0.0           lmtest_0.9-40              
##  [89] Matrix_1.6-1.1              zoo_1.8-12                 
##  [91] base64enc_0.1-3             beeswarm_0.4.0             
##  [93] ggridges_0.5.4              png_0.1-8                  
##  [95] viridisLite_0.4.2           rjson_0.2.21               
##  [97] bitops_1.0-7                R.oo_1.25.0                
##  [99] KernSmooth_2.23-22          spam_2.10-0                
## [101] DelayedMatrixStats_1.20.0   blob_1.2.4                 
## [103] stringr_1.5.0               parallelly_1.36.0          
## [105] spatstat.random_3.2-1       readr_2.1.4                
## [107] CNEr_1.34.0                 scales_1.2.1               
## [109] memoise_2.0.1               magrittr_2.0.3             
## [111] plyr_1.8.9                  ica_1.0-3                  
## [113] zlibbioc_1.44.0             compiler_4.2.2             
## [115] BiocIO_1.8.0                RColorBrewer_1.1-3         
## [117] fitdistrplus_1.1-11         Rsamtools_2.14.0           
## [119] cli_3.6.1                   listenv_0.9.0              
## [121] patchwork_1.1.3             pbapply_1.7-2              
## [123] htmlTable_2.4.1             Formula_1.2-5              
## [125] MASS_7.3-58.2               tidyselect_1.2.0           
## [127] stringi_1.7.12              glmGamPoi_1.10.2           
## [129] textshaping_0.3.6           highr_0.10                 
## [131] yaml_2.3.7                  ggrepel_0.9.4              
## [133] grid_4.2.2                  VariantAnnotation_1.44.1   
## [135] sass_0.4.7                  fastmatch_1.1-4            
## [137] tools_4.2.2                 future.apply_1.11.0        
## [139] parallel_4.2.2              rstudioapi_0.14            
## [141] TFMPvalue_0.0.9             foreign_0.8-84             
## [143] gridExtra_2.3               farver_2.1.1               
## [145] Rtsne_0.16                  digest_0.6.33              
## [147] pracma_2.4.2                shiny_1.7.5.1              
## [149] Rcpp_1.0.11                 later_1.3.1                
## [151] RcppAnnoy_0.0.21            httr_1.4.7                 
## [153] biovizBase_1.46.0           colorspace_2.1-0           
## [155] XML_3.99-0.14               fs_1.6.3                   
## [157] tensor_1.5                  reticulate_1.34.0          
## [159] splines_4.2.2               uwot_0.1.16                
## [161] RcppRoll_0.3.0              spatstat.utils_3.0-4       
## [163] pkgdown_2.0.7               plotly_4.10.3              
## [165] systemfonts_1.0.4           xtable_1.8-4               
## [167] poweRlaw_0.70.6             jsonlite_1.8.7             
## [169] R6_2.5.1                    Hmisc_5.1-1                
## [171] pillar_1.9.0                htmltools_0.5.6.1          
## [173] mime_0.12                   DT_0.30                    
## [175] glue_1.6.2                  fastmap_1.1.1              
## [177] BiocParallel_1.32.6         codetools_0.2-19           
## [179] utf8_1.2.4                  lattice_0.21-9             
## [181] bslib_0.5.1                 spatstat.sparse_3.0-3      
## [183] tibble_3.2.1                curl_5.1.0                 
## [185] ggbeeswarm_0.7.1            leiden_0.4.3               
## [187] gtools_3.9.4                GO.db_3.16.0               
## [189] survival_3.5-7              rmarkdown_2.25             
## [191] desc_1.4.2                  munsell_0.5.0              
## [193] GenomeInfoDbData_1.2.9      reshape2_1.4.4             
## [195] gtable_0.3.4
```

Example 121 (unknown):
```unknown
## R version 4.2.2 Patched (2022-11-10 r83330)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.6 LTS
## 
## Matrix products: default
## BLAS:   /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.9.0
## LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.9.0
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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       
## 
## attached base packages:
## [1] stats4    stats     graphics  grDevices utils     datasets  methods  
## [8] base     
## 
## other attached packages:
##  [1] BSgenome.Hsapiens.UCSC.hg38_1.4.5 BSgenome_1.66.3                  
##  [3] rtracklayer_1.58.0                Biostrings_2.66.0                
##  [5] XVector_0.38.0                    motifmatchr_1.20.0               
##  [7] TFBSTools_1.36.0                  JASPAR2020_0.99.10               
##  [9] chromVAR_1.20.2                   EnsDb.Hsapiens.v86_2.99.0        
## [11] ensembldb_2.22.0                  AnnotationFilter_1.22.0          
## [13] GenomicFeatures_1.50.4            AnnotationDbi_1.60.2             
## [15] Biobase_2.58.0                    GenomicRanges_1.50.2             
## [17] GenomeInfoDb_1.34.9               IRanges_2.32.0                   
## [19] S4Vectors_0.36.2                  BiocGenerics_0.44.0              
## [21] Signac_1.12.9000                  ggplot2_3.4.4                    
## [23] dplyr_1.1.3                       cowplot_1.1.1                    
## [25] thp1.eccite.SeuratData_3.1.5      stxBrain.SeuratData_0.1.1        
## [27] ssHippo.SeuratData_3.1.4          pbmcsca.SeuratData_3.0.0         
## [29] pbmcref.SeuratData_1.0.0          pbmcMultiome.SeuratData_0.1.4    
## [31] pbmc3k.SeuratData_3.1.4           panc8.SeuratData_3.0.2           
## [33] ifnb.SeuratData_3.0.0             hcabm40k.SeuratData_3.0.0        
## [35] cbmc.SeuratData_3.1.4             bmcite.SeuratData_0.3.0          
## [37] SeuratData_0.2.2.9001             Seurat_5.0.0                     
## [39] SeuratObject_5.0.0                sp_2.1-1                         
## 
## loaded via a namespace (and not attached):
##   [1] rappdirs_0.3.3              scattermore_1.2            
##   [3] R.methodsS3_1.8.2           ragg_1.2.5                 
##   [5] nabor_0.5.0                 tidyr_1.3.0                
##   [7] bit64_4.0.5                 knitr_1.45                 
##   [9] R.utils_2.12.2              irlba_2.3.5.1              
##  [11] DelayedArray_0.24.0         rpart_4.1.19               
##  [13] data.table_1.14.8           KEGGREST_1.38.0            
##  [15] RCurl_1.98-1.12             generics_0.1.3             
##  [17] RSQLite_2.3.1               RANN_2.6.1                 
##  [19] future_1.33.0               tzdb_0.4.0                 
##  [21] bit_4.0.5                   spatstat.data_3.0-3        
##  [23] xml2_1.3.5                  httpuv_1.6.12              
##  [25] SummarizedExperiment_1.28.0 DirichletMultinomial_1.40.0
##  [27] xfun_0.40                   hms_1.1.3                  
##  [29] jquerylib_0.1.4             evaluate_0.22              
##  [31] promises_1.2.1              fansi_1.0.5                
##  [33] restfulr_0.0.15             progress_1.2.2             
##  [35] caTools_1.18.2              dbplyr_2.3.4               
##  [37] igraph_1.5.1                DBI_1.1.3                  
##  [39] htmlwidgets_1.6.2           spatstat.geom_3.2-7        
##  [41] purrr_1.0.2                 ellipsis_0.3.2             
##  [43] RSpectra_0.16-1             backports_1.4.1            
##  [45] annotate_1.76.0             sparseMatrixStats_1.10.0   
##  [47] biomaRt_2.54.1              deldir_1.0-9               
##  [49] MatrixGenerics_1.10.0       vctrs_0.6.4                
##  [51] ROCR_1.0-11                 abind_1.4-5                
##  [53] cachem_1.0.8                withr_2.5.2                
##  [55] progressr_0.14.0            presto_1.0.0               
##  [57] checkmate_2.2.0             sctransform_0.4.1          
##  [59] GenomicAlignments_1.34.1    prettyunits_1.1.1          
##  [61] goftest_1.2-3               cluster_2.1.4              
##  [63] seqLogo_1.64.0              dotCall64_1.1-0            
##  [65] lazyeval_0.2.2              crayon_1.5.2               
##  [67] hdf5r_1.3.8                 spatstat.explore_3.2-5     
##  [69] pkgconfig_2.0.3             labeling_0.4.3             
##  [71] nlme_3.1-162                vipor_0.4.5                
##  [73] ProtGenerics_1.30.0         nnet_7.3-18                
##  [75] rlang_1.1.1                 globals_0.16.2             
##  [77] lifecycle_1.0.3             miniUI_0.1.1.1             
##  [79] filelock_1.0.2              fastDummies_1.7.3          
##  [81] BiocFileCache_2.6.1         dichromat_2.0-0.1          
##  [83] ggrastr_1.0.1               rprojroot_2.0.3            
##  [85] polyclip_1.10-6             RcppHNSW_0.5.0             
##  [87] matrixStats_1.0.0           lmtest_0.9-40              
##  [89] Matrix_1.6-1.1              zoo_1.8-12                 
##  [91] base64enc_0.1-3             beeswarm_0.4.0             
##  [93] ggridges_0.5.4              png_0.1-8                  
##  [95] viridisLite_0.4.2           rjson_0.2.21               
##  [97] bitops_1.0-7                R.oo_1.25.0                
##  [99] KernSmooth_2.23-22          spam_2.10-0                
## [101] DelayedMatrixStats_1.20.0   blob_1.2.4                 
## [103] stringr_1.5.0               parallelly_1.36.0          
## [105] spatstat.random_3.2-1       readr_2.1.4                
## [107] CNEr_1.34.0                 scales_1.2.1               
## [109] memoise_2.0.1               magrittr_2.0.3             
## [111] plyr_1.8.9                  ica_1.0-3                  
## [113] zlibbioc_1.44.0             compiler_4.2.2             
## [115] BiocIO_1.8.0                RColorBrewer_1.1-3         
## [117] fitdistrplus_1.1-11         Rsamtools_2.14.0           
## [119] cli_3.6.1                   listenv_0.9.0              
## [121] patchwork_1.1.3             pbapply_1.7-2              
## [123] htmlTable_2.4.1             Formula_1.2-5              
## [125] MASS_7.3-58.2               tidyselect_1.2.0           
## [127] stringi_1.7.12              glmGamPoi_1.10.2           
## [129] textshaping_0.3.6           highr_0.10                 
## [131] yaml_2.3.7                  ggrepel_0.9.4              
## [133] grid_4.2.2                  VariantAnnotation_1.44.1   
## [135] sass_0.4.7                  fastmatch_1.1-4            
## [137] tools_4.2.2                 future.apply_1.11.0        
## [139] parallel_4.2.2              rstudioapi_0.14            
## [141] TFMPvalue_0.0.9             foreign_0.8-84             
## [143] gridExtra_2.3               farver_2.1.1               
## [145] Rtsne_0.16                  digest_0.6.33              
## [147] pracma_2.4.2                shiny_1.7.5.1              
## [149] Rcpp_1.0.11                 later_1.3.1                
## [151] RcppAnnoy_0.0.21            httr_1.4.7                 
## [153] biovizBase_1.46.0           colorspace_2.1-0           
## [155] XML_3.99-0.14               fs_1.6.3                   
## [157] tensor_1.5                  reticulate_1.34.0          
## [159] splines_4.2.2               uwot_0.1.16                
## [161] RcppRoll_0.3.0              spatstat.utils_3.0-4       
## [163] pkgdown_2.0.7               plotly_4.10.3              
## [165] systemfonts_1.0.4           xtable_1.8-4               
## [167] poweRlaw_0.70.6             jsonlite_1.8.7             
## [169] R6_2.5.1                    Hmisc_5.1-1                
## [171] pillar_1.9.0                htmltools_0.5.6.1          
## [173] mime_0.12                   DT_0.30                    
## [175] glue_1.6.2                  fastmap_1.1.1              
## [177] BiocParallel_1.32.6         codetools_0.2-19           
## [179] utf8_1.2.4                  lattice_0.21-9             
## [181] bslib_0.5.1                 spatstat.sparse_3.0-3      
## [183] tibble_3.2.1                curl_5.1.0                 
## [185] ggbeeswarm_0.7.1            leiden_0.4.3               
## [187] gtools_3.9.4                GO.db_3.16.0               
## [189] survival_3.5-7              rmarkdown_2.25             
## [191] desc_1.4.2                  munsell_0.5.0              
## [193] GenomeInfoDbData_1.2.9      reshape2_1.4.4             
## [195] gtable_0.3.4
```

---

## Analysis, visualization, and integration of Visium HD spatial datasets with Seurat • Seurat

**URL:** http://127.0.0.1:9173/seurat/articles/archive/index.html

**Contents:**
- Documentation Archive
- Version 2-4 tutorials
    - PBMC scATAC-seq Vignette
    - Cell-Cycle Scoring and Regression
    - Interoperability between single-cell object formats
    - Differential expression testing
    - Seurat - Dimensional Reduction Vignette
    - Parallelization in Seurat with future
    - Demultiplexing with hashtag oligos (HTOs)
    - Tutorial: Integrating stimulated vs. control PBMC datasets to learn cell- type specific responses
    - Integration and Label Transfer
    - Mapping and annotating query datasets
    - Tips for integrating large datasets
    - Fast integration using reciprocal PCA (RPCA)
    - Seurat - Interaction Tips
    - Guided Clustering of the Microwell-seq Mouse Cell Atlas
    - Seurat - Combining Two 10X Runs
    - Mixscape Vignette
    - Multimodal reference mapping
    - Using Seurat with multi-modal data
    - Guided tutorial — 2,700 PBMCs
    - Using sctransform in Seurat
    - SCTransform v2
    - Analysis, visualization, and integration of spatial datasets with Seurat
    - New data visualization methods in v3.0
    - Weighted Nearest Neighbor Analysis
- Version 1.3-1.4 tutorials
- Version <=1.2 tutorials
- Contents

In version 4, the Seurat documentation was transitioned to pkgdown. Here we provide access to all previous versions of the documentation.

For versions 1.3-1.4, we provide access to the old documentation pages here

For versions <=1.2, we provide access to the old documentation pages here

Developed by Rahul Satija, Satija Lab and Collaborators.

Site built with pkgdown 2.0.7.

**Examples:**

Example 1 (unknown):
```unknown
vignettes/archive.Rmd
```

Example 2 (unknown):
```unknown
archive.Rmd
```

---

## Analysis, visualization, and integration of Visium HD spatial datasets with Seurat • Seurat

**URL:** http://127.0.0.1:9173/seurat/articles/seurat5_integration/index.html

**Contents:**
- Integrative analysis in Seurat v5
    - Compiled: October 31, 2023
- Introduction
- Layers in the Seurat v5 object
- Perform streamlined (one-line) integrative analysis
- Contents

Integration of single-cell sequencing datasets, for example across experimental batches, donors, or conditions, is often an important step in scRNA-seq workflows. Integrative analysis can help to match shared cell types and states across datasets, which can boost statistical power, and most importantly, facilitate accurate comparative analysis across datasets. In previous versions of Seurat we introduced methods for integrative analysis, including our ‘anchor-based’ integration workflow. Many labs have also published powerful and pioneering methods, including Harmony and scVI, for integrative analysis. We recognize that while the goal of matching shared cell types across datasets may be important for many problems, users may also be concerned about which method to use, or that integration could result in a loss of biological resolution. In Seurat v5, we introduce more flexible and streamlined infrastructure to run different integration algorithms with a single line of code. This makes it easier to explore the results of different integration methods, and to compare these results to a workflow that excludes integration steps. For this vignette, we use a dataset of human PBMC profiled with seven different technologies, profiled as part of a systematic comparative analysis (pbmcsca). The data is available as part of our SeuratData package.

Seurat v5 assays store data in layers. These layers can store raw, un-normalized counts (layer='counts'), normalized data (layer='data'), or z-scored/variance-stabilized data (layer='scale.data'). We can load in the data, remove low-quality cells, and obtain predicted cell annotations (which will be useful for assessing integration later), using our Azimuth pipeline.

The object contains data from nine different batches (stored in the Method column in the object metadata), representing seven different technologies. We will aim to integrate the different batches together. In previous versions of Seurat, we would require the data to be represented as nine different Seurat objects. When using Seurat v5 assays, we can instead keep all the data in one object, but simply split the layers. After splitting, there are now 18 layers (a counts and data layer for each batch). We can also run a standard scRNA-seq analysis (i.e. without integration). Note that since the data is split into layers, normalization and variable feature identification is performed for each batch independently (a consensus set of variable features is automatically identified).

We can now visualize the results of a standard analysis without integration. Note that cells are grouping both by cell type and by underlying method. While a UMAP analysis is just a visualization of this, clustering this dataset would return predominantly batch-specific clusters. Especially if previous cell-type annotations were not available, this would make downstream analysis extremely challenging.

Seurat v5 enables streamlined integrative analysis using the IntegrateLayers function. The method currently supports five integration methods. Each of these methods performs integration in low-dimensional space, and returns a dimensional reduction (i.e. integrated.rpca) that aims to co-embed shared cell types across batches:

Note that our anchor-based RPCA integration represents a faster and more conservative (less correction) method for integration. For interested users, we discuss this method in more detail in our previous RPCA vignette

You can find more detail on each method, and any installation prerequisites, in Seurat’s documentation (for example, ?scVIIntegration). For example, scVI integration requires reticulate which can be installed from CRAN (install.packages("reticulate")) as well as scvi-tools and its dependencies installed in a conda environment. Please see scVI installation instructions here.

Each of the following lines perform a new integration using a single line of code:

For any of the methods, we can now visualize and cluster the datasets. We show this for CCA integration and scVI, but you can do this for any method

We hope that by simplifying the process of performing integrative analysis, users can more carefully evaluate the biological information retained in the integrated dataset. For example, users can compare the expression of biological markers based on different clustering solutions, or visualize one method’s clustering solution on different UMAP visualizations.

Once integrative analysis is complete, you can rejoin the layers - which collapses the individual datasets together and recreates the original counts and data layers. You will need to do this before performing any differential expression analysis. However, you can always resplit the layers in case you would like to reperform integrative analysis.

Lastly, users can also perform integration using sctransform-normalized data (see our SCTransform vignette for more information), by first running SCTransform normalization, and then setting the normalization.method argument in IntegrateLayers.

Developed by Rahul Satija, Satija Lab and Collaborators.

Site built with pkgdown 2.0.7.

**Examples:**

Example 1 (unknown):
```unknown
vignettes/seurat5_integration.Rmd
```

Example 2 (unknown):
```unknown
seurat5_integration.Rmd
```

Example 3 (unknown):
```unknown
library(Seurat)
library(SeuratData)
library(SeuratWrappers)
library(Azimuth)
library(ggplot2)
library(patchwork)
options(future.globals.maxSize = 1e9)
```

Example 4 (r):
```r
library(Seurat)
library(SeuratData)
library(SeuratWrappers)
library(Azimuth)
library(ggplot2)
library(patchwork)
options(future.globals.maxSize = 1e9)
```

Example 5 (unknown):
```unknown
layer='counts'
```

Example 6 (unknown):
```unknown
layer='data'
```

Example 7 (unknown):
```unknown
layer='scale.data'
```

Example 8 (unknown):
```unknown
# load in the pbmc systematic comparative analysis dataset
obj <- LoadData("pbmcsca")
obj <- subset(obj, nFeature_RNA > 1000)
obj <- RunAzimuth(obj, reference = "pbmcref")
# currently, the object has two layers in the RNA assay: counts, and data
obj
```

Example 9 (r):
```r
# load in the pbmc systematic comparative analysis dataset
obj <- LoadData("pbmcsca")
obj <- subset(obj, nFeature_RNA > 1000)
obj <- RunAzimuth(obj, reference = "pbmcref")
# currently, the object has two layers in the RNA assay: counts, and data
obj
```

Example 10 (r):
```r
# load in the pbmc systematic comparative analysis dataset
obj <- LoadData("pbmcsca")
obj <- subset(obj, nFeature_RNA > 1000)
obj <- RunAzimuth(obj, reference = "pbmcref")
# currently, the object has two layers in the RNA assay: counts, and data
obj
```

Example 11 (python):
```python
## An object of class Seurat 
## 33789 features across 10434 samples within 4 assays 
## Active assay: RNA (33694 features, 0 variable features)
##  2 layers present: counts, data
##  3 other assays present: prediction.score.celltype.l1, prediction.score.celltype.l2, prediction.score.celltype.l3
##  2 dimensional reductions calculated: integrated_dr, ref.umap
```

Example 12 (python):
```python
## An object of class Seurat 
## 33789 features across 10434 samples within 4 assays 
## Active assay: RNA (33694 features, 0 variable features)
##  2 layers present: counts, data
##  3 other assays present: prediction.score.celltype.l1, prediction.score.celltype.l2, prediction.score.celltype.l3
##  2 dimensional reductions calculated: integrated_dr, ref.umap
```

Example 13 (unknown):
```unknown
obj[["RNA"]] <- split(obj[["RNA"]], f = obj$Method)
obj
```

Example 14 (r):
```r
obj[["RNA"]] <- split(obj[["RNA"]], f = obj$Method)
obj
```

Example 15 (r):
```r
obj[["RNA"]] <- split(obj[["RNA"]], f = obj$Method)
obj
```

Example 16 (python):
```python
## An object of class Seurat 
## 33789 features across 10434 samples within 4 assays 
## Active assay: RNA (33694 features, 0 variable features)
##  18 layers present: counts.Smart-seq2, counts.CEL-Seq2, counts.10x_Chromium_v2_A, counts.10x_Chromium_v2_B, counts.10x_Chromium_v3, counts.Drop-seq, counts.Seq-Well, counts.inDrops, counts.10x_Chromium_v2, data.Smart-seq2, data.CEL-Seq2, data.10x_Chromium_v2_A, data.10x_Chromium_v2_B, data.10x_Chromium_v3, data.Drop-seq, data.Seq-Well, data.inDrops, data.10x_Chromium_v2
##  3 other assays present: prediction.score.celltype.l1, prediction.score.celltype.l2, prediction.score.celltype.l3
##  2 dimensional reductions calculated: integrated_dr, ref.umap
```

Example 17 (python):
```python
## An object of class Seurat 
## 33789 features across 10434 samples within 4 assays 
## Active assay: RNA (33694 features, 0 variable features)
##  18 layers present: counts.Smart-seq2, counts.CEL-Seq2, counts.10x_Chromium_v2_A, counts.10x_Chromium_v2_B, counts.10x_Chromium_v3, counts.Drop-seq, counts.Seq-Well, counts.inDrops, counts.10x_Chromium_v2, data.Smart-seq2, data.CEL-Seq2, data.10x_Chromium_v2_A, data.10x_Chromium_v2_B, data.10x_Chromium_v3, data.Drop-seq, data.Seq-Well, data.inDrops, data.10x_Chromium_v2
##  3 other assays present: prediction.score.celltype.l1, prediction.score.celltype.l2, prediction.score.celltype.l3
##  2 dimensional reductions calculated: integrated_dr, ref.umap
```

Example 18 (unknown):
```unknown
obj <- NormalizeData(obj)
obj <- FindVariableFeatures(obj)
obj <- ScaleData(obj)
obj <- RunPCA(obj)
```

Example 19 (r):
```r
obj <- NormalizeData(obj)
obj <- FindVariableFeatures(obj)
obj <- ScaleData(obj)
obj <- RunPCA(obj)
```

Example 20 (r):
```r
obj <- NormalizeData(obj)
obj <- FindVariableFeatures(obj)
obj <- ScaleData(obj)
obj <- RunPCA(obj)
```

Example 21 (unknown):
```unknown
obj <- FindNeighbors(obj, dims = 1:30, reduction = "pca")
obj <- FindClusters(obj, resolution = 2, cluster.name = "unintegrated_clusters")
```

Example 22 (r):
```r
obj <- FindNeighbors(obj, dims = 1:30, reduction = "pca")
obj <- FindClusters(obj, resolution = 2, cluster.name = "unintegrated_clusters")
```

Example 23 (r):
```r
obj <- FindNeighbors(obj, dims = 1:30, reduction = "pca")
obj <- FindClusters(obj, resolution = 2, cluster.name = "unintegrated_clusters")
```

Example 24 (unknown):
```unknown
## Modularity Optimizer version 1.3.0 by Ludo Waltman and Nees Jan van Eck
## 
## Number of nodes: 10434
## Number of edges: 412660
## 
## Running Louvain algorithm...
## Maximum modularity in 10 random starts: 0.8981
## Number of communities: 48
## Elapsed time: 0 seconds
```

Example 25 (unknown):
```unknown
## Modularity Optimizer version 1.3.0 by Ludo Waltman and Nees Jan van Eck
## 
## Number of nodes: 10434
## Number of edges: 412660
## 
## Running Louvain algorithm...
## Maximum modularity in 10 random starts: 0.8981
## Number of communities: 48
## Elapsed time: 0 seconds
```

Example 26 (unknown):
```unknown
obj <- RunUMAP(obj, dims = 1:30, reduction = "pca", reduction.name = "umap.unintegrated")
# visualize by batch and cell type annotation
# cell type annotations were previously added by Azimuth
DimPlot(obj, reduction = "umap.unintegrated", group.by = c("Method", "predicted.celltype.l2"))
```

Example 27 (r):
```r
obj <- RunUMAP(obj, dims = 1:30, reduction = "pca", reduction.name = "umap.unintegrated")
# visualize by batch and cell type annotation
# cell type annotations were previously added by Azimuth
DimPlot(obj, reduction = "umap.unintegrated", group.by = c("Method", "predicted.celltype.l2"))
```

Example 28 (r):
```r
obj <- RunUMAP(obj, dims = 1:30, reduction = "pca", reduction.name = "umap.unintegrated")
# visualize by batch and cell type annotation
# cell type annotations were previously added by Azimuth
DimPlot(obj, reduction = "umap.unintegrated", group.by = c("Method", "predicted.celltype.l2"))
```

Example 29 (unknown):
```unknown
IntegrateLayers
```

Example 30 (unknown):
```unknown
integrated.rpca
```

Example 31 (unknown):
```unknown
method=CCAIntegration
```

Example 32 (unknown):
```unknown
method=RPCAIntegration
```

Example 33 (unknown):
```unknown
method=HarmonyIntegration
```

Example 34 (unknown):
```unknown
method= FastMNNIntegration
```

Example 35 (unknown):
```unknown
method=scVIIntegration
```

Example 36 (unknown):
```unknown
?scVIIntegration
```

Example 37 (unknown):
```unknown
install.packages("reticulate")
```

Example 38 (unknown):
```unknown
obj <- IntegrateLayers(
  object = obj, method = CCAIntegration,
  orig.reduction = "pca", new.reduction = "integrated.cca",
  verbose = FALSE
)
```

Example 39 (r):
```r
obj <- IntegrateLayers(
  object = obj, method = CCAIntegration,
  orig.reduction = "pca", new.reduction = "integrated.cca",
  verbose = FALSE
)
```

Example 40 (r):
```r
obj <- IntegrateLayers(
  object = obj, method = CCAIntegration,
  orig.reduction = "pca", new.reduction = "integrated.cca",
  verbose = FALSE
)
```

Example 41 (unknown):
```unknown
obj <- IntegrateLayers(
  object = obj, method = RPCAIntegration,
  orig.reduction = "pca", new.reduction = "integrated.rpca",
  verbose = FALSE
)
```

Example 42 (r):
```r
obj <- IntegrateLayers(
  object = obj, method = RPCAIntegration,
  orig.reduction = "pca", new.reduction = "integrated.rpca",
  verbose = FALSE
)
```

Example 43 (r):
```r
obj <- IntegrateLayers(
  object = obj, method = RPCAIntegration,
  orig.reduction = "pca", new.reduction = "integrated.rpca",
  verbose = FALSE
)
```

Example 44 (unknown):
```unknown
obj <- IntegrateLayers(
  object = obj, method = HarmonyIntegration,
  orig.reduction = "pca", new.reduction = "harmony",
  verbose = FALSE
)
```

Example 45 (r):
```r
obj <- IntegrateLayers(
  object = obj, method = HarmonyIntegration,
  orig.reduction = "pca", new.reduction = "harmony",
  verbose = FALSE
)
```

Example 46 (r):
```r
obj <- IntegrateLayers(
  object = obj, method = HarmonyIntegration,
  orig.reduction = "pca", new.reduction = "harmony",
  verbose = FALSE
)
```

Example 47 (unknown):
```unknown
obj <- IntegrateLayers(
  object = obj, method = FastMNNIntegration,
  new.reduction = "integrated.mnn",
  verbose = FALSE
)
```

Example 48 (r):
```r
obj <- IntegrateLayers(
  object = obj, method = FastMNNIntegration,
  new.reduction = "integrated.mnn",
  verbose = FALSE
)
```

Example 49 (r):
```r
obj <- IntegrateLayers(
  object = obj, method = FastMNNIntegration,
  new.reduction = "integrated.mnn",
  verbose = FALSE
)
```

Example 50 (unknown):
```unknown
obj <- IntegrateLayers(
  object = obj, method = scVIIntegration,
  new.reduction = "integrated.scvi",
  conda_env = "../miniconda3/envs/scvi-env", verbose = FALSE
)
```

Example 51 (r):
```r
obj <- IntegrateLayers(
  object = obj, method = scVIIntegration,
  new.reduction = "integrated.scvi",
  conda_env = "../miniconda3/envs/scvi-env", verbose = FALSE
)
```

Example 52 (r):
```r
obj <- IntegrateLayers(
  object = obj, method = scVIIntegration,
  new.reduction = "integrated.scvi",
  conda_env = "../miniconda3/envs/scvi-env", verbose = FALSE
)
```

Example 53 (unknown):
```unknown
obj <- FindNeighbors(obj, reduction = "integrated.cca", dims = 1:30)
obj <- FindClusters(obj, resolution = 2, cluster.name = "cca_clusters")
```

Example 54 (r):
```r
obj <- FindNeighbors(obj, reduction = "integrated.cca", dims = 1:30)
obj <- FindClusters(obj, resolution = 2, cluster.name = "cca_clusters")
```

Example 55 (r):
```r
obj <- FindNeighbors(obj, reduction = "integrated.cca", dims = 1:30)
obj <- FindClusters(obj, resolution = 2, cluster.name = "cca_clusters")
```

Example 56 (unknown):
```unknown
## Modularity Optimizer version 1.3.0 by Ludo Waltman and Nees Jan van Eck
## 
## Number of nodes: 10434
## Number of edges: 617402
## 
## Running Louvain algorithm...
## Maximum modularity in 10 random starts: 0.8037
## Number of communities: 25
## Elapsed time: 1 seconds
```

Example 57 (unknown):
```unknown
## Modularity Optimizer version 1.3.0 by Ludo Waltman and Nees Jan van Eck
## 
## Number of nodes: 10434
## Number of edges: 617402
## 
## Running Louvain algorithm...
## Maximum modularity in 10 random starts: 0.8037
## Number of communities: 25
## Elapsed time: 1 seconds
```

Example 58 (unknown):
```unknown
obj <- RunUMAP(obj, reduction = "integrated.cca", dims = 1:30, reduction.name = "umap.cca")
p1 <- DimPlot(
  obj,
  reduction = "umap.cca",
  group.by = c("Method", "predicted.celltype.l2", "cca_clusters"),
  combine = FALSE, label.size = 2
)

obj <- FindNeighbors(obj, reduction = "integrated.scvi", dims = 1:30)
obj <- FindClusters(obj, resolution = 2, cluster.name = "scvi_clusters")
```

Example 59 (r):
```r
obj <- RunUMAP(obj, reduction = "integrated.cca", dims = 1:30, reduction.name = "umap.cca")
p1 <- DimPlot(
  obj,
  reduction = "umap.cca",
  group.by = c("Method", "predicted.celltype.l2", "cca_clusters"),
  combine = FALSE, label.size = 2
)

obj <- FindNeighbors(obj, reduction = "integrated.scvi", dims = 1:30)
obj <- FindClusters(obj, resolution = 2, cluster.name = "scvi_clusters")
```

Example 60 (r):
```r
obj <- RunUMAP(obj, reduction = "integrated.cca", dims = 1:30, reduction.name = "umap.cca")
p1 <- DimPlot(
  obj,
  reduction = "umap.cca",
  group.by = c("Method", "predicted.celltype.l2", "cca_clusters"),
  combine = FALSE, label.size = 2
)

obj <- FindNeighbors(obj, reduction = "integrated.scvi", dims = 1:30)
obj <- FindClusters(obj, resolution = 2, cluster.name = "scvi_clusters")
```

Example 61 (unknown):
```unknown
## Modularity Optimizer version 1.3.0 by Ludo Waltman and Nees Jan van Eck
## 
## Number of nodes: 10434
## Number of edges: 354664
## 
## Running Louvain algorithm...
## Maximum modularity in 10 random starts: 0.7942
## Number of communities: 22
## Elapsed time: 1 seconds
```

Example 62 (unknown):
```unknown
## Modularity Optimizer version 1.3.0 by Ludo Waltman and Nees Jan van Eck
## 
## Number of nodes: 10434
## Number of edges: 354664
## 
## Running Louvain algorithm...
## Maximum modularity in 10 random starts: 0.7942
## Number of communities: 22
## Elapsed time: 1 seconds
```

Example 63 (unknown):
```unknown
obj <- RunUMAP(obj, reduction = "integrated.scvi", dims = 1:30, reduction.name = "umap.scvi")
p2 <- DimPlot(
  obj,
  reduction = "umap.scvi",
  group.by = c("Method", "predicted.celltype.l2", "scvi_clusters"),
  combine = FALSE, label.size = 2
)

wrap_plots(c(p1, p2), ncol = 2, byrow = F)
```

Example 64 (r):
```r
obj <- RunUMAP(obj, reduction = "integrated.scvi", dims = 1:30, reduction.name = "umap.scvi")
p2 <- DimPlot(
  obj,
  reduction = "umap.scvi",
  group.by = c("Method", "predicted.celltype.l2", "scvi_clusters"),
  combine = FALSE, label.size = 2
)

wrap_plots(c(p1, p2), ncol = 2, byrow = F)
```

Example 65 (r):
```r
obj <- RunUMAP(obj, reduction = "integrated.scvi", dims = 1:30, reduction.name = "umap.scvi")
p2 <- DimPlot(
  obj,
  reduction = "umap.scvi",
  group.by = c("Method", "predicted.celltype.l2", "scvi_clusters"),
  combine = FALSE, label.size = 2
)

wrap_plots(c(p1, p2), ncol = 2, byrow = F)
```

Example 66 (unknown):
```unknown
p1 <- VlnPlot(
  obj,
  features = "rna_CD8A", group.by = "unintegrated_clusters"
) + NoLegend() + ggtitle("CD8A - Unintegrated Clusters")
p2 <- VlnPlot(
  obj, "rna_CD8A",
  group.by = "cca_clusters"
) + NoLegend() + ggtitle("CD8A - CCA Clusters")
p3 <- VlnPlot(
  obj, "rna_CD8A",
  group.by = "scvi_clusters"
) + NoLegend() + ggtitle("CD8A - scVI Clusters")
p1 | p2 | p3
```

Example 67 (r):
```r
p1 <- VlnPlot(
  obj,
  features = "rna_CD8A", group.by = "unintegrated_clusters"
) + NoLegend() + ggtitle("CD8A - Unintegrated Clusters")
p2 <- VlnPlot(
  obj, "rna_CD8A",
  group.by = "cca_clusters"
) + NoLegend() + ggtitle("CD8A - CCA Clusters")
p3 <- VlnPlot(
  obj, "rna_CD8A",
  group.by = "scvi_clusters"
) + NoLegend() + ggtitle("CD8A - scVI Clusters")
p1 | p2 | p3
```

Example 68 (r):
```r
p1 <- VlnPlot(
  obj,
  features = "rna_CD8A", group.by = "unintegrated_clusters"
) + NoLegend() + ggtitle("CD8A - Unintegrated Clusters")
p2 <- VlnPlot(
  obj, "rna_CD8A",
  group.by = "cca_clusters"
) + NoLegend() + ggtitle("CD8A - CCA Clusters")
p3 <- VlnPlot(
  obj, "rna_CD8A",
  group.by = "scvi_clusters"
) + NoLegend() + ggtitle("CD8A - scVI Clusters")
p1 | p2 | p3
```

Example 69 (unknown):
```unknown
obj <- RunUMAP(obj, reduction = "integrated.rpca", dims = 1:30, reduction.name = "umap.rpca")
p4 <- DimPlot(obj, reduction = "umap.unintegrated", group.by = c("cca_clusters"))
p5 <- DimPlot(obj, reduction = "umap.rpca", group.by = c("cca_clusters"))
p6 <- DimPlot(obj, reduction = "umap.scvi", group.by = c("cca_clusters"))
p4 | p5 | p6
```

Example 70 (r):
```r
obj <- RunUMAP(obj, reduction = "integrated.rpca", dims = 1:30, reduction.name = "umap.rpca")
p4 <- DimPlot(obj, reduction = "umap.unintegrated", group.by = c("cca_clusters"))
p5 <- DimPlot(obj, reduction = "umap.rpca", group.by = c("cca_clusters"))
p6 <- DimPlot(obj, reduction = "umap.scvi", group.by = c("cca_clusters"))
p4 | p5 | p6
```

Example 71 (r):
```r
obj <- RunUMAP(obj, reduction = "integrated.rpca", dims = 1:30, reduction.name = "umap.rpca")
p4 <- DimPlot(obj, reduction = "umap.unintegrated", group.by = c("cca_clusters"))
p5 <- DimPlot(obj, reduction = "umap.rpca", group.by = c("cca_clusters"))
p6 <- DimPlot(obj, reduction = "umap.scvi", group.by = c("cca_clusters"))
p4 | p5 | p6
```

Example 72 (unknown):
```unknown
obj <- JoinLayers(obj)
obj
```

Example 73 (r):
```r
obj <- JoinLayers(obj)
obj
```

Example 74 (r):
```r
obj <- JoinLayers(obj)
obj
```

Example 75 (python):
```python
## An object of class Seurat 
## 35789 features across 10434 samples within 5 assays 
## Active assay: RNA (33694 features, 2000 variable features)
##  3 layers present: data, counts, scale.data
##  4 other assays present: prediction.score.celltype.l1, prediction.score.celltype.l2, prediction.score.celltype.l3, mnn.reconstructed
##  12 dimensional reductions calculated: integrated_dr, ref.umap, pca, umap.unintegrated, integrated.cca, integrated.rpca, harmony, integrated.mnn, integrated.scvi, umap.cca, umap.scvi, umap.rpca
```

Example 76 (python):
```python
## An object of class Seurat 
## 35789 features across 10434 samples within 5 assays 
## Active assay: RNA (33694 features, 2000 variable features)
##  3 layers present: data, counts, scale.data
##  4 other assays present: prediction.score.celltype.l1, prediction.score.celltype.l2, prediction.score.celltype.l3, mnn.reconstructed
##  12 dimensional reductions calculated: integrated_dr, ref.umap, pca, umap.unintegrated, integrated.cca, integrated.rpca, harmony, integrated.mnn, integrated.scvi, umap.cca, umap.scvi, umap.rpca
```

Example 77 (unknown):
```unknown
normalization.method
```

Example 78 (unknown):
```unknown
IntegrateLayers
```

Example 79 (unknown):
```unknown
options(future.globals.maxSize = 3e+09)
obj <- SCTransform(obj)
obj <- RunPCA(obj, npcs = 30, verbose = F)
obj <- IntegrateLayers(
  object = obj,
  method = RPCAIntegration,
  normalization.method = "SCT",
  verbose = F
)
obj <- FindNeighbors(obj, dims = 1:30, reduction = "integrated.dr")
obj <- FindClusters(obj, resolution = 2)
```

Example 80 (r):
```r
options(future.globals.maxSize = 3e+09)
obj <- SCTransform(obj)
obj <- RunPCA(obj, npcs = 30, verbose = F)
obj <- IntegrateLayers(
  object = obj,
  method = RPCAIntegration,
  normalization.method = "SCT",
  verbose = F
)
obj <- FindNeighbors(obj, dims = 1:30, reduction = "integrated.dr")
obj <- FindClusters(obj, resolution = 2)
```

Example 81 (r):
```r
options(future.globals.maxSize = 3e+09)
obj <- SCTransform(obj)
obj <- RunPCA(obj, npcs = 30, verbose = F)
obj <- IntegrateLayers(
  object = obj,
  method = RPCAIntegration,
  normalization.method = "SCT",
  verbose = F
)
obj <- FindNeighbors(obj, dims = 1:30, reduction = "integrated.dr")
obj <- FindClusters(obj, resolution = 2)
```

Example 82 (unknown):
```unknown
## Modularity Optimizer version 1.3.0 by Ludo Waltman and Nees Jan van Eck
## 
## Number of nodes: 10434
## Number of edges: 449127
## 
## Running Louvain algorithm...
## Maximum modularity in 10 random starts: 0.8354
## Number of communities: 26
## Elapsed time: 1 seconds
```

Example 83 (unknown):
```unknown
## Modularity Optimizer version 1.3.0 by Ludo Waltman and Nees Jan van Eck
## 
## Number of nodes: 10434
## Number of edges: 449127
## 
## Running Louvain algorithm...
## Maximum modularity in 10 random starts: 0.8354
## Number of communities: 26
## Elapsed time: 1 seconds
```

Example 84 (unknown):
```unknown
obj <- RunUMAP(obj, dims = 1:30, reduction = "integrated.dr")
```

Example 85 (r):
```r
obj <- RunUMAP(obj, dims = 1:30, reduction = "integrated.dr")
```

Example 86 (r):
```r
obj <- RunUMAP(obj, dims = 1:30, reduction = "integrated.dr")
```

Example 87 (unknown):
```unknown
sessionInfo()
```

Example 88 (r):
```r
sessionInfo()
```

Example 89 (r):
```r
sessionInfo()
```

Example 90 (unknown):
```unknown
## R version 4.2.2 Patched (2022-11-10 r83330)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.6 LTS
## 
## Matrix products: default
## BLAS:   /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.9.0
## LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.9.0
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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       
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
##  [1] patchwork_1.1.3               ggplot2_3.4.4                
##  [3] Azimuth_0.4.6.9004            shinyBS_0.61.1               
##  [5] SeuratWrappers_0.3.19         thp1.eccite.SeuratData_3.1.5 
##  [7] stxBrain.SeuratData_0.1.1     ssHippo.SeuratData_3.1.4     
##  [9] pbmcsca.SeuratData_3.0.0      pbmcref.SeuratData_1.0.0     
## [11] pbmcMultiome.SeuratData_0.1.4 pbmc3k.SeuratData_3.1.4      
## [13] panc8.SeuratData_3.0.2        ifnb.SeuratData_3.0.0        
## [15] hcabm40k.SeuratData_3.0.0     cbmc.SeuratData_3.1.4        
## [17] bmcite.SeuratData_0.3.0       SeuratData_0.2.2.9001        
## [19] Seurat_5.0.1                  SeuratObject_5.0.1           
## [21] sp_2.1-1                     
## 
## loaded via a namespace (and not attached):
##   [1] rsvd_1.0.5                        ica_1.0-3                        
##   [3] RcppRoll_0.3.0                    Rsamtools_2.14.0                 
##   [5] lmtest_0.9-40                     rprojroot_2.0.3                  
##   [7] crayon_1.5.2                      MASS_7.3-58.2                    
##   [9] rhdf5filters_1.10.1               nlme_3.1-162                     
##  [11] rlang_1.1.1                       XVector_0.38.0                   
##  [13] ROCR_1.0-11                       irlba_2.3.5.1                    
##  [15] filelock_1.0.2                    BiocParallel_1.32.6              
##  [17] rjson_0.2.21                      CNEr_1.34.0                      
##  [19] bit64_4.0.5                       glue_1.6.2                       
##  [21] harmony_1.0.3                     poweRlaw_0.70.6                  
##  [23] sctransform_0.4.1                 vipor_0.4.5                      
##  [25] parallel_4.2.2                    spatstat.sparse_3.0-3            
##  [27] AnnotationDbi_1.60.2              SeuratDisk_0.0.0.9020            
##  [29] BiocGenerics_0.44.0               shinydashboard_0.7.2             
##  [31] dotCall64_1.1-0                   spatstat.geom_3.2-7              
##  [33] tidyselect_1.2.0                  SummarizedExperiment_1.28.0      
##  [35] fitdistrplus_1.1-11               XML_3.99-0.14                    
##  [37] tidyr_1.3.0                       zoo_1.8-12                       
##  [39] GenomicAlignments_1.34.1          xtable_1.8-4                     
##  [41] RcppHNSW_0.5.0                    magrittr_2.0.3                   
##  [43] evaluate_0.22                     scuttle_1.8.4                    
##  [45] cli_3.6.1                         zlibbioc_1.44.0                  
##  [47] miniUI_0.1.1.1                    bslib_0.5.1                      
##  [49] fastmatch_1.1-4                   ensembldb_2.22.0                 
##  [51] fastDummies_1.7.3                 shiny_1.7.5.1                    
##  [53] BiocSingular_1.14.0               xfun_0.40                        
##  [55] cluster_2.1.4                     caTools_1.18.2                   
##  [57] KEGGREST_1.38.0                   tibble_3.2.1                     
##  [59] ggrepel_0.9.4                     listenv_0.9.0                    
##  [61] TFMPvalue_0.0.9                   Biostrings_2.66.0                
##  [63] png_0.1-8                         future_1.33.0                    
##  [65] withr_2.5.2                       bitops_1.0-7                     
##  [67] plyr_1.8.9                        cellranger_1.1.0                 
##  [69] AnnotationFilter_1.22.0           pracma_2.4.2                     
##  [71] pillar_1.9.0                      cachem_1.0.8                     
##  [73] GenomicFeatures_1.50.4            fs_1.6.3                         
##  [75] hdf5r_1.3.8                       DelayedMatrixStats_1.20.0        
##  [77] vctrs_0.6.4                       ellipsis_0.3.2                   
##  [79] generics_0.1.3                    tools_4.2.2                      
##  [81] beeswarm_0.4.0                    munsell_0.5.0                    
##  [83] DelayedArray_0.24.0               fastmap_1.1.1                    
##  [85] compiler_4.2.2                    abind_1.4-5                      
##  [87] httpuv_1.6.12                     rtracklayer_1.58.0               
##  [89] plotly_4.10.3                     GenomeInfoDbData_1.2.9           
##  [91] gridExtra_2.3                     lattice_0.21-9                   
##  [93] deldir_1.0-9                      utf8_1.2.4                       
##  [95] later_1.3.1                       dplyr_1.1.3                      
##  [97] BiocFileCache_2.6.1               jsonlite_1.8.7                   
##  [99] scales_1.2.1                      ScaledMatrix_1.6.0               
## [101] pbapply_1.7-2                     sparseMatrixStats_1.10.0         
## [103] lazyeval_0.2.2                    promises_1.2.1                   
## [105] R.utils_2.12.2                    goftest_1.2-3                    
## [107] spatstat.utils_3.0-4              reticulate_1.34.0                
## [109] rmarkdown_2.25                    pkgdown_2.0.7                    
## [111] cowplot_1.1.1                     textshaping_0.3.6                
## [113] glmGamPoi_1.10.2                  Rtsne_0.16                       
## [115] BSgenome_1.66.3                   Biobase_2.58.0                   
## [117] uwot_0.1.16                       igraph_1.5.1                     
## [119] survival_3.5-7                    ResidualMatrix_1.8.0             
## [121] yaml_2.3.7                        systemfonts_1.0.4                
## [123] htmltools_0.5.6.1                 memoise_2.0.1                    
## [125] BiocIO_1.8.0                      IRanges_2.32.0                   
## [127] viridisLite_0.4.2                 digest_0.6.33                    
## [129] RhpcBLASctl_0.23-42               mime_0.12                        
## [131] rappdirs_0.3.3                    spam_2.10-0                      
## [133] RSQLite_2.3.1                     future.apply_1.11.0              
## [135] remotes_2.4.2.1                   data.table_1.14.8                
## [137] blob_1.2.4                        JASPAR2020_0.99.10               
## [139] S4Vectors_0.36.2                  R.oo_1.25.0                      
## [141] TFBSTools_1.36.0                  ragg_1.2.5                       
## [143] styler_1.10.2                     splines_4.2.2                    
## [145] labeling_0.4.3                    Rhdf5lib_1.20.0                  
## [147] googledrive_2.1.1                 ProtGenerics_1.30.0              
## [149] RCurl_1.98-1.12                   hms_1.1.3                        
## [151] rhdf5_2.42.1                      colorspace_2.1-0                 
## [153] BiocManager_1.30.22               ggbeeswarm_0.7.1                 
## [155] GenomicRanges_1.50.2              Signac_1.12.9000                 
## [157] ggrastr_1.0.1                     sass_0.4.7                       
## [159] Rcpp_1.0.11                       BSgenome.Hsapiens.UCSC.hg38_1.4.5
## [161] RANN_2.6.1                        fansi_1.0.5                      
## [163] tzdb_0.4.0                        parallelly_1.36.0                
## [165] R6_2.5.1                          grid_4.2.2                       
## [167] ggridges_0.5.4                    lifecycle_1.0.3                  
## [169] curl_5.1.0                        googlesheets4_1.1.1              
## [171] leiden_0.4.3                      jquerylib_0.1.4                  
## [173] Matrix_1.6-1.1                    desc_1.4.2                       
## [175] RcppAnnoy_0.0.21                  RColorBrewer_1.1-3               
## [177] spatstat.explore_3.2-5            stringr_1.5.0                    
## [179] R.cache_0.16.0                    htmlwidgets_1.6.2                
## [181] beachmat_2.14.2                   polyclip_1.10-6                  
## [183] biomaRt_2.54.1                    purrr_1.0.2                      
## [185] seqLogo_1.64.0                    globals_0.16.2                   
## [187] spatstat.random_3.2-1             progressr_0.14.0                 
## [189] batchelor_1.14.1                  codetools_0.2-19                 
## [191] matrixStats_1.0.0                 GO.db_3.16.0                     
## [193] gtools_3.9.4                      prettyunits_1.1.1                
## [195] SingleCellExperiment_1.20.1       dbplyr_2.3.4                     
## [197] RSpectra_0.16-1                   R.methodsS3_1.8.2                
## [199] GenomeInfoDb_1.34.9               gtable_0.3.4                     
## [201] DBI_1.1.3                         stats4_4.2.2                     
## [203] tensor_1.5                        httr_1.4.7                       
## [205] highr_0.10                        KernSmooth_2.23-22               
## [207] stringi_1.7.12                    presto_1.0.0                     
## [209] progress_1.2.2                    reshape2_1.4.4                   
## [211] farver_2.1.1                      annotate_1.76.0                  
## [213] DT_0.30                           xml2_1.3.5                       
## [215] EnsDb.Hsapiens.v86_2.99.0         shinyjs_2.1.0                    
## [217] BiocNeighbors_1.16.0              restfulr_0.0.15                  
## [219] readr_2.1.4                       scattermore_1.2                  
## [221] bit_4.0.5                         MatrixGenerics_1.10.0            
## [223] spatstat.data_3.0-3               pkgconfig_2.0.3                  
## [225] gargle_1.5.2                      DirichletMultinomial_1.40.0      
## [227] knitr_1.45
```

Example 91 (unknown):
```unknown
## R version 4.2.2 Patched (2022-11-10 r83330)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.6 LTS
## 
## Matrix products: default
## BLAS:   /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.9.0
## LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.9.0
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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       
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
##  [1] patchwork_1.1.3               ggplot2_3.4.4                
##  [3] Azimuth_0.4.6.9004            shinyBS_0.61.1               
##  [5] SeuratWrappers_0.3.19         thp1.eccite.SeuratData_3.1.5 
##  [7] stxBrain.SeuratData_0.1.1     ssHippo.SeuratData_3.1.4     
##  [9] pbmcsca.SeuratData_3.0.0      pbmcref.SeuratData_1.0.0     
## [11] pbmcMultiome.SeuratData_0.1.4 pbmc3k.SeuratData_3.1.4      
## [13] panc8.SeuratData_3.0.2        ifnb.SeuratData_3.0.0        
## [15] hcabm40k.SeuratData_3.0.0     cbmc.SeuratData_3.1.4        
## [17] bmcite.SeuratData_0.3.0       SeuratData_0.2.2.9001        
## [19] Seurat_5.0.1                  SeuratObject_5.0.1           
## [21] sp_2.1-1                     
## 
## loaded via a namespace (and not attached):
##   [1] rsvd_1.0.5                        ica_1.0-3                        
##   [3] RcppRoll_0.3.0                    Rsamtools_2.14.0                 
##   [5] lmtest_0.9-40                     rprojroot_2.0.3                  
##   [7] crayon_1.5.2                      MASS_7.3-58.2                    
##   [9] rhdf5filters_1.10.1               nlme_3.1-162                     
##  [11] rlang_1.1.1                       XVector_0.38.0                   
##  [13] ROCR_1.0-11                       irlba_2.3.5.1                    
##  [15] filelock_1.0.2                    BiocParallel_1.32.6              
##  [17] rjson_0.2.21                      CNEr_1.34.0                      
##  [19] bit64_4.0.5                       glue_1.6.2                       
##  [21] harmony_1.0.3                     poweRlaw_0.70.6                  
##  [23] sctransform_0.4.1                 vipor_0.4.5                      
##  [25] parallel_4.2.2                    spatstat.sparse_3.0-3            
##  [27] AnnotationDbi_1.60.2              SeuratDisk_0.0.0.9020            
##  [29] BiocGenerics_0.44.0               shinydashboard_0.7.2             
##  [31] dotCall64_1.1-0                   spatstat.geom_3.2-7              
##  [33] tidyselect_1.2.0                  SummarizedExperiment_1.28.0      
##  [35] fitdistrplus_1.1-11               XML_3.99-0.14                    
##  [37] tidyr_1.3.0                       zoo_1.8-12                       
##  [39] GenomicAlignments_1.34.1          xtable_1.8-4                     
##  [41] RcppHNSW_0.5.0                    magrittr_2.0.3                   
##  [43] evaluate_0.22                     scuttle_1.8.4                    
##  [45] cli_3.6.1                         zlibbioc_1.44.0                  
##  [47] miniUI_0.1.1.1                    bslib_0.5.1                      
##  [49] fastmatch_1.1-4                   ensembldb_2.22.0                 
##  [51] fastDummies_1.7.3                 shiny_1.7.5.1                    
##  [53] BiocSingular_1.14.0               xfun_0.40                        
##  [55] cluster_2.1.4                     caTools_1.18.2                   
##  [57] KEGGREST_1.38.0                   tibble_3.2.1                     
##  [59] ggrepel_0.9.4                     listenv_0.9.0                    
##  [61] TFMPvalue_0.0.9                   Biostrings_2.66.0                
##  [63] png_0.1-8                         future_1.33.0                    
##  [65] withr_2.5.2                       bitops_1.0-7                     
##  [67] plyr_1.8.9                        cellranger_1.1.0                 
##  [69] AnnotationFilter_1.22.0           pracma_2.4.2                     
##  [71] pillar_1.9.0                      cachem_1.0.8                     
##  [73] GenomicFeatures_1.50.4            fs_1.6.3                         
##  [75] hdf5r_1.3.8                       DelayedMatrixStats_1.20.0        
##  [77] vctrs_0.6.4                       ellipsis_0.3.2                   
##  [79] generics_0.1.3                    tools_4.2.2                      
##  [81] beeswarm_0.4.0                    munsell_0.5.0                    
##  [83] DelayedArray_0.24.0               fastmap_1.1.1                    
##  [85] compiler_4.2.2                    abind_1.4-5                      
##  [87] httpuv_1.6.12                     rtracklayer_1.58.0               
##  [89] plotly_4.10.3                     GenomeInfoDbData_1.2.9           
##  [91] gridExtra_2.3                     lattice_0.21-9                   
##  [93] deldir_1.0-9                      utf8_1.2.4                       
##  [95] later_1.3.1                       dplyr_1.1.3                      
##  [97] BiocFileCache_2.6.1               jsonlite_1.8.7                   
##  [99] scales_1.2.1                      ScaledMatrix_1.6.0               
## [101] pbapply_1.7-2                     sparseMatrixStats_1.10.0         
## [103] lazyeval_0.2.2                    promises_1.2.1                   
## [105] R.utils_2.12.2                    goftest_1.2-3                    
## [107] spatstat.utils_3.0-4              reticulate_1.34.0                
## [109] rmarkdown_2.25                    pkgdown_2.0.7                    
## [111] cowplot_1.1.1                     textshaping_0.3.6                
## [113] glmGamPoi_1.10.2                  Rtsne_0.16                       
## [115] BSgenome_1.66.3                   Biobase_2.58.0                   
## [117] uwot_0.1.16                       igraph_1.5.1                     
## [119] survival_3.5-7                    ResidualMatrix_1.8.0             
## [121] yaml_2.3.7                        systemfonts_1.0.4                
## [123] htmltools_0.5.6.1                 memoise_2.0.1                    
## [125] BiocIO_1.8.0                      IRanges_2.32.0                   
## [127] viridisLite_0.4.2                 digest_0.6.33                    
## [129] RhpcBLASctl_0.23-42               mime_0.12                        
## [131] rappdirs_0.3.3                    spam_2.10-0                      
## [133] RSQLite_2.3.1                     future.apply_1.11.0              
## [135] remotes_2.4.2.1                   data.table_1.14.8                
## [137] blob_1.2.4                        JASPAR2020_0.99.10               
## [139] S4Vectors_0.36.2                  R.oo_1.25.0                      
## [141] TFBSTools_1.36.0                  ragg_1.2.5                       
## [143] styler_1.10.2                     splines_4.2.2                    
## [145] labeling_0.4.3                    Rhdf5lib_1.20.0                  
## [147] googledrive_2.1.1                 ProtGenerics_1.30.0              
## [149] RCurl_1.98-1.12                   hms_1.1.3                        
## [151] rhdf5_2.42.1                      colorspace_2.1-0                 
## [153] BiocManager_1.30.22               ggbeeswarm_0.7.1                 
## [155] GenomicRanges_1.50.2              Signac_1.12.9000                 
## [157] ggrastr_1.0.1                     sass_0.4.7                       
## [159] Rcpp_1.0.11                       BSgenome.Hsapiens.UCSC.hg38_1.4.5
## [161] RANN_2.6.1                        fansi_1.0.5                      
## [163] tzdb_0.4.0                        parallelly_1.36.0                
## [165] R6_2.5.1                          grid_4.2.2                       
## [167] ggridges_0.5.4                    lifecycle_1.0.3                  
## [169] curl_5.1.0                        googlesheets4_1.1.1              
## [171] leiden_0.4.3                      jquerylib_0.1.4                  
## [173] Matrix_1.6-1.1                    desc_1.4.2                       
## [175] RcppAnnoy_0.0.21                  RColorBrewer_1.1-3               
## [177] spatstat.explore_3.2-5            stringr_1.5.0                    
## [179] R.cache_0.16.0                    htmlwidgets_1.6.2                
## [181] beachmat_2.14.2                   polyclip_1.10-6                  
## [183] biomaRt_2.54.1                    purrr_1.0.2                      
## [185] seqLogo_1.64.0                    globals_0.16.2                   
## [187] spatstat.random_3.2-1             progressr_0.14.0                 
## [189] batchelor_1.14.1                  codetools_0.2-19                 
## [191] matrixStats_1.0.0                 GO.db_3.16.0                     
## [193] gtools_3.9.4                      prettyunits_1.1.1                
## [195] SingleCellExperiment_1.20.1       dbplyr_2.3.4                     
## [197] RSpectra_0.16-1                   R.methodsS3_1.8.2                
## [199] GenomeInfoDb_1.34.9               gtable_0.3.4                     
## [201] DBI_1.1.3                         stats4_4.2.2                     
## [203] tensor_1.5                        httr_1.4.7                       
## [205] highr_0.10                        KernSmooth_2.23-22               
## [207] stringi_1.7.12                    presto_1.0.0                     
## [209] progress_1.2.2                    reshape2_1.4.4                   
## [211] farver_2.1.1                      annotate_1.76.0                  
## [213] DT_0.30                           xml2_1.3.5                       
## [215] EnsDb.Hsapiens.v86_2.99.0         shinyjs_2.1.0                    
## [217] BiocNeighbors_1.16.0              restfulr_0.0.15                  
## [219] readr_2.1.4                       scattermore_1.2                  
## [221] bit_4.0.5                         MatrixGenerics_1.10.0            
## [223] spatstat.data_3.0-3               pkgconfig_2.0.3                  
## [225] gargle_1.5.2                      DirichletMultinomial_1.40.0      
## [227] knitr_1.45
```

---

## Cell-Cycle Scoring and Regression

**URL:** http://127.0.0.1:9173/seurat/archive/v3.0/cell_cycle_vignette/index.html

**Contents:**
- Cell-Cycle Scoring and Regression
    - Compiled: 2019-06-24
  - Assign Cell-Cycle Scores
  - Regress out cell cycle scores during data scaling
  - Alternate Workflow

We demonstrate how to mitigate the effects of cell cycle heterogeneity in scRNA-seq data by calculating cell cycle phase scores based on canonical markers, and regressing these out of the data during pre-processing. We demonstrate this on a dataset of murine hematopoietic progenitors (Nestorowa et al., Blood 2016.You can download the files needed to run this vignette here.

If we run a PCA on our object, using the variable genes we found in FindVariableFeatures above, we see that while most of the variance can be explained by lineage, PC8 and PC10 are split on cell-cycle genes including TOP2A and MKI67. We will attempt to regress this signal from the data, so that cell-cycle heterogneity does not contribute to PCA or downstream analysis.

First, we assign each cell a score, based on its expression of G2/M and S phase markers. These marker sets should be anticorrelated in their expression levels, and cells expressing neither are likely not cycling and in G1 phase.

We assign scores in the CellCycleScoring function, which stores S and G2/M scores in object meta data, along with the predicted classification of each cell in either G2M, S or G1 phase. CellCycleScoring can also set the identity of the Seurat object to the cell-cycle phase by passing set.ident = TRUE (the original identities are stored as old.ident). Please note that Seurat does not use the discrete classifications (G2M/G1/S) in downstream cell cycle regression. Instead, it uses the quantitative scores for G2M and S phase. However, we provide our predicted classifications in case they are of interest.

We score single cells based on the scoring strategy described in Tirosh et al. 2016. See ?AddModuleScore in Seurat for more information, this function can be used to calculate supervised module scores for any gene list.

We now attempt to subtract (‘regress out’) this source of heterogeneity from the data. For users of Seurat v1.4, this was implemented in RegressOut. However, as the results of this procedure are stored in the scaled data slot (therefore overwriting the output of ScaleData), we now merge this functionality into the ScaleData function itself.

For each gene, Seurat models the relationship between gene expression and the S and G2M cell cycle scores. The scaled residuals of this model represent a ‘corrected’ expression matrix, that can be used downstream for dimensional reduction.

As the best cell cycle markers are extremely well conserved across tissues and species, we have found this procedure to work robustly and reliably on diverse datasets.

The procedure above removes all signal associated with cell cycle. In some cases, we’ve found that this can negatively impact downstream analysis, particularly in differentiating processes (like murine hematopoiesis), where stem cells are quiescent and differentiated cells are proliferating (or vice versa). In this case, regressing out all cell cycle effects can blur the distinction between stem and progenitor cells as well.

As an alternative, we suggest regressing out the difference between the G2M and S phase scores. This means that signals separating non-cycling cells and cycling cells will be maintained, but differences in cell cycle phase amongst proliferating cells (which are often uninteresting), will be regressed out of the data

**Examples:**

Example 1 (r):
```r
library(Seurat)

# Read in the expression matrix The first row is a header row, the first column is rownames
exp.mat <- read.table(file = "../data/nestorawa_forcellcycle_expressionMatrix.txt", header = TRUE, 
    as.is = TRUE, row.names = 1)

# A list of cell cycle markers, from Tirosh et al, 2015, is loaded with Seurat.  We can
# segregate this list into markers of G2/M phase and markers of S phase
s.genes <- cc.genes$s.genes
g2m.genes <- cc.genes$g2m.genes

# Create our Seurat object and complete the initalization steps
marrow <- CreateSeuratObject(counts = exp.mat)
marrow <- NormalizeData(marrow)
marrow <- FindVariableFeatures(marrow, selection.method = "vst")
marrow <- ScaleData(marrow, features = rownames(marrow))
```

Example 2 (r):
```r
library(Seurat)

# Read in the expression matrix The first row is a header row, the first column is rownames
exp.mat <- read.table(file = "../data/nestorawa_forcellcycle_expressionMatrix.txt", header = TRUE, 
    as.is = TRUE, row.names = 1)

# A list of cell cycle markers, from Tirosh et al, 2015, is loaded with Seurat.  We can
# segregate this list into markers of G2/M phase and markers of S phase
s.genes <- cc.genes$s.genes
g2m.genes <- cc.genes$g2m.genes

# Create our Seurat object and complete the initalization steps
marrow <- CreateSeuratObject(counts = exp.mat)
marrow <- NormalizeData(marrow)
marrow <- FindVariableFeatures(marrow, selection.method = "vst")
marrow <- ScaleData(marrow, features = rownames(marrow))
```

Example 3 (unknown):
```unknown
FindVariableFeatures
```

Example 4 (r):
```r
marrow <- RunPCA(marrow, features = VariableFeatures(marrow), ndims.print = 6:10, nfeatures.print = 10)
```

Example 5 (r):
```r
marrow <- RunPCA(marrow, features = VariableFeatures(marrow), ndims.print = 6:10, nfeatures.print = 10)
```

Example 6 (unknown):
```unknown
## PC_ 6 
## Positive:  SELL, ARL6IP1, CCL9, CD34, ADGRL4, BPIFC, NUSAP1, FAM64A, CD244, C030034L19RIK 
## Negative:  LY6C2, AA467197, CYBB, MGST2, ITGB2, PF4, CD74, ATP1B1, GP1BB, TREM3 
## PC_ 7 
## Positive:  F13A1, LY86, CFP, IRF8, CSF1R, TIFAB, IFI209, CCR2, TNS4, MS4A6C 
## Negative:  HDC, CPA3, PGLYRP1, MS4A3, NKG7, UBE2C, CCNB1, NUSAP1, PLK1, FUT8 
## PC_ 8 
## Positive:  NUSAP1, UBE2C, KIF23, PLK1, CENPF, FAM64A, CCNB1, H2AFX, ID2, CDC20 
## Negative:  WFDC17, SLC35D3, ADGRL4, VLDLR, CD33, H2AFY, P2RY14, IFI206, CCL9, CD34 
## PC_ 9 
## Positive:  IGKC, JCHAIN, LY6D, MZB1, CD74, IGLC2, FCRLA, IGKV4-50, IGHM, IGHV9-1 
## Negative:  SLC2A6, HBA-A1, HBA-A2, IGHV8-7, FCER1G, F13A1, HBB-BS, PLD4, HBB-BT, IGFBP4 
## PC_ 10 
## Positive:  H2AFX, FAM64A, ZFP383, NUSAP1, CDC25B, CENPF, GBP10, TOP2A, GBP6, GFRA1 
## Negative:  CTSW, XKRX, PRR5L, RORA, MBOAT4, A630014C17RIK, ZFP105, COL9A3, CLEC2I, TRAT1
```

Example 7 (unknown):
```unknown
## PC_ 6 
## Positive:  SELL, ARL6IP1, CCL9, CD34, ADGRL4, BPIFC, NUSAP1, FAM64A, CD244, C030034L19RIK 
## Negative:  LY6C2, AA467197, CYBB, MGST2, ITGB2, PF4, CD74, ATP1B1, GP1BB, TREM3 
## PC_ 7 
## Positive:  F13A1, LY86, CFP, IRF8, CSF1R, TIFAB, IFI209, CCR2, TNS4, MS4A6C 
## Negative:  HDC, CPA3, PGLYRP1, MS4A3, NKG7, UBE2C, CCNB1, NUSAP1, PLK1, FUT8 
## PC_ 8 
## Positive:  NUSAP1, UBE2C, KIF23, PLK1, CENPF, FAM64A, CCNB1, H2AFX, ID2, CDC20 
## Negative:  WFDC17, SLC35D3, ADGRL4, VLDLR, CD33, H2AFY, P2RY14, IFI206, CCL9, CD34 
## PC_ 9 
## Positive:  IGKC, JCHAIN, LY6D, MZB1, CD74, IGLC2, FCRLA, IGKV4-50, IGHM, IGHV9-1 
## Negative:  SLC2A6, HBA-A1, HBA-A2, IGHV8-7, FCER1G, F13A1, HBB-BS, PLD4, HBB-BT, IGFBP4 
## PC_ 10 
## Positive:  H2AFX, FAM64A, ZFP383, NUSAP1, CDC25B, CENPF, GBP10, TOP2A, GBP6, GFRA1 
## Negative:  CTSW, XKRX, PRR5L, RORA, MBOAT4, A630014C17RIK, ZFP105, COL9A3, CLEC2I, TRAT1
```

Example 8 (r):
```r
DimHeatmap(marrow, dims = c(8, 10))
```

Example 9 (r):
```r
DimHeatmap(marrow, dims = c(8, 10))
```

Example 10 (unknown):
```unknown
CellCycleScoring
```

Example 11 (unknown):
```unknown
CellCycleScoring
```

Example 12 (unknown):
```unknown
set.ident = TRUE
```

Example 13 (r):
```r
marrow <- CellCycleScoring(marrow, s.features = s.genes, g2m.features = g2m.genes, set.ident = TRUE)

# view cell cycle scores and phase assignments
head(marrow[[]])
```

Example 14 (r):
```r
marrow <- CellCycleScoring(marrow, s.features = s.genes, g2m.features = g2m.genes, set.ident = TRUE)

# view cell cycle scores and phase assignments
head(marrow[[]])
```

Example 15 (r):
```r
# Visualize the distribution of cell cycle markers across
RidgePlot(marrow, features = c("PCNA", "TOP2A", "MCM6", "MKI67"), ncol = 2)
```

Example 16 (r):
```r
# Visualize the distribution of cell cycle markers across
RidgePlot(marrow, features = c("PCNA", "TOP2A", "MCM6", "MKI67"), ncol = 2)
```

Example 17 (r):
```r
# Running a PCA on cell cycle genes reveals, unsurprisingly, that cells separate entirely by
# phase
marrow <- RunPCA(marrow, features = c(s.genes, g2m.genes))
```

Example 18 (r):
```r
# Running a PCA on cell cycle genes reveals, unsurprisingly, that cells separate entirely by
# phase
marrow <- RunPCA(marrow, features = c(s.genes, g2m.genes))
```

Example 19 (unknown):
```unknown
## PC_ 1 
## Positive:  BIRC5, MKI67, HMGB2, CDK1, CDCA3, TOP2A, CKS1B, CDCA8, UBE2C, HMMR 
##     AURKB, TACC3, TUBB4B, KIF11, CKAP2L, RRM1, NUSAP1, TPX2, NUF2, CKS2 
##     AURKA, SMC4, CDC20, CENPA, RRM2, TYMS, BUB1, NCAPD2, CCNB2, CENPF 
## Negative:  UNG, MSH2, CASP8AP2, RFC2, CDCA7, CTCF, DTL, MCM6, CHAF1B, HELLS 
##     PSRC1, BRIP1, UBR7, WDR76, GAS2L3, POLD3, BLM, G2E3, MCM4, LBR 
##     MCM2, HN1, DSCC1, CKAP5, USP1, GINS2, ANP32E, PRIM1, RPA2, FAM64A 
## PC_ 2 
## Positive:  UBE2C, FAM64A, CENPF, NUSAP1, GAS2L3, KIF2C, KIF23, CENPE, HMMR, TPX2 
##     PSRC1, AURKA, KIF11, CKS2, CCNB2, CKAP5, CDC20, CDC25C, CENPA, CKAP2L 
##     G2E3, CDCA8, HN1, KIF20B, NEK2, BUB1, DLGAP5, MKI67, GTSE1, CDCA2 
## Negative:  UHRF1, MCM6, PCNA, MCM4, MCM2, UNG, MCM5, TIPIN, HELLS, RRM2 
##     SLBP, NASP, GINS2, RPA2, CDC6, DTL, PRIM1, CCNE2, CDCA7, DSCC1 
##     CHAF1B, RAD51, CDC45, POLA1, CLSPN, ATAD2, EXO1, RRM1, TYMS, RFC2 
## PC_ 3 
## Positive:  CENPA, CCNB2, CDC6, CCNE2, CDC20, FEN1, CDCA3, RANGAP1, TUBB4B, LBR 
##     RRM1, CKS2, CDCA8, BIRC5, NEK2, RRM2, NASP, RPA2, HMGB2, HMMR 
##     UBR7, SLBP, BUB1, KIF2C, TPX2, MCM2, MCM4, TIPIN, CKAP2, GINS2 
## Negative:  TOP2A, POLA1, RFC2, AURKB, CDCA2, FAM64A, BRIP1, NDC80, TYMS, NUSAP1 
##     CDK1, GAS2L3, KIF23, SMC4, HN1, WDR76, E2F8, TTK, ATAD2, PRIM1 
##     TMPO, KIF11, CBX5, ANLN, CTCF, CKAP2L, G2E3, CKAP5, HELLS, KIF20B 
## PC_ 4 
## Positive:  CDCA7, FAM64A, RFC2, GAS2L3, UNG, MSH2, CKAP2, KIF23, MCM2, MCM4 
##     HN1, HELLS, MCM5, CDC20, USP1, PSRC1, LBR, MCM6, G2E3, POLD3 
##     DTL, KIF2C, RPA2, CKAP5, CENPE, NEK2, DLGAP5, ECT2, CCNB2, UBR7 
## Negative:  E2F8, RAD51AP1, TYMS, RRM2, RAD51, BLM, CLSPN, MKI67, NDC80, BIRC5 
##     AURKB, CDCA3, ATAD2, NUF2, CDC6, TOP2A, POLA1, CKS2, ANLN, PCNA 
##     CCNE2, ANP32E, HMGB2, CTCF, TUBB4B, RRM1, CDC45, SLBP, KIF11, CENPA 
## PC_ 5 
## Positive:  ANP32E, CASP8AP2, HELLS, TMPO, HMGB2, NCAPD2, WDR76, CTCF, CKS2, CCNB2 
##     POLA1, CKS1B, USP1, ATAD2, E2F8, SMC4, FAM64A, TIPIN, KIF20B, CDCA7 
##     UNG, SLBP, UBR7, MKI67, DTL, PSRC1, NASP, CENPA, CENPE, CDCA3 
## Negative:  FEN1, CHAF1B, HN1, CDC45, MSH2, AURKA, LBR, RAD51, CDCA2, GINS2 
##     AURKB, CDK1, UBE2C, DSCC1, GTSE1, TUBB4B, RRM2, KIF23, ANLN, G2E3 
##     EXO1, POLD3, TTK, RRM1, NUSAP1, TACC3, RAD51AP1, NEK2, CKAP2L, CDC20
```

Example 20 (unknown):
```unknown
## PC_ 1 
## Positive:  BIRC5, MKI67, HMGB2, CDK1, CDCA3, TOP2A, CKS1B, CDCA8, UBE2C, HMMR 
##     AURKB, TACC3, TUBB4B, KIF11, CKAP2L, RRM1, NUSAP1, TPX2, NUF2, CKS2 
##     AURKA, SMC4, CDC20, CENPA, RRM2, TYMS, BUB1, NCAPD2, CCNB2, CENPF 
## Negative:  UNG, MSH2, CASP8AP2, RFC2, CDCA7, CTCF, DTL, MCM6, CHAF1B, HELLS 
##     PSRC1, BRIP1, UBR7, WDR76, GAS2L3, POLD3, BLM, G2E3, MCM4, LBR 
##     MCM2, HN1, DSCC1, CKAP5, USP1, GINS2, ANP32E, PRIM1, RPA2, FAM64A 
## PC_ 2 
## Positive:  UBE2C, FAM64A, CENPF, NUSAP1, GAS2L3, KIF2C, KIF23, CENPE, HMMR, TPX2 
##     PSRC1, AURKA, KIF11, CKS2, CCNB2, CKAP5, CDC20, CDC25C, CENPA, CKAP2L 
##     G2E3, CDCA8, HN1, KIF20B, NEK2, BUB1, DLGAP5, MKI67, GTSE1, CDCA2 
## Negative:  UHRF1, MCM6, PCNA, MCM4, MCM2, UNG, MCM5, TIPIN, HELLS, RRM2 
##     SLBP, NASP, GINS2, RPA2, CDC6, DTL, PRIM1, CCNE2, CDCA7, DSCC1 
##     CHAF1B, RAD51, CDC45, POLA1, CLSPN, ATAD2, EXO1, RRM1, TYMS, RFC2 
## PC_ 3 
## Positive:  CENPA, CCNB2, CDC6, CCNE2, CDC20, FEN1, CDCA3, RANGAP1, TUBB4B, LBR 
##     RRM1, CKS2, CDCA8, BIRC5, NEK2, RRM2, NASP, RPA2, HMGB2, HMMR 
##     UBR7, SLBP, BUB1, KIF2C, TPX2, MCM2, MCM4, TIPIN, CKAP2, GINS2 
## Negative:  TOP2A, POLA1, RFC2, AURKB, CDCA2, FAM64A, BRIP1, NDC80, TYMS, NUSAP1 
##     CDK1, GAS2L3, KIF23, SMC4, HN1, WDR76, E2F8, TTK, ATAD2, PRIM1 
##     TMPO, KIF11, CBX5, ANLN, CTCF, CKAP2L, G2E3, CKAP5, HELLS, KIF20B 
## PC_ 4 
## Positive:  CDCA7, FAM64A, RFC2, GAS2L3, UNG, MSH2, CKAP2, KIF23, MCM2, MCM4 
##     HN1, HELLS, MCM5, CDC20, USP1, PSRC1, LBR, MCM6, G2E3, POLD3 
##     DTL, KIF2C, RPA2, CKAP5, CENPE, NEK2, DLGAP5, ECT2, CCNB2, UBR7 
## Negative:  E2F8, RAD51AP1, TYMS, RRM2, RAD51, BLM, CLSPN, MKI67, NDC80, BIRC5 
##     AURKB, CDCA3, ATAD2, NUF2, CDC6, TOP2A, POLA1, CKS2, ANLN, PCNA 
##     CCNE2, ANP32E, HMGB2, CTCF, TUBB4B, RRM1, CDC45, SLBP, KIF11, CENPA 
## PC_ 5 
## Positive:  ANP32E, CASP8AP2, HELLS, TMPO, HMGB2, NCAPD2, WDR76, CTCF, CKS2, CCNB2 
##     POLA1, CKS1B, USP1, ATAD2, E2F8, SMC4, FAM64A, TIPIN, KIF20B, CDCA7 
##     UNG, SLBP, UBR7, MKI67, DTL, PSRC1, NASP, CENPA, CENPE, CDCA3 
## Negative:  FEN1, CHAF1B, HN1, CDC45, MSH2, AURKA, LBR, RAD51, CDCA2, GINS2 
##     AURKB, CDK1, UBE2C, DSCC1, GTSE1, TUBB4B, RRM2, KIF23, ANLN, G2E3 
##     EXO1, POLD3, TTK, RRM1, NUSAP1, TACC3, RAD51AP1, NEK2, CKAP2L, CDC20
```

Example 21 (r):
```r
DimPlot(marrow)
```

Example 22 (r):
```r
DimPlot(marrow)
```

Example 23 (unknown):
```unknown
?AddModuleScore
```

Example 24 (r):
```r
marrow <- ScaleData(marrow, vars.to.regress = c("S.Score", "G2M.Score"), features = rownames(marrow))
```

Example 25 (r):
```r
marrow <- ScaleData(marrow, vars.to.regress = c("S.Score", "G2M.Score"), features = rownames(marrow))
```

Example 26 (r):
```r
# Now, a PCA on the variable genes no longer returns components associated with cell cycle
marrow <- RunPCA(marrow, features = VariableFeatures(marrow), nfeatures.print = 10)
```

Example 27 (r):
```r
# Now, a PCA on the variable genes no longer returns components associated with cell cycle
marrow <- RunPCA(marrow, features = VariableFeatures(marrow), nfeatures.print = 10)
```

Example 28 (unknown):
```unknown
## PC_ 1 
## Positive:  BLVRB, CAR2, KLF1, AQP1, CES2G, ERMAP, CAR1, FAM132A, RHD, SPHK1 
## Negative:  TMSB4X, H2AFY, CORO1A, PLAC8, EMB, MPO, PRTN3, CD34, LCP1, LAPTM5 
## PC_ 2 
## Positive:  ANGPT1, ADGRG1, MEIS1, ITGA2B, MPL, APOE, DAPP1, RAB37, GATA2, F2R 
## Negative:  LY6C2, ELANE, HP, ANXA3, IGSF6, CTSG, CLEC12A, TIFAB, SLPI, ALAS1 
## PC_ 3 
## Positive:  APOE, GATA2, NKG7, MUC13, MS4A3, RAB44, HDC, CPA3, FCGR3, ELANE 
## Negative:  FLT3, DNTT, LSP1, WFDC17, MYL10, GIMAP6, LAX1, GPR171, TBXA2R, IL12A 
## PC_ 4 
## Positive:  CSRP3, DNTT, ST8SIA6, MPEG1, SCIN, LGALS1, CMAH, RGL1, MFSD2B, APOE 
## Negative:  PROCR, HLF, MPL, MMRN1, SERPINA3G, ESAM, GSTM1, D630039A03RIK, MYL10, LY6A 
## PC_ 5 
## Positive:  PF4, GP1BB, SDPR, F2RL2, RAB27B, SLC14A1, TREML1, PBX1, F2R, TUBA8 
## Negative:  CPA3, LMO4, IKZF2, IFITM1, FUT8, MS4A2, SIGLECF, CSRP3, RAB44, HDC
```

Example 29 (unknown):
```unknown
## PC_ 1 
## Positive:  BLVRB, CAR2, KLF1, AQP1, CES2G, ERMAP, CAR1, FAM132A, RHD, SPHK1 
## Negative:  TMSB4X, H2AFY, CORO1A, PLAC8, EMB, MPO, PRTN3, CD34, LCP1, LAPTM5 
## PC_ 2 
## Positive:  ANGPT1, ADGRG1, MEIS1, ITGA2B, MPL, APOE, DAPP1, RAB37, GATA2, F2R 
## Negative:  LY6C2, ELANE, HP, ANXA3, IGSF6, CTSG, CLEC12A, TIFAB, SLPI, ALAS1 
## PC_ 3 
## Positive:  APOE, GATA2, NKG7, MUC13, MS4A3, RAB44, HDC, CPA3, FCGR3, ELANE 
## Negative:  FLT3, DNTT, LSP1, WFDC17, MYL10, GIMAP6, LAX1, GPR171, TBXA2R, IL12A 
## PC_ 4 
## Positive:  CSRP3, DNTT, ST8SIA6, MPEG1, SCIN, LGALS1, CMAH, RGL1, MFSD2B, APOE 
## Negative:  PROCR, HLF, MPL, MMRN1, SERPINA3G, ESAM, GSTM1, D630039A03RIK, MYL10, LY6A 
## PC_ 5 
## Positive:  PF4, GP1BB, SDPR, F2RL2, RAB27B, SLC14A1, TREML1, PBX1, F2R, TUBA8 
## Negative:  CPA3, LMO4, IKZF2, IFITM1, FUT8, MS4A2, SIGLECF, CSRP3, RAB44, HDC
```

Example 30 (r):
```r
# When running a PCA on only cell cycle genes, cells no longer separate by cell-cycle phase
marrow <- RunPCA(marrow, features = c(s.genes, g2m.genes))
```

Example 31 (r):
```r
# When running a PCA on only cell cycle genes, cells no longer separate by cell-cycle phase
marrow <- RunPCA(marrow, features = c(s.genes, g2m.genes))
```

Example 32 (unknown):
```unknown
## PC_ 1 
## Positive:  CENPA, CCNB2, CDC6, CDCA3, BIRC5, CDC20, CCNE2, RRM2, RRM1, HMGB2 
##     TUBB4B, CDCA8, FEN1, CKS2, NASP, TIPIN, SLBP, RANGAP1, HMMR, RPA2 
##     MCM2, MCM4, NEK2, TPX2, BUB1, LBR, CKS1B, GINS2, KIF2C, UBR7 
## Negative:  TOP2A, AURKB, NUSAP1, FAM64A, CDCA2, RFC2, POLA1, GAS2L3, KIF23, CDK1 
##     SMC4, KIF11, HN1, BRIP1, NDC80, TYMS, TTK, CKAP2L, CKAP5, CENPF 
##     E2F8, G2E3, ATAD2, PRIM1, ANLN, WDR76, KIF20B, TMPO, CTCF, CBX5 
## PC_ 2 
## Positive:  CDCA7, CDC20, UNG, FAM64A, GAS2L3, MCM4, KIF2C, MCM2, MCM5, CKAP2 
##     PSRC1, KIF23, NEK2, RFC2, CENPE, CKAP5, DLGAP5, HN1, USP1, MSH2 
##     CCNB2, UBE2C, MCM6, DTL, CENPF, RPA2, G2E3, NUSAP1, UBR7, TPX2 
## Negative:  TYMS, BIRC5, MKI67, RRM2, AURKB, TOP2A, RAD51AP1, PCNA, RAD51, CDCA3 
##     CLSPN, NUF2, ATAD2, NDC80, POLA1, HMGB2, E2F8, CDK1, CDC45, UHRF1 
##     RRM1, KIF11, CCNE2, CDC6, BRIP1, SLBP, TACC3, TTK, ANLN, TUBB4B 
## PC_ 3 
## Positive:  HMGB2, NCAPD2, HELLS, CCNB2, FAM64A, MKI67, ANP32E, CASP8AP2, ATAD2, CKS1B 
##     TMPO, CKS2, DTL, E2F8, SMC4, CTCF, KIF20B, WDR76, UNG, POLA1 
##     PSRC1, TIPIN, USP1, CDCA3, SLBP, CENPE, CENPA, CDCA8, CDCA7, TPX2 
## Negative:  UBE2C, AURKA, HMMR, CDK1, FEN1, TUBB4B, AURKB, MCM6, RRM1, CHAF1B 
##     HN1, MCM2, GINS2, GTSE1, NUSAP1, CDC45, RRM2, NEK2, CKAP2L, TTK 
##     CDC20, ANLN, RAD51, TACC3, CDCA2, BIRC5, RAD51AP1, CENPF, CDC6, MCM5 
## PC_ 4 
## Positive:  MCM2, MCM6, TMPO, MCM5, CKS2, ANP32E, CBX5, TIPIN, CKS1B, UBE2C 
##     POLA1, HMGB2, WDR76, SLBP, PRIM1, NASP, PCNA, MCM4, AURKA, UBR7 
##     BLM, RFC2, CDCA7, SMC4, TOP2A, AURKB, TUBB4B, GINS2, CTCF, RANGAP1 
## Negative:  CCNE2, KIF23, RRM2, FAM64A, EXO1, CDC45, GAS2L3, HJURP, FEN1, CLSPN 
##     RAD51, DTL, CDC20, CDC6, PSRC1, CDCA2, LBR, NUF2, NUSAP1, DLGAP5 
##     UHRF1, RAD51AP1, DSCC1, CCNB2, CHAF1B, TACC3, CKAP5, NEK2, BIRC5, BRIP1 
## PC_ 5 
## Positive:  E2F8, BLM, CKS2, TUBB4B, ANP32E, PSRC1, CKAP5, ANLN, CDC6, NEK2 
##     CENPA, DSCC1, KIF20B, UBR7, HJURP, USP1, HN1, DLGAP5, WDR76, CCNE2 
##     G2E3, TMPO, POLA1, UNG, RRM2, EXO1, DTL, CKAP2, ATAD2, HMMR 
## Negative:  CDCA7, HELLS, CKS1B, BIRC5, CDCA8, NCAPD2, AURKB, CCNB2, NUF2, KIF23 
##     FAM64A, CKAP2L, CDCA3, MSH2, RFC2, MKI67, TIPIN, NASP, BRIP1, RAD51 
##     POLD3, TPX2, CDC45, AURKA, TACC3, MCM5, CDC25C, LBR, RRM1, MCM2
```

Example 33 (unknown):
```unknown
## PC_ 1 
## Positive:  CENPA, CCNB2, CDC6, CDCA3, BIRC5, CDC20, CCNE2, RRM2, RRM1, HMGB2 
##     TUBB4B, CDCA8, FEN1, CKS2, NASP, TIPIN, SLBP, RANGAP1, HMMR, RPA2 
##     MCM2, MCM4, NEK2, TPX2, BUB1, LBR, CKS1B, GINS2, KIF2C, UBR7 
## Negative:  TOP2A, AURKB, NUSAP1, FAM64A, CDCA2, RFC2, POLA1, GAS2L3, KIF23, CDK1 
##     SMC4, KIF11, HN1, BRIP1, NDC80, TYMS, TTK, CKAP2L, CKAP5, CENPF 
##     E2F8, G2E3, ATAD2, PRIM1, ANLN, WDR76, KIF20B, TMPO, CTCF, CBX5 
## PC_ 2 
## Positive:  CDCA7, CDC20, UNG, FAM64A, GAS2L3, MCM4, KIF2C, MCM2, MCM5, CKAP2 
##     PSRC1, KIF23, NEK2, RFC2, CENPE, CKAP5, DLGAP5, HN1, USP1, MSH2 
##     CCNB2, UBE2C, MCM6, DTL, CENPF, RPA2, G2E3, NUSAP1, UBR7, TPX2 
## Negative:  TYMS, BIRC5, MKI67, RRM2, AURKB, TOP2A, RAD51AP1, PCNA, RAD51, CDCA3 
##     CLSPN, NUF2, ATAD2, NDC80, POLA1, HMGB2, E2F8, CDK1, CDC45, UHRF1 
##     RRM1, KIF11, CCNE2, CDC6, BRIP1, SLBP, TACC3, TTK, ANLN, TUBB4B 
## PC_ 3 
## Positive:  HMGB2, NCAPD2, HELLS, CCNB2, FAM64A, MKI67, ANP32E, CASP8AP2, ATAD2, CKS1B 
##     TMPO, CKS2, DTL, E2F8, SMC4, CTCF, KIF20B, WDR76, UNG, POLA1 
##     PSRC1, TIPIN, USP1, CDCA3, SLBP, CENPE, CENPA, CDCA8, CDCA7, TPX2 
## Negative:  UBE2C, AURKA, HMMR, CDK1, FEN1, TUBB4B, AURKB, MCM6, RRM1, CHAF1B 
##     HN1, MCM2, GINS2, GTSE1, NUSAP1, CDC45, RRM2, NEK2, CKAP2L, TTK 
##     CDC20, ANLN, RAD51, TACC3, CDCA2, BIRC5, RAD51AP1, CENPF, CDC6, MCM5 
## PC_ 4 
## Positive:  MCM2, MCM6, TMPO, MCM5, CKS2, ANP32E, CBX5, TIPIN, CKS1B, UBE2C 
##     POLA1, HMGB2, WDR76, SLBP, PRIM1, NASP, PCNA, MCM4, AURKA, UBR7 
##     BLM, RFC2, CDCA7, SMC4, TOP2A, AURKB, TUBB4B, GINS2, CTCF, RANGAP1 
## Negative:  CCNE2, KIF23, RRM2, FAM64A, EXO1, CDC45, GAS2L3, HJURP, FEN1, CLSPN 
##     RAD51, DTL, CDC20, CDC6, PSRC1, CDCA2, LBR, NUF2, NUSAP1, DLGAP5 
##     UHRF1, RAD51AP1, DSCC1, CCNB2, CHAF1B, TACC3, CKAP5, NEK2, BIRC5, BRIP1 
## PC_ 5 
## Positive:  E2F8, BLM, CKS2, TUBB4B, ANP32E, PSRC1, CKAP5, ANLN, CDC6, NEK2 
##     CENPA, DSCC1, KIF20B, UBR7, HJURP, USP1, HN1, DLGAP5, WDR76, CCNE2 
##     G2E3, TMPO, POLA1, UNG, RRM2, EXO1, DTL, CKAP2, ATAD2, HMMR 
## Negative:  CDCA7, HELLS, CKS1B, BIRC5, CDCA8, NCAPD2, AURKB, CCNB2, NUF2, KIF23 
##     FAM64A, CKAP2L, CDCA3, MSH2, RFC2, MKI67, TIPIN, NASP, BRIP1, RAD51 
##     POLD3, TPX2, CDC45, AURKA, TACC3, MCM5, CDC25C, LBR, RRM1, MCM2
```

Example 34 (r):
```r
DimPlot(marrow)
```

Example 35 (r):
```r
DimPlot(marrow)
```

Example 36 (r):
```r
marrow$CC.Difference <- marrow$S.Score - marrow$G2M.Score
marrow <- ScaleData(marrow, vars.to.regress = "CC.Difference", features = rownames(marrow))
```

Example 37 (r):
```r
marrow$CC.Difference <- marrow$S.Score - marrow$G2M.Score
marrow <- ScaleData(marrow, vars.to.regress = "CC.Difference", features = rownames(marrow))
```

Example 38 (r):
```r
# cell cycle effects strongly mitigated in PCA
marrow <- RunPCA(marrow, features = VariableFeatures(marrow), nfeatures.print = 10)
```

Example 39 (r):
```r
# cell cycle effects strongly mitigated in PCA
marrow <- RunPCA(marrow, features = VariableFeatures(marrow), nfeatures.print = 10)
```

Example 40 (unknown):
```unknown
## PC_ 1 
## Positive:  BLVRB, KLF1, ERMAP, FAM132A, CAR2, RHD, CES2G, SPHK1, AQP1, SLC38A5 
## Negative:  TMSB4X, CORO1A, PLAC8, H2AFY, LAPTM5, CD34, LCP1, TMEM176B, IGFBP4, EMB 
## PC_ 2 
## Positive:  APOE, GATA2, RAB37, ANGPT1, ADGRG1, F2R, MEIS1, MPL, PDZK1IP1, DAPP1 
## Negative:  CTSG, ELANE, LY6C2, HP, CLEC12A, ANXA3, IGSF6, TIFAB, SLPI, MPO 
## PC_ 3 
## Positive:  APOE, GATA2, NKG7, MUC13, ITGA2B, TUBA8, CPA3, RAB44, SLC18A2, CD9 
## Negative:  DNTT, FLT3, WFDC17, LSP1, MYL10, LAX1, GIMAP6, IGHM, CD24A, MN1 
## PC_ 4 
## Positive:  CSRP3, ST8SIA6, SCIN, LGALS1, APOE, ITGB7, MFSD2B, RGL1, DNTT, IGHV1-23 
## Negative:  MPL, MMRN1, PROCR, SERPINA3G, HLF, ESAM, PTGS1, D630039A03RIK, NDN, PPIC 
## PC_ 5 
## Positive:  HDC, FCGR3, LMO4, IFITM1, HLF, PROCR, CSRP3, CPA3, PGLYRP1, IKZF2 
## Negative:  GP1BB, PF4, SDPR, F2RL2, TREML1, RAB27B, SLC14A1, PBX1, PLEK, TUBA8
```

Example 41 (unknown):
```unknown
## PC_ 1 
## Positive:  BLVRB, KLF1, ERMAP, FAM132A, CAR2, RHD, CES2G, SPHK1, AQP1, SLC38A5 
## Negative:  TMSB4X, CORO1A, PLAC8, H2AFY, LAPTM5, CD34, LCP1, TMEM176B, IGFBP4, EMB 
## PC_ 2 
## Positive:  APOE, GATA2, RAB37, ANGPT1, ADGRG1, F2R, MEIS1, MPL, PDZK1IP1, DAPP1 
## Negative:  CTSG, ELANE, LY6C2, HP, CLEC12A, ANXA3, IGSF6, TIFAB, SLPI, MPO 
## PC_ 3 
## Positive:  APOE, GATA2, NKG7, MUC13, ITGA2B, TUBA8, CPA3, RAB44, SLC18A2, CD9 
## Negative:  DNTT, FLT3, WFDC17, LSP1, MYL10, LAX1, GIMAP6, IGHM, CD24A, MN1 
## PC_ 4 
## Positive:  CSRP3, ST8SIA6, SCIN, LGALS1, APOE, ITGB7, MFSD2B, RGL1, DNTT, IGHV1-23 
## Negative:  MPL, MMRN1, PROCR, SERPINA3G, HLF, ESAM, PTGS1, D630039A03RIK, NDN, PPIC 
## PC_ 5 
## Positive:  HDC, FCGR3, LMO4, IFITM1, HLF, PROCR, CSRP3, CPA3, PGLYRP1, IKZF2 
## Negative:  GP1BB, PF4, SDPR, F2RL2, TREML1, RAB27B, SLC14A1, PBX1, PLEK, TUBA8
```

Example 42 (r):
```r
# when running a PCA on cell cycle genes, actively proliferating cells remain distinct from G1
# cells however, within actively proliferating cells, G2M and S phase cells group together
marrow <- RunPCA(marrow, features = c(s.genes, g2m.genes))
```

Example 43 (r):
```r
# when running a PCA on cell cycle genes, actively proliferating cells remain distinct from G1
# cells however, within actively proliferating cells, G2M and S phase cells group together
marrow <- RunPCA(marrow, features = c(s.genes, g2m.genes))
```

Example 44 (unknown):
```unknown
## PC_ 1 
## Positive:  BIRC5, RRM2, MKI67, HMGB2, CDK1, RRM1, CDCA3, TOP2A, UBE2C, CKS1B 
##     PCNA, UHRF1, TYMS, MCM5, CDCA8, TIPIN, HMMR, TUBB4B, NASP, TACC3 
##     AURKB, CDC45, RAD51, KIF11, NUSAP1, TPX2, SLBP, CKAP2L, NUF2, CDC6 
## Negative:  PSRC1, CTCF, GAS2L3, MSH2, CASP8AP2, G2E3, CKAP5, HN1, FAM64A, RFC2 
##     UNG, KIF23, CDCA7, BLM, BRIP1, LBR, ANP32E, UBR7, DTL, CDC25C 
##     POLD3, CHAF1B, WDR76, CENPE, E2F8, ECT2, CKAP2, USP1, CDCA2, NDC80 
## PC_ 2 
## Positive:  TOP2A, FAM64A, RFC2, CDCA2, AURKB, NUSAP1, POLA1, KIF23, GAS2L3, BRIP1 
##     HN1, CDK1, KIF11, NDC80, TTK, SMC4, TYMS, CKAP2L, E2F8, CENPF 
##     PRIM1, WDR76, ATAD2, CKAP5, ANLN, G2E3, TMPO, CBX5, KIF20B, CTCF 
## Negative:  CENPA, CCNB2, CDC6, CDC20, CCNE2, FEN1, CDCA3, CKS2, RANGAP1, TUBB4B 
##     RRM2, BIRC5, CDCA8, NASP, RRM1, HMGB2, SLBP, LBR, NEK2, RPA2 
##     MCM2, UBR7, HMMR, MCM4, TIPIN, BUB1, TPX2, KIF2C, GINS2, UNG 
## PC_ 3 
## Positive:  E2F8, TYMS, RAD51AP1, AURKB, RRM2, RAD51, MKI67, CLSPN, TOP2A, NDC80 
##     BLM, ATAD2, BIRC5, POLA1, PCNA, NUF2, CDCA3, ANLN, CDC6, CTCF 
##     ANP32E, CKS2, HMGB2, SLBP, TUBB4B, CDC45, KIF11, CCNE2, RRM1, BRIP1 
## Negative:  CDCA7, FAM64A, GAS2L3, UNG, KIF23, CDC20, PSRC1, KIF2C, RFC2, CKAP2 
##     MCM4, MSH2, HN1, MCM2, CENPE, CCNB2, HELLS, MCM5, NEK2, USP1 
##     CKAP5, DTL, CENPF, G2E3, NUSAP1, RPA2, DLGAP5, LBR, MCM6, POLD3 
## PC_ 4 
## Positive:  HELLS, NCAPD2, FAM64A, HMGB2, CASP8AP2, CCNB2, ANP32E, CKS1B, CTCF, TMPO 
##     WDR76, CKS2, UNG, ATAD2, POLA1, SMC4, DTL, MKI67, CDCA7, KIF20B 
##     TIPIN, USP1, E2F8, PSRC1, UHRF1, CENPE, CDCA3, CDCA8, SLBP, TPX2 
## Negative:  AURKA, CHAF1B, FEN1, UBE2C, HN1, TUBB4B, HMMR, MCM6, NEK2, GTSE1 
##     ANLN, MSH2, GINS2, MCM2, CDC20, G2E3, AURKB, LBR, CDC45, NUSAP1 
##     CDK1, CDCA2, RRM1, TTK, CKAP2L, BLM, RAD51, DSCC1, CENPF, RRM2 
## PC_ 5 
## Positive:  ANP32E, MCM6, BLM, TMPO, MCM2, CKS2, UBR7, WDR76, POLA1, MCM5 
##     HN1, E2F8, RFC2, CBX5, MCM4, TUBB4B, CKAP5, UBE2C, USP1, PRIM1 
##     ANLN, SLBP, CTCF, CASP8AP2, G2E3, NEK2, UNG, AURKA, SMC4, TIPIN 
## Negative:  KIF23, CCNE2, FAM64A, GAS2L3, RAD51, CLSPN, EXO1, CDC45, NUF2, RRM2 
##     HELLS, CCNB2, FEN1, BRIP1, BIRC5, CDCA2, DTL, UHRF1, NCAPD2, POLD3 
##     HJURP, CDC25C, TACC3, RAD51AP1, LBR, CDC6, NDC80, NUSAP1, MKI67, CHAF1B
```

Example 45 (unknown):
```unknown
## PC_ 1 
## Positive:  BIRC5, RRM2, MKI67, HMGB2, CDK1, RRM1, CDCA3, TOP2A, UBE2C, CKS1B 
##     PCNA, UHRF1, TYMS, MCM5, CDCA8, TIPIN, HMMR, TUBB4B, NASP, TACC3 
##     AURKB, CDC45, RAD51, KIF11, NUSAP1, TPX2, SLBP, CKAP2L, NUF2, CDC6 
## Negative:  PSRC1, CTCF, GAS2L3, MSH2, CASP8AP2, G2E3, CKAP5, HN1, FAM64A, RFC2 
##     UNG, KIF23, CDCA7, BLM, BRIP1, LBR, ANP32E, UBR7, DTL, CDC25C 
##     POLD3, CHAF1B, WDR76, CENPE, E2F8, ECT2, CKAP2, USP1, CDCA2, NDC80 
## PC_ 2 
## Positive:  TOP2A, FAM64A, RFC2, CDCA2, AURKB, NUSAP1, POLA1, KIF23, GAS2L3, BRIP1 
##     HN1, CDK1, KIF11, NDC80, TTK, SMC4, TYMS, CKAP2L, E2F8, CENPF 
##     PRIM1, WDR76, ATAD2, CKAP5, ANLN, G2E3, TMPO, CBX5, KIF20B, CTCF 
## Negative:  CENPA, CCNB2, CDC6, CDC20, CCNE2, FEN1, CDCA3, CKS2, RANGAP1, TUBB4B 
##     RRM2, BIRC5, CDCA8, NASP, RRM1, HMGB2, SLBP, LBR, NEK2, RPA2 
##     MCM2, UBR7, HMMR, MCM4, TIPIN, BUB1, TPX2, KIF2C, GINS2, UNG 
## PC_ 3 
## Positive:  E2F8, TYMS, RAD51AP1, AURKB, RRM2, RAD51, MKI67, CLSPN, TOP2A, NDC80 
##     BLM, ATAD2, BIRC5, POLA1, PCNA, NUF2, CDCA3, ANLN, CDC6, CTCF 
##     ANP32E, CKS2, HMGB2, SLBP, TUBB4B, CDC45, KIF11, CCNE2, RRM1, BRIP1 
## Negative:  CDCA7, FAM64A, GAS2L3, UNG, KIF23, CDC20, PSRC1, KIF2C, RFC2, CKAP2 
##     MCM4, MSH2, HN1, MCM2, CENPE, CCNB2, HELLS, MCM5, NEK2, USP1 
##     CKAP5, DTL, CENPF, G2E3, NUSAP1, RPA2, DLGAP5, LBR, MCM6, POLD3 
## PC_ 4 
## Positive:  HELLS, NCAPD2, FAM64A, HMGB2, CASP8AP2, CCNB2, ANP32E, CKS1B, CTCF, TMPO 
##     WDR76, CKS2, UNG, ATAD2, POLA1, SMC4, DTL, MKI67, CDCA7, KIF20B 
##     TIPIN, USP1, E2F8, PSRC1, UHRF1, CENPE, CDCA3, CDCA8, SLBP, TPX2 
## Negative:  AURKA, CHAF1B, FEN1, UBE2C, HN1, TUBB4B, HMMR, MCM6, NEK2, GTSE1 
##     ANLN, MSH2, GINS2, MCM2, CDC20, G2E3, AURKB, LBR, CDC45, NUSAP1 
##     CDK1, CDCA2, RRM1, TTK, CKAP2L, BLM, RAD51, DSCC1, CENPF, RRM2 
## PC_ 5 
## Positive:  ANP32E, MCM6, BLM, TMPO, MCM2, CKS2, UBR7, WDR76, POLA1, MCM5 
##     HN1, E2F8, RFC2, CBX5, MCM4, TUBB4B, CKAP5, UBE2C, USP1, PRIM1 
##     ANLN, SLBP, CTCF, CASP8AP2, G2E3, NEK2, UNG, AURKA, SMC4, TIPIN 
## Negative:  KIF23, CCNE2, FAM64A, GAS2L3, RAD51, CLSPN, EXO1, CDC45, NUF2, RRM2 
##     HELLS, CCNB2, FEN1, BRIP1, BIRC5, CDCA2, DTL, UHRF1, NCAPD2, POLD3 
##     HJURP, CDC25C, TACC3, RAD51AP1, LBR, CDC6, NDC80, NUSAP1, MKI67, CHAF1B
```

Example 46 (r):
```r
DimPlot(marrow)
```

Example 47 (r):
```r
DimPlot(marrow)
```

---

## Analysis, visualization, and integration of Visium HD spatial datasets with Seurat • Seurat

**URL:** http://127.0.0.1:9173/articles_extensions.html

**Contents:**
- Seurat Extension Packages
- Signac
- SeuratData
- SeuratWrappers
- SeuratDisk
- Azimuth
- BPCells
- presto
- Contents

In addition to the core Seurat package, we provide several extensions that enhance the functionality and utility of Seurat. A brief description of each is listed below with links to more complete documentation and examples.

Signac is an R toolkit that extends Seurat for the analysis, interpretation, and exploration of single-cell chromatin datasets. The software supports the following features:

For documentation and vignettes, click here.

SeuratData is a mechanism for distributing datasets in the form of Seurat objects using R’s internal package and data management systems. It represents an easy way for users to get access to datasets that are used in the Seurat vignettes. For more information, click here.

In order to facilitate the use of community tools with Seurat, we provide the SeuratWrappers package, which contains code to run other analysis tools on Seurat objects. For a full list of supported packages and vignettes, please see our vignettes page.

The SeuratDisk package introduces the h5Seurat file format for the storage and analysis of multimodal single-cell and spatially-resolved expression experiments. The SeuratDisk package provides functions to save Seurat objects as h5Seurat files, and functions for rapid on-disk conversion between h5Seurat and AnnData formats with the goal of enhancing interoperability between Seurat and Scanpy. For more information, click here

Azimuth is a web application that uses an annotated reference dataset to automate the processing, analysis, and interpretation of a new single-cell RNA-seq experiment. Azimuth leverages a ‘reference-based mapping’ pipeline that inputs a counts matrix of gene expression in single cells, and performs normalization, visualization, cell annotation, and differential expression (biomarker discovery). All results can be explored within the app, and easily downloaded for additional downstream analysis. To use the Azimuth web app, visit the Azimuth website here.

Developed by Greenleaf Lab, BPCells is an R package that allows for computationally efficient single-cell analysis. It utilizes bit-packing compression to store counts matrices on disk and C++ code to cache operations. BPCells is an R package that allows for computationally efficient single-cell analysis. It utilizes bit-packing compression to store counts matrices on disk and C++ code to cache operations.

Developed by Korunsky/Raychaudhari labs, presto performs a fast Wilcoxon rank sum test and auROC analysis. Seurat uses the presto package to perform fast differential expression.

Developed by Rahul Satija, Satija Lab and Collaborators.

Site built with pkgdown 2.0.7.

**Examples:**

Example 1 (unknown):
```unknown
vignettes/extensions.Rmd
```

Example 2 (unknown):
```unknown
extensions.Rmd
```

---

## Tips for integrating large datasets • Seurat

**URL:** http://127.0.0.1:9173/seurat/archive/v4.3/integration_large_datasets/index.html

**Contents:**
- Tips for integrating large datasets
    - Compiled: 2023-03-27

For very large datasets, the standard integration workflow can sometimes be prohibitively computationally expensive. In this workflow, we employ two options that can improve efficiency and runtimes:Reciprocal PCA (RPCA)Reference-based integrationThe main efficiency improvements are gained in FindIntegrationAnchors(). First, we use reciprocal PCA (RPCA) instead of CCA, to identify an effective space in which to find anchors. When determining anchors between any two datasets using reciprocal PCA, we project each dataset into the others PCA space and constrain the anchors by the same mutual neighborhood requirement. All downstream integration steps remain the same and we are able to ‘correct’ (or harmonize) the datasets.Additionally, we use reference-based integration. In the standard workflow, we identify anchors between all pairs of datasets. While this gives datasets equal weight in downstream integration, it can also become computationally intensive. For example when integrating 10 different datasets, we perform 45 different pairwise comparisons. As an alternative, we introduce here the possibility of specifying one or more of the datasets as the ‘reference’ for integrated analysis, with the remainder designated as ‘query’ datasets. In this workflow, we do not identify anchors between pairs of query datasets, reducing the number of comparisons. For example, when integrating 10 datasets with one specified as a reference, we perform only 9 comparisons. Reference-based integration can be applied to either log-normalized or SCTransform-normalized datasets.This alternative workflow consists of the following steps:Create a list of Seurat objects to integratePerform normalization, feature selection, and scaling separately for each datasetRun PCA on each object in the listIntegrate datasets, and proceed with joint analysisIn general, we observe strikingly similar results between the standard workflow and the one demonstrated here, with substantial reduction in compute time and memory. However, if the datasets are highly divergent (for example, cross-modality mapping or cross-species mapping), where only a small subset of features can be used to facilitate integration, and you may observe superior results using CCA.For this example, we will be using the “Immune Cell Atlas” data from the Human Cell Atlas which can be found here. library(Seurat)After acquiring the data, we first perform standard normalization and variable feature selection. bm280k.data <- Read10X_h5("../data/ica_bone_marrow_h5.h5") bm280k <- CreateSeuratObject(counts = bm280k.data, min.cells = 100, min.features = 500) bm280k.list <- SplitObject(bm280k, split.by = "orig.ident") bm280k.list <- lapply(X = bm280k.list, FUN = function(x) { x <- NormalizeData(x, verbose = FALSE) x <- FindVariableFeatures(x, verbose = FALSE) })Next, select features for downstream integration, and run PCA on each object in the list, which is required for running the alternative reciprocal PCA workflow. features <- SelectIntegrationFeatures(object.list = bm280k.list) bm280k.list <- lapply(X = bm280k.list, FUN = function(x) { x <- ScaleData(x, features = features, verbose = FALSE) x <- RunPCA(x, features = features, verbose = FALSE) })Since this dataset contains both men and women, we will chose one male and one female (BM1 and BM2) to use in a reference-based workflow. We determined donor sex by examining the expression of the XIST gene. anchors <- FindIntegrationAnchors(object.list = bm280k.list, reference = c(1, 2), reduction = "rpca", dims = 1:50) bm280k.integrated <- IntegrateData(anchorset = anchors, dims = 1:50) bm280k.integrated <- ScaleData(bm280k.integrated, verbose = FALSE) bm280k.integrated <- RunPCA(bm280k.integrated, verbose = FALSE) bm280k.integrated <- RunUMAP(bm280k.integrated, dims = 1:50) DimPlot(bm280k.integrated, group.by = "orig.ident")Session Info sessionInfo()## R version 4.2.0 (2022-04-22) ## Platform: x86_64-pc-linux-gnu (64-bit) ## Running under: Ubuntu 20.04.5 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/liblapack.so.3 ## ## locale: ## [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C ## [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8 ## [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 ## ## attached base packages: ## [1] stats graphics grDevices utils datasets methods base ## ## other attached packages: ## [1] ggplot2_3.4.1 SeuratObject_4.1.3 Seurat_4.3.0 ## ## loaded via a namespace (and not attached): ## [1] Rtsne_0.16 colorspace_2.1-0 deldir_1.0-6 ## [4] ellipsis_0.3.2 ggridges_0.5.4 rprojroot_2.0.3 ## [7] fs_1.6.1 spatstat.data_3.0-0 farver_2.1.1 ## [10] leiden_0.4.3 listenv_0.9.0 bit64_4.0.5 ## [13] ggrepel_0.9.3 fansi_1.0.4 codetools_0.2-18 ## [16] splines_4.2.0 cachem_1.0.7 knitr_1.42 ## [19] polyclip_1.10-4 jsonlite_1.8.4 ica_1.0-3 ## [22] cluster_2.1.3 png_0.1-8 uwot_0.1.14 ## [25] spatstat.sparse_3.0-0 shiny_1.7.4 sctransform_0.3.5 ## [28] compiler_4.2.0 httr_1.4.5 Matrix_1.5-3 ## [31] fastmap_1.1.1 lazyeval_0.2.2 cli_3.6.0 ## [34] later_1.3.0 formatR_1.14 htmltools_0.5.4 ## [37] tools_4.2.0 igraph_1.4.1 gtable_0.3.1 ## [40] glue_1.6.2 RANN_2.6.1 reshape2_1.4.4 ## [43] dplyr_1.1.0 Rcpp_1.0.10 scattermore_0.8 ## [46] jquerylib_0.1.4 pkgdown_2.0.7 vctrs_0.5.2 ## [49] nlme_3.1-157 spatstat.explore_3.0-6 progressr_0.13.0 ## [52] lmtest_0.9-40 spatstat.random_3.1-3 xfun_0.37 ## [55] stringr_1.5.0 globals_0.16.2 mime_0.12 ## [58] miniUI_0.1.1.1 lifecycle_1.0.3 irlba_2.3.5.1 ## [61] goftest_1.2-3 future_1.31.0 MASS_7.3-56 ## [64] zoo_1.8-11 scales_1.2.1 ragg_1.2.5 ## [67] promises_1.2.0.1 spatstat.utils_3.0-1 parallel_4.2.0 ## [70] RColorBrewer_1.1-3 yaml_2.3.7 memoise_2.0.1 ## [73] reticulate_1.28 pbapply_1.7-0 gridExtra_2.3 ## [76] sass_0.4.5 stringi_1.7.12 highr_0.10 ## [79] desc_1.4.2 rlang_1.0.6 pkgconfig_2.0.3 ## [82] systemfonts_1.0.4 matrixStats_0.63.0 evaluate_0.20 ## [85] lattice_0.20-45 tensor_1.5 ROCR_1.0-11 ## [88] purrr_1.0.1 labeling_0.4.2 patchwork_1.1.2 ## [91] htmlwidgets_1.6.1 bit_4.0.5 cowplot_1.1.1 ## [94] tidyselect_1.2.0 parallelly_1.34.0 RcppAnnoy_0.0.20 ## [97] plyr_1.8.8 magrittr_2.0.3 R6_2.5.1 ## [100] generics_0.1.3 withr_2.5.0 pillar_1.8.1 ## [103] fitdistrplus_1.1-8 abind_1.4-5 survival_3.3-1 ## [106] sp_1.6-0 tibble_3.1.8 future.apply_1.10.0 ## [109] hdf5r_1.3.8 KernSmooth_2.23-20 utf8_1.2.3 ## [112] spatstat.geom_3.0-6 plotly_4.10.1 rmarkdown_2.20 ## [115] grid_4.2.0 data.table_1.14.8 digest_0.6.31 ## [118] xtable_1.8-4 tidyr_1.3.0 httpuv_1.6.9 ## [121] textshaping_0.3.6 munsell_0.5.0 viridisLite_0.4.1 ## [124] bslib_0.4.2

The main efficiency improvements are gained in FindIntegrationAnchors(). First, we use reciprocal PCA (RPCA) instead of CCA, to identify an effective space in which to find anchors. When determining anchors between any two datasets using reciprocal PCA, we project each dataset into the others PCA space and constrain the anchors by the same mutual neighborhood requirement. All downstream integration steps remain the same and we are able to ‘correct’ (or harmonize) the datasets.Additionally, we use reference-based integration. In the standard workflow, we identify anchors between all pairs of datasets. While this gives datasets equal weight in downstream integration, it can also become computationally intensive. For example when integrating 10 different datasets, we perform 45 different pairwise comparisons. As an alternative, we introduce here the possibility of specifying one or more of the datasets as the ‘reference’ for integrated analysis, with the remainder designated as ‘query’ datasets. In this workflow, we do not identify anchors between pairs of query datasets, reducing the number of comparisons. For example, when integrating 10 datasets with one specified as a reference, we perform only 9 comparisons. Reference-based integration can be applied to either log-normalized or SCTransform-normalized datasets.This alternative workflow consists of the following steps:Create a list of Seurat objects to integratePerform normalization, feature selection, and scaling separately for each datasetRun PCA on each object in the listIntegrate datasets, and proceed with joint analysisIn general, we observe strikingly similar results between the standard workflow and the one demonstrated here, with substantial reduction in compute time and memory. However, if the datasets are highly divergent (for example, cross-modality mapping or cross-species mapping), where only a small subset of features can be used to facilitate integration, and you may observe superior results using CCA.For this example, we will be using the “Immune Cell Atlas” data from the Human Cell Atlas which can be found here. library(Seurat)After acquiring the data, we first perform standard normalization and variable feature selection. bm280k.data <- Read10X_h5("../data/ica_bone_marrow_h5.h5") bm280k <- CreateSeuratObject(counts = bm280k.data, min.cells = 100, min.features = 500) bm280k.list <- SplitObject(bm280k, split.by = "orig.ident") bm280k.list <- lapply(X = bm280k.list, FUN = function(x) { x <- NormalizeData(x, verbose = FALSE) x <- FindVariableFeatures(x, verbose = FALSE) })Next, select features for downstream integration, and run PCA on each object in the list, which is required for running the alternative reciprocal PCA workflow. features <- SelectIntegrationFeatures(object.list = bm280k.list) bm280k.list <- lapply(X = bm280k.list, FUN = function(x) { x <- ScaleData(x, features = features, verbose = FALSE) x <- RunPCA(x, features = features, verbose = FALSE) })Since this dataset contains both men and women, we will chose one male and one female (BM1 and BM2) to use in a reference-based workflow. We determined donor sex by examining the expression of the XIST gene. anchors <- FindIntegrationAnchors(object.list = bm280k.list, reference = c(1, 2), reduction = "rpca", dims = 1:50) bm280k.integrated <- IntegrateData(anchorset = anchors, dims = 1:50) bm280k.integrated <- ScaleData(bm280k.integrated, verbose = FALSE) bm280k.integrated <- RunPCA(bm280k.integrated, verbose = FALSE) bm280k.integrated <- RunUMAP(bm280k.integrated, dims = 1:50) DimPlot(bm280k.integrated, group.by = "orig.ident")Session Info sessionInfo()## R version 4.2.0 (2022-04-22) ## Platform: x86_64-pc-linux-gnu (64-bit) ## Running under: Ubuntu 20.04.5 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/liblapack.so.3 ## ## locale: ## [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C ## [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8 ## [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 ## ## attached base packages: ## [1] stats graphics grDevices utils datasets methods base ## ## other attached packages: ## [1] ggplot2_3.4.1 SeuratObject_4.1.3 Seurat_4.3.0 ## ## loaded via a namespace (and not attached): ## [1] Rtsne_0.16 colorspace_2.1-0 deldir_1.0-6 ## [4] ellipsis_0.3.2 ggridges_0.5.4 rprojroot_2.0.3 ## [7] fs_1.6.1 spatstat.data_3.0-0 farver_2.1.1 ## [10] leiden_0.4.3 listenv_0.9.0 bit64_4.0.5 ## [13] ggrepel_0.9.3 fansi_1.0.4 codetools_0.2-18 ## [16] splines_4.2.0 cachem_1.0.7 knitr_1.42 ## [19] polyclip_1.10-4 jsonlite_1.8.4 ica_1.0-3 ## [22] cluster_2.1.3 png_0.1-8 uwot_0.1.14 ## [25] spatstat.sparse_3.0-0 shiny_1.7.4 sctransform_0.3.5 ## [28] compiler_4.2.0 httr_1.4.5 Matrix_1.5-3 ## [31] fastmap_1.1.1 lazyeval_0.2.2 cli_3.6.0 ## [34] later_1.3.0 formatR_1.14 htmltools_0.5.4 ## [37] tools_4.2.0 igraph_1.4.1 gtable_0.3.1 ## [40] glue_1.6.2 RANN_2.6.1 reshape2_1.4.4 ## [43] dplyr_1.1.0 Rcpp_1.0.10 scattermore_0.8 ## [46] jquerylib_0.1.4 pkgdown_2.0.7 vctrs_0.5.2 ## [49] nlme_3.1-157 spatstat.explore_3.0-6 progressr_0.13.0 ## [52] lmtest_0.9-40 spatstat.random_3.1-3 xfun_0.37 ## [55] stringr_1.5.0 globals_0.16.2 mime_0.12 ## [58] miniUI_0.1.1.1 lifecycle_1.0.3 irlba_2.3.5.1 ## [61] goftest_1.2-3 future_1.31.0 MASS_7.3-56 ## [64] zoo_1.8-11 scales_1.2.1 ragg_1.2.5 ## [67] promises_1.2.0.1 spatstat.utils_3.0-1 parallel_4.2.0 ## [70] RColorBrewer_1.1-3 yaml_2.3.7 memoise_2.0.1 ## [73] reticulate_1.28 pbapply_1.7-0 gridExtra_2.3 ## [76] sass_0.4.5 stringi_1.7.12 highr_0.10 ## [79] desc_1.4.2 rlang_1.0.6 pkgconfig_2.0.3 ## [82] systemfonts_1.0.4 matrixStats_0.63.0 evaluate_0.20 ## [85] lattice_0.20-45 tensor_1.5 ROCR_1.0-11 ## [88] purrr_1.0.1 labeling_0.4.2 patchwork_1.1.2 ## [91] htmlwidgets_1.6.1 bit_4.0.5 cowplot_1.1.1 ## [94] tidyselect_1.2.0 parallelly_1.34.0 RcppAnnoy_0.0.20 ## [97] plyr_1.8.8 magrittr_2.0.3 R6_2.5.1 ## [100] generics_0.1.3 withr_2.5.0 pillar_1.8.1 ## [103] fitdistrplus_1.1-8 abind_1.4-5 survival_3.3-1 ## [106] sp_1.6-0 tibble_3.1.8 future.apply_1.10.0 ## [109] hdf5r_1.3.8 KernSmooth_2.23-20 utf8_1.2.3 ## [112] spatstat.geom_3.0-6 plotly_4.10.1 rmarkdown_2.20 ## [115] grid_4.2.0 data.table_1.14.8 digest_0.6.31 ## [118] xtable_1.8-4 tidyr_1.3.0 httpuv_1.6.9 ## [121] textshaping_0.3.6 munsell_0.5.0 viridisLite_0.4.1 ## [124] bslib_0.4.2

Additionally, we use reference-based integration. In the standard workflow, we identify anchors between all pairs of datasets. While this gives datasets equal weight in downstream integration, it can also become computationally intensive. For example when integrating 10 different datasets, we perform 45 different pairwise comparisons. As an alternative, we introduce here the possibility of specifying one or more of the datasets as the ‘reference’ for integrated analysis, with the remainder designated as ‘query’ datasets. In this workflow, we do not identify anchors between pairs of query datasets, reducing the number of comparisons. For example, when integrating 10 datasets with one specified as a reference, we perform only 9 comparisons. Reference-based integration can be applied to either log-normalized or SCTransform-normalized datasets.This alternative workflow consists of the following steps:Create a list of Seurat objects to integratePerform normalization, feature selection, and scaling separately for each datasetRun PCA on each object in the listIntegrate datasets, and proceed with joint analysisIn general, we observe strikingly similar results between the standard workflow and the one demonstrated here, with substantial reduction in compute time and memory. However, if the datasets are highly divergent (for example, cross-modality mapping or cross-species mapping), where only a small subset of features can be used to facilitate integration, and you may observe superior results using CCA.For this example, we will be using the “Immune Cell Atlas” data from the Human Cell Atlas which can be found here. library(Seurat)After acquiring the data, we first perform standard normalization and variable feature selection. bm280k.data <- Read10X_h5("../data/ica_bone_marrow_h5.h5") bm280k <- CreateSeuratObject(counts = bm280k.data, min.cells = 100, min.features = 500) bm280k.list <- SplitObject(bm280k, split.by = "orig.ident") bm280k.list <- lapply(X = bm280k.list, FUN = function(x) { x <- NormalizeData(x, verbose = FALSE) x <- FindVariableFeatures(x, verbose = FALSE) })Next, select features for downstream integration, and run PCA on each object in the list, which is required for running the alternative reciprocal PCA workflow. features <- SelectIntegrationFeatures(object.list = bm280k.list) bm280k.list <- lapply(X = bm280k.list, FUN = function(x) { x <- ScaleData(x, features = features, verbose = FALSE) x <- RunPCA(x, features = features, verbose = FALSE) })Since this dataset contains both men and women, we will chose one male and one female (BM1 and BM2) to use in a reference-based workflow. We determined donor sex by examining the expression of the XIST gene. anchors <- FindIntegrationAnchors(object.list = bm280k.list, reference = c(1, 2), reduction = "rpca", dims = 1:50) bm280k.integrated <- IntegrateData(anchorset = anchors, dims = 1:50) bm280k.integrated <- ScaleData(bm280k.integrated, verbose = FALSE) bm280k.integrated <- RunPCA(bm280k.integrated, verbose = FALSE) bm280k.integrated <- RunUMAP(bm280k.integrated, dims = 1:50) DimPlot(bm280k.integrated, group.by = "orig.ident")Session Info sessionInfo()## R version 4.2.0 (2022-04-22) ## Platform: x86_64-pc-linux-gnu (64-bit) ## Running under: Ubuntu 20.04.5 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/liblapack.so.3 ## ## locale: ## [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C ## [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8 ## [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 ## ## attached base packages: ## [1] stats graphics grDevices utils datasets methods base ## ## other attached packages: ## [1] ggplot2_3.4.1 SeuratObject_4.1.3 Seurat_4.3.0 ## ## loaded via a namespace (and not attached): ## [1] Rtsne_0.16 colorspace_2.1-0 deldir_1.0-6 ## [4] ellipsis_0.3.2 ggridges_0.5.4 rprojroot_2.0.3 ## [7] fs_1.6.1 spatstat.data_3.0-0 farver_2.1.1 ## [10] leiden_0.4.3 listenv_0.9.0 bit64_4.0.5 ## [13] ggrepel_0.9.3 fansi_1.0.4 codetools_0.2-18 ## [16] splines_4.2.0 cachem_1.0.7 knitr_1.42 ## [19] polyclip_1.10-4 jsonlite_1.8.4 ica_1.0-3 ## [22] cluster_2.1.3 png_0.1-8 uwot_0.1.14 ## [25] spatstat.sparse_3.0-0 shiny_1.7.4 sctransform_0.3.5 ## [28] compiler_4.2.0 httr_1.4.5 Matrix_1.5-3 ## [31] fastmap_1.1.1 lazyeval_0.2.2 cli_3.6.0 ## [34] later_1.3.0 formatR_1.14 htmltools_0.5.4 ## [37] tools_4.2.0 igraph_1.4.1 gtable_0.3.1 ## [40] glue_1.6.2 RANN_2.6.1 reshape2_1.4.4 ## [43] dplyr_1.1.0 Rcpp_1.0.10 scattermore_0.8 ## [46] jquerylib_0.1.4 pkgdown_2.0.7 vctrs_0.5.2 ## [49] nlme_3.1-157 spatstat.explore_3.0-6 progressr_0.13.0 ## [52] lmtest_0.9-40 spatstat.random_3.1-3 xfun_0.37 ## [55] stringr_1.5.0 globals_0.16.2 mime_0.12 ## [58] miniUI_0.1.1.1 lifecycle_1.0.3 irlba_2.3.5.1 ## [61] goftest_1.2-3 future_1.31.0 MASS_7.3-56 ## [64] zoo_1.8-11 scales_1.2.1 ragg_1.2.5 ## [67] promises_1.2.0.1 spatstat.utils_3.0-1 parallel_4.2.0 ## [70] RColorBrewer_1.1-3 yaml_2.3.7 memoise_2.0.1 ## [73] reticulate_1.28 pbapply_1.7-0 gridExtra_2.3 ## [76] sass_0.4.5 stringi_1.7.12 highr_0.10 ## [79] desc_1.4.2 rlang_1.0.6 pkgconfig_2.0.3 ## [82] systemfonts_1.0.4 matrixStats_0.63.0 evaluate_0.20 ## [85] lattice_0.20-45 tensor_1.5 ROCR_1.0-11 ## [88] purrr_1.0.1 labeling_0.4.2 patchwork_1.1.2 ## [91] htmlwidgets_1.6.1 bit_4.0.5 cowplot_1.1.1 ## [94] tidyselect_1.2.0 parallelly_1.34.0 RcppAnnoy_0.0.20 ## [97] plyr_1.8.8 magrittr_2.0.3 R6_2.5.1 ## [100] generics_0.1.3 withr_2.5.0 pillar_1.8.1 ## [103] fitdistrplus_1.1-8 abind_1.4-5 survival_3.3-1 ## [106] sp_1.6-0 tibble_3.1.8 future.apply_1.10.0 ## [109] hdf5r_1.3.8 KernSmooth_2.23-20 utf8_1.2.3 ## [112] spatstat.geom_3.0-6 plotly_4.10.1 rmarkdown_2.20 ## [115] grid_4.2.0 data.table_1.14.8 digest_0.6.31 ## [118] xtable_1.8-4 tidyr_1.3.0 httpuv_1.6.9 ## [121] textshaping_0.3.6 munsell_0.5.0 viridisLite_0.4.1 ## [124] bslib_0.4.2

This alternative workflow consists of the following steps:Create a list of Seurat objects to integratePerform normalization, feature selection, and scaling separately for each datasetRun PCA on each object in the listIntegrate datasets, and proceed with joint analysisIn general, we observe strikingly similar results between the standard workflow and the one demonstrated here, with substantial reduction in compute time and memory. However, if the datasets are highly divergent (for example, cross-modality mapping or cross-species mapping), where only a small subset of features can be used to facilitate integration, and you may observe superior results using CCA.For this example, we will be using the “Immune Cell Atlas” data from the Human Cell Atlas which can be found here. library(Seurat)After acquiring the data, we first perform standard normalization and variable feature selection. bm280k.data <- Read10X_h5("../data/ica_bone_marrow_h5.h5") bm280k <- CreateSeuratObject(counts = bm280k.data, min.cells = 100, min.features = 500) bm280k.list <- SplitObject(bm280k, split.by = "orig.ident") bm280k.list <- lapply(X = bm280k.list, FUN = function(x) { x <- NormalizeData(x, verbose = FALSE) x <- FindVariableFeatures(x, verbose = FALSE) })Next, select features for downstream integration, and run PCA on each object in the list, which is required for running the alternative reciprocal PCA workflow. features <- SelectIntegrationFeatures(object.list = bm280k.list) bm280k.list <- lapply(X = bm280k.list, FUN = function(x) { x <- ScaleData(x, features = features, verbose = FALSE) x <- RunPCA(x, features = features, verbose = FALSE) })Since this dataset contains both men and women, we will chose one male and one female (BM1 and BM2) to use in a reference-based workflow. We determined donor sex by examining the expression of the XIST gene. anchors <- FindIntegrationAnchors(object.list = bm280k.list, reference = c(1, 2), reduction = "rpca", dims = 1:50) bm280k.integrated <- IntegrateData(anchorset = anchors, dims = 1:50) bm280k.integrated <- ScaleData(bm280k.integrated, verbose = FALSE) bm280k.integrated <- RunPCA(bm280k.integrated, verbose = FALSE) bm280k.integrated <- RunUMAP(bm280k.integrated, dims = 1:50) DimPlot(bm280k.integrated, group.by = "orig.ident")Session Info sessionInfo()## R version 4.2.0 (2022-04-22) ## Platform: x86_64-pc-linux-gnu (64-bit) ## Running under: Ubuntu 20.04.5 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/liblapack.so.3 ## ## locale: ## [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C ## [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8 ## [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 ## ## attached base packages: ## [1] stats graphics grDevices utils datasets methods base ## ## other attached packages: ## [1] ggplot2_3.4.1 SeuratObject_4.1.3 Seurat_4.3.0 ## ## loaded via a namespace (and not attached): ## [1] Rtsne_0.16 colorspace_2.1-0 deldir_1.0-6 ## [4] ellipsis_0.3.2 ggridges_0.5.4 rprojroot_2.0.3 ## [7] fs_1.6.1 spatstat.data_3.0-0 farver_2.1.1 ## [10] leiden_0.4.3 listenv_0.9.0 bit64_4.0.5 ## [13] ggrepel_0.9.3 fansi_1.0.4 codetools_0.2-18 ## [16] splines_4.2.0 cachem_1.0.7 knitr_1.42 ## [19] polyclip_1.10-4 jsonlite_1.8.4 ica_1.0-3 ## [22] cluster_2.1.3 png_0.1-8 uwot_0.1.14 ## [25] spatstat.sparse_3.0-0 shiny_1.7.4 sctransform_0.3.5 ## [28] compiler_4.2.0 httr_1.4.5 Matrix_1.5-3 ## [31] fastmap_1.1.1 lazyeval_0.2.2 cli_3.6.0 ## [34] later_1.3.0 formatR_1.14 htmltools_0.5.4 ## [37] tools_4.2.0 igraph_1.4.1 gtable_0.3.1 ## [40] glue_1.6.2 RANN_2.6.1 reshape2_1.4.4 ## [43] dplyr_1.1.0 Rcpp_1.0.10 scattermore_0.8 ## [46] jquerylib_0.1.4 pkgdown_2.0.7 vctrs_0.5.2 ## [49] nlme_3.1-157 spatstat.explore_3.0-6 progressr_0.13.0 ## [52] lmtest_0.9-40 spatstat.random_3.1-3 xfun_0.37 ## [55] stringr_1.5.0 globals_0.16.2 mime_0.12 ## [58] miniUI_0.1.1.1 lifecycle_1.0.3 irlba_2.3.5.1 ## [61] goftest_1.2-3 future_1.31.0 MASS_7.3-56 ## [64] zoo_1.8-11 scales_1.2.1 ragg_1.2.5 ## [67] promises_1.2.0.1 spatstat.utils_3.0-1 parallel_4.2.0 ## [70] RColorBrewer_1.1-3 yaml_2.3.7 memoise_2.0.1 ## [73] reticulate_1.28 pbapply_1.7-0 gridExtra_2.3 ## [76] sass_0.4.5 stringi_1.7.12 highr_0.10 ## [79] desc_1.4.2 rlang_1.0.6 pkgconfig_2.0.3 ## [82] systemfonts_1.0.4 matrixStats_0.63.0 evaluate_0.20 ## [85] lattice_0.20-45 tensor_1.5 ROCR_1.0-11 ## [88] purrr_1.0.1 labeling_0.4.2 patchwork_1.1.2 ## [91] htmlwidgets_1.6.1 bit_4.0.5 cowplot_1.1.1 ## [94] tidyselect_1.2.0 parallelly_1.34.0 RcppAnnoy_0.0.20 ## [97] plyr_1.8.8 magrittr_2.0.3 R6_2.5.1 ## [100] generics_0.1.3 withr_2.5.0 pillar_1.8.1 ## [103] fitdistrplus_1.1-8 abind_1.4-5 survival_3.3-1 ## [106] sp_1.6-0 tibble_3.1.8 future.apply_1.10.0 ## [109] hdf5r_1.3.8 KernSmooth_2.23-20 utf8_1.2.3 ## [112] spatstat.geom_3.0-6 plotly_4.10.1 rmarkdown_2.20 ## [115] grid_4.2.0 data.table_1.14.8 digest_0.6.31 ## [118] xtable_1.8-4 tidyr_1.3.0 httpuv_1.6.9 ## [121] textshaping_0.3.6 munsell_0.5.0 viridisLite_0.4.1 ## [124] bslib_0.4.2

In general, we observe strikingly similar results between the standard workflow and the one demonstrated here, with substantial reduction in compute time and memory. However, if the datasets are highly divergent (for example, cross-modality mapping or cross-species mapping), where only a small subset of features can be used to facilitate integration, and you may observe superior results using CCA.For this example, we will be using the “Immune Cell Atlas” data from the Human Cell Atlas which can be found here. library(Seurat)After acquiring the data, we first perform standard normalization and variable feature selection. bm280k.data <- Read10X_h5("../data/ica_bone_marrow_h5.h5") bm280k <- CreateSeuratObject(counts = bm280k.data, min.cells = 100, min.features = 500) bm280k.list <- SplitObject(bm280k, split.by = "orig.ident") bm280k.list <- lapply(X = bm280k.list, FUN = function(x) { x <- NormalizeData(x, verbose = FALSE) x <- FindVariableFeatures(x, verbose = FALSE) })Next, select features for downstream integration, and run PCA on each object in the list, which is required for running the alternative reciprocal PCA workflow. features <- SelectIntegrationFeatures(object.list = bm280k.list) bm280k.list <- lapply(X = bm280k.list, FUN = function(x) { x <- ScaleData(x, features = features, verbose = FALSE) x <- RunPCA(x, features = features, verbose = FALSE) })Since this dataset contains both men and women, we will chose one male and one female (BM1 and BM2) to use in a reference-based workflow. We determined donor sex by examining the expression of the XIST gene. anchors <- FindIntegrationAnchors(object.list = bm280k.list, reference = c(1, 2), reduction = "rpca", dims = 1:50) bm280k.integrated <- IntegrateData(anchorset = anchors, dims = 1:50) bm280k.integrated <- ScaleData(bm280k.integrated, verbose = FALSE) bm280k.integrated <- RunPCA(bm280k.integrated, verbose = FALSE) bm280k.integrated <- RunUMAP(bm280k.integrated, dims = 1:50) DimPlot(bm280k.integrated, group.by = "orig.ident")Session Info sessionInfo()## R version 4.2.0 (2022-04-22) ## Platform: x86_64-pc-linux-gnu (64-bit) ## Running under: Ubuntu 20.04.5 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/liblapack.so.3 ## ## locale: ## [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C ## [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8 ## [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 ## ## attached base packages: ## [1] stats graphics grDevices utils datasets methods base ## ## other attached packages: ## [1] ggplot2_3.4.1 SeuratObject_4.1.3 Seurat_4.3.0 ## ## loaded via a namespace (and not attached): ## [1] Rtsne_0.16 colorspace_2.1-0 deldir_1.0-6 ## [4] ellipsis_0.3.2 ggridges_0.5.4 rprojroot_2.0.3 ## [7] fs_1.6.1 spatstat.data_3.0-0 farver_2.1.1 ## [10] leiden_0.4.3 listenv_0.9.0 bit64_4.0.5 ## [13] ggrepel_0.9.3 fansi_1.0.4 codetools_0.2-18 ## [16] splines_4.2.0 cachem_1.0.7 knitr_1.42 ## [19] polyclip_1.10-4 jsonlite_1.8.4 ica_1.0-3 ## [22] cluster_2.1.3 png_0.1-8 uwot_0.1.14 ## [25] spatstat.sparse_3.0-0 shiny_1.7.4 sctransform_0.3.5 ## [28] compiler_4.2.0 httr_1.4.5 Matrix_1.5-3 ## [31] fastmap_1.1.1 lazyeval_0.2.2 cli_3.6.0 ## [34] later_1.3.0 formatR_1.14 htmltools_0.5.4 ## [37] tools_4.2.0 igraph_1.4.1 gtable_0.3.1 ## [40] glue_1.6.2 RANN_2.6.1 reshape2_1.4.4 ## [43] dplyr_1.1.0 Rcpp_1.0.10 scattermore_0.8 ## [46] jquerylib_0.1.4 pkgdown_2.0.7 vctrs_0.5.2 ## [49] nlme_3.1-157 spatstat.explore_3.0-6 progressr_0.13.0 ## [52] lmtest_0.9-40 spatstat.random_3.1-3 xfun_0.37 ## [55] stringr_1.5.0 globals_0.16.2 mime_0.12 ## [58] miniUI_0.1.1.1 lifecycle_1.0.3 irlba_2.3.5.1 ## [61] goftest_1.2-3 future_1.31.0 MASS_7.3-56 ## [64] zoo_1.8-11 scales_1.2.1 ragg_1.2.5 ## [67] promises_1.2.0.1 spatstat.utils_3.0-1 parallel_4.2.0 ## [70] RColorBrewer_1.1-3 yaml_2.3.7 memoise_2.0.1 ## [73] reticulate_1.28 pbapply_1.7-0 gridExtra_2.3 ## [76] sass_0.4.5 stringi_1.7.12 highr_0.10 ## [79] desc_1.4.2 rlang_1.0.6 pkgconfig_2.0.3 ## [82] systemfonts_1.0.4 matrixStats_0.63.0 evaluate_0.20 ## [85] lattice_0.20-45 tensor_1.5 ROCR_1.0-11 ## [88] purrr_1.0.1 labeling_0.4.2 patchwork_1.1.2 ## [91] htmlwidgets_1.6.1 bit_4.0.5 cowplot_1.1.1 ## [94] tidyselect_1.2.0 parallelly_1.34.0 RcppAnnoy_0.0.20 ## [97] plyr_1.8.8 magrittr_2.0.3 R6_2.5.1 ## [100] generics_0.1.3 withr_2.5.0 pillar_1.8.1 ## [103] fitdistrplus_1.1-8 abind_1.4-5 survival_3.3-1 ## [106] sp_1.6-0 tibble_3.1.8 future.apply_1.10.0 ## [109] hdf5r_1.3.8 KernSmooth_2.23-20 utf8_1.2.3 ## [112] spatstat.geom_3.0-6 plotly_4.10.1 rmarkdown_2.20 ## [115] grid_4.2.0 data.table_1.14.8 digest_0.6.31 ## [118] xtable_1.8-4 tidyr_1.3.0 httpuv_1.6.9 ## [121] textshaping_0.3.6 munsell_0.5.0 viridisLite_0.4.1 ## [124] bslib_0.4.2

For this example, we will be using the “Immune Cell Atlas” data from the Human Cell Atlas which can be found here. library(Seurat)After acquiring the data, we first perform standard normalization and variable feature selection. bm280k.data <- Read10X_h5("../data/ica_bone_marrow_h5.h5") bm280k <- CreateSeuratObject(counts = bm280k.data, min.cells = 100, min.features = 500) bm280k.list <- SplitObject(bm280k, split.by = "orig.ident") bm280k.list <- lapply(X = bm280k.list, FUN = function(x) { x <- NormalizeData(x, verbose = FALSE) x <- FindVariableFeatures(x, verbose = FALSE) })Next, select features for downstream integration, and run PCA on each object in the list, which is required for running the alternative reciprocal PCA workflow. features <- SelectIntegrationFeatures(object.list = bm280k.list) bm280k.list <- lapply(X = bm280k.list, FUN = function(x) { x <- ScaleData(x, features = features, verbose = FALSE) x <- RunPCA(x, features = features, verbose = FALSE) })Since this dataset contains both men and women, we will chose one male and one female (BM1 and BM2) to use in a reference-based workflow. We determined donor sex by examining the expression of the XIST gene. anchors <- FindIntegrationAnchors(object.list = bm280k.list, reference = c(1, 2), reduction = "rpca", dims = 1:50) bm280k.integrated <- IntegrateData(anchorset = anchors, dims = 1:50) bm280k.integrated <- ScaleData(bm280k.integrated, verbose = FALSE) bm280k.integrated <- RunPCA(bm280k.integrated, verbose = FALSE) bm280k.integrated <- RunUMAP(bm280k.integrated, dims = 1:50) DimPlot(bm280k.integrated, group.by = "orig.ident")Session Info sessionInfo()## R version 4.2.0 (2022-04-22) ## Platform: x86_64-pc-linux-gnu (64-bit) ## Running under: Ubuntu 20.04.5 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/liblapack.so.3 ## ## locale: ## [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C ## [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8 ## [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 ## ## attached base packages: ## [1] stats graphics grDevices utils datasets methods base ## ## other attached packages: ## [1] ggplot2_3.4.1 SeuratObject_4.1.3 Seurat_4.3.0 ## ## loaded via a namespace (and not attached): ## [1] Rtsne_0.16 colorspace_2.1-0 deldir_1.0-6 ## [4] ellipsis_0.3.2 ggridges_0.5.4 rprojroot_2.0.3 ## [7] fs_1.6.1 spatstat.data_3.0-0 farver_2.1.1 ## [10] leiden_0.4.3 listenv_0.9.0 bit64_4.0.5 ## [13] ggrepel_0.9.3 fansi_1.0.4 codetools_0.2-18 ## [16] splines_4.2.0 cachem_1.0.7 knitr_1.42 ## [19] polyclip_1.10-4 jsonlite_1.8.4 ica_1.0-3 ## [22] cluster_2.1.3 png_0.1-8 uwot_0.1.14 ## [25] spatstat.sparse_3.0-0 shiny_1.7.4 sctransform_0.3.5 ## [28] compiler_4.2.0 httr_1.4.5 Matrix_1.5-3 ## [31] fastmap_1.1.1 lazyeval_0.2.2 cli_3.6.0 ## [34] later_1.3.0 formatR_1.14 htmltools_0.5.4 ## [37] tools_4.2.0 igraph_1.4.1 gtable_0.3.1 ## [40] glue_1.6.2 RANN_2.6.1 reshape2_1.4.4 ## [43] dplyr_1.1.0 Rcpp_1.0.10 scattermore_0.8 ## [46] jquerylib_0.1.4 pkgdown_2.0.7 vctrs_0.5.2 ## [49] nlme_3.1-157 spatstat.explore_3.0-6 progressr_0.13.0 ## [52] lmtest_0.9-40 spatstat.random_3.1-3 xfun_0.37 ## [55] stringr_1.5.0 globals_0.16.2 mime_0.12 ## [58] miniUI_0.1.1.1 lifecycle_1.0.3 irlba_2.3.5.1 ## [61] goftest_1.2-3 future_1.31.0 MASS_7.3-56 ## [64] zoo_1.8-11 scales_1.2.1 ragg_1.2.5 ## [67] promises_1.2.0.1 spatstat.utils_3.0-1 parallel_4.2.0 ## [70] RColorBrewer_1.1-3 yaml_2.3.7 memoise_2.0.1 ## [73] reticulate_1.28 pbapply_1.7-0 gridExtra_2.3 ## [76] sass_0.4.5 stringi_1.7.12 highr_0.10 ## [79] desc_1.4.2 rlang_1.0.6 pkgconfig_2.0.3 ## [82] systemfonts_1.0.4 matrixStats_0.63.0 evaluate_0.20 ## [85] lattice_0.20-45 tensor_1.5 ROCR_1.0-11 ## [88] purrr_1.0.1 labeling_0.4.2 patchwork_1.1.2 ## [91] htmlwidgets_1.6.1 bit_4.0.5 cowplot_1.1.1 ## [94] tidyselect_1.2.0 parallelly_1.34.0 RcppAnnoy_0.0.20 ## [97] plyr_1.8.8 magrittr_2.0.3 R6_2.5.1 ## [100] generics_0.1.3 withr_2.5.0 pillar_1.8.1 ## [103] fitdistrplus_1.1-8 abind_1.4-5 survival_3.3-1 ## [106] sp_1.6-0 tibble_3.1.8 future.apply_1.10.0 ## [109] hdf5r_1.3.8 KernSmooth_2.23-20 utf8_1.2.3 ## [112] spatstat.geom_3.0-6 plotly_4.10.1 rmarkdown_2.20 ## [115] grid_4.2.0 data.table_1.14.8 digest_0.6.31 ## [118] xtable_1.8-4 tidyr_1.3.0 httpuv_1.6.9 ## [121] textshaping_0.3.6 munsell_0.5.0 viridisLite_0.4.1 ## [124] bslib_0.4.2

After acquiring the data, we first perform standard normalization and variable feature selection. bm280k.data <- Read10X_h5("../data/ica_bone_marrow_h5.h5") bm280k <- CreateSeuratObject(counts = bm280k.data, min.cells = 100, min.features = 500) bm280k.list <- SplitObject(bm280k, split.by = "orig.ident") bm280k.list <- lapply(X = bm280k.list, FUN = function(x) { x <- NormalizeData(x, verbose = FALSE) x <- FindVariableFeatures(x, verbose = FALSE) })Next, select features for downstream integration, and run PCA on each object in the list, which is required for running the alternative reciprocal PCA workflow. features <- SelectIntegrationFeatures(object.list = bm280k.list) bm280k.list <- lapply(X = bm280k.list, FUN = function(x) { x <- ScaleData(x, features = features, verbose = FALSE) x <- RunPCA(x, features = features, verbose = FALSE) })Since this dataset contains both men and women, we will chose one male and one female (BM1 and BM2) to use in a reference-based workflow. We determined donor sex by examining the expression of the XIST gene. anchors <- FindIntegrationAnchors(object.list = bm280k.list, reference = c(1, 2), reduction = "rpca", dims = 1:50) bm280k.integrated <- IntegrateData(anchorset = anchors, dims = 1:50) bm280k.integrated <- ScaleData(bm280k.integrated, verbose = FALSE) bm280k.integrated <- RunPCA(bm280k.integrated, verbose = FALSE) bm280k.integrated <- RunUMAP(bm280k.integrated, dims = 1:50) DimPlot(bm280k.integrated, group.by = "orig.ident")Session Info sessionInfo()## R version 4.2.0 (2022-04-22) ## Platform: x86_64-pc-linux-gnu (64-bit) ## Running under: Ubuntu 20.04.5 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/liblapack.so.3 ## ## locale: ## [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C ## [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8 ## [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 ## ## attached base packages: ## [1] stats graphics grDevices utils datasets methods base ## ## other attached packages: ## [1] ggplot2_3.4.1 SeuratObject_4.1.3 Seurat_4.3.0 ## ## loaded via a namespace (and not attached): ## [1] Rtsne_0.16 colorspace_2.1-0 deldir_1.0-6 ## [4] ellipsis_0.3.2 ggridges_0.5.4 rprojroot_2.0.3 ## [7] fs_1.6.1 spatstat.data_3.0-0 farver_2.1.1 ## [10] leiden_0.4.3 listenv_0.9.0 bit64_4.0.5 ## [13] ggrepel_0.9.3 fansi_1.0.4 codetools_0.2-18 ## [16] splines_4.2.0 cachem_1.0.7 knitr_1.42 ## [19] polyclip_1.10-4 jsonlite_1.8.4 ica_1.0-3 ## [22] cluster_2.1.3 png_0.1-8 uwot_0.1.14 ## [25] spatstat.sparse_3.0-0 shiny_1.7.4 sctransform_0.3.5 ## [28] compiler_4.2.0 httr_1.4.5 Matrix_1.5-3 ## [31] fastmap_1.1.1 lazyeval_0.2.2 cli_3.6.0 ## [34] later_1.3.0 formatR_1.14 htmltools_0.5.4 ## [37] tools_4.2.0 igraph_1.4.1 gtable_0.3.1 ## [40] glue_1.6.2 RANN_2.6.1 reshape2_1.4.4 ## [43] dplyr_1.1.0 Rcpp_1.0.10 scattermore_0.8 ## [46] jquerylib_0.1.4 pkgdown_2.0.7 vctrs_0.5.2 ## [49] nlme_3.1-157 spatstat.explore_3.0-6 progressr_0.13.0 ## [52] lmtest_0.9-40 spatstat.random_3.1-3 xfun_0.37 ## [55] stringr_1.5.0 globals_0.16.2 mime_0.12 ## [58] miniUI_0.1.1.1 lifecycle_1.0.3 irlba_2.3.5.1 ## [61] goftest_1.2-3 future_1.31.0 MASS_7.3-56 ## [64] zoo_1.8-11 scales_1.2.1 ragg_1.2.5 ## [67] promises_1.2.0.1 spatstat.utils_3.0-1 parallel_4.2.0 ## [70] RColorBrewer_1.1-3 yaml_2.3.7 memoise_2.0.1 ## [73] reticulate_1.28 pbapply_1.7-0 gridExtra_2.3 ## [76] sass_0.4.5 stringi_1.7.12 highr_0.10 ## [79] desc_1.4.2 rlang_1.0.6 pkgconfig_2.0.3 ## [82] systemfonts_1.0.4 matrixStats_0.63.0 evaluate_0.20 ## [85] lattice_0.20-45 tensor_1.5 ROCR_1.0-11 ## [88] purrr_1.0.1 labeling_0.4.2 patchwork_1.1.2 ## [91] htmlwidgets_1.6.1 bit_4.0.5 cowplot_1.1.1 ## [94] tidyselect_1.2.0 parallelly_1.34.0 RcppAnnoy_0.0.20 ## [97] plyr_1.8.8 magrittr_2.0.3 R6_2.5.1 ## [100] generics_0.1.3 withr_2.5.0 pillar_1.8.1 ## [103] fitdistrplus_1.1-8 abind_1.4-5 survival_3.3-1 ## [106] sp_1.6-0 tibble_3.1.8 future.apply_1.10.0 ## [109] hdf5r_1.3.8 KernSmooth_2.23-20 utf8_1.2.3 ## [112] spatstat.geom_3.0-6 plotly_4.10.1 rmarkdown_2.20 ## [115] grid_4.2.0 data.table_1.14.8 digest_0.6.31 ## [118] xtable_1.8-4 tidyr_1.3.0 httpuv_1.6.9 ## [121] textshaping_0.3.6 munsell_0.5.0 viridisLite_0.4.1 ## [124] bslib_0.4.2

Next, select features for downstream integration, and run PCA on each object in the list, which is required for running the alternative reciprocal PCA workflow. features <- SelectIntegrationFeatures(object.list = bm280k.list) bm280k.list <- lapply(X = bm280k.list, FUN = function(x) { x <- ScaleData(x, features = features, verbose = FALSE) x <- RunPCA(x, features = features, verbose = FALSE) })Since this dataset contains both men and women, we will chose one male and one female (BM1 and BM2) to use in a reference-based workflow. We determined donor sex by examining the expression of the XIST gene. anchors <- FindIntegrationAnchors(object.list = bm280k.list, reference = c(1, 2), reduction = "rpca", dims = 1:50) bm280k.integrated <- IntegrateData(anchorset = anchors, dims = 1:50) bm280k.integrated <- ScaleData(bm280k.integrated, verbose = FALSE) bm280k.integrated <- RunPCA(bm280k.integrated, verbose = FALSE) bm280k.integrated <- RunUMAP(bm280k.integrated, dims = 1:50) DimPlot(bm280k.integrated, group.by = "orig.ident")Session Info sessionInfo()## R version 4.2.0 (2022-04-22) ## Platform: x86_64-pc-linux-gnu (64-bit) ## Running under: Ubuntu 20.04.5 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/liblapack.so.3 ## ## locale: ## [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C ## [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8 ## [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 ## ## attached base packages: ## [1] stats graphics grDevices utils datasets methods base ## ## other attached packages: ## [1] ggplot2_3.4.1 SeuratObject_4.1.3 Seurat_4.3.0 ## ## loaded via a namespace (and not attached): ## [1] Rtsne_0.16 colorspace_2.1-0 deldir_1.0-6 ## [4] ellipsis_0.3.2 ggridges_0.5.4 rprojroot_2.0.3 ## [7] fs_1.6.1 spatstat.data_3.0-0 farver_2.1.1 ## [10] leiden_0.4.3 listenv_0.9.0 bit64_4.0.5 ## [13] ggrepel_0.9.3 fansi_1.0.4 codetools_0.2-18 ## [16] splines_4.2.0 cachem_1.0.7 knitr_1.42 ## [19] polyclip_1.10-4 jsonlite_1.8.4 ica_1.0-3 ## [22] cluster_2.1.3 png_0.1-8 uwot_0.1.14 ## [25] spatstat.sparse_3.0-0 shiny_1.7.4 sctransform_0.3.5 ## [28] compiler_4.2.0 httr_1.4.5 Matrix_1.5-3 ## [31] fastmap_1.1.1 lazyeval_0.2.2 cli_3.6.0 ## [34] later_1.3.0 formatR_1.14 htmltools_0.5.4 ## [37] tools_4.2.0 igraph_1.4.1 gtable_0.3.1 ## [40] glue_1.6.2 RANN_2.6.1 reshape2_1.4.4 ## [43] dplyr_1.1.0 Rcpp_1.0.10 scattermore_0.8 ## [46] jquerylib_0.1.4 pkgdown_2.0.7 vctrs_0.5.2 ## [49] nlme_3.1-157 spatstat.explore_3.0-6 progressr_0.13.0 ## [52] lmtest_0.9-40 spatstat.random_3.1-3 xfun_0.37 ## [55] stringr_1.5.0 globals_0.16.2 mime_0.12 ## [58] miniUI_0.1.1.1 lifecycle_1.0.3 irlba_2.3.5.1 ## [61] goftest_1.2-3 future_1.31.0 MASS_7.3-56 ## [64] zoo_1.8-11 scales_1.2.1 ragg_1.2.5 ## [67] promises_1.2.0.1 spatstat.utils_3.0-1 parallel_4.2.0 ## [70] RColorBrewer_1.1-3 yaml_2.3.7 memoise_2.0.1 ## [73] reticulate_1.28 pbapply_1.7-0 gridExtra_2.3 ## [76] sass_0.4.5 stringi_1.7.12 highr_0.10 ## [79] desc_1.4.2 rlang_1.0.6 pkgconfig_2.0.3 ## [82] systemfonts_1.0.4 matrixStats_0.63.0 evaluate_0.20 ## [85] lattice_0.20-45 tensor_1.5 ROCR_1.0-11 ## [88] purrr_1.0.1 labeling_0.4.2 patchwork_1.1.2 ## [91] htmlwidgets_1.6.1 bit_4.0.5 cowplot_1.1.1 ## [94] tidyselect_1.2.0 parallelly_1.34.0 RcppAnnoy_0.0.20 ## [97] plyr_1.8.8 magrittr_2.0.3 R6_2.5.1 ## [100] generics_0.1.3 withr_2.5.0 pillar_1.8.1 ## [103] fitdistrplus_1.1-8 abind_1.4-5 survival_3.3-1 ## [106] sp_1.6-0 tibble_3.1.8 future.apply_1.10.0 ## [109] hdf5r_1.3.8 KernSmooth_2.23-20 utf8_1.2.3 ## [112] spatstat.geom_3.0-6 plotly_4.10.1 rmarkdown_2.20 ## [115] grid_4.2.0 data.table_1.14.8 digest_0.6.31 ## [118] xtable_1.8-4 tidyr_1.3.0 httpuv_1.6.9 ## [121] textshaping_0.3.6 munsell_0.5.0 viridisLite_0.4.1 ## [124] bslib_0.4.2

Since this dataset contains both men and women, we will chose one male and one female (BM1 and BM2) to use in a reference-based workflow. We determined donor sex by examining the expression of the XIST gene. anchors <- FindIntegrationAnchors(object.list = bm280k.list, reference = c(1, 2), reduction = "rpca", dims = 1:50) bm280k.integrated <- IntegrateData(anchorset = anchors, dims = 1:50) bm280k.integrated <- ScaleData(bm280k.integrated, verbose = FALSE) bm280k.integrated <- RunPCA(bm280k.integrated, verbose = FALSE) bm280k.integrated <- RunUMAP(bm280k.integrated, dims = 1:50) DimPlot(bm280k.integrated, group.by = "orig.ident")Session Info sessionInfo()## R version 4.2.0 (2022-04-22) ## Platform: x86_64-pc-linux-gnu (64-bit) ## Running under: Ubuntu 20.04.5 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/liblapack.so.3 ## ## locale: ## [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C ## [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8 ## [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 ## ## attached base packages: ## [1] stats graphics grDevices utils datasets methods base ## ## other attached packages: ## [1] ggplot2_3.4.1 SeuratObject_4.1.3 Seurat_4.3.0 ## ## loaded via a namespace (and not attached): ## [1] Rtsne_0.16 colorspace_2.1-0 deldir_1.0-6 ## [4] ellipsis_0.3.2 ggridges_0.5.4 rprojroot_2.0.3 ## [7] fs_1.6.1 spatstat.data_3.0-0 farver_2.1.1 ## [10] leiden_0.4.3 listenv_0.9.0 bit64_4.0.5 ## [13] ggrepel_0.9.3 fansi_1.0.4 codetools_0.2-18 ## [16] splines_4.2.0 cachem_1.0.7 knitr_1.42 ## [19] polyclip_1.10-4 jsonlite_1.8.4 ica_1.0-3 ## [22] cluster_2.1.3 png_0.1-8 uwot_0.1.14 ## [25] spatstat.sparse_3.0-0 shiny_1.7.4 sctransform_0.3.5 ## [28] compiler_4.2.0 httr_1.4.5 Matrix_1.5-3 ## [31] fastmap_1.1.1 lazyeval_0.2.2 cli_3.6.0 ## [34] later_1.3.0 formatR_1.14 htmltools_0.5.4 ## [37] tools_4.2.0 igraph_1.4.1 gtable_0.3.1 ## [40] glue_1.6.2 RANN_2.6.1 reshape2_1.4.4 ## [43] dplyr_1.1.0 Rcpp_1.0.10 scattermore_0.8 ## [46] jquerylib_0.1.4 pkgdown_2.0.7 vctrs_0.5.2 ## [49] nlme_3.1-157 spatstat.explore_3.0-6 progressr_0.13.0 ## [52] lmtest_0.9-40 spatstat.random_3.1-3 xfun_0.37 ## [55] stringr_1.5.0 globals_0.16.2 mime_0.12 ## [58] miniUI_0.1.1.1 lifecycle_1.0.3 irlba_2.3.5.1 ## [61] goftest_1.2-3 future_1.31.0 MASS_7.3-56 ## [64] zoo_1.8-11 scales_1.2.1 ragg_1.2.5 ## [67] promises_1.2.0.1 spatstat.utils_3.0-1 parallel_4.2.0 ## [70] RColorBrewer_1.1-3 yaml_2.3.7 memoise_2.0.1 ## [73] reticulate_1.28 pbapply_1.7-0 gridExtra_2.3 ## [76] sass_0.4.5 stringi_1.7.12 highr_0.10 ## [79] desc_1.4.2 rlang_1.0.6 pkgconfig_2.0.3 ## [82] systemfonts_1.0.4 matrixStats_0.63.0 evaluate_0.20 ## [85] lattice_0.20-45 tensor_1.5 ROCR_1.0-11 ## [88] purrr_1.0.1 labeling_0.4.2 patchwork_1.1.2 ## [91] htmlwidgets_1.6.1 bit_4.0.5 cowplot_1.1.1 ## [94] tidyselect_1.2.0 parallelly_1.34.0 RcppAnnoy_0.0.20 ## [97] plyr_1.8.8 magrittr_2.0.3 R6_2.5.1 ## [100] generics_0.1.3 withr_2.5.0 pillar_1.8.1 ## [103] fitdistrplus_1.1-8 abind_1.4-5 survival_3.3-1 ## [106] sp_1.6-0 tibble_3.1.8 future.apply_1.10.0 ## [109] hdf5r_1.3.8 KernSmooth_2.23-20 utf8_1.2.3 ## [112] spatstat.geom_3.0-6 plotly_4.10.1 rmarkdown_2.20 ## [115] grid_4.2.0 data.table_1.14.8 digest_0.6.31 ## [118] xtable_1.8-4 tidyr_1.3.0 httpuv_1.6.9 ## [121] textshaping_0.3.6 munsell_0.5.0 viridisLite_0.4.1 ## [124] bslib_0.4.2

Session Info sessionInfo()## R version 4.2.0 (2022-04-22) ## Platform: x86_64-pc-linux-gnu (64-bit) ## Running under: Ubuntu 20.04.5 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/liblapack.so.3 ## ## locale: ## [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C ## [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8 ## [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 ## ## attached base packages: ## [1] stats graphics grDevices utils datasets methods base ## ## other attached packages: ## [1] ggplot2_3.4.1 SeuratObject_4.1.3 Seurat_4.3.0 ## ## loaded via a namespace (and not attached): ## [1] Rtsne_0.16 colorspace_2.1-0 deldir_1.0-6 ## [4] ellipsis_0.3.2 ggridges_0.5.4 rprojroot_2.0.3 ## [7] fs_1.6.1 spatstat.data_3.0-0 farver_2.1.1 ## [10] leiden_0.4.3 listenv_0.9.0 bit64_4.0.5 ## [13] ggrepel_0.9.3 fansi_1.0.4 codetools_0.2-18 ## [16] splines_4.2.0 cachem_1.0.7 knitr_1.42 ## [19] polyclip_1.10-4 jsonlite_1.8.4 ica_1.0-3 ## [22] cluster_2.1.3 png_0.1-8 uwot_0.1.14 ## [25] spatstat.sparse_3.0-0 shiny_1.7.4 sctransform_0.3.5 ## [28] compiler_4.2.0 httr_1.4.5 Matrix_1.5-3 ## [31] fastmap_1.1.1 lazyeval_0.2.2 cli_3.6.0 ## [34] later_1.3.0 formatR_1.14 htmltools_0.5.4 ## [37] tools_4.2.0 igraph_1.4.1 gtable_0.3.1 ## [40] glue_1.6.2 RANN_2.6.1 reshape2_1.4.4 ## [43] dplyr_1.1.0 Rcpp_1.0.10 scattermore_0.8 ## [46] jquerylib_0.1.4 pkgdown_2.0.7 vctrs_0.5.2 ## [49] nlme_3.1-157 spatstat.explore_3.0-6 progressr_0.13.0 ## [52] lmtest_0.9-40 spatstat.random_3.1-3 xfun_0.37 ## [55] stringr_1.5.0 globals_0.16.2 mime_0.12 ## [58] miniUI_0.1.1.1 lifecycle_1.0.3 irlba_2.3.5.1 ## [61] goftest_1.2-3 future_1.31.0 MASS_7.3-56 ## [64] zoo_1.8-11 scales_1.2.1 ragg_1.2.5 ## [67] promises_1.2.0.1 spatstat.utils_3.0-1 parallel_4.2.0 ## [70] RColorBrewer_1.1-3 yaml_2.3.7 memoise_2.0.1 ## [73] reticulate_1.28 pbapply_1.7-0 gridExtra_2.3 ## [76] sass_0.4.5 stringi_1.7.12 highr_0.10 ## [79] desc_1.4.2 rlang_1.0.6 pkgconfig_2.0.3 ## [82] systemfonts_1.0.4 matrixStats_0.63.0 evaluate_0.20 ## [85] lattice_0.20-45 tensor_1.5 ROCR_1.0-11 ## [88] purrr_1.0.1 labeling_0.4.2 patchwork_1.1.2 ## [91] htmlwidgets_1.6.1 bit_4.0.5 cowplot_1.1.1 ## [94] tidyselect_1.2.0 parallelly_1.34.0 RcppAnnoy_0.0.20 ## [97] plyr_1.8.8 magrittr_2.0.3 R6_2.5.1 ## [100] generics_0.1.3 withr_2.5.0 pillar_1.8.1 ## [103] fitdistrplus_1.1-8 abind_1.4-5 survival_3.3-1 ## [106] sp_1.6-0 tibble_3.1.8 future.apply_1.10.0 ## [109] hdf5r_1.3.8 KernSmooth_2.23-20 utf8_1.2.3 ## [112] spatstat.geom_3.0-6 plotly_4.10.1 rmarkdown_2.20 ## [115] grid_4.2.0 data.table_1.14.8 digest_0.6.31 ## [118] xtable_1.8-4 tidyr_1.3.0 httpuv_1.6.9 ## [121] textshaping_0.3.6 munsell_0.5.0 viridisLite_0.4.1 ## [124] bslib_0.4.2

sessionInfo()## R version 4.2.0 (2022-04-22) ## Platform: x86_64-pc-linux-gnu (64-bit) ## Running under: Ubuntu 20.04.5 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/liblapack.so.3 ## ## locale: ## [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C ## [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8 ## [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 ## ## attached base packages: ## [1] stats graphics grDevices utils datasets methods base ## ## other attached packages: ## [1] ggplot2_3.4.1 SeuratObject_4.1.3 Seurat_4.3.0 ## ## loaded via a namespace (and not attached): ## [1] Rtsne_0.16 colorspace_2.1-0 deldir_1.0-6 ## [4] ellipsis_0.3.2 ggridges_0.5.4 rprojroot_2.0.3 ## [7] fs_1.6.1 spatstat.data_3.0-0 farver_2.1.1 ## [10] leiden_0.4.3 listenv_0.9.0 bit64_4.0.5 ## [13] ggrepel_0.9.3 fansi_1.0.4 codetools_0.2-18 ## [16] splines_4.2.0 cachem_1.0.7 knitr_1.42 ## [19] polyclip_1.10-4 jsonlite_1.8.4 ica_1.0-3 ## [22] cluster_2.1.3 png_0.1-8 uwot_0.1.14 ## [25] spatstat.sparse_3.0-0 shiny_1.7.4 sctransform_0.3.5 ## [28] compiler_4.2.0 httr_1.4.5 Matrix_1.5-3 ## [31] fastmap_1.1.1 lazyeval_0.2.2 cli_3.6.0 ## [34] later_1.3.0 formatR_1.14 htmltools_0.5.4 ## [37] tools_4.2.0 igraph_1.4.1 gtable_0.3.1 ## [40] glue_1.6.2 RANN_2.6.1 reshape2_1.4.4 ## [43] dplyr_1.1.0 Rcpp_1.0.10 scattermore_0.8 ## [46] jquerylib_0.1.4 pkgdown_2.0.7 vctrs_0.5.2 ## [49] nlme_3.1-157 spatstat.explore_3.0-6 progressr_0.13.0 ## [52] lmtest_0.9-40 spatstat.random_3.1-3 xfun_0.37 ## [55] stringr_1.5.0 globals_0.16.2 mime_0.12 ## [58] miniUI_0.1.1.1 lifecycle_1.0.3 irlba_2.3.5.1 ## [61] goftest_1.2-3 future_1.31.0 MASS_7.3-56 ## [64] zoo_1.8-11 scales_1.2.1 ragg_1.2.5 ## [67] promises_1.2.0.1 spatstat.utils_3.0-1 parallel_4.2.0 ## [70] RColorBrewer_1.1-3 yaml_2.3.7 memoise_2.0.1 ## [73] reticulate_1.28 pbapply_1.7-0 gridExtra_2.3 ## [76] sass_0.4.5 stringi_1.7.12 highr_0.10 ## [79] desc_1.4.2 rlang_1.0.6 pkgconfig_2.0.3 ## [82] systemfonts_1.0.4 matrixStats_0.63.0 evaluate_0.20 ## [85] lattice_0.20-45 tensor_1.5 ROCR_1.0-11 ## [88] purrr_1.0.1 labeling_0.4.2 patchwork_1.1.2 ## [91] htmlwidgets_1.6.1 bit_4.0.5 cowplot_1.1.1 ## [94] tidyselect_1.2.0 parallelly_1.34.0 RcppAnnoy_0.0.20 ## [97] plyr_1.8.8 magrittr_2.0.3 R6_2.5.1 ## [100] generics_0.1.3 withr_2.5.0 pillar_1.8.1 ## [103] fitdistrplus_1.1-8 abind_1.4-5 survival_3.3-1 ## [106] sp_1.6-0 tibble_3.1.8 future.apply_1.10.0 ## [109] hdf5r_1.3.8 KernSmooth_2.23-20 utf8_1.2.3 ## [112] spatstat.geom_3.0-6 plotly_4.10.1 rmarkdown_2.20 ## [115] grid_4.2.0 data.table_1.14.8 digest_0.6.31 ## [118] xtable_1.8-4 tidyr_1.3.0 httpuv_1.6.9 ## [121] textshaping_0.3.6 munsell_0.5.0 viridisLite_0.4.1 ## [124] bslib_0.4.2

Developed by Paul Hoffman, Satija Lab and Collaborators.

Developed by Paul Hoffman, Satija Lab and Collaborators.

Site built with pkgdown 2.0.7.

Site built with pkgdown 2.0.7.

**Examples:**

Example 1 (unknown):
```unknown
vignettes/integration_large_datasets.Rmd
```

Example 2 (unknown):
```unknown
integration_large_datasets.Rmd
```

Example 3 (unknown):
```unknown
FindIntegrationAnchors()
```

Example 4 (unknown):
```unknown
library(Seurat)
```

Example 5 (r):
```r
library(Seurat)
```

Example 6 (r):
```r
library(Seurat)
```

Example 7 (javascript):
```javascript
bm280k.data <- Read10X_h5("../data/ica_bone_marrow_h5.h5")
bm280k <- CreateSeuratObject(counts = bm280k.data, min.cells = 100, min.features = 500)
bm280k.list <- SplitObject(bm280k, split.by = "orig.ident")
bm280k.list <- lapply(X = bm280k.list, FUN = function(x) {
    x <- NormalizeData(x, verbose = FALSE)
    x <- FindVariableFeatures(x, verbose = FALSE)
})
```

Example 8 (r):
```r
bm280k.data <- Read10X_h5("../data/ica_bone_marrow_h5.h5")
bm280k <- CreateSeuratObject(counts = bm280k.data, min.cells = 100, min.features = 500)
bm280k.list <- SplitObject(bm280k, split.by = "orig.ident")
bm280k.list <- lapply(X = bm280k.list, FUN = function(x) {
    x <- NormalizeData(x, verbose = FALSE)
    x <- FindVariableFeatures(x, verbose = FALSE)
})
```

Example 9 (r):
```r
bm280k.data <- Read10X_h5("../data/ica_bone_marrow_h5.h5")
bm280k <- CreateSeuratObject(counts = bm280k.data, min.cells = 100, min.features = 500)
bm280k.list <- SplitObject(bm280k, split.by = "orig.ident")
bm280k.list <- lapply(X = bm280k.list, FUN = function(x) {
    x <- NormalizeData(x, verbose = FALSE)
    x <- FindVariableFeatures(x, verbose = FALSE)
})
```

Example 10 (javascript):
```javascript
features <- SelectIntegrationFeatures(object.list = bm280k.list)
bm280k.list <- lapply(X = bm280k.list, FUN = function(x) {
    x <- ScaleData(x, features = features, verbose = FALSE)
    x <- RunPCA(x, features = features, verbose = FALSE)
})
```

Example 11 (r):
```r
features <- SelectIntegrationFeatures(object.list = bm280k.list)
bm280k.list <- lapply(X = bm280k.list, FUN = function(x) {
    x <- ScaleData(x, features = features, verbose = FALSE)
    x <- RunPCA(x, features = features, verbose = FALSE)
})
```

Example 12 (r):
```r
features <- SelectIntegrationFeatures(object.list = bm280k.list)
bm280k.list <- lapply(X = bm280k.list, FUN = function(x) {
    x <- ScaleData(x, features = features, verbose = FALSE)
    x <- RunPCA(x, features = features, verbose = FALSE)
})
```

Example 13 (unknown):
```unknown
anchors <- FindIntegrationAnchors(object.list = bm280k.list, reference = c(1, 2), reduction = "rpca",
    dims = 1:50)
bm280k.integrated <- IntegrateData(anchorset = anchors, dims = 1:50)
```

Example 14 (r):
```r
anchors <- FindIntegrationAnchors(object.list = bm280k.list, reference = c(1, 2), reduction = "rpca",
    dims = 1:50)
bm280k.integrated <- IntegrateData(anchorset = anchors, dims = 1:50)
```

Example 15 (r):
```r
anchors <- FindIntegrationAnchors(object.list = bm280k.list, reference = c(1, 2), reduction = "rpca",
    dims = 1:50)
bm280k.integrated <- IntegrateData(anchorset = anchors, dims = 1:50)
```

Example 16 (unknown):
```unknown
bm280k.integrated <- ScaleData(bm280k.integrated, verbose = FALSE)
bm280k.integrated <- RunPCA(bm280k.integrated, verbose = FALSE)
bm280k.integrated <- RunUMAP(bm280k.integrated, dims = 1:50)
```

Example 17 (r):
```r
bm280k.integrated <- ScaleData(bm280k.integrated, verbose = FALSE)
bm280k.integrated <- RunPCA(bm280k.integrated, verbose = FALSE)
bm280k.integrated <- RunUMAP(bm280k.integrated, dims = 1:50)
```

Example 18 (r):
```r
bm280k.integrated <- ScaleData(bm280k.integrated, verbose = FALSE)
bm280k.integrated <- RunPCA(bm280k.integrated, verbose = FALSE)
bm280k.integrated <- RunUMAP(bm280k.integrated, dims = 1:50)
```

Example 19 (unknown):
```unknown
DimPlot(bm280k.integrated, group.by = "orig.ident")
```

Example 20 (r):
```r
DimPlot(bm280k.integrated, group.by = "orig.ident")
```

Example 21 (r):
```r
DimPlot(bm280k.integrated, group.by = "orig.ident")
```

Example 22 (unknown):
```unknown
sessionInfo()
```

Example 23 (r):
```r
sessionInfo()
```

Example 24 (r):
```r
sessionInfo()
```

Example 25 (unknown):
```unknown
## R version 4.2.0 (2022-04-22)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.5 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/liblapack.so.3
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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       
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
## [1] ggplot2_3.4.1      SeuratObject_4.1.3 Seurat_4.3.0      
## 
## loaded via a namespace (and not attached):
##   [1] Rtsne_0.16             colorspace_2.1-0       deldir_1.0-6          
##   [4] ellipsis_0.3.2         ggridges_0.5.4         rprojroot_2.0.3       
##   [7] fs_1.6.1               spatstat.data_3.0-0    farver_2.1.1          
##  [10] leiden_0.4.3           listenv_0.9.0          bit64_4.0.5           
##  [13] ggrepel_0.9.3          fansi_1.0.4            codetools_0.2-18      
##  [16] splines_4.2.0          cachem_1.0.7           knitr_1.42            
##  [19] polyclip_1.10-4        jsonlite_1.8.4         ica_1.0-3             
##  [22] cluster_2.1.3          png_0.1-8              uwot_0.1.14           
##  [25] spatstat.sparse_3.0-0  shiny_1.7.4            sctransform_0.3.5     
##  [28] compiler_4.2.0         httr_1.4.5             Matrix_1.5-3          
##  [31] fastmap_1.1.1          lazyeval_0.2.2         cli_3.6.0             
##  [34] later_1.3.0            formatR_1.14           htmltools_0.5.4       
##  [37] tools_4.2.0            igraph_1.4.1           gtable_0.3.1          
##  [40] glue_1.6.2             RANN_2.6.1             reshape2_1.4.4        
##  [43] dplyr_1.1.0            Rcpp_1.0.10            scattermore_0.8       
##  [46] jquerylib_0.1.4        pkgdown_2.0.7          vctrs_0.5.2           
##  [49] nlme_3.1-157           spatstat.explore_3.0-6 progressr_0.13.0      
##  [52] lmtest_0.9-40          spatstat.random_3.1-3  xfun_0.37             
##  [55] stringr_1.5.0          globals_0.16.2         mime_0.12             
##  [58] miniUI_0.1.1.1         lifecycle_1.0.3        irlba_2.3.5.1         
##  [61] goftest_1.2-3          future_1.31.0          MASS_7.3-56           
##  [64] zoo_1.8-11             scales_1.2.1           ragg_1.2.5            
##  [67] promises_1.2.0.1       spatstat.utils_3.0-1   parallel_4.2.0        
##  [70] RColorBrewer_1.1-3     yaml_2.3.7             memoise_2.0.1         
##  [73] reticulate_1.28        pbapply_1.7-0          gridExtra_2.3         
##  [76] sass_0.4.5             stringi_1.7.12         highr_0.10            
##  [79] desc_1.4.2             rlang_1.0.6            pkgconfig_2.0.3       
##  [82] systemfonts_1.0.4      matrixStats_0.63.0     evaluate_0.20         
##  [85] lattice_0.20-45        tensor_1.5             ROCR_1.0-11           
##  [88] purrr_1.0.1            labeling_0.4.2         patchwork_1.1.2       
##  [91] htmlwidgets_1.6.1      bit_4.0.5              cowplot_1.1.1         
##  [94] tidyselect_1.2.0       parallelly_1.34.0      RcppAnnoy_0.0.20      
##  [97] plyr_1.8.8             magrittr_2.0.3         R6_2.5.1              
## [100] generics_0.1.3         withr_2.5.0            pillar_1.8.1          
## [103] fitdistrplus_1.1-8     abind_1.4-5            survival_3.3-1        
## [106] sp_1.6-0               tibble_3.1.8           future.apply_1.10.0   
## [109] hdf5r_1.3.8            KernSmooth_2.23-20     utf8_1.2.3            
## [112] spatstat.geom_3.0-6    plotly_4.10.1          rmarkdown_2.20        
## [115] grid_4.2.0             data.table_1.14.8      digest_0.6.31         
## [118] xtable_1.8-4           tidyr_1.3.0            httpuv_1.6.9          
## [121] textshaping_0.3.6      munsell_0.5.0          viridisLite_0.4.1     
## [124] bslib_0.4.2
```

Example 26 (unknown):
```unknown
## R version 4.2.0 (2022-04-22)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.5 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/liblapack.so.3
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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       
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
## [1] ggplot2_3.4.1      SeuratObject_4.1.3 Seurat_4.3.0      
## 
## loaded via a namespace (and not attached):
##   [1] Rtsne_0.16             colorspace_2.1-0       deldir_1.0-6          
##   [4] ellipsis_0.3.2         ggridges_0.5.4         rprojroot_2.0.3       
##   [7] fs_1.6.1               spatstat.data_3.0-0    farver_2.1.1          
##  [10] leiden_0.4.3           listenv_0.9.0          bit64_4.0.5           
##  [13] ggrepel_0.9.3          fansi_1.0.4            codetools_0.2-18      
##  [16] splines_4.2.0          cachem_1.0.7           knitr_1.42            
##  [19] polyclip_1.10-4        jsonlite_1.8.4         ica_1.0-3             
##  [22] cluster_2.1.3          png_0.1-8              uwot_0.1.14           
##  [25] spatstat.sparse_3.0-0  shiny_1.7.4            sctransform_0.3.5     
##  [28] compiler_4.2.0         httr_1.4.5             Matrix_1.5-3          
##  [31] fastmap_1.1.1          lazyeval_0.2.2         cli_3.6.0             
##  [34] later_1.3.0            formatR_1.14           htmltools_0.5.4       
##  [37] tools_4.2.0            igraph_1.4.1           gtable_0.3.1          
##  [40] glue_1.6.2             RANN_2.6.1             reshape2_1.4.4        
##  [43] dplyr_1.1.0            Rcpp_1.0.10            scattermore_0.8       
##  [46] jquerylib_0.1.4        pkgdown_2.0.7          vctrs_0.5.2           
##  [49] nlme_3.1-157           spatstat.explore_3.0-6 progressr_0.13.0      
##  [52] lmtest_0.9-40          spatstat.random_3.1-3  xfun_0.37             
##  [55] stringr_1.5.0          globals_0.16.2         mime_0.12             
##  [58] miniUI_0.1.1.1         lifecycle_1.0.3        irlba_2.3.5.1         
##  [61] goftest_1.2-3          future_1.31.0          MASS_7.3-56           
##  [64] zoo_1.8-11             scales_1.2.1           ragg_1.2.5            
##  [67] promises_1.2.0.1       spatstat.utils_3.0-1   parallel_4.2.0        
##  [70] RColorBrewer_1.1-3     yaml_2.3.7             memoise_2.0.1         
##  [73] reticulate_1.28        pbapply_1.7-0          gridExtra_2.3         
##  [76] sass_0.4.5             stringi_1.7.12         highr_0.10            
##  [79] desc_1.4.2             rlang_1.0.6            pkgconfig_2.0.3       
##  [82] systemfonts_1.0.4      matrixStats_0.63.0     evaluate_0.20         
##  [85] lattice_0.20-45        tensor_1.5             ROCR_1.0-11           
##  [88] purrr_1.0.1            labeling_0.4.2         patchwork_1.1.2       
##  [91] htmlwidgets_1.6.1      bit_4.0.5              cowplot_1.1.1         
##  [94] tidyselect_1.2.0       parallelly_1.34.0      RcppAnnoy_0.0.20      
##  [97] plyr_1.8.8             magrittr_2.0.3         R6_2.5.1              
## [100] generics_0.1.3         withr_2.5.0            pillar_1.8.1          
## [103] fitdistrplus_1.1-8     abind_1.4-5            survival_3.3-1        
## [106] sp_1.6-0               tibble_3.1.8           future.apply_1.10.0   
## [109] hdf5r_1.3.8            KernSmooth_2.23-20     utf8_1.2.3            
## [112] spatstat.geom_3.0-6    plotly_4.10.1          rmarkdown_2.20        
## [115] grid_4.2.0             data.table_1.14.8      digest_0.6.31         
## [118] xtable_1.8-4           tidyr_1.3.0            httpuv_1.6.9          
## [121] textshaping_0.3.6      munsell_0.5.0          viridisLite_0.4.1     
## [124] bslib_0.4.2
```

---

## Analysis, visualization, and integration of Visium HD spatial datasets with Seurat • Seurat

**URL:** http://127.0.0.1:9173/articles_hashing_vignette.html

**Contents:**
- Demultiplexing with hashtag oligos (HTOs)
    - Compiled: 2023-11-14
- 8-HTO dataset from human PBMCs
  - Basic setup
  - Adding HTO data as an independent assay
  - Demultiplex cells based on HTO enrichment
  - Visualize demultiplexing results
- 12-HTO dataset from four human cell lines
  - Create Seurat object, add HTO data and perform normalization
  - Demultiplex data
  - Visualize demultiplexing results
  - Visualize RNA clustering
- Contents

Developed in collaboration with the Technology Innovation Group at NYGC, Cell Hashing uses oligo-tagged antibodies against ubiquitously expressed surface proteins to place a “sample barcode” on each single cell, enabling different samples to be multiplexed together and run in a single experiment. For more information, please refer to this paper.

This vignette will give a brief demonstration on how to work with data produced with Cell Hashing in Seurat. Applied to two datasets, we can successfully demultiplex cells to their the original sample-of-origin, and identify cross-sample doublets.

Setup Seurat object and add in the HTO data

You can read more about working with multi-modal data here

Here we use the Seurat function HTODemux() to assign single cells back to their sample origins.

Output from running HTODemux() is saved in the object metadata. We can visualize how many cells are classified as singlets, doublets and negative/ambiguous cells.

Visualize enrichment for selected HTOs with ridge plots

Visualize pairs of HTO signals to confirm mutual exclusivity in singlets

Compare number of UMIs for singlets, doublets and negative cells

Generate a two dimensional tSNE embedding for HTOs. Here we are grouping cells by singlets and doublets for simplicity.

Create an HTO heatmap, based on Figure 1C in the Cell Hashing paper.

Cluster and visualize cells using the usual scRNA-seq workflow, and examine for the potential presence of batch effects.

Distribution of selected HTOs grouped by classification, displayed by ridge plots

Visualize HTO signals in a heatmap

Developed by Rahul Satija, Satija Lab and Collaborators.

Site built with pkgdown 2.0.7.

**Examples:**

Example 1 (unknown):
```unknown
vignettes/hashing_vignette.Rmd
```

Example 2 (unknown):
```unknown
hashing_vignette.Rmd
```

Example 3 (unknown):
```unknown
library(Seurat)
```

Example 4 (r):
```r
library(Seurat)
```

Example 5 (r):
```r
library(Seurat)
```

Example 6 (python):
```python
# Load in the UMI matrix
pbmc.umis <- readRDS("/brahms/shared/vignette-data/pbmc_umi_mtx.rds")

# For generating a hashtag count matrix from FASTQ files, please refer to
# https://github.com/Hoohm/CITE-seq-Count.  Load in the HTO count matrix
pbmc.htos <- readRDS("/brahms/shared/vignette-data/pbmc_hto_mtx.rds")

# Select cell barcodes detected by both RNA and HTO In the example datasets we have already
# filtered the cells for you, but perform this step for clarity.
joint.bcs <- intersect(colnames(pbmc.umis), colnames(pbmc.htos))

# Subset RNA and HTO counts by joint cell barcodes
pbmc.umis <- pbmc.umis[, joint.bcs]
pbmc.htos <- as.matrix(pbmc.htos[, joint.bcs])

# Confirm that the HTO have the correct names
rownames(pbmc.htos)
```

Example 7 (r):
```r
# Load in the UMI matrix
pbmc.umis <- readRDS("/brahms/shared/vignette-data/pbmc_umi_mtx.rds")

# For generating a hashtag count matrix from FASTQ files, please refer to
# https://github.com/Hoohm/CITE-seq-Count.  Load in the HTO count matrix
pbmc.htos <- readRDS("/brahms/shared/vignette-data/pbmc_hto_mtx.rds")

# Select cell barcodes detected by both RNA and HTO In the example datasets we have already
# filtered the cells for you, but perform this step for clarity.
joint.bcs <- intersect(colnames(pbmc.umis), colnames(pbmc.htos))

# Subset RNA and HTO counts by joint cell barcodes
pbmc.umis <- pbmc.umis[, joint.bcs]
pbmc.htos <- as.matrix(pbmc.htos[, joint.bcs])

# Confirm that the HTO have the correct names
rownames(pbmc.htos)
```

Example 8 (r):
```r
# Load in the UMI matrix
pbmc.umis <- readRDS("/brahms/shared/vignette-data/pbmc_umi_mtx.rds")

# For generating a hashtag count matrix from FASTQ files, please refer to
# https://github.com/Hoohm/CITE-seq-Count.  Load in the HTO count matrix
pbmc.htos <- readRDS("/brahms/shared/vignette-data/pbmc_hto_mtx.rds")

# Select cell barcodes detected by both RNA and HTO In the example datasets we have already
# filtered the cells for you, but perform this step for clarity.
joint.bcs <- intersect(colnames(pbmc.umis), colnames(pbmc.htos))

# Subset RNA and HTO counts by joint cell barcodes
pbmc.umis <- pbmc.umis[, joint.bcs]
pbmc.htos <- as.matrix(pbmc.htos[, joint.bcs])

# Confirm that the HTO have the correct names
rownames(pbmc.htos)
```

Example 9 (unknown):
```unknown
## [1] "HTO_A" "HTO_B" "HTO_C" "HTO_D" "HTO_E" "HTO_F" "HTO_G" "HTO_H"
```

Example 10 (unknown):
```unknown
## [1] "HTO_A" "HTO_B" "HTO_C" "HTO_D" "HTO_E" "HTO_F" "HTO_G" "HTO_H"
```

Example 11 (unknown):
```unknown
# Setup Seurat object
pbmc.hashtag <- CreateSeuratObject(counts = Matrix::Matrix(as.matrix(pbmc.umis), sparse = T))

# Normalize RNA data with log normalization
pbmc.hashtag <- NormalizeData(pbmc.hashtag)
# Find and scale variable features
pbmc.hashtag <- FindVariableFeatures(pbmc.hashtag, selection.method = "mean.var.plot")
pbmc.hashtag <- ScaleData(pbmc.hashtag, features = VariableFeatures(pbmc.hashtag))
```

Example 12 (r):
```r
# Setup Seurat object
pbmc.hashtag <- CreateSeuratObject(counts = Matrix::Matrix(as.matrix(pbmc.umis), sparse = T))

# Normalize RNA data with log normalization
pbmc.hashtag <- NormalizeData(pbmc.hashtag)
# Find and scale variable features
pbmc.hashtag <- FindVariableFeatures(pbmc.hashtag, selection.method = "mean.var.plot")
pbmc.hashtag <- ScaleData(pbmc.hashtag, features = VariableFeatures(pbmc.hashtag))
```

Example 13 (r):
```r
# Setup Seurat object
pbmc.hashtag <- CreateSeuratObject(counts = Matrix::Matrix(as.matrix(pbmc.umis), sparse = T))

# Normalize RNA data with log normalization
pbmc.hashtag <- NormalizeData(pbmc.hashtag)
# Find and scale variable features
pbmc.hashtag <- FindVariableFeatures(pbmc.hashtag, selection.method = "mean.var.plot")
pbmc.hashtag <- ScaleData(pbmc.hashtag, features = VariableFeatures(pbmc.hashtag))
```

Example 14 (python):
```python
# Add HTO data as a new assay independent from RNA
pbmc.hashtag[["HTO"]] <- CreateAssayObject(counts = pbmc.htos)
# Normalize HTO data, here we use centered log-ratio (CLR) transformation
pbmc.hashtag <- NormalizeData(pbmc.hashtag, assay = "HTO", normalization.method = "CLR")
```

Example 15 (r):
```r
# Add HTO data as a new assay independent from RNA
pbmc.hashtag[["HTO"]] <- CreateAssayObject(counts = pbmc.htos)
# Normalize HTO data, here we use centered log-ratio (CLR) transformation
pbmc.hashtag <- NormalizeData(pbmc.hashtag, assay = "HTO", normalization.method = "CLR")
```

Example 16 (r):
```r
# Add HTO data as a new assay independent from RNA
pbmc.hashtag[["HTO"]] <- CreateAssayObject(counts = pbmc.htos)
# Normalize HTO data, here we use centered log-ratio (CLR) transformation
pbmc.hashtag <- NormalizeData(pbmc.hashtag, assay = "HTO", normalization.method = "CLR")
```

Example 17 (unknown):
```unknown
# If you have a very large dataset we suggest using k_function = 'clara'. This is a k-medoid
# clustering function for large applications You can also play with additional parameters (see
# documentation for HTODemux()) to adjust the threshold for classification Here we are using
# the default settings
pbmc.hashtag <- HTODemux(pbmc.hashtag, assay = "HTO", positive.quantile = 0.99)
```

Example 18 (r):
```r
# If you have a very large dataset we suggest using k_function = 'clara'. This is a k-medoid
# clustering function for large applications You can also play with additional parameters (see
# documentation for HTODemux()) to adjust the threshold for classification Here we are using
# the default settings
pbmc.hashtag <- HTODemux(pbmc.hashtag, assay = "HTO", positive.quantile = 0.99)
```

Example 19 (r):
```r
# If you have a very large dataset we suggest using k_function = 'clara'. This is a k-medoid
# clustering function for large applications You can also play with additional parameters (see
# documentation for HTODemux()) to adjust the threshold for classification Here we are using
# the default settings
pbmc.hashtag <- HTODemux(pbmc.hashtag, assay = "HTO", positive.quantile = 0.99)
```

Example 20 (unknown):
```unknown
# Global classification results
table(pbmc.hashtag$HTO_classification.global)
```

Example 21 (r):
```r
# Global classification results
table(pbmc.hashtag$HTO_classification.global)
```

Example 22 (r):
```r
# Global classification results
table(pbmc.hashtag$HTO_classification.global)
```

Example 23 (javascript):
```javascript
## 
##  Doublet Negative  Singlet 
##     2598      346    13972
```

Example 24 (javascript):
```javascript
## 
##  Doublet Negative  Singlet 
##     2598      346    13972
```

Example 25 (unknown):
```unknown
# Group cells based on the max HTO signal
Idents(pbmc.hashtag) <- "HTO_maxID"
RidgePlot(pbmc.hashtag, assay = "HTO", features = rownames(pbmc.hashtag[["HTO"]])[1:2], ncol = 2)
```

Example 26 (r):
```r
# Group cells based on the max HTO signal
Idents(pbmc.hashtag) <- "HTO_maxID"
RidgePlot(pbmc.hashtag, assay = "HTO", features = rownames(pbmc.hashtag[["HTO"]])[1:2], ncol = 2)
```

Example 27 (r):
```r
# Group cells based on the max HTO signal
Idents(pbmc.hashtag) <- "HTO_maxID"
RidgePlot(pbmc.hashtag, assay = "HTO", features = rownames(pbmc.hashtag[["HTO"]])[1:2], ncol = 2)
```

Example 28 (unknown):
```unknown
FeatureScatter(pbmc.hashtag, feature1 = "hto_HTO-A", feature2 = "hto_HTO-B")
```

Example 29 (r):
```r
FeatureScatter(pbmc.hashtag, feature1 = "hto_HTO-A", feature2 = "hto_HTO-B")
```

Example 30 (r):
```r
FeatureScatter(pbmc.hashtag, feature1 = "hto_HTO-A", feature2 = "hto_HTO-B")
```

Example 31 (unknown):
```unknown
Idents(pbmc.hashtag) <- "HTO_classification.global"
VlnPlot(pbmc.hashtag, features = "nCount_RNA", pt.size = 0.1, log = TRUE)
```

Example 32 (r):
```r
Idents(pbmc.hashtag) <- "HTO_classification.global"
VlnPlot(pbmc.hashtag, features = "nCount_RNA", pt.size = 0.1, log = TRUE)
```

Example 33 (r):
```r
Idents(pbmc.hashtag) <- "HTO_classification.global"
VlnPlot(pbmc.hashtag, features = "nCount_RNA", pt.size = 0.1, log = TRUE)
```

Example 34 (python):
```python
# First, we will remove negative cells from the object
pbmc.hashtag.subset <- subset(pbmc.hashtag, idents = "Negative", invert = TRUE)

# Calculate a tSNE embedding of the HTO data
DefaultAssay(pbmc.hashtag.subset) <- "HTO"
pbmc.hashtag.subset <- ScaleData(pbmc.hashtag.subset, features = rownames(pbmc.hashtag.subset),
    verbose = FALSE)
pbmc.hashtag.subset <- RunPCA(pbmc.hashtag.subset, features = rownames(pbmc.hashtag.subset), approx = FALSE)
pbmc.hashtag.subset <- RunTSNE(pbmc.hashtag.subset, dims = 1:8, perplexity = 100)
DimPlot(pbmc.hashtag.subset)
```

Example 35 (r):
```r
# First, we will remove negative cells from the object
pbmc.hashtag.subset <- subset(pbmc.hashtag, idents = "Negative", invert = TRUE)

# Calculate a tSNE embedding of the HTO data
DefaultAssay(pbmc.hashtag.subset) <- "HTO"
pbmc.hashtag.subset <- ScaleData(pbmc.hashtag.subset, features = rownames(pbmc.hashtag.subset),
    verbose = FALSE)
pbmc.hashtag.subset <- RunPCA(pbmc.hashtag.subset, features = rownames(pbmc.hashtag.subset), approx = FALSE)
pbmc.hashtag.subset <- RunTSNE(pbmc.hashtag.subset, dims = 1:8, perplexity = 100)
DimPlot(pbmc.hashtag.subset)
```

Example 36 (r):
```r
# First, we will remove negative cells from the object
pbmc.hashtag.subset <- subset(pbmc.hashtag, idents = "Negative", invert = TRUE)

# Calculate a tSNE embedding of the HTO data
DefaultAssay(pbmc.hashtag.subset) <- "HTO"
pbmc.hashtag.subset <- ScaleData(pbmc.hashtag.subset, features = rownames(pbmc.hashtag.subset),
    verbose = FALSE)
pbmc.hashtag.subset <- RunPCA(pbmc.hashtag.subset, features = rownames(pbmc.hashtag.subset), approx = FALSE)
pbmc.hashtag.subset <- RunTSNE(pbmc.hashtag.subset, dims = 1:8, perplexity = 100)
DimPlot(pbmc.hashtag.subset)
```

Example 37 (javascript):
```javascript
# You can also visualize the more detailed classification result by running Idents(object) <-
# 'HTO_classification' before plotting. Here, you can see that each of the small clouds on the
# tSNE plot corresponds to one of the 28 possible doublet combinations.
```

Example 38 (r):
```r
# You can also visualize the more detailed classification result by running Idents(object) <-
# 'HTO_classification' before plotting. Here, you can see that each of the small clouds on the
# tSNE plot corresponds to one of the 28 possible doublet combinations.
```

Example 39 (r):
```r
# You can also visualize the more detailed classification result by running Idents(object) <-
# 'HTO_classification' before plotting. Here, you can see that each of the small clouds on the
# tSNE plot corresponds to one of the 28 possible doublet combinations.
```

Example 40 (unknown):
```unknown
# To increase the efficiency of plotting, you can subsample cells using the num.cells argument
HTOHeatmap(pbmc.hashtag, assay = "HTO", ncells = 5000)
```

Example 41 (r):
```r
# To increase the efficiency of plotting, you can subsample cells using the num.cells argument
HTOHeatmap(pbmc.hashtag, assay = "HTO", ncells = 5000)
```

Example 42 (r):
```r
# To increase the efficiency of plotting, you can subsample cells using the num.cells argument
HTOHeatmap(pbmc.hashtag, assay = "HTO", ncells = 5000)
```

Example 43 (javascript):
```javascript
# Extract the singlets
pbmc.singlet <- subset(pbmc.hashtag, idents = "Singlet")

# Select the top 1000 most variable features
pbmc.singlet <- FindVariableFeatures(pbmc.singlet, selection.method = "mean.var.plot")

# Scaling RNA data, we only scale the variable features here for efficiency
pbmc.singlet <- ScaleData(pbmc.singlet, features = VariableFeatures(pbmc.singlet))

# Run PCA
pbmc.singlet <- RunPCA(pbmc.singlet, features = VariableFeatures(pbmc.singlet))
```

Example 44 (r):
```r
# Extract the singlets
pbmc.singlet <- subset(pbmc.hashtag, idents = "Singlet")

# Select the top 1000 most variable features
pbmc.singlet <- FindVariableFeatures(pbmc.singlet, selection.method = "mean.var.plot")

# Scaling RNA data, we only scale the variable features here for efficiency
pbmc.singlet <- ScaleData(pbmc.singlet, features = VariableFeatures(pbmc.singlet))

# Run PCA
pbmc.singlet <- RunPCA(pbmc.singlet, features = VariableFeatures(pbmc.singlet))
```

Example 45 (r):
```r
# Extract the singlets
pbmc.singlet <- subset(pbmc.hashtag, idents = "Singlet")

# Select the top 1000 most variable features
pbmc.singlet <- FindVariableFeatures(pbmc.singlet, selection.method = "mean.var.plot")

# Scaling RNA data, we only scale the variable features here for efficiency
pbmc.singlet <- ScaleData(pbmc.singlet, features = VariableFeatures(pbmc.singlet))

# Run PCA
pbmc.singlet <- RunPCA(pbmc.singlet, features = VariableFeatures(pbmc.singlet))
```

Example 46 (javascript):
```javascript
# We select the top 10 PCs for clustering and tSNE based on PCElbowPlot
pbmc.singlet <- FindNeighbors(pbmc.singlet, reduction = "pca", dims = 1:10)
pbmc.singlet <- FindClusters(pbmc.singlet, resolution = 0.6, verbose = FALSE)
pbmc.singlet <- RunTSNE(pbmc.singlet, reduction = "pca", dims = 1:10)

# Projecting singlet identities on TSNE visualization
DimPlot(pbmc.singlet, group.by = "HTO_classification")
```

Example 47 (r):
```r
# We select the top 10 PCs for clustering and tSNE based on PCElbowPlot
pbmc.singlet <- FindNeighbors(pbmc.singlet, reduction = "pca", dims = 1:10)
pbmc.singlet <- FindClusters(pbmc.singlet, resolution = 0.6, verbose = FALSE)
pbmc.singlet <- RunTSNE(pbmc.singlet, reduction = "pca", dims = 1:10)

# Projecting singlet identities on TSNE visualization
DimPlot(pbmc.singlet, group.by = "HTO_classification")
```

Example 48 (r):
```r
# We select the top 10 PCs for clustering and tSNE based on PCElbowPlot
pbmc.singlet <- FindNeighbors(pbmc.singlet, reduction = "pca", dims = 1:10)
pbmc.singlet <- FindClusters(pbmc.singlet, resolution = 0.6, verbose = FALSE)
pbmc.singlet <- RunTSNE(pbmc.singlet, reduction = "pca", dims = 1:10)

# Projecting singlet identities on TSNE visualization
DimPlot(pbmc.singlet, group.by = "HTO_classification")
```

Example 49 (unknown):
```unknown
# Read in UMI count matrix for RNA
hto12.umis <- readRDS("/brahms/shared/vignette-data/hto12_umi_mtx.rds")

# Read in HTO count matrix
hto12.htos <- readRDS("/brahms/shared/vignette-data/hto12_hto_mtx.rds")

# Select cell barcodes detected in both RNA and HTO
cells.use <- intersect(rownames(hto12.htos), colnames(hto12.umis))

# Create Seurat object and add HTO data
hto12 <- CreateSeuratObject(counts = Matrix::Matrix(as.matrix(hto12.umis[, cells.use]), sparse = T),
    min.features = 300)
hto12[["HTO"]] <- CreateAssayObject(counts = t(x = hto12.htos[colnames(hto12), 1:12]))

# Normalize data
hto12 <- NormalizeData(hto12)
hto12 <- NormalizeData(hto12, assay = "HTO", normalization.method = "CLR")
```

Example 50 (r):
```r
# Read in UMI count matrix for RNA
hto12.umis <- readRDS("/brahms/shared/vignette-data/hto12_umi_mtx.rds")

# Read in HTO count matrix
hto12.htos <- readRDS("/brahms/shared/vignette-data/hto12_hto_mtx.rds")

# Select cell barcodes detected in both RNA and HTO
cells.use <- intersect(rownames(hto12.htos), colnames(hto12.umis))

# Create Seurat object and add HTO data
hto12 <- CreateSeuratObject(counts = Matrix::Matrix(as.matrix(hto12.umis[, cells.use]), sparse = T),
    min.features = 300)
hto12[["HTO"]] <- CreateAssayObject(counts = t(x = hto12.htos[colnames(hto12), 1:12]))

# Normalize data
hto12 <- NormalizeData(hto12)
hto12 <- NormalizeData(hto12, assay = "HTO", normalization.method = "CLR")
```

Example 51 (r):
```r
# Read in UMI count matrix for RNA
hto12.umis <- readRDS("/brahms/shared/vignette-data/hto12_umi_mtx.rds")

# Read in HTO count matrix
hto12.htos <- readRDS("/brahms/shared/vignette-data/hto12_hto_mtx.rds")

# Select cell barcodes detected in both RNA and HTO
cells.use <- intersect(rownames(hto12.htos), colnames(hto12.umis))

# Create Seurat object and add HTO data
hto12 <- CreateSeuratObject(counts = Matrix::Matrix(as.matrix(hto12.umis[, cells.use]), sparse = T),
    min.features = 300)
hto12[["HTO"]] <- CreateAssayObject(counts = t(x = hto12.htos[colnames(hto12), 1:12]))

# Normalize data
hto12 <- NormalizeData(hto12)
hto12 <- NormalizeData(hto12, assay = "HTO", normalization.method = "CLR")
```

Example 52 (unknown):
```unknown
hto12 <- HTODemux(hto12, assay = "HTO", positive.quantile = 0.99)
```

Example 53 (r):
```r
hto12 <- HTODemux(hto12, assay = "HTO", positive.quantile = 0.99)
```

Example 54 (r):
```r
hto12 <- HTODemux(hto12, assay = "HTO", positive.quantile = 0.99)
```

Example 55 (unknown):
```unknown
RidgePlot(hto12, assay = "HTO", features = c("HEK-A", "K562-B", "KG1-A", "THP1-C"), ncol = 2)
```

Example 56 (r):
```r
RidgePlot(hto12, assay = "HTO", features = c("HEK-A", "K562-B", "KG1-A", "THP1-C"), ncol = 2)
```

Example 57 (r):
```r
RidgePlot(hto12, assay = "HTO", features = c("HEK-A", "K562-B", "KG1-A", "THP1-C"), ncol = 2)
```

Example 58 (unknown):
```unknown
HTOHeatmap(hto12, assay = "HTO")
```

Example 59 (r):
```r
HTOHeatmap(hto12, assay = "HTO")
```

Example 60 (r):
```r
HTOHeatmap(hto12, assay = "HTO")
```

Example 61 (unknown):
```unknown
# Remove the negative cells
hto12 <- subset(hto12, idents = "Negative", invert = TRUE)

# Run PCA on most variable features
hto12 <- FindVariableFeatures(hto12, selection.method = "mean.var.plot")
hto12 <- ScaleData(hto12, features = VariableFeatures(hto12))
hto12 <- RunPCA(hto12)
hto12 <- RunTSNE(hto12, dims = 1:5, perplexity = 100)
DimPlot(hto12) + NoLegend()
```

Example 62 (r):
```r
# Remove the negative cells
hto12 <- subset(hto12, idents = "Negative", invert = TRUE)

# Run PCA on most variable features
hto12 <- FindVariableFeatures(hto12, selection.method = "mean.var.plot")
hto12 <- ScaleData(hto12, features = VariableFeatures(hto12))
hto12 <- RunPCA(hto12)
hto12 <- RunTSNE(hto12, dims = 1:5, perplexity = 100)
DimPlot(hto12) + NoLegend()
```

Example 63 (r):
```r
# Remove the negative cells
hto12 <- subset(hto12, idents = "Negative", invert = TRUE)

# Run PCA on most variable features
hto12 <- FindVariableFeatures(hto12, selection.method = "mean.var.plot")
hto12 <- ScaleData(hto12, features = VariableFeatures(hto12))
hto12 <- RunPCA(hto12)
hto12 <- RunTSNE(hto12, dims = 1:5, perplexity = 100)
DimPlot(hto12) + NoLegend()
```

Example 64 (unknown):
```unknown
sessionInfo()
```

Example 65 (r):
```r
sessionInfo()
```

Example 66 (r):
```r
sessionInfo()
```

Example 67 (unknown):
```unknown
## R version 4.2.2 Patched (2022-11-10 r83330)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.6 LTS
## 
## Matrix products: default
## BLAS:   /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.9.0
## LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.9.0
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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       
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
## [1] Seurat_5.0.0       SeuratObject_5.0.0 sp_2.1-1          
## 
## loaded via a namespace (and not attached):
##   [1] ggbeeswarm_0.7.1       Rtsne_0.16             colorspace_2.1-0      
##   [4] deldir_1.0-9           ellipsis_0.3.2         ggridges_0.5.4        
##   [7] rprojroot_2.0.4        RcppHNSW_0.5.0         fs_1.6.3              
##  [10] spatstat.data_3.0-3    farver_2.1.1           leiden_0.4.3          
##  [13] listenv_0.9.0          ggrepel_0.9.4          RSpectra_0.16-1       
##  [16] fansi_1.0.5            codetools_0.2-19       splines_4.2.2         
##  [19] cachem_1.0.8           knitr_1.45             polyclip_1.10-6       
##  [22] spam_2.10-0            jsonlite_1.8.7         ica_1.0-3             
##  [25] cluster_2.1.4          png_0.1-8              uwot_0.1.16           
##  [28] spatstat.sparse_3.0-3  sctransform_0.4.1      shiny_1.7.5.1         
##  [31] compiler_4.2.2         httr_1.4.7             Matrix_1.6-1.1        
##  [34] fastmap_1.1.1          lazyeval_0.2.2         cli_3.6.1             
##  [37] later_1.3.1            formatR_1.14           htmltools_0.5.6.1     
##  [40] tools_4.2.2            igraph_1.5.1           dotCall64_1.1-0       
##  [43] gtable_0.3.4           glue_1.6.2             reshape2_1.4.4        
##  [46] RANN_2.6.1             dplyr_1.1.3            Rcpp_1.0.11           
##  [49] scattermore_1.2        jquerylib_0.1.4        pkgdown_2.0.7         
##  [52] vctrs_0.6.4            nlme_3.1-162           spatstat.explore_3.2-5
##  [55] progressr_0.14.0       lmtest_0.9-40          spatstat.random_3.2-1 
##  [58] xfun_0.40              stringr_1.5.0          globals_0.16.2        
##  [61] mime_0.12              miniUI_0.1.1.1         lifecycle_1.0.4       
##  [64] irlba_2.3.5.1          goftest_1.2-3          future_1.33.0         
##  [67] MASS_7.3-58.2          zoo_1.8-12             scales_1.2.1          
##  [70] spatstat.utils_3.0-4   ragg_1.2.5             promises_1.2.1        
##  [73] parallel_4.2.2         RColorBrewer_1.1-3     yaml_2.3.7            
##  [76] gridExtra_2.3          memoise_2.0.1          reticulate_1.34.0     
##  [79] pbapply_1.7-2          ggrastr_1.0.1          ggplot2_3.4.4         
##  [82] sass_0.4.7             stringi_1.7.12         highr_0.10            
##  [85] desc_1.4.2             fastDummies_1.7.3      rlang_1.1.1           
##  [88] pkgconfig_2.0.3        systemfonts_1.0.4      matrixStats_1.0.0     
##  [91] evaluate_0.22          lattice_0.21-9         tensor_1.5            
##  [94] ROCR_1.0-11            purrr_1.0.2            labeling_0.4.3        
##  [97] patchwork_1.1.3        htmlwidgets_1.6.2      cowplot_1.1.1         
## [100] tidyselect_1.2.0       parallelly_1.36.0      RcppAnnoy_0.0.21      
## [103] plyr_1.8.9             magrittr_2.0.3         R6_2.5.1              
## [106] generics_0.1.3         withr_2.5.2            pillar_1.9.0          
## [109] fitdistrplus_1.1-11    abind_1.4-5            survival_3.5-7        
## [112] tibble_3.2.1           future.apply_1.11.0    KernSmooth_2.23-22    
## [115] utf8_1.2.4             spatstat.geom_3.2-7    plotly_4.10.3         
## [118] rmarkdown_2.25         grid_4.2.2             data.table_1.14.8     
## [121] digest_0.6.33          xtable_1.8-4           tidyr_1.3.0           
## [124] httpuv_1.6.12          textshaping_0.3.6      munsell_0.5.0         
## [127] beeswarm_0.4.0         viridisLite_0.4.2      vipor_0.4.5           
## [130] bslib_0.5.1
```

Example 68 (unknown):
```unknown
## R version 4.2.2 Patched (2022-11-10 r83330)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.6 LTS
## 
## Matrix products: default
## BLAS:   /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.9.0
## LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.9.0
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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       
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
## [1] Seurat_5.0.0       SeuratObject_5.0.0 sp_2.1-1          
## 
## loaded via a namespace (and not attached):
##   [1] ggbeeswarm_0.7.1       Rtsne_0.16             colorspace_2.1-0      
##   [4] deldir_1.0-9           ellipsis_0.3.2         ggridges_0.5.4        
##   [7] rprojroot_2.0.4        RcppHNSW_0.5.0         fs_1.6.3              
##  [10] spatstat.data_3.0-3    farver_2.1.1           leiden_0.4.3          
##  [13] listenv_0.9.0          ggrepel_0.9.4          RSpectra_0.16-1       
##  [16] fansi_1.0.5            codetools_0.2-19       splines_4.2.2         
##  [19] cachem_1.0.8           knitr_1.45             polyclip_1.10-6       
##  [22] spam_2.10-0            jsonlite_1.8.7         ica_1.0-3             
##  [25] cluster_2.1.4          png_0.1-8              uwot_0.1.16           
##  [28] spatstat.sparse_3.0-3  sctransform_0.4.1      shiny_1.7.5.1         
##  [31] compiler_4.2.2         httr_1.4.7             Matrix_1.6-1.1        
##  [34] fastmap_1.1.1          lazyeval_0.2.2         cli_3.6.1             
##  [37] later_1.3.1            formatR_1.14           htmltools_0.5.6.1     
##  [40] tools_4.2.2            igraph_1.5.1           dotCall64_1.1-0       
##  [43] gtable_0.3.4           glue_1.6.2             reshape2_1.4.4        
##  [46] RANN_2.6.1             dplyr_1.1.3            Rcpp_1.0.11           
##  [49] scattermore_1.2        jquerylib_0.1.4        pkgdown_2.0.7         
##  [52] vctrs_0.6.4            nlme_3.1-162           spatstat.explore_3.2-5
##  [55] progressr_0.14.0       lmtest_0.9-40          spatstat.random_3.2-1 
##  [58] xfun_0.40              stringr_1.5.0          globals_0.16.2        
##  [61] mime_0.12              miniUI_0.1.1.1         lifecycle_1.0.4       
##  [64] irlba_2.3.5.1          goftest_1.2-3          future_1.33.0         
##  [67] MASS_7.3-58.2          zoo_1.8-12             scales_1.2.1          
##  [70] spatstat.utils_3.0-4   ragg_1.2.5             promises_1.2.1        
##  [73] parallel_4.2.2         RColorBrewer_1.1-3     yaml_2.3.7            
##  [76] gridExtra_2.3          memoise_2.0.1          reticulate_1.34.0     
##  [79] pbapply_1.7-2          ggrastr_1.0.1          ggplot2_3.4.4         
##  [82] sass_0.4.7             stringi_1.7.12         highr_0.10            
##  [85] desc_1.4.2             fastDummies_1.7.3      rlang_1.1.1           
##  [88] pkgconfig_2.0.3        systemfonts_1.0.4      matrixStats_1.0.0     
##  [91] evaluate_0.22          lattice_0.21-9         tensor_1.5            
##  [94] ROCR_1.0-11            purrr_1.0.2            labeling_0.4.3        
##  [97] patchwork_1.1.3        htmlwidgets_1.6.2      cowplot_1.1.1         
## [100] tidyselect_1.2.0       parallelly_1.36.0      RcppAnnoy_0.0.21      
## [103] plyr_1.8.9             magrittr_2.0.3         R6_2.5.1              
## [106] generics_0.1.3         withr_2.5.2            pillar_1.9.0          
## [109] fitdistrplus_1.1-11    abind_1.4-5            survival_3.5-7        
## [112] tibble_3.2.1           future.apply_1.11.0    KernSmooth_2.23-22    
## [115] utf8_1.2.4             spatstat.geom_3.2-7    plotly_4.10.3         
## [118] rmarkdown_2.25         grid_4.2.2             data.table_1.14.8     
## [121] digest_0.6.33          xtable_1.8-4           tidyr_1.3.0           
## [124] httpuv_1.6.12          textshaping_0.3.6      munsell_0.5.0         
## [127] beeswarm_0.4.0         viridisLite_0.4.2      vipor_0.4.5           
## [130] bslib_0.5.1
```

---

## Analysis, visualization, and integration of Visium HD spatial datasets with Seurat • Seurat

**URL:** http://127.0.0.1:9173/articles_seurat5_essential_commands.html

**Contents:**
- Seurat v5 Command Cheat Sheet
    - Compiled: October 31, 2023
- Load datasets
- Access and store expression data
- Access cell names and metadata
- Create Seurat or Assay objects
- Working with layers
- Accessing additional data
- Contents

Here, we describe important commands and functions to store, access, and process data using Seurat v5. To demonstrate commamnds, we use a dataset of 3,000 PBMC (stored in-memory), and a dataset of 1.3M E18 mouse neurons (stored on-disk), which we constructed as described in the BPCells vignette.

The $ and double-bracket [[]] symbols can be used as efficient accessor functions for Seurat5 assays.

Despite the drastic difference in dataset size, the 1.3M cell dataset occupies a small memory footprint thanks to on-disk storage.

Get cell names. Since Seurat v5 object doesn’t require all assays have the same cells, Cells() is designed to get cell names of the default assay and colnames() is deigned to get cell names of the entire object

Access object metadata

By setting a global option (Seurat.object.assay.version), you can default to creating either Seurat v3 assays, or Seurat v5 assays. The use of v5 assays is set by default upon package loading, which ensures backwards compatibiltiy with existing workflows.

CreateAssayObject() and CreateAssay5Object() can be used to create v3 and v5 assay regardless of the setting in Seurat.object.assay.version

Assay5 objects are more flexible, and can be used to store only a data layer, with no counts data. This can be used to create Seurat objects that require less space

We can also convert (cast) between Assay and Assay5 objects with as().

Seurat v5 assays store data in layers. These layers can store raw, un-normalized counts (layer='counts'), normalized data (layer='data'), or z-scored/variance-stabilized data (layer='scale.data').

Prior to performing integration analysis in Seurat v5, we can split the layers into groups. The IntegrateLayers function, described in our vignette, will then align shared cell types across these layers. After performing integration, you can rejoin the layers.

If you have multiple counts matrices, you can also create a Seurat object that is initialized with multiple layers.

Developed by Rahul Satija, Satija Lab and Collaborators.

Site built with pkgdown 2.0.7.

**Examples:**

Example 1 (unknown):
```unknown
vignettes/seurat5_essential_commands.Rmd
```

Example 2 (unknown):
```unknown
seurat5_essential_commands.Rmd
```

Example 3 (unknown):
```unknown
library(Seurat)
library(SeuratData)
library(BPCells)
library(dplyr)
options(Seurat.object.assay.version = "v5")
```

Example 4 (r):
```r
library(Seurat)
library(SeuratData)
library(BPCells)
library(dplyr)
options(Seurat.object.assay.version = "v5")
```

Example 5 (r):
```r
library(Seurat)
library(SeuratData)
library(BPCells)
library(dplyr)
options(Seurat.object.assay.version = "v5")
```

Example 6 (unknown):
```unknown
pbmc3k <- LoadData("pbmc3k")
mousebrain1m <- readRDS("/brahms/hartmana/vignette_data/1p3_million_mouse_brain.rds")

#  RNA assay is of the Assay5 class
class(pbmc3k[["RNA"]])
class(mousebrain1m[["RNA"]])
```

Example 7 (r):
```r
pbmc3k <- LoadData("pbmc3k")
mousebrain1m <- readRDS("/brahms/hartmana/vignette_data/1p3_million_mouse_brain.rds")

#  RNA assay is of the Assay5 class
class(pbmc3k[["RNA"]])
class(mousebrain1m[["RNA"]])
```

Example 8 (r):
```r
pbmc3k <- LoadData("pbmc3k")
mousebrain1m <- readRDS("/brahms/hartmana/vignette_data/1p3_million_mouse_brain.rds")

#  RNA assay is of the Assay5 class
class(pbmc3k[["RNA"]])
class(mousebrain1m[["RNA"]])
```

Example 9 (python):
```python
# access the counts matrix from the RNA assay
counts_matrix <- pbmc3k[["RNA"]]$counts

# Add a layer
# Equivalent to running pbmc3k <-NormalizeData(pbmc3k)
pbmc3k[["RNA"]]$data <- NormalizeData(pbmc3k[["RNA"]]$counts)

# Delete a layer
pbmc3k[["RNA"]]$data <- NULL

# pbmc3k counts matrix is stored in-memory
class(pbmc3k[["RNA"]]$counts)

# 1.3M cell dataset counts matrix is stored on-disk
class(mousebrain1m[["RNA"]]$counts)
```

Example 10 (r):
```r
# access the counts matrix from the RNA assay
counts_matrix <- pbmc3k[["RNA"]]$counts

# Add a layer
# Equivalent to running pbmc3k <-NormalizeData(pbmc3k)
pbmc3k[["RNA"]]$data <- NormalizeData(pbmc3k[["RNA"]]$counts)

# Delete a layer
pbmc3k[["RNA"]]$data <- NULL

# pbmc3k counts matrix is stored in-memory
class(pbmc3k[["RNA"]]$counts)

# 1.3M cell dataset counts matrix is stored on-disk
class(mousebrain1m[["RNA"]]$counts)
```

Example 11 (r):
```r
# access the counts matrix from the RNA assay
counts_matrix <- pbmc3k[["RNA"]]$counts

# Add a layer
# Equivalent to running pbmc3k <-NormalizeData(pbmc3k)
pbmc3k[["RNA"]]$data <- NormalizeData(pbmc3k[["RNA"]]$counts)

# Delete a layer
pbmc3k[["RNA"]]$data <- NULL

# pbmc3k counts matrix is stored in-memory
class(pbmc3k[["RNA"]]$counts)

# 1.3M cell dataset counts matrix is stored on-disk
class(mousebrain1m[["RNA"]]$counts)
```

Example 12 (unknown):
```unknown
paste("PBMC 3k contains", length(colnames(pbmc3k)), "cells")
paste("Mouse brain 1.3M contains", length(colnames(mousebrain1m)), "cells")

# Despite the mouse brain dataset containing 1.3 million cells, the assay is under 350Mbs in size due to on-disk storage
paste("PBMC 3k assay size:", format(object.size(pbmc3k[["RNA"]]), units = "Mb"))
paste("Mouse brain 1.3M assay size:", format(object.size(mousebrain1m[["RNA"]]), units = "Mb"))
```

Example 13 (r):
```r
paste("PBMC 3k contains", length(colnames(pbmc3k)), "cells")
paste("Mouse brain 1.3M contains", length(colnames(mousebrain1m)), "cells")

# Despite the mouse brain dataset containing 1.3 million cells, the assay is under 350Mbs in size due to on-disk storage
paste("PBMC 3k assay size:", format(object.size(pbmc3k[["RNA"]]), units = "Mb"))
paste("Mouse brain 1.3M assay size:", format(object.size(mousebrain1m[["RNA"]]), units = "Mb"))
```

Example 14 (r):
```r
paste("PBMC 3k contains", length(colnames(pbmc3k)), "cells")
paste("Mouse brain 1.3M contains", length(colnames(mousebrain1m)), "cells")

# Despite the mouse brain dataset containing 1.3 million cells, the assay is under 350Mbs in size due to on-disk storage
paste("PBMC 3k assay size:", format(object.size(pbmc3k[["RNA"]]), units = "Mb"))
paste("Mouse brain 1.3M assay size:", format(object.size(mousebrain1m[["RNA"]]), units = "Mb"))
```

Example 15 (unknown):
```unknown
pbmc3k[["RNAsub"]] <- subset(pbmc3k[["RNA"]], cells = colnames(pbmc3k)[1:100])
DefaultAssay(pbmc3k) <- "RNAsub"
length(Cells(pbmc3k))
length(colnames(pbmc3k))
```

Example 16 (r):
```r
pbmc3k[["RNAsub"]] <- subset(pbmc3k[["RNA"]], cells = colnames(pbmc3k)[1:100])
DefaultAssay(pbmc3k) <- "RNAsub"
length(Cells(pbmc3k))
length(colnames(pbmc3k))
```

Example 17 (r):
```r
pbmc3k[["RNAsub"]] <- subset(pbmc3k[["RNA"]], cells = colnames(pbmc3k)[1:100])
DefaultAssay(pbmc3k) <- "RNAsub"
length(Cells(pbmc3k))
length(colnames(pbmc3k))
```

Example 18 (python):
```python
# get all object metadata
pbmc_metadata <- pbmc3k[[]]

# get list of metadata columns
colnames(pbmc_metadata)

# get annotations stored in metadata
annotations <- pbmc3k$seurat_annotations
```

Example 19 (r):
```r
# get all object metadata
pbmc_metadata <- pbmc3k[[]]

# get list of metadata columns
colnames(pbmc_metadata)

# get annotations stored in metadata
annotations <- pbmc3k$seurat_annotations
```

Example 20 (r):
```r
# get all object metadata
pbmc_metadata <- pbmc3k[[]]

# get list of metadata columns
colnames(pbmc_metadata)

# get annotations stored in metadata
annotations <- pbmc3k$seurat_annotations
```

Example 21 (unknown):
```unknown
Seurat.object.assay.version
```

Example 22 (unknown):
```unknown
# create v3 assays
options(Seurat.object.assay.version = "v3")
pbmc.counts <- Read10X(data.dir = "/brahms/hartmana/vignette_data/pbmc3k/filtered_gene_bc_matrices/hg19/")
pbmc <- CreateSeuratObject(counts = pbmc.counts)
class(pbmc[["RNA"]])

# create v5 assays
options(Seurat.object.assay.version = "v5")
pbmc.counts <- Read10X(data.dir = "/brahms/hartmana/vignette_data/pbmc3k/filtered_gene_bc_matrices/hg19/")
pbmc <- CreateSeuratObject(counts = pbmc.counts)
class(pbmc[["RNA"]])
```

Example 23 (r):
```r
# create v3 assays
options(Seurat.object.assay.version = "v3")
pbmc.counts <- Read10X(data.dir = "/brahms/hartmana/vignette_data/pbmc3k/filtered_gene_bc_matrices/hg19/")
pbmc <- CreateSeuratObject(counts = pbmc.counts)
class(pbmc[["RNA"]])

# create v5 assays
options(Seurat.object.assay.version = "v5")
pbmc.counts <- Read10X(data.dir = "/brahms/hartmana/vignette_data/pbmc3k/filtered_gene_bc_matrices/hg19/")
pbmc <- CreateSeuratObject(counts = pbmc.counts)
class(pbmc[["RNA"]])
```

Example 24 (r):
```r
# create v3 assays
options(Seurat.object.assay.version = "v3")
pbmc.counts <- Read10X(data.dir = "/brahms/hartmana/vignette_data/pbmc3k/filtered_gene_bc_matrices/hg19/")
pbmc <- CreateSeuratObject(counts = pbmc.counts)
class(pbmc[["RNA"]])

# create v5 assays
options(Seurat.object.assay.version = "v5")
pbmc.counts <- Read10X(data.dir = "/brahms/hartmana/vignette_data/pbmc3k/filtered_gene_bc_matrices/hg19/")
pbmc <- CreateSeuratObject(counts = pbmc.counts)
class(pbmc[["RNA"]])
```

Example 25 (unknown):
```unknown
CreateAssayObject()
```

Example 26 (unknown):
```unknown
CreateAssay5Object()
```

Example 27 (unknown):
```unknown
Seurat.object.assay.version
```

Example 28 (unknown):
```unknown
# create a v3 assay
assay.v3 <- CreateAssayObject(counts = pbmc.counts)

# create a v5 assay
assay.v5 <- CreateAssay5Object(counts = pbmc.counts)

class(assay.v3)
class(assay.v5)
```

Example 29 (r):
```r
# create a v3 assay
assay.v3 <- CreateAssayObject(counts = pbmc.counts)

# create a v5 assay
assay.v5 <- CreateAssay5Object(counts = pbmc.counts)

class(assay.v3)
class(assay.v5)
```

Example 30 (r):
```r
# create a v3 assay
assay.v3 <- CreateAssayObject(counts = pbmc.counts)

# create a v5 assay
assay.v5 <- CreateAssay5Object(counts = pbmc.counts)

class(assay.v3)
class(assay.v5)
```

Example 31 (unknown):
```unknown
# create an assay using only normalized data
assay.v5 <- CreateAssay5Object(data = log1p(pbmc.counts))

# create a Seurat object based on this assay
pbmc3k_slim <- CreateSeuratObject(assay.v5)
pbmc3k_slim
```

Example 32 (r):
```r
# create an assay using only normalized data
assay.v5 <- CreateAssay5Object(data = log1p(pbmc.counts))

# create a Seurat object based on this assay
pbmc3k_slim <- CreateSeuratObject(assay.v5)
pbmc3k_slim
```

Example 33 (r):
```r
# create an assay using only normalized data
assay.v5 <- CreateAssay5Object(data = log1p(pbmc.counts))

# create a Seurat object based on this assay
pbmc3k_slim <- CreateSeuratObject(assay.v5)
pbmc3k_slim
```

Example 34 (unknown):
```unknown
# convert a v5 assay to a v3 assay
pbmc3k[["RNA3"]] <- as(object = pbmc3k[["RNA"]], Class = "Assay")

# convert a v3 assay to a v5 assay
pbmc3k[["RNA5"]] <- as(object = pbmc3k[["RNA3"]], Class = "Assay5")
```

Example 35 (r):
```r
# convert a v5 assay to a v3 assay
pbmc3k[["RNA3"]] <- as(object = pbmc3k[["RNA"]], Class = "Assay")

# convert a v3 assay to a v5 assay
pbmc3k[["RNA5"]] <- as(object = pbmc3k[["RNA3"]], Class = "Assay5")
```

Example 36 (r):
```r
# convert a v5 assay to a v3 assay
pbmc3k[["RNA3"]] <- as(object = pbmc3k[["RNA"]], Class = "Assay")

# convert a v3 assay to a v5 assay
pbmc3k[["RNA5"]] <- as(object = pbmc3k[["RNA3"]], Class = "Assay5")
```

Example 37 (unknown):
```unknown
layer='counts'
```

Example 38 (unknown):
```unknown
layer='data'
```

Example 39 (unknown):
```unknown
layer='scale.data'
```

Example 40 (python):
```python
# by default, creates an RNA assay with a counts layer
obj <- CreateSeuratObject(counts = pbmc.counts)
obj

# creates a normalized data layer
obj <- NormalizeData(obj, verbose = FALSE)
obj

# extract only the layer names from an assay
Layers(obj[["RNA"]])
```

Example 41 (r):
```r
# by default, creates an RNA assay with a counts layer
obj <- CreateSeuratObject(counts = pbmc.counts)
obj

# creates a normalized data layer
obj <- NormalizeData(obj, verbose = FALSE)
obj

# extract only the layer names from an assay
Layers(obj[["RNA"]])
```

Example 42 (r):
```r
# by default, creates an RNA assay with a counts layer
obj <- CreateSeuratObject(counts = pbmc.counts)
obj

# creates a normalized data layer
obj <- NormalizeData(obj, verbose = FALSE)
obj

# extract only the layer names from an assay
Layers(obj[["RNA"]])
```

Example 43 (unknown):
```unknown
IntegrateLayers
```

Example 44 (unknown):
```unknown
# create random batches
pbmc3k$batch <- sample(c("batchA", "batchB", "batchC"), ncol(pbmc3k), replace = TRUE)

# split layers
pbmc3k[["RNA"]] <- split(pbmc3k[["RNA"]], f = pbmc3k$batch)
Layers(pbmc3k[["RNA"]])

# rejoin layers
pbmc3k[["RNA"]] <- JoinLayers(pbmc3k[["RNA"]])
Layers(pbmc3k[["RNA"]])
```

Example 45 (r):
```r
# create random batches
pbmc3k$batch <- sample(c("batchA", "batchB", "batchC"), ncol(pbmc3k), replace = TRUE)

# split layers
pbmc3k[["RNA"]] <- split(pbmc3k[["RNA"]], f = pbmc3k$batch)
Layers(pbmc3k[["RNA"]])

# rejoin layers
pbmc3k[["RNA"]] <- JoinLayers(pbmc3k[["RNA"]])
Layers(pbmc3k[["RNA"]])
```

Example 46 (r):
```r
# create random batches
pbmc3k$batch <- sample(c("batchA", "batchB", "batchC"), ncol(pbmc3k), replace = TRUE)

# split layers
pbmc3k[["RNA"]] <- split(pbmc3k[["RNA"]], f = pbmc3k$batch)
Layers(pbmc3k[["RNA"]])

# rejoin layers
pbmc3k[["RNA"]] <- JoinLayers(pbmc3k[["RNA"]])
Layers(pbmc3k[["RNA"]])
```

Example 47 (unknown):
```unknown
batchA_counts <- pbmc.counts[, 1:200]
batchB_counts <- pbmc.counts[, 201:400]
batchC_counts <- pbmc.counts[, 401:600]
count_list <- list(batchA_counts, batchB_counts, batchC_counts)
names(count_list) <- c("batchA", "batchB", "batchC")

# create a Seurat object initialized with multiple layers
obj <- CreateSeuratObject(counts = count_list)
Layers(obj[["RNA"]])
```

Example 48 (r):
```r
batchA_counts <- pbmc.counts[, 1:200]
batchB_counts <- pbmc.counts[, 201:400]
batchC_counts <- pbmc.counts[, 401:600]
count_list <- list(batchA_counts, batchB_counts, batchC_counts)
names(count_list) <- c("batchA", "batchB", "batchC")

# create a Seurat object initialized with multiple layers
obj <- CreateSeuratObject(counts = count_list)
Layers(obj[["RNA"]])
```

Example 49 (r):
```r
batchA_counts <- pbmc.counts[, 1:200]
batchB_counts <- pbmc.counts[, 201:400]
batchC_counts <- pbmc.counts[, 401:600]
count_list <- list(batchA_counts, batchB_counts, batchC_counts)
names(count_list) <- c("batchA", "batchB", "batchC")

# create a Seurat object initialized with multiple layers
obj <- CreateSeuratObject(counts = count_list)
Layers(obj[["RNA"]])
```

Example 50 (python):
```python
pbmc3k <- FindVariableFeatures(pbmc3k, verbose = FALSE)
pbmc3k <- ScaleData(pbmc3k, verbose = FALSE)
pbmc3k <- RunPCA(pbmc3k, verbose = FALSE)

# return variable features

# returns information from both assay, cell embeddings and meta.data as a data.frame
fetch_df <- FetchData(object = pbmc3k, layer = "counts", vars = c("rna_MS4A1", "PC_1", "nCount_RNA"))
head(fetch_df)

# get cell embeddings
head(Embeddings(object = pbmc3k[["pca"]])[, 1:5])

# get feature loadings
head(Loadings(object = pbmc3k[["pca"]])[, 1:5])
```

Example 51 (r):
```r
pbmc3k <- FindVariableFeatures(pbmc3k, verbose = FALSE)
pbmc3k <- ScaleData(pbmc3k, verbose = FALSE)
pbmc3k <- RunPCA(pbmc3k, verbose = FALSE)

# return variable features

# returns information from both assay, cell embeddings and meta.data as a data.frame
fetch_df <- FetchData(object = pbmc3k, layer = "counts", vars = c("rna_MS4A1", "PC_1", "nCount_RNA"))
head(fetch_df)

# get cell embeddings
head(Embeddings(object = pbmc3k[["pca"]])[, 1:5])

# get feature loadings
head(Loadings(object = pbmc3k[["pca"]])[, 1:5])
```

Example 52 (r):
```r
pbmc3k <- FindVariableFeatures(pbmc3k, verbose = FALSE)
pbmc3k <- ScaleData(pbmc3k, verbose = FALSE)
pbmc3k <- RunPCA(pbmc3k, verbose = FALSE)

# return variable features

# returns information from both assay, cell embeddings and meta.data as a data.frame
fetch_df <- FetchData(object = pbmc3k, layer = "counts", vars = c("rna_MS4A1", "PC_1", "nCount_RNA"))
head(fetch_df)

# get cell embeddings
head(Embeddings(object = pbmc3k[["pca"]])[, 1:5])

# get feature loadings
head(Loadings(object = pbmc3k[["pca"]])[, 1:5])
```

Example 53 (unknown):
```unknown
sessionInfo()
```

Example 54 (r):
```r
sessionInfo()
```

Example 55 (r):
```r
sessionInfo()
```

---

## Analysis, visualization, and integration of Visium HD spatial datasets with Seurat • Seurat

**URL:** http://127.0.0.1:9173/articles_pbmc3k_tutorial.html

**Contents:**
- Seurat - Guided Clustering Tutorial
    - Compiled: October 31, 2023
- Setup the Seurat Object
- Standard pre-processing workflow
  - QC and selecting cells for further analysis
- Normalizing the data
- Identification of highly variable features (feature selection)
- Scaling the data
- Perform linear dimensional reduction
- Determine the ‘dimensionality’ of the dataset
- Cluster the cells
- Run non-linear dimensional reduction (UMAP/tSNE)
- Finding differentially expressed features (cluster biomarkers)
- Assigning cell type identity to clusters
- Contents

For this tutorial, we will be analyzing the a dataset of Peripheral Blood Mononuclear Cells (PBMC) freely available from 10X Genomics. There are 2,700 single cells that were sequenced on the Illumina NextSeq 500. The raw data can be found here.

We start by reading in the data. The Read10X() function reads in the output of the cellranger pipeline from 10X, returning a unique molecular identified (UMI) count matrix. The values in this matrix represent the number of molecules for each feature (i.e. gene; row) that are detected in each cell (column). Note that more recent versions of cellranger now also output using the h5 file format, which can be read in using the Read10X_h5() function in Seurat.

We next use the count matrix to create a Seurat object. The object serves as a container that contains both data (like the count matrix) and analysis (like PCA, or clustering results) for a single-cell dataset. For more information, check out our [Seurat object interaction vignette], or our GitHub Wiki. For example, in Seurat v5, the count matrix is stored in pbmc[["RNA"]]$counts.

What does data in a count matrix look like?

The . values in the matrix represent 0s (no molecules detected). Since most values in an scRNA-seq matrix are 0, Seurat uses a sparse-matrix representation whenever possible. This results in significant memory and speed savings for Drop-seq/inDrop/10x data.

The steps below encompass the standard pre-processing workflow for scRNA-seq data in Seurat. These represent the selection and filtration of cells based on QC metrics, data normalization and scaling, and the detection of highly variable features.

Seurat allows you to easily explore QC metrics and filter cells based on any user-defined criteria. A few QC metrics commonly used by the community include

Where are QC metrics stored in Seurat?

In the example below, we visualize QC metrics, and use these to filter cells.

After removing unwanted cells from the dataset, the next step is to normalize the data. By default, we employ a global-scaling normalization method “LogNormalize” that normalizes the feature expression measurements for each cell by the total expression, multiplies this by a scale factor (10,000 by default), and log-transforms the result. In Seurat v5, Normalized values are stored in pbmc[["RNA"]]$data.

For clarity, in this previous line of code (and in future commands), we provide the default values for certain parameters in the function call. However, this isn’t required and the same behavior can be achieved with:

While this method of normalization is standard and widely used in scRNA-seq analysis, global-scaling relies on an assumption that each cell originally contains the same number of RNA molecules. We and others have developed alternative workflows for the single cell preprocessing that do not make these assumptions. For users who are interested, please check out our SCTransform() normalization workflow. The method is described in ourpaper, with a separate vignette using Seurat here. The use of SCTransform replaces the need to run NormalizeData, FindVariableFeatures, or ScaleData (described below.)

We next calculate a subset of features that exhibit high cell-to-cell variation in the dataset (i.e, they are highly expressed in some cells, and lowly expressed in others). We and others have found that focusing on these genes in downstream analysis helps to highlight biological signal in single-cell datasets.

Our procedure in Seurat is described in detail here, and improves on previous versions by directly modeling the mean-variance relationship inherent in single-cell data, and is implemented in the FindVariableFeatures() function. By default, we return 2,000 features per dataset. These will be used in downstream analysis, like PCA.

Next, we apply a linear transformation (‘scaling’) that is a standard pre-processing step prior to dimensional reduction techniques like PCA. The ScaleData() function:

How can I remove unwanted sources of variation

In Seurat, we also use the ScaleData() function to remove unwanted sources of variation from a single-cell dataset. For example, we could ‘regress out’ heterogeneity associated with (for example) cell cycle stage, or mitochondrial contamination i.e.:

Next we perform PCA on the scaled data. By default, only the previously determined variable features are used as input, but can be defined using features argument if you wish to choose a different subset (if you do want to use a custom subset of features, make sure you pass these to ScaleData first).

For the first principal components, Seurat outputs a list of genes with the most positive and negative loadings, representing modules of genes that exhibit either correlation (or anti-correlation) across single-cells in the dataset.

Seurat provides several useful ways of visualizing both cells and features that define the PCA, including VizDimReduction(), DimPlot(), and DimHeatmap()

In particular DimHeatmap() allows for easy exploration of the primary sources of heterogeneity in a dataset, and can be useful when trying to decide which PCs to include for further downstream analyses. Both cells and features are ordered according to their PCA scores. Setting cells to a number plots the ‘extreme’ cells on both ends of the spectrum, which dramatically speeds plotting for large datasets. Though clearly a supervised analysis, we find this to be a valuable tool for exploring correlated feature sets.

To overcome the extensive technical noise in any single feature for scRNA-seq data, Seurat clusters cells based on their PCA scores, with each PC essentially representing a ‘metafeature’ that combines information across a correlated feature set. The top principal components therefore represent a robust compression of the dataset. However, how many components should we choose to include? 10? 20? 100?

In Macosko et al, we implemented a resampling test inspired by the JackStraw procedure. While still available in Seurat (see previous vignette), this is a slow and computationally expensive procedure, and we is no longer routinely used in single cell analysis.

An alternative heuristic method generates an ‘Elbow plot’: a ranking of principle components based on the percentage of variance explained by each one (ElbowPlot() function). In this example, we can observe an ‘elbow’ around PC9-10, suggesting that the majority of true signal is captured in the first 10 PCs.

Identifying the true dimensionality of a dataset – can be challenging/uncertain for the user. We therefore suggest these multiple approaches for users. The first is more supervised, exploring PCs to determine relevant sources of heterogeneity, and could be used in conjunction with GSEA for example. The second (ElbowPlot) The third is a heuristic that is commonly used, and can be calculated instantly. In this example, we might have been justified in choosing anything between PC 7-12 as a cutoff.

We chose 10 here, but encourage users to consider the following:

Seurat applies a graph-based clustering approach, building upon initial strategies in (Macosko et al). Importantly, the distance metric which drives the clustering analysis (based on previously identified PCs) remains the same. However, our approach to partitioning the cellular distance matrix into clusters has dramatically improved. Our approach was heavily inspired by recent manuscripts which applied graph-based clustering approaches to scRNA-seq data [SNN-Cliq, Xu and Su, Bioinformatics, 2015] and CyTOF data [PhenoGraph, Levine et al., Cell, 2015]. Briefly, these methods embed cells in a graph structure - for example a K-nearest neighbor (KNN) graph, with edges drawn between cells with similar feature expression patterns, and then attempt to partition this graph into highly interconnected ‘quasi-cliques’ or ‘communities’.

As in PhenoGraph, we first construct a KNN graph based on the euclidean distance in PCA space, and refine the edge weights between any two cells based on the shared overlap in their local neighborhoods (Jaccard similarity). This step is performed using the FindNeighbors() function, and takes as input the previously defined dimensionality of the dataset (first 10 PCs).

To cluster the cells, we next apply modularity optimization techniques such as the Louvain algorithm (default) or SLM [SLM, Blondel et al., Journal of Statistical Mechanics], to iteratively group cells together, with the goal of optimizing the standard modularity function. The FindClusters() function implements this procedure, and contains a resolution parameter that sets the ‘granularity’ of the downstream clustering, with increased values leading to a greater number of clusters. We find that setting this parameter between 0.4-1.2 typically returns good results for single-cell datasets of around 3K cells. Optimal resolution often increases for larger datasets. The clusters can be found using the Idents() function.

Seurat offers several non-linear dimensional reduction techniques, such as tSNE and UMAP, to visualize and explore these datasets. The goal of these algorithms is to learn underlying structure in the dataset, in order to place similar cells together in low-dimensional space. Therefore, cells that are grouped together within graph-based clusters determined above should co-localize on these dimension reduction plots.

While we and others have routinely found 2D visualization techniques like tSNE and UMAP to be valuable tools for exploring datasets, all visualization techniques have limitations, and cannot fully represent the complexity of the underlying data. In particular, these methods aim to preserve local distances in the dataset (i.e. ensuring that cells with very similar gene expression profiles co-localize), but often do not preserve more global relationships. We encourage users to leverage techniques like UMAP for visualization, but to avoid drawing biological conclusions solely on the basis of visualization techniques.

You can save the object at this point so that it can easily be loaded back in without having to rerun the computationally intensive steps performed above, or easily shared with collaborators.

Seurat can help you find markers that define clusters via differential expression (DE). By default, it identifies positive and negative markers of a single cluster (specified in ident.1), compared to all other cells. FindAllMarkers() automates this process for all clusters, but you can also test groups of clusters vs. each other, or against all cells.

In Seurat v5, we use the presto package (as described here and available for installation here), to dramatically improve the speed of DE analysis, particularly for large datasets. For users who are not using presto, you can examine the documentation for this function (?FindMarkers) to explore the min.pct and logfc.threshold parameters, which can be increased in order to increase the speed of DE testing.

Seurat has several tests for differential expression which can be set with the test.use parameter (see our DE vignette for details). For example, the ROC test returns the ‘classification power’ for any individual marker (ranging from 0 - random, to 1 - perfect).

We include several tools for visualizing marker expression. VlnPlot() (shows expression probability distributions across clusters), and FeaturePlot() (visualizes feature expression on a tSNE or PCA plot) are our most commonly used visualizations. We also suggest exploring RidgePlot(), CellScatter(), and DotPlot() as additional methods to view your dataset.

DoHeatmap() generates an expression heatmap for given cells and features. In this case, we are plotting the top 20 markers (or all markers if less than 20) for each cluster.

Fortunately in the case of this dataset, we can use canonical markers to easily match the unbiased clustering to known cell types:

Developed by Rahul Satija, Satija Lab and Collaborators.

Site built with pkgdown 2.0.7.

**Examples:**

Example 1 (unknown):
```unknown
vignettes/pbmc3k_tutorial.Rmd
```

Example 2 (unknown):
```unknown
pbmc3k_tutorial.Rmd
```

Example 3 (unknown):
```unknown
Read10X_h5()
```

Example 4 (unknown):
```unknown
pbmc[["RNA"]]$counts
```

Example 5 (unknown):
```unknown
library(dplyr)
library(Seurat)
library(patchwork)

# Load the PBMC dataset
pbmc.data <- Read10X(data.dir = "/brahms/mollag/practice/filtered_gene_bc_matrices/hg19/")
# Initialize the Seurat object with the raw (non-normalized data).
pbmc <- CreateSeuratObject(counts = pbmc.data, project = "pbmc3k", min.cells = 3, min.features = 200)
pbmc
```

Example 6 (r):
```r
library(dplyr)
library(Seurat)
library(patchwork)

# Load the PBMC dataset
pbmc.data <- Read10X(data.dir = "/brahms/mollag/practice/filtered_gene_bc_matrices/hg19/")
# Initialize the Seurat object with the raw (non-normalized data).
pbmc <- CreateSeuratObject(counts = pbmc.data, project = "pbmc3k", min.cells = 3, min.features = 200)
pbmc
```

Example 7 (r):
```r
library(dplyr)
library(Seurat)
library(patchwork)

# Load the PBMC dataset
pbmc.data <- Read10X(data.dir = "/brahms/mollag/practice/filtered_gene_bc_matrices/hg19/")
# Initialize the Seurat object with the raw (non-normalized data).
pbmc <- CreateSeuratObject(counts = pbmc.data, project = "pbmc3k", min.cells = 3, min.features = 200)
pbmc
```

Example 8 (python):
```python
## An object of class Seurat 
## 13714 features across 2700 samples within 1 assay 
## Active assay: RNA (13714 features, 0 variable features)
##  1 layer present: counts
```

Example 9 (python):
```python
## An object of class Seurat 
## 13714 features across 2700 samples within 1 assay 
## Active assay: RNA (13714 features, 0 variable features)
##  1 layer present: counts
```

Example 10 (unknown):
```unknown
# Lets examine a few genes in the first thirty cells
pbmc.data[c("CD3D", "TCL1A", "MS4A1"), 1:30]
```

Example 11 (r):
```r
# Lets examine a few genes in the first thirty cells
pbmc.data[c("CD3D", "TCL1A", "MS4A1"), 1:30]
```

Example 12 (r):
```r
# Lets examine a few genes in the first thirty cells
pbmc.data[c("CD3D", "TCL1A", "MS4A1"), 1:30]
```

Example 13 (python):
```python
## 3 x 30 sparse Matrix of class "dgCMatrix"
##                                                                    
## CD3D  4 . 10 . . 1 2 3 1 . . 2 7 1 . . 1 3 . 2  3 . . . . . 3 4 1 5
## TCL1A . .  . . . . . . 1 . . . . . . . . . . .  . 1 . . . . . . . .
## MS4A1 . 6  . . . . . . 1 1 1 . . . . . . . . . 36 1 2 . . 2 . . . .
```

Example 14 (python):
```python
## 3 x 30 sparse Matrix of class "dgCMatrix"
##                                                                    
## CD3D  4 . 10 . . 1 2 3 1 . . 2 7 1 . . 1 3 . 2  3 . . . . . 3 4 1 5
## TCL1A . .  . . . . . . 1 . . . . . . . . . . .  . 1 . . . . . . . .
## MS4A1 . 6  . . . . . . 1 1 1 . . . . . . . . . 36 1 2 . . 2 . . . .
```

Example 15 (unknown):
```unknown
dense.size <- object.size(as.matrix(pbmc.data))
dense.size
```

Example 16 (r):
```r
dense.size <- object.size(as.matrix(pbmc.data))
dense.size
```

Example 17 (r):
```r
dense.size <- object.size(as.matrix(pbmc.data))
dense.size
```

Example 18 (unknown):
```unknown
## 709591472 bytes
```

Example 19 (unknown):
```unknown
## 709591472 bytes
```

Example 20 (unknown):
```unknown
sparse.size <- object.size(pbmc.data)
sparse.size
```

Example 21 (r):
```r
sparse.size <- object.size(pbmc.data)
sparse.size
```

Example 22 (r):
```r
sparse.size <- object.size(pbmc.data)
sparse.size
```

Example 23 (unknown):
```unknown
## 29905192 bytes
```

Example 24 (unknown):
```unknown
## 29905192 bytes
```

Example 25 (unknown):
```unknown
dense.size/sparse.size
```

Example 26 (r):
```r
dense.size/sparse.size
```

Example 27 (r):
```r
dense.size/sparse.size
```

Example 28 (unknown):
```unknown
## 23.7 bytes
```

Example 29 (unknown):
```unknown
## 23.7 bytes
```

Example 30 (unknown):
```unknown
PercentageFeatureSet()
```

Example 31 (python):
```python
# The [[ operator can add columns to object metadata. This is a great place to stash QC stats
pbmc[["percent.mt"]] <- PercentageFeatureSet(pbmc, pattern = "^MT-")
```

Example 32 (r):
```r
# The [[ operator can add columns to object metadata. This is a great place to stash QC stats
pbmc[["percent.mt"]] <- PercentageFeatureSet(pbmc, pattern = "^MT-")
```

Example 33 (r):
```r
# The [[ operator can add columns to object metadata. This is a great place to stash QC stats
pbmc[["percent.mt"]] <- PercentageFeatureSet(pbmc, pattern = "^MT-")
```

Example 34 (unknown):
```unknown
CreateSeuratObject()
```

Example 35 (unknown):
```unknown
# Show QC metrics for the first 5 cells
head(pbmc@meta.data, 5)
```

Example 36 (r):
```r
# Show QC metrics for the first 5 cells
head(pbmc@meta.data, 5)
```

Example 37 (r):
```r
# Show QC metrics for the first 5 cells
head(pbmc@meta.data, 5)
```

Example 38 (unknown):
```unknown
##                  orig.ident nCount_RNA nFeature_RNA percent.mt
## AAACATACAACCAC-1     pbmc3k       2419          779  3.0177759
## AAACATTGAGCTAC-1     pbmc3k       4903         1352  3.7935958
## AAACATTGATCAGC-1     pbmc3k       3147         1129  0.8897363
## AAACCGTGCTTCCG-1     pbmc3k       2639          960  1.7430845
## AAACCGTGTATGCG-1     pbmc3k        980          521  1.2244898
```

Example 39 (unknown):
```unknown
##                  orig.ident nCount_RNA nFeature_RNA percent.mt
## AAACATACAACCAC-1     pbmc3k       2419          779  3.0177759
## AAACATTGAGCTAC-1     pbmc3k       4903         1352  3.7935958
## AAACATTGATCAGC-1     pbmc3k       3147         1129  0.8897363
## AAACCGTGCTTCCG-1     pbmc3k       2639          960  1.7430845
## AAACCGTGTATGCG-1     pbmc3k        980          521  1.2244898
```

Example 40 (unknown):
```unknown
# Visualize QC metrics as a violin plot
VlnPlot(pbmc, features = c("nFeature_RNA", "nCount_RNA", "percent.mt"), ncol = 3)
```

Example 41 (r):
```r
# Visualize QC metrics as a violin plot
VlnPlot(pbmc, features = c("nFeature_RNA", "nCount_RNA", "percent.mt"), ncol = 3)
```

Example 42 (r):
```r
# Visualize QC metrics as a violin plot
VlnPlot(pbmc, features = c("nFeature_RNA", "nCount_RNA", "percent.mt"), ncol = 3)
```

Example 43 (python):
```python
# FeatureScatter is typically used to visualize feature-feature relationships, but can be used
# for anything calculated by the object, i.e. columns in object metadata, PC scores etc.

plot1 <- FeatureScatter(pbmc, feature1 = "nCount_RNA", feature2 = "percent.mt")
plot2 <- FeatureScatter(pbmc, feature1 = "nCount_RNA", feature2 = "nFeature_RNA")
plot1 + plot2
```

Example 44 (r):
```r
# FeatureScatter is typically used to visualize feature-feature relationships, but can be used
# for anything calculated by the object, i.e. columns in object metadata, PC scores etc.

plot1 <- FeatureScatter(pbmc, feature1 = "nCount_RNA", feature2 = "percent.mt")
plot2 <- FeatureScatter(pbmc, feature1 = "nCount_RNA", feature2 = "nFeature_RNA")
plot1 + plot2
```

Example 45 (r):
```r
# FeatureScatter is typically used to visualize feature-feature relationships, but can be used
# for anything calculated by the object, i.e. columns in object metadata, PC scores etc.

plot1 <- FeatureScatter(pbmc, feature1 = "nCount_RNA", feature2 = "percent.mt")
plot2 <- FeatureScatter(pbmc, feature1 = "nCount_RNA", feature2 = "nFeature_RNA")
plot1 + plot2
```

Example 46 (unknown):
```unknown
pbmc <- subset(pbmc, subset = nFeature_RNA > 200 & nFeature_RNA < 2500 & percent.mt < 5)
```

Example 47 (r):
```r
pbmc <- subset(pbmc, subset = nFeature_RNA > 200 & nFeature_RNA < 2500 & percent.mt < 5)
```

Example 48 (r):
```r
pbmc <- subset(pbmc, subset = nFeature_RNA > 200 & nFeature_RNA < 2500 & percent.mt < 5)
```

Example 49 (unknown):
```unknown
pbmc[["RNA"]]$data
```

Example 50 (unknown):
```unknown
pbmc <- NormalizeData(pbmc, normalization.method = "LogNormalize", scale.factor = 10000)
```

Example 51 (r):
```r
pbmc <- NormalizeData(pbmc, normalization.method = "LogNormalize", scale.factor = 10000)
```

Example 52 (r):
```r
pbmc <- NormalizeData(pbmc, normalization.method = "LogNormalize", scale.factor = 10000)
```

Example 53 (unknown):
```unknown
pbmc <- NormalizeData(pbmc)
```

Example 54 (r):
```r
pbmc <- NormalizeData(pbmc)
```

Example 55 (r):
```r
pbmc <- NormalizeData(pbmc)
```

Example 56 (unknown):
```unknown
SCTransform()
```

Example 57 (unknown):
```unknown
SCTransform
```

Example 58 (unknown):
```unknown
NormalizeData
```

Example 59 (unknown):
```unknown
FindVariableFeatures
```

Example 60 (unknown):
```unknown
FindVariableFeatures()
```

Example 61 (unknown):
```unknown
pbmc <- FindVariableFeatures(pbmc, selection.method = "vst", nfeatures = 2000)

# Identify the 10 most highly variable genes
top10 <- head(VariableFeatures(pbmc), 10)

# plot variable features with and without labels
plot1 <- VariableFeaturePlot(pbmc)
plot2 <- LabelPoints(plot = plot1, points = top10, repel = TRUE)
plot1 + plot2
```

Example 62 (r):
```r
pbmc <- FindVariableFeatures(pbmc, selection.method = "vst", nfeatures = 2000)

# Identify the 10 most highly variable genes
top10 <- head(VariableFeatures(pbmc), 10)

# plot variable features with and without labels
plot1 <- VariableFeaturePlot(pbmc)
plot2 <- LabelPoints(plot = plot1, points = top10, repel = TRUE)
plot1 + plot2
```

Example 63 (r):
```r
pbmc <- FindVariableFeatures(pbmc, selection.method = "vst", nfeatures = 2000)

# Identify the 10 most highly variable genes
top10 <- head(VariableFeatures(pbmc), 10)

# plot variable features with and without labels
plot1 <- VariableFeaturePlot(pbmc)
plot2 <- LabelPoints(plot = plot1, points = top10, repel = TRUE)
plot1 + plot2
```

Example 64 (unknown):
```unknown
ScaleData()
```

Example 65 (unknown):
```unknown
pbmc[["RNA"]]$scale.data
```

Example 66 (unknown):
```unknown
all.genes <- rownames(pbmc)
pbmc <- ScaleData(pbmc, features = all.genes)
```

Example 67 (r):
```r
all.genes <- rownames(pbmc)
pbmc <- ScaleData(pbmc, features = all.genes)
```

Example 68 (r):
```r
all.genes <- rownames(pbmc)
pbmc <- ScaleData(pbmc, features = all.genes)
```

Example 69 (unknown):
```unknown
ScaleData()
```

Example 70 (unknown):
```unknown
pbmc <- ScaleData(pbmc, vars.to.regress = "percent.mt")
```

Example 71 (r):
```r
pbmc <- ScaleData(pbmc, vars.to.regress = "percent.mt")
```

Example 72 (r):
```r
pbmc <- ScaleData(pbmc, vars.to.regress = "percent.mt")
```

Example 73 (unknown):
```unknown
SCTransform()
```

Example 74 (unknown):
```unknown
ScaleData()
```

Example 75 (unknown):
```unknown
SCTransform()
```

Example 76 (unknown):
```unknown
vars.to.regress
```

Example 77 (unknown):
```unknown
pbmc <- RunPCA(pbmc, features = VariableFeatures(object = pbmc))
```

Example 78 (r):
```r
pbmc <- RunPCA(pbmc, features = VariableFeatures(object = pbmc))
```

Example 79 (r):
```r
pbmc <- RunPCA(pbmc, features = VariableFeatures(object = pbmc))
```

Example 80 (unknown):
```unknown
VizDimReduction()
```

Example 81 (unknown):
```unknown
DimHeatmap()
```

Example 82 (python):
```python
# Examine and visualize PCA results a few different ways
print(pbmc[["pca"]], dims = 1:5, nfeatures = 5)
```

Example 83 (r):
```r
# Examine and visualize PCA results a few different ways
print(pbmc[["pca"]], dims = 1:5, nfeatures = 5)
```

Example 84 (r):
```r
# Examine and visualize PCA results a few different ways
print(pbmc[["pca"]], dims = 1:5, nfeatures = 5)
```

Example 85 (unknown):
```unknown
## PC_ 1 
## Positive:  CST3, TYROBP, LST1, AIF1, FTL 
## Negative:  MALAT1, LTB, IL32, IL7R, CD2 
## PC_ 2 
## Positive:  CD79A, MS4A1, TCL1A, HLA-DQA1, HLA-DQB1 
## Negative:  NKG7, PRF1, CST7, GZMB, GZMA 
## PC_ 3 
## Positive:  HLA-DQA1, CD79A, CD79B, HLA-DQB1, HLA-DPB1 
## Negative:  PPBP, PF4, SDPR, SPARC, GNG11 
## PC_ 4 
## Positive:  HLA-DQA1, CD79B, CD79A, MS4A1, HLA-DQB1 
## Negative:  VIM, IL7R, S100A6, IL32, S100A8 
## PC_ 5 
## Positive:  GZMB, NKG7, S100A8, FGFBP2, GNLY 
## Negative:  LTB, IL7R, CKB, VIM, MS4A7
```

Example 86 (unknown):
```unknown
## PC_ 1 
## Positive:  CST3, TYROBP, LST1, AIF1, FTL 
## Negative:  MALAT1, LTB, IL32, IL7R, CD2 
## PC_ 2 
## Positive:  CD79A, MS4A1, TCL1A, HLA-DQA1, HLA-DQB1 
## Negative:  NKG7, PRF1, CST7, GZMB, GZMA 
## PC_ 3 
## Positive:  HLA-DQA1, CD79A, CD79B, HLA-DQB1, HLA-DPB1 
## Negative:  PPBP, PF4, SDPR, SPARC, GNG11 
## PC_ 4 
## Positive:  HLA-DQA1, CD79B, CD79A, MS4A1, HLA-DQB1 
## Negative:  VIM, IL7R, S100A6, IL32, S100A8 
## PC_ 5 
## Positive:  GZMB, NKG7, S100A8, FGFBP2, GNLY 
## Negative:  LTB, IL7R, CKB, VIM, MS4A7
```

Example 87 (unknown):
```unknown
VizDimLoadings(pbmc, dims = 1:2, reduction = "pca")
```

Example 88 (r):
```r
VizDimLoadings(pbmc, dims = 1:2, reduction = "pca")
```

Example 89 (r):
```r
VizDimLoadings(pbmc, dims = 1:2, reduction = "pca")
```

Example 90 (unknown):
```unknown
DimPlot(pbmc, reduction = "pca") + NoLegend()
```

Example 91 (r):
```r
DimPlot(pbmc, reduction = "pca") + NoLegend()
```

Example 92 (r):
```r
DimPlot(pbmc, reduction = "pca") + NoLegend()
```

Example 93 (unknown):
```unknown
DimHeatmap()
```

Example 94 (unknown):
```unknown
DimHeatmap(pbmc, dims = 1, cells = 500, balanced = TRUE)
```

Example 95 (r):
```r
DimHeatmap(pbmc, dims = 1, cells = 500, balanced = TRUE)
```

Example 96 (r):
```r
DimHeatmap(pbmc, dims = 1, cells = 500, balanced = TRUE)
```

Example 97 (unknown):
```unknown
DimHeatmap(pbmc, dims = 1:15, cells = 500, balanced = TRUE)
```

Example 98 (r):
```r
DimHeatmap(pbmc, dims = 1:15, cells = 500, balanced = TRUE)
```

Example 99 (r):
```r
DimHeatmap(pbmc, dims = 1:15, cells = 500, balanced = TRUE)
```

Example 100 (unknown):
```unknown
ElbowPlot()
```

Example 101 (unknown):
```unknown
ElbowPlot(pbmc)
```

Example 102 (r):
```r
ElbowPlot(pbmc)
```

Example 103 (r):
```r
ElbowPlot(pbmc)
```

Example 104 (unknown):
```unknown
FindNeighbors()
```

Example 105 (unknown):
```unknown
FindClusters()
```

Example 106 (unknown):
```unknown
pbmc <- FindNeighbors(pbmc, dims = 1:10)
pbmc <- FindClusters(pbmc, resolution = 0.5)
```

Example 107 (r):
```r
pbmc <- FindNeighbors(pbmc, dims = 1:10)
pbmc <- FindClusters(pbmc, resolution = 0.5)
```

Example 108 (r):
```r
pbmc <- FindNeighbors(pbmc, dims = 1:10)
pbmc <- FindClusters(pbmc, resolution = 0.5)
```

Example 109 (unknown):
```unknown
## Modularity Optimizer version 1.3.0 by Ludo Waltman and Nees Jan van Eck
## 
## Number of nodes: 2638
## Number of edges: 95965
## 
## Running Louvain algorithm...
## Maximum modularity in 10 random starts: 0.8723
## Number of communities: 9
## Elapsed time: 0 seconds
```

Example 110 (unknown):
```unknown
## Modularity Optimizer version 1.3.0 by Ludo Waltman and Nees Jan van Eck
## 
## Number of nodes: 2638
## Number of edges: 95965
## 
## Running Louvain algorithm...
## Maximum modularity in 10 random starts: 0.8723
## Number of communities: 9
## Elapsed time: 0 seconds
```

Example 111 (unknown):
```unknown
# Look at cluster IDs of the first 5 cells
head(Idents(pbmc), 5)
```

Example 112 (r):
```r
# Look at cluster IDs of the first 5 cells
head(Idents(pbmc), 5)
```

Example 113 (r):
```r
# Look at cluster IDs of the first 5 cells
head(Idents(pbmc), 5)
```

Example 114 (unknown):
```unknown
## AAACATACAACCAC-1 AAACATTGAGCTAC-1 AAACATTGATCAGC-1 AAACCGTGCTTCCG-1 
##                2                3                2                1 
## AAACCGTGTATGCG-1 
##                6 
## Levels: 0 1 2 3 4 5 6 7 8
```

Example 115 (unknown):
```unknown
## AAACATACAACCAC-1 AAACATTGAGCTAC-1 AAACATTGATCAGC-1 AAACCGTGCTTCCG-1 
##                2                3                2                1 
## AAACCGTGTATGCG-1 
##                6 
## Levels: 0 1 2 3 4 5 6 7 8
```

Example 116 (unknown):
```unknown
pbmc <- RunUMAP(pbmc, dims = 1:10)
```

Example 117 (r):
```r
pbmc <- RunUMAP(pbmc, dims = 1:10)
```

Example 118 (r):
```r
pbmc <- RunUMAP(pbmc, dims = 1:10)
```

Example 119 (unknown):
```unknown
# note that you can set `label = TRUE` or use the LabelClusters function to help label
# individual clusters
DimPlot(pbmc, reduction = "umap")
```

Example 120 (r):
```r
# note that you can set `label = TRUE` or use the LabelClusters function to help label
# individual clusters
DimPlot(pbmc, reduction = "umap")
```

Example 121 (r):
```r
# note that you can set `label = TRUE` or use the LabelClusters function to help label
# individual clusters
DimPlot(pbmc, reduction = "umap")
```

Example 122 (unknown):
```unknown
saveRDS(pbmc, file = "../output/pbmc_tutorial.rds")
```

Example 123 (r):
```r
saveRDS(pbmc, file = "../output/pbmc_tutorial.rds")
```

Example 124 (r):
```r
saveRDS(pbmc, file = "../output/pbmc_tutorial.rds")
```

Example 125 (unknown):
```unknown
FindAllMarkers()
```

Example 126 (unknown):
```unknown
?FindMarkers
```

Example 127 (unknown):
```unknown
logfc.threshold
```

Example 128 (unknown):
```unknown
# find all markers of cluster 2
cluster2.markers <- FindMarkers(pbmc, ident.1 = 2)
head(cluster2.markers, n = 5)
```

Example 129 (r):
```r
# find all markers of cluster 2
cluster2.markers <- FindMarkers(pbmc, ident.1 = 2)
head(cluster2.markers, n = 5)
```

Example 130 (r):
```r
# find all markers of cluster 2
cluster2.markers <- FindMarkers(pbmc, ident.1 = 2)
head(cluster2.markers, n = 5)
```

Example 131 (unknown):
```unknown
##             p_val avg_log2FC pct.1 pct.2    p_val_adj
## IL32 2.593535e-91  1.3221171 0.949 0.466 3.556774e-87
## LTB  7.994465e-87  1.3450377 0.981 0.644 1.096361e-82
## CD3D 3.922451e-70  1.0562099 0.922 0.433 5.379250e-66
## IL7R 1.130870e-66  1.4256944 0.748 0.327 1.550876e-62
## LDHB 4.082189e-65  0.9765875 0.953 0.614 5.598314e-61
```

Example 132 (unknown):
```unknown
##             p_val avg_log2FC pct.1 pct.2    p_val_adj
## IL32 2.593535e-91  1.3221171 0.949 0.466 3.556774e-87
## LTB  7.994465e-87  1.3450377 0.981 0.644 1.096361e-82
## CD3D 3.922451e-70  1.0562099 0.922 0.433 5.379250e-66
## IL7R 1.130870e-66  1.4256944 0.748 0.327 1.550876e-62
## LDHB 4.082189e-65  0.9765875 0.953 0.614 5.598314e-61
```

Example 133 (python):
```python
# find all markers distinguishing cluster 5 from clusters 0 and 3
cluster5.markers <- FindMarkers(pbmc, ident.1 = 5, ident.2 = c(0, 3))
head(cluster5.markers, n = 5)
```

Example 134 (r):
```r
# find all markers distinguishing cluster 5 from clusters 0 and 3
cluster5.markers <- FindMarkers(pbmc, ident.1 = 5, ident.2 = c(0, 3))
head(cluster5.markers, n = 5)
```

Example 135 (r):
```r
# find all markers distinguishing cluster 5 from clusters 0 and 3
cluster5.markers <- FindMarkers(pbmc, ident.1 = 5, ident.2 = c(0, 3))
head(cluster5.markers, n = 5)
```

Example 136 (unknown):
```unknown
##                       p_val avg_log2FC pct.1 pct.2     p_val_adj
## FCGR3A        2.150929e-209   6.832372 0.975 0.039 2.949784e-205
## IFITM3        6.103366e-199   6.181000 0.975 0.048 8.370156e-195
## CFD           8.891428e-198   6.052575 0.938 0.037 1.219370e-193
## CD68          2.374425e-194   5.493138 0.926 0.035 3.256286e-190
## RP11-290F20.3 9.308287e-191   6.335402 0.840 0.016 1.276538e-186
```

Example 137 (unknown):
```unknown
##                       p_val avg_log2FC pct.1 pct.2     p_val_adj
## FCGR3A        2.150929e-209   6.832372 0.975 0.039 2.949784e-205
## IFITM3        6.103366e-199   6.181000 0.975 0.048 8.370156e-195
## CFD           8.891428e-198   6.052575 0.938 0.037 1.219370e-193
## CD68          2.374425e-194   5.493138 0.926 0.035 3.256286e-190
## RP11-290F20.3 9.308287e-191   6.335402 0.840 0.016 1.276538e-186
```

Example 138 (unknown):
```unknown
# find markers for every cluster compared to all remaining cells, report only the positive
# ones
pbmc.markers <- FindAllMarkers(pbmc, only.pos = TRUE)
pbmc.markers %>%
    group_by(cluster) %>%
    dplyr::filter(avg_log2FC > 1)
```

Example 139 (r):
```r
# find markers for every cluster compared to all remaining cells, report only the positive
# ones
pbmc.markers <- FindAllMarkers(pbmc, only.pos = TRUE)
pbmc.markers %>%
    group_by(cluster) %>%
    dplyr::filter(avg_log2FC > 1)
```

Example 140 (r):
```r
# find markers for every cluster compared to all remaining cells, report only the positive
# ones
pbmc.markers <- FindAllMarkers(pbmc, only.pos = TRUE)
pbmc.markers %>%
    group_by(cluster) %>%
    dplyr::filter(avg_log2FC > 1)
```

Example 141 (unknown):
```unknown
## # A tibble: 7,046 × 7
## # Groups:   cluster [9]
##        p_val avg_log2FC pct.1 pct.2 p_val_adj cluster gene     
##        <dbl>      <dbl> <dbl> <dbl>     <dbl> <fct>   <chr>    
##  1 1.74e-109       1.19 0.897 0.593 2.39e-105 0       LDHB     
##  2 1.17e- 83       2.37 0.435 0.108 1.60e- 79 0       CCR7     
##  3 8.94e- 79       1.09 0.838 0.403 1.23e- 74 0       CD3D     
##  4 3.05e- 53       1.02 0.722 0.399 4.19e- 49 0       CD3E     
##  5 3.28e- 49       2.10 0.333 0.103 4.50e- 45 0       LEF1     
##  6 6.66e- 49       1.25 0.623 0.358 9.13e- 45 0       NOSIP    
##  7 9.31e- 44       2.02 0.328 0.11  1.28e- 39 0       PRKCQ-AS1
##  8 4.69e- 43       1.53 0.435 0.184 6.43e- 39 0       PIK3IP1  
##  9 1.47e- 39       2.70 0.195 0.04  2.01e- 35 0       FHIT     
## 10 2.44e- 33       1.94 0.262 0.087 3.34e- 29 0       MAL      
## # ℹ 7,036 more rows
```

Example 142 (unknown):
```unknown
## # A tibble: 7,046 × 7
## # Groups:   cluster [9]
##        p_val avg_log2FC pct.1 pct.2 p_val_adj cluster gene     
##        <dbl>      <dbl> <dbl> <dbl>     <dbl> <fct>   <chr>    
##  1 1.74e-109       1.19 0.897 0.593 2.39e-105 0       LDHB     
##  2 1.17e- 83       2.37 0.435 0.108 1.60e- 79 0       CCR7     
##  3 8.94e- 79       1.09 0.838 0.403 1.23e- 74 0       CD3D     
##  4 3.05e- 53       1.02 0.722 0.399 4.19e- 49 0       CD3E     
##  5 3.28e- 49       2.10 0.333 0.103 4.50e- 45 0       LEF1     
##  6 6.66e- 49       1.25 0.623 0.358 9.13e- 45 0       NOSIP    
##  7 9.31e- 44       2.02 0.328 0.11  1.28e- 39 0       PRKCQ-AS1
##  8 4.69e- 43       1.53 0.435 0.184 6.43e- 39 0       PIK3IP1  
##  9 1.47e- 39       2.70 0.195 0.04  2.01e- 35 0       FHIT     
## 10 2.44e- 33       1.94 0.262 0.087 3.34e- 29 0       MAL      
## # ℹ 7,036 more rows
```

Example 143 (unknown):
```unknown
cluster0.markers <- FindMarkers(pbmc, ident.1 = 0, logfc.threshold = 0.25, test.use = "roc", only.pos = TRUE)
```

Example 144 (r):
```r
cluster0.markers <- FindMarkers(pbmc, ident.1 = 0, logfc.threshold = 0.25, test.use = "roc", only.pos = TRUE)
```

Example 145 (r):
```r
cluster0.markers <- FindMarkers(pbmc, ident.1 = 0, logfc.threshold = 0.25, test.use = "roc", only.pos = TRUE)
```

Example 146 (unknown):
```unknown
FeaturePlot()
```

Example 147 (unknown):
```unknown
RidgePlot()
```

Example 148 (unknown):
```unknown
CellScatter()
```

Example 149 (unknown):
```unknown
VlnPlot(pbmc, features = c("MS4A1", "CD79A"))
```

Example 150 (r):
```r
VlnPlot(pbmc, features = c("MS4A1", "CD79A"))
```

Example 151 (r):
```r
VlnPlot(pbmc, features = c("MS4A1", "CD79A"))
```

Example 152 (unknown):
```unknown
# you can plot raw counts as well
VlnPlot(pbmc, features = c("NKG7", "PF4"), slot = "counts", log = TRUE)
```

Example 153 (r):
```r
# you can plot raw counts as well
VlnPlot(pbmc, features = c("NKG7", "PF4"), slot = "counts", log = TRUE)
```

Example 154 (r):
```r
# you can plot raw counts as well
VlnPlot(pbmc, features = c("NKG7", "PF4"), slot = "counts", log = TRUE)
```

Example 155 (unknown):
```unknown
FeaturePlot(pbmc, features = c("MS4A1", "GNLY", "CD3E", "CD14", "FCER1A", "FCGR3A", "LYZ", "PPBP",
    "CD8A"))
```

Example 156 (r):
```r
FeaturePlot(pbmc, features = c("MS4A1", "GNLY", "CD3E", "CD14", "FCER1A", "FCGR3A", "LYZ", "PPBP",
    "CD8A"))
```

Example 157 (r):
```r
FeaturePlot(pbmc, features = c("MS4A1", "GNLY", "CD3E", "CD14", "FCER1A", "FCGR3A", "LYZ", "PPBP",
    "CD8A"))
```

Example 158 (unknown):
```unknown
DoHeatmap()
```

Example 159 (unknown):
```unknown
pbmc.markers %>%
    group_by(cluster) %>%
    dplyr::filter(avg_log2FC > 1) %>%
    slice_head(n = 10) %>%
    ungroup() -> top10
DoHeatmap(pbmc, features = top10$gene) + NoLegend()
```

Example 160 (r):
```r
pbmc.markers %>%
    group_by(cluster) %>%
    dplyr::filter(avg_log2FC > 1) %>%
    slice_head(n = 10) %>%
    ungroup() -> top10
DoHeatmap(pbmc, features = top10$gene) + NoLegend()
```

Example 161 (r):
```r
pbmc.markers %>%
    group_by(cluster) %>%
    dplyr::filter(avg_log2FC > 1) %>%
    slice_head(n = 10) %>%
    ungroup() -> top10
DoHeatmap(pbmc, features = top10$gene) + NoLegend()
```

Example 162 (unknown):
```unknown
new.cluster.ids <- c("Naive CD4 T", "CD14+ Mono", "Memory CD4 T", "B", "CD8 T", "FCGR3A+ Mono",
    "NK", "DC", "Platelet")
names(new.cluster.ids) <- levels(pbmc)
pbmc <- RenameIdents(pbmc, new.cluster.ids)
DimPlot(pbmc, reduction = "umap", label = TRUE, pt.size = 0.5) + NoLegend()
```

Example 163 (r):
```r
new.cluster.ids <- c("Naive CD4 T", "CD14+ Mono", "Memory CD4 T", "B", "CD8 T", "FCGR3A+ Mono",
    "NK", "DC", "Platelet")
names(new.cluster.ids) <- levels(pbmc)
pbmc <- RenameIdents(pbmc, new.cluster.ids)
DimPlot(pbmc, reduction = "umap", label = TRUE, pt.size = 0.5) + NoLegend()
```

Example 164 (r):
```r
new.cluster.ids <- c("Naive CD4 T", "CD14+ Mono", "Memory CD4 T", "B", "CD8 T", "FCGR3A+ Mono",
    "NK", "DC", "Platelet")
names(new.cluster.ids) <- levels(pbmc)
pbmc <- RenameIdents(pbmc, new.cluster.ids)
DimPlot(pbmc, reduction = "umap", label = TRUE, pt.size = 0.5) + NoLegend()
```

Example 165 (unknown):
```unknown
library(ggplot2)
plot <- DimPlot(pbmc, reduction = "umap", label = TRUE, label.size = 4.5) + xlab("UMAP 1") + ylab("UMAP 2") +
    theme(axis.title = element_text(size = 18), legend.text = element_text(size = 18)) + guides(colour = guide_legend(override.aes = list(size = 10)))
ggsave(filename = "../output/images/pbmc3k_umap.jpg", height = 7, width = 12, plot = plot, quality = 50)
```

Example 166 (r):
```r
library(ggplot2)
plot <- DimPlot(pbmc, reduction = "umap", label = TRUE, label.size = 4.5) + xlab("UMAP 1") + ylab("UMAP 2") +
    theme(axis.title = element_text(size = 18), legend.text = element_text(size = 18)) + guides(colour = guide_legend(override.aes = list(size = 10)))
ggsave(filename = "../output/images/pbmc3k_umap.jpg", height = 7, width = 12, plot = plot, quality = 50)
```

Example 167 (r):
```r
library(ggplot2)
plot <- DimPlot(pbmc, reduction = "umap", label = TRUE, label.size = 4.5) + xlab("UMAP 1") + ylab("UMAP 2") +
    theme(axis.title = element_text(size = 18), legend.text = element_text(size = 18)) + guides(colour = guide_legend(override.aes = list(size = 10)))
ggsave(filename = "../output/images/pbmc3k_umap.jpg", height = 7, width = 12, plot = plot, quality = 50)
```

Example 168 (unknown):
```unknown
saveRDS(pbmc, file = "../output/pbmc3k_final.rds")
```

Example 169 (r):
```r
saveRDS(pbmc, file = "../output/pbmc3k_final.rds")
```

Example 170 (r):
```r
saveRDS(pbmc, file = "../output/pbmc3k_final.rds")
```

Example 171 (unknown):
```unknown
sessionInfo()
```

Example 172 (r):
```r
sessionInfo()
```

Example 173 (r):
```r
sessionInfo()
```

Example 174 (unknown):
```unknown
## R version 4.2.2 Patched (2022-11-10 r83330)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.6 LTS
## 
## Matrix products: default
## BLAS:   /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.9.0
## LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.9.0
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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       
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
## [1] ggplot2_3.4.4      patchwork_1.1.3    Seurat_5.0.0       SeuratObject_5.0.0
## [5] sp_2.1-1           dplyr_1.1.3       
## 
## loaded via a namespace (and not attached):
##   [1] spam_2.10-0            systemfonts_1.0.4      plyr_1.8.9            
##   [4] igraph_1.5.1           lazyeval_0.2.2         splines_4.2.2         
##   [7] RcppHNSW_0.5.0         listenv_0.9.0          scattermore_1.2       
##  [10] digest_0.6.33          htmltools_0.5.6.1      fansi_1.0.5           
##  [13] magrittr_2.0.3         memoise_2.0.1          tensor_1.5            
##  [16] cluster_2.1.4          ROCR_1.0-11            limma_3.54.1          
##  [19] globals_0.16.2         matrixStats_1.0.0      R.utils_2.12.2        
##  [22] pkgdown_2.0.7          spatstat.sparse_3.0-3  colorspace_2.1-0      
##  [25] ggrepel_0.9.4          textshaping_0.3.6      xfun_0.40             
##  [28] jsonlite_1.8.7         progressr_0.14.0       spatstat.data_3.0-3   
##  [31] survival_3.5-7         zoo_1.8-12             glue_1.6.2            
##  [34] polyclip_1.10-6        gtable_0.3.4           leiden_0.4.3          
##  [37] future.apply_1.11.0    abind_1.4-5            scales_1.2.1          
##  [40] spatstat.random_3.2-1  miniUI_0.1.1.1         Rcpp_1.0.11           
##  [43] viridisLite_0.4.2      xtable_1.8-4           reticulate_1.34.0     
##  [46] dotCall64_1.1-0        htmlwidgets_1.6.2      httr_1.4.7            
##  [49] RColorBrewer_1.1-3     ellipsis_0.3.2         ica_1.0-3             
##  [52] pkgconfig_2.0.3        R.methodsS3_1.8.2      farver_2.1.1          
##  [55] sass_0.4.7             uwot_0.1.16            deldir_1.0-9          
##  [58] utf8_1.2.4             tidyselect_1.2.0       labeling_0.4.3        
##  [61] rlang_1.1.1            reshape2_1.4.4         later_1.3.1           
##  [64] munsell_0.5.0          tools_4.2.2            cachem_1.0.8          
##  [67] cli_3.6.1              generics_0.1.3         ggridges_0.5.4        
##  [70] evaluate_0.22          stringr_1.5.0          fastmap_1.1.1         
##  [73] yaml_2.3.7             ragg_1.2.5             goftest_1.2-3         
##  [76] knitr_1.45             fs_1.6.3               fitdistrplus_1.1-11   
##  [79] purrr_1.0.2            RANN_2.6.1             pbapply_1.7-2         
##  [82] future_1.33.0          nlme_3.1-162           mime_0.12             
##  [85] formatR_1.14           ggrastr_1.0.1          R.oo_1.25.0           
##  [88] compiler_4.2.2         beeswarm_0.4.0         plotly_4.10.3         
##  [91] png_0.1-8              spatstat.utils_3.0-4   tibble_3.2.1          
##  [94] bslib_0.5.1            stringi_1.7.12         highr_0.10            
##  [97] desc_1.4.2             RSpectra_0.16-1        lattice_0.21-9        
## [100] Matrix_1.6-1.1         vctrs_0.6.4            pillar_1.9.0          
## [103] lifecycle_1.0.3        spatstat.geom_3.2-7    lmtest_0.9-40         
## [106] jquerylib_0.1.4        RcppAnnoy_0.0.21       data.table_1.14.8     
## [109] cowplot_1.1.1          irlba_2.3.5.1          httpuv_1.6.12         
## [112] R6_2.5.1               promises_1.2.1         KernSmooth_2.23-22    
## [115] gridExtra_2.3          vipor_0.4.5            parallelly_1.36.0     
## [118] codetools_0.2-19       fastDummies_1.7.3      MASS_7.3-58.2         
## [121] rprojroot_2.0.3        withr_2.5.2            presto_1.0.0          
## [124] sctransform_0.4.1      parallel_4.2.2         grid_4.2.2            
## [127] tidyr_1.3.0            rmarkdown_2.25         Rtsne_0.16            
## [130] spatstat.explore_3.2-5 shiny_1.7.5.1          ggbeeswarm_0.7.1
```

Example 175 (unknown):
```unknown
## R version 4.2.2 Patched (2022-11-10 r83330)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.6 LTS
## 
## Matrix products: default
## BLAS:   /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.9.0
## LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.9.0
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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       
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
## [1] ggplot2_3.4.4      patchwork_1.1.3    Seurat_5.0.0       SeuratObject_5.0.0
## [5] sp_2.1-1           dplyr_1.1.3       
## 
## loaded via a namespace (and not attached):
##   [1] spam_2.10-0            systemfonts_1.0.4      plyr_1.8.9            
##   [4] igraph_1.5.1           lazyeval_0.2.2         splines_4.2.2         
##   [7] RcppHNSW_0.5.0         listenv_0.9.0          scattermore_1.2       
##  [10] digest_0.6.33          htmltools_0.5.6.1      fansi_1.0.5           
##  [13] magrittr_2.0.3         memoise_2.0.1          tensor_1.5            
##  [16] cluster_2.1.4          ROCR_1.0-11            limma_3.54.1          
##  [19] globals_0.16.2         matrixStats_1.0.0      R.utils_2.12.2        
##  [22] pkgdown_2.0.7          spatstat.sparse_3.0-3  colorspace_2.1-0      
##  [25] ggrepel_0.9.4          textshaping_0.3.6      xfun_0.40             
##  [28] jsonlite_1.8.7         progressr_0.14.0       spatstat.data_3.0-3   
##  [31] survival_3.5-7         zoo_1.8-12             glue_1.6.2            
##  [34] polyclip_1.10-6        gtable_0.3.4           leiden_0.4.3          
##  [37] future.apply_1.11.0    abind_1.4-5            scales_1.2.1          
##  [40] spatstat.random_3.2-1  miniUI_0.1.1.1         Rcpp_1.0.11           
##  [43] viridisLite_0.4.2      xtable_1.8-4           reticulate_1.34.0     
##  [46] dotCall64_1.1-0        htmlwidgets_1.6.2      httr_1.4.7            
##  [49] RColorBrewer_1.1-3     ellipsis_0.3.2         ica_1.0-3             
##  [52] pkgconfig_2.0.3        R.methodsS3_1.8.2      farver_2.1.1          
##  [55] sass_0.4.7             uwot_0.1.16            deldir_1.0-9          
##  [58] utf8_1.2.4             tidyselect_1.2.0       labeling_0.4.3        
##  [61] rlang_1.1.1            reshape2_1.4.4         later_1.3.1           
##  [64] munsell_0.5.0          tools_4.2.2            cachem_1.0.8          
##  [67] cli_3.6.1              generics_0.1.3         ggridges_0.5.4        
##  [70] evaluate_0.22          stringr_1.5.0          fastmap_1.1.1         
##  [73] yaml_2.3.7             ragg_1.2.5             goftest_1.2-3         
##  [76] knitr_1.45             fs_1.6.3               fitdistrplus_1.1-11   
##  [79] purrr_1.0.2            RANN_2.6.1             pbapply_1.7-2         
##  [82] future_1.33.0          nlme_3.1-162           mime_0.12             
##  [85] formatR_1.14           ggrastr_1.0.1          R.oo_1.25.0           
##  [88] compiler_4.2.2         beeswarm_0.4.0         plotly_4.10.3         
##  [91] png_0.1-8              spatstat.utils_3.0-4   tibble_3.2.1          
##  [94] bslib_0.5.1            stringi_1.7.12         highr_0.10            
##  [97] desc_1.4.2             RSpectra_0.16-1        lattice_0.21-9        
## [100] Matrix_1.6-1.1         vctrs_0.6.4            pillar_1.9.0          
## [103] lifecycle_1.0.3        spatstat.geom_3.2-7    lmtest_0.9-40         
## [106] jquerylib_0.1.4        RcppAnnoy_0.0.21       data.table_1.14.8     
## [109] cowplot_1.1.1          irlba_2.3.5.1          httpuv_1.6.12         
## [112] R6_2.5.1               promises_1.2.1         KernSmooth_2.23-22    
## [115] gridExtra_2.3          vipor_0.4.5            parallelly_1.36.0     
## [118] codetools_0.2-19       fastDummies_1.7.3      MASS_7.3-58.2         
## [121] rprojroot_2.0.3        withr_2.5.2            presto_1.0.0          
## [124] sctransform_0.4.1      parallel_4.2.2         grid_4.2.2            
## [127] tidyr_1.3.0            rmarkdown_2.25         Rtsne_0.16            
## [130] spatstat.explore_3.2-5 shiny_1.7.5.1          ggbeeswarm_0.7.1
```

---

## Analysis, visualization, and integration of Visium HD spatial datasets with Seurat • Seurat

**URL:** http://127.0.0.1:9173/articles_seurat5_integration.html

**Contents:**
- Integrative analysis in Seurat v5
    - Compiled: October 31, 2023
- Introduction
- Layers in the Seurat v5 object
- Perform streamlined (one-line) integrative analysis
- Contents

Integration of single-cell sequencing datasets, for example across experimental batches, donors, or conditions, is often an important step in scRNA-seq workflows. Integrative analysis can help to match shared cell types and states across datasets, which can boost statistical power, and most importantly, facilitate accurate comparative analysis across datasets. In previous versions of Seurat we introduced methods for integrative analysis, including our ‘anchor-based’ integration workflow. Many labs have also published powerful and pioneering methods, including Harmony and scVI, for integrative analysis. We recognize that while the goal of matching shared cell types across datasets may be important for many problems, users may also be concerned about which method to use, or that integration could result in a loss of biological resolution. In Seurat v5, we introduce more flexible and streamlined infrastructure to run different integration algorithms with a single line of code. This makes it easier to explore the results of different integration methods, and to compare these results to a workflow that excludes integration steps. For this vignette, we use a dataset of human PBMC profiled with seven different technologies, profiled as part of a systematic comparative analysis (pbmcsca). The data is available as part of our SeuratData package.

Seurat v5 assays store data in layers. These layers can store raw, un-normalized counts (layer='counts'), normalized data (layer='data'), or z-scored/variance-stabilized data (layer='scale.data'). We can load in the data, remove low-quality cells, and obtain predicted cell annotations (which will be useful for assessing integration later), using our Azimuth pipeline.

The object contains data from nine different batches (stored in the Method column in the object metadata), representing seven different technologies. We will aim to integrate the different batches together. In previous versions of Seurat, we would require the data to be represented as nine different Seurat objects. When using Seurat v5 assays, we can instead keep all the data in one object, but simply split the layers. After splitting, there are now 18 layers (a counts and data layer for each batch). We can also run a standard scRNA-seq analysis (i.e. without integration). Note that since the data is split into layers, normalization and variable feature identification is performed for each batch independently (a consensus set of variable features is automatically identified).

We can now visualize the results of a standard analysis without integration. Note that cells are grouping both by cell type and by underlying method. While a UMAP analysis is just a visualization of this, clustering this dataset would return predominantly batch-specific clusters. Especially if previous cell-type annotations were not available, this would make downstream analysis extremely challenging.

Seurat v5 enables streamlined integrative analysis using the IntegrateLayers function. The method currently supports five integration methods. Each of these methods performs integration in low-dimensional space, and returns a dimensional reduction (i.e. integrated.rpca) that aims to co-embed shared cell types across batches:

Note that our anchor-based RPCA integration represents a faster and more conservative (less correction) method for integration. For interested users, we discuss this method in more detail in our previous RPCA vignette

You can find more detail on each method, and any installation prerequisites, in Seurat’s documentation (for example, ?scVIIntegration). For example, scVI integration requires reticulate which can be installed from CRAN (install.packages("reticulate")) as well as scvi-tools and its dependencies installed in a conda environment. Please see scVI installation instructions here.

Each of the following lines perform a new integration using a single line of code:

For any of the methods, we can now visualize and cluster the datasets. We show this for CCA integration and scVI, but you can do this for any method

We hope that by simplifying the process of performing integrative analysis, users can more carefully evaluate the biological information retained in the integrated dataset. For example, users can compare the expression of biological markers based on different clustering solutions, or visualize one method’s clustering solution on different UMAP visualizations.

Once integrative analysis is complete, you can rejoin the layers - which collapses the individual datasets together and recreates the original counts and data layers. You will need to do this before performing any differential expression analysis. However, you can always resplit the layers in case you would like to reperform integrative analysis.

Lastly, users can also perform integration using sctransform-normalized data (see our SCTransform vignette for more information), by first running SCTransform normalization, and then setting the normalization.method argument in IntegrateLayers.

Developed by Rahul Satija, Satija Lab and Collaborators.

Site built with pkgdown 2.0.7.

**Examples:**

Example 1 (unknown):
```unknown
vignettes/seurat5_integration.Rmd
```

Example 2 (unknown):
```unknown
seurat5_integration.Rmd
```

Example 3 (unknown):
```unknown
library(Seurat)
library(SeuratData)
library(SeuratWrappers)
library(Azimuth)
library(ggplot2)
library(patchwork)
options(future.globals.maxSize = 1e9)
```

Example 4 (r):
```r
library(Seurat)
library(SeuratData)
library(SeuratWrappers)
library(Azimuth)
library(ggplot2)
library(patchwork)
options(future.globals.maxSize = 1e9)
```

Example 5 (unknown):
```unknown
layer='counts'
```

Example 6 (unknown):
```unknown
layer='data'
```

Example 7 (unknown):
```unknown
layer='scale.data'
```

Example 8 (unknown):
```unknown
# load in the pbmc systematic comparative analysis dataset
obj <- LoadData("pbmcsca")
obj <- subset(obj, nFeature_RNA > 1000)
obj <- RunAzimuth(obj, reference = "pbmcref")
# currently, the object has two layers in the RNA assay: counts, and data
obj
```

Example 9 (r):
```r
# load in the pbmc systematic comparative analysis dataset
obj <- LoadData("pbmcsca")
obj <- subset(obj, nFeature_RNA > 1000)
obj <- RunAzimuth(obj, reference = "pbmcref")
# currently, the object has two layers in the RNA assay: counts, and data
obj
```

Example 10 (r):
```r
# load in the pbmc systematic comparative analysis dataset
obj <- LoadData("pbmcsca")
obj <- subset(obj, nFeature_RNA > 1000)
obj <- RunAzimuth(obj, reference = "pbmcref")
# currently, the object has two layers in the RNA assay: counts, and data
obj
```

Example 11 (python):
```python
## An object of class Seurat 
## 33789 features across 10434 samples within 4 assays 
## Active assay: RNA (33694 features, 0 variable features)
##  2 layers present: counts, data
##  3 other assays present: prediction.score.celltype.l1, prediction.score.celltype.l2, prediction.score.celltype.l3
##  2 dimensional reductions calculated: integrated_dr, ref.umap
```

Example 12 (python):
```python
## An object of class Seurat 
## 33789 features across 10434 samples within 4 assays 
## Active assay: RNA (33694 features, 0 variable features)
##  2 layers present: counts, data
##  3 other assays present: prediction.score.celltype.l1, prediction.score.celltype.l2, prediction.score.celltype.l3
##  2 dimensional reductions calculated: integrated_dr, ref.umap
```

Example 13 (unknown):
```unknown
obj[["RNA"]] <- split(obj[["RNA"]], f = obj$Method)
obj
```

Example 14 (r):
```r
obj[["RNA"]] <- split(obj[["RNA"]], f = obj$Method)
obj
```

Example 15 (r):
```r
obj[["RNA"]] <- split(obj[["RNA"]], f = obj$Method)
obj
```

Example 16 (python):
```python
## An object of class Seurat 
## 33789 features across 10434 samples within 4 assays 
## Active assay: RNA (33694 features, 0 variable features)
##  18 layers present: counts.Smart-seq2, counts.CEL-Seq2, counts.10x_Chromium_v2_A, counts.10x_Chromium_v2_B, counts.10x_Chromium_v3, counts.Drop-seq, counts.Seq-Well, counts.inDrops, counts.10x_Chromium_v2, data.Smart-seq2, data.CEL-Seq2, data.10x_Chromium_v2_A, data.10x_Chromium_v2_B, data.10x_Chromium_v3, data.Drop-seq, data.Seq-Well, data.inDrops, data.10x_Chromium_v2
##  3 other assays present: prediction.score.celltype.l1, prediction.score.celltype.l2, prediction.score.celltype.l3
##  2 dimensional reductions calculated: integrated_dr, ref.umap
```

Example 17 (python):
```python
## An object of class Seurat 
## 33789 features across 10434 samples within 4 assays 
## Active assay: RNA (33694 features, 0 variable features)
##  18 layers present: counts.Smart-seq2, counts.CEL-Seq2, counts.10x_Chromium_v2_A, counts.10x_Chromium_v2_B, counts.10x_Chromium_v3, counts.Drop-seq, counts.Seq-Well, counts.inDrops, counts.10x_Chromium_v2, data.Smart-seq2, data.CEL-Seq2, data.10x_Chromium_v2_A, data.10x_Chromium_v2_B, data.10x_Chromium_v3, data.Drop-seq, data.Seq-Well, data.inDrops, data.10x_Chromium_v2
##  3 other assays present: prediction.score.celltype.l1, prediction.score.celltype.l2, prediction.score.celltype.l3
##  2 dimensional reductions calculated: integrated_dr, ref.umap
```

Example 18 (unknown):
```unknown
obj <- NormalizeData(obj)
obj <- FindVariableFeatures(obj)
obj <- ScaleData(obj)
obj <- RunPCA(obj)
```

Example 19 (r):
```r
obj <- NormalizeData(obj)
obj <- FindVariableFeatures(obj)
obj <- ScaleData(obj)
obj <- RunPCA(obj)
```

Example 20 (r):
```r
obj <- NormalizeData(obj)
obj <- FindVariableFeatures(obj)
obj <- ScaleData(obj)
obj <- RunPCA(obj)
```

Example 21 (unknown):
```unknown
obj <- FindNeighbors(obj, dims = 1:30, reduction = "pca")
obj <- FindClusters(obj, resolution = 2, cluster.name = "unintegrated_clusters")
```

Example 22 (r):
```r
obj <- FindNeighbors(obj, dims = 1:30, reduction = "pca")
obj <- FindClusters(obj, resolution = 2, cluster.name = "unintegrated_clusters")
```

Example 23 (r):
```r
obj <- FindNeighbors(obj, dims = 1:30, reduction = "pca")
obj <- FindClusters(obj, resolution = 2, cluster.name = "unintegrated_clusters")
```

Example 24 (unknown):
```unknown
## Modularity Optimizer version 1.3.0 by Ludo Waltman and Nees Jan van Eck
## 
## Number of nodes: 10434
## Number of edges: 412660
## 
## Running Louvain algorithm...
## Maximum modularity in 10 random starts: 0.8981
## Number of communities: 48
## Elapsed time: 0 seconds
```

Example 25 (unknown):
```unknown
## Modularity Optimizer version 1.3.0 by Ludo Waltman and Nees Jan van Eck
## 
## Number of nodes: 10434
## Number of edges: 412660
## 
## Running Louvain algorithm...
## Maximum modularity in 10 random starts: 0.8981
## Number of communities: 48
## Elapsed time: 0 seconds
```

Example 26 (unknown):
```unknown
obj <- RunUMAP(obj, dims = 1:30, reduction = "pca", reduction.name = "umap.unintegrated")
# visualize by batch and cell type annotation
# cell type annotations were previously added by Azimuth
DimPlot(obj, reduction = "umap.unintegrated", group.by = c("Method", "predicted.celltype.l2"))
```

Example 27 (r):
```r
obj <- RunUMAP(obj, dims = 1:30, reduction = "pca", reduction.name = "umap.unintegrated")
# visualize by batch and cell type annotation
# cell type annotations were previously added by Azimuth
DimPlot(obj, reduction = "umap.unintegrated", group.by = c("Method", "predicted.celltype.l2"))
```

Example 28 (r):
```r
obj <- RunUMAP(obj, dims = 1:30, reduction = "pca", reduction.name = "umap.unintegrated")
# visualize by batch and cell type annotation
# cell type annotations were previously added by Azimuth
DimPlot(obj, reduction = "umap.unintegrated", group.by = c("Method", "predicted.celltype.l2"))
```

Example 29 (unknown):
```unknown
IntegrateLayers
```

Example 30 (unknown):
```unknown
integrated.rpca
```

Example 31 (unknown):
```unknown
method=CCAIntegration
```

Example 32 (unknown):
```unknown
method=RPCAIntegration
```

Example 33 (unknown):
```unknown
method=HarmonyIntegration
```

Example 34 (unknown):
```unknown
method= FastMNNIntegration
```

Example 35 (unknown):
```unknown
method=scVIIntegration
```

Example 36 (unknown):
```unknown
?scVIIntegration
```

Example 37 (unknown):
```unknown
install.packages("reticulate")
```

Example 38 (unknown):
```unknown
obj <- IntegrateLayers(
  object = obj, method = CCAIntegration,
  orig.reduction = "pca", new.reduction = "integrated.cca",
  verbose = FALSE
)
```

Example 39 (r):
```r
obj <- IntegrateLayers(
  object = obj, method = CCAIntegration,
  orig.reduction = "pca", new.reduction = "integrated.cca",
  verbose = FALSE
)
```

Example 40 (r):
```r
obj <- IntegrateLayers(
  object = obj, method = CCAIntegration,
  orig.reduction = "pca", new.reduction = "integrated.cca",
  verbose = FALSE
)
```

Example 41 (unknown):
```unknown
obj <- IntegrateLayers(
  object = obj, method = RPCAIntegration,
  orig.reduction = "pca", new.reduction = "integrated.rpca",
  verbose = FALSE
)
```

Example 42 (r):
```r
obj <- IntegrateLayers(
  object = obj, method = RPCAIntegration,
  orig.reduction = "pca", new.reduction = "integrated.rpca",
  verbose = FALSE
)
```

Example 43 (r):
```r
obj <- IntegrateLayers(
  object = obj, method = RPCAIntegration,
  orig.reduction = "pca", new.reduction = "integrated.rpca",
  verbose = FALSE
)
```

Example 44 (unknown):
```unknown
obj <- IntegrateLayers(
  object = obj, method = HarmonyIntegration,
  orig.reduction = "pca", new.reduction = "harmony",
  verbose = FALSE
)
```

Example 45 (r):
```r
obj <- IntegrateLayers(
  object = obj, method = HarmonyIntegration,
  orig.reduction = "pca", new.reduction = "harmony",
  verbose = FALSE
)
```

Example 46 (r):
```r
obj <- IntegrateLayers(
  object = obj, method = HarmonyIntegration,
  orig.reduction = "pca", new.reduction = "harmony",
  verbose = FALSE
)
```

Example 47 (unknown):
```unknown
obj <- IntegrateLayers(
  object = obj, method = FastMNNIntegration,
  new.reduction = "integrated.mnn",
  verbose = FALSE
)
```

Example 48 (r):
```r
obj <- IntegrateLayers(
  object = obj, method = FastMNNIntegration,
  new.reduction = "integrated.mnn",
  verbose = FALSE
)
```

Example 49 (r):
```r
obj <- IntegrateLayers(
  object = obj, method = FastMNNIntegration,
  new.reduction = "integrated.mnn",
  verbose = FALSE
)
```

Example 50 (unknown):
```unknown
obj <- IntegrateLayers(
  object = obj, method = scVIIntegration,
  new.reduction = "integrated.scvi",
  conda_env = "../miniconda3/envs/scvi-env", verbose = FALSE
)
```

Example 51 (r):
```r
obj <- IntegrateLayers(
  object = obj, method = scVIIntegration,
  new.reduction = "integrated.scvi",
  conda_env = "../miniconda3/envs/scvi-env", verbose = FALSE
)
```

Example 52 (r):
```r
obj <- IntegrateLayers(
  object = obj, method = scVIIntegration,
  new.reduction = "integrated.scvi",
  conda_env = "../miniconda3/envs/scvi-env", verbose = FALSE
)
```

Example 53 (unknown):
```unknown
obj <- FindNeighbors(obj, reduction = "integrated.cca", dims = 1:30)
obj <- FindClusters(obj, resolution = 2, cluster.name = "cca_clusters")
```

Example 54 (r):
```r
obj <- FindNeighbors(obj, reduction = "integrated.cca", dims = 1:30)
obj <- FindClusters(obj, resolution = 2, cluster.name = "cca_clusters")
```

Example 55 (r):
```r
obj <- FindNeighbors(obj, reduction = "integrated.cca", dims = 1:30)
obj <- FindClusters(obj, resolution = 2, cluster.name = "cca_clusters")
```

Example 56 (unknown):
```unknown
## Modularity Optimizer version 1.3.0 by Ludo Waltman and Nees Jan van Eck
## 
## Number of nodes: 10434
## Number of edges: 617402
## 
## Running Louvain algorithm...
## Maximum modularity in 10 random starts: 0.8037
## Number of communities: 25
## Elapsed time: 1 seconds
```

Example 57 (unknown):
```unknown
## Modularity Optimizer version 1.3.0 by Ludo Waltman and Nees Jan van Eck
## 
## Number of nodes: 10434
## Number of edges: 617402
## 
## Running Louvain algorithm...
## Maximum modularity in 10 random starts: 0.8037
## Number of communities: 25
## Elapsed time: 1 seconds
```

Example 58 (unknown):
```unknown
obj <- RunUMAP(obj, reduction = "integrated.cca", dims = 1:30, reduction.name = "umap.cca")
p1 <- DimPlot(
  obj,
  reduction = "umap.cca",
  group.by = c("Method", "predicted.celltype.l2", "cca_clusters"),
  combine = FALSE, label.size = 2
)

obj <- FindNeighbors(obj, reduction = "integrated.scvi", dims = 1:30)
obj <- FindClusters(obj, resolution = 2, cluster.name = "scvi_clusters")
```

Example 59 (r):
```r
obj <- RunUMAP(obj, reduction = "integrated.cca", dims = 1:30, reduction.name = "umap.cca")
p1 <- DimPlot(
  obj,
  reduction = "umap.cca",
  group.by = c("Method", "predicted.celltype.l2", "cca_clusters"),
  combine = FALSE, label.size = 2
)

obj <- FindNeighbors(obj, reduction = "integrated.scvi", dims = 1:30)
obj <- FindClusters(obj, resolution = 2, cluster.name = "scvi_clusters")
```

Example 60 (r):
```r
obj <- RunUMAP(obj, reduction = "integrated.cca", dims = 1:30, reduction.name = "umap.cca")
p1 <- DimPlot(
  obj,
  reduction = "umap.cca",
  group.by = c("Method", "predicted.celltype.l2", "cca_clusters"),
  combine = FALSE, label.size = 2
)

obj <- FindNeighbors(obj, reduction = "integrated.scvi", dims = 1:30)
obj <- FindClusters(obj, resolution = 2, cluster.name = "scvi_clusters")
```

Example 61 (unknown):
```unknown
## Modularity Optimizer version 1.3.0 by Ludo Waltman and Nees Jan van Eck
## 
## Number of nodes: 10434
## Number of edges: 354664
## 
## Running Louvain algorithm...
## Maximum modularity in 10 random starts: 0.7942
## Number of communities: 22
## Elapsed time: 1 seconds
```

Example 62 (unknown):
```unknown
## Modularity Optimizer version 1.3.0 by Ludo Waltman and Nees Jan van Eck
## 
## Number of nodes: 10434
## Number of edges: 354664
## 
## Running Louvain algorithm...
## Maximum modularity in 10 random starts: 0.7942
## Number of communities: 22
## Elapsed time: 1 seconds
```

Example 63 (unknown):
```unknown
obj <- RunUMAP(obj, reduction = "integrated.scvi", dims = 1:30, reduction.name = "umap.scvi")
p2 <- DimPlot(
  obj,
  reduction = "umap.scvi",
  group.by = c("Method", "predicted.celltype.l2", "scvi_clusters"),
  combine = FALSE, label.size = 2
)

wrap_plots(c(p1, p2), ncol = 2, byrow = F)
```

Example 64 (r):
```r
obj <- RunUMAP(obj, reduction = "integrated.scvi", dims = 1:30, reduction.name = "umap.scvi")
p2 <- DimPlot(
  obj,
  reduction = "umap.scvi",
  group.by = c("Method", "predicted.celltype.l2", "scvi_clusters"),
  combine = FALSE, label.size = 2
)

wrap_plots(c(p1, p2), ncol = 2, byrow = F)
```

Example 65 (r):
```r
obj <- RunUMAP(obj, reduction = "integrated.scvi", dims = 1:30, reduction.name = "umap.scvi")
p2 <- DimPlot(
  obj,
  reduction = "umap.scvi",
  group.by = c("Method", "predicted.celltype.l2", "scvi_clusters"),
  combine = FALSE, label.size = 2
)

wrap_plots(c(p1, p2), ncol = 2, byrow = F)
```

Example 66 (unknown):
```unknown
p1 <- VlnPlot(
  obj,
  features = "rna_CD8A", group.by = "unintegrated_clusters"
) + NoLegend() + ggtitle("CD8A - Unintegrated Clusters")
p2 <- VlnPlot(
  obj, "rna_CD8A",
  group.by = "cca_clusters"
) + NoLegend() + ggtitle("CD8A - CCA Clusters")
p3 <- VlnPlot(
  obj, "rna_CD8A",
  group.by = "scvi_clusters"
) + NoLegend() + ggtitle("CD8A - scVI Clusters")
p1 | p2 | p3
```

Example 67 (r):
```r
p1 <- VlnPlot(
  obj,
  features = "rna_CD8A", group.by = "unintegrated_clusters"
) + NoLegend() + ggtitle("CD8A - Unintegrated Clusters")
p2 <- VlnPlot(
  obj, "rna_CD8A",
  group.by = "cca_clusters"
) + NoLegend() + ggtitle("CD8A - CCA Clusters")
p3 <- VlnPlot(
  obj, "rna_CD8A",
  group.by = "scvi_clusters"
) + NoLegend() + ggtitle("CD8A - scVI Clusters")
p1 | p2 | p3
```

Example 68 (r):
```r
p1 <- VlnPlot(
  obj,
  features = "rna_CD8A", group.by = "unintegrated_clusters"
) + NoLegend() + ggtitle("CD8A - Unintegrated Clusters")
p2 <- VlnPlot(
  obj, "rna_CD8A",
  group.by = "cca_clusters"
) + NoLegend() + ggtitle("CD8A - CCA Clusters")
p3 <- VlnPlot(
  obj, "rna_CD8A",
  group.by = "scvi_clusters"
) + NoLegend() + ggtitle("CD8A - scVI Clusters")
p1 | p2 | p3
```

Example 69 (unknown):
```unknown
obj <- RunUMAP(obj, reduction = "integrated.rpca", dims = 1:30, reduction.name = "umap.rpca")
p4 <- DimPlot(obj, reduction = "umap.unintegrated", group.by = c("cca_clusters"))
p5 <- DimPlot(obj, reduction = "umap.rpca", group.by = c("cca_clusters"))
p6 <- DimPlot(obj, reduction = "umap.scvi", group.by = c("cca_clusters"))
p4 | p5 | p6
```

Example 70 (r):
```r
obj <- RunUMAP(obj, reduction = "integrated.rpca", dims = 1:30, reduction.name = "umap.rpca")
p4 <- DimPlot(obj, reduction = "umap.unintegrated", group.by = c("cca_clusters"))
p5 <- DimPlot(obj, reduction = "umap.rpca", group.by = c("cca_clusters"))
p6 <- DimPlot(obj, reduction = "umap.scvi", group.by = c("cca_clusters"))
p4 | p5 | p6
```

Example 71 (r):
```r
obj <- RunUMAP(obj, reduction = "integrated.rpca", dims = 1:30, reduction.name = "umap.rpca")
p4 <- DimPlot(obj, reduction = "umap.unintegrated", group.by = c("cca_clusters"))
p5 <- DimPlot(obj, reduction = "umap.rpca", group.by = c("cca_clusters"))
p6 <- DimPlot(obj, reduction = "umap.scvi", group.by = c("cca_clusters"))
p4 | p5 | p6
```

Example 72 (unknown):
```unknown
obj <- JoinLayers(obj)
obj
```

Example 73 (r):
```r
obj <- JoinLayers(obj)
obj
```

Example 74 (r):
```r
obj <- JoinLayers(obj)
obj
```

Example 75 (python):
```python
## An object of class Seurat 
## 35789 features across 10434 samples within 5 assays 
## Active assay: RNA (33694 features, 2000 variable features)
##  3 layers present: data, counts, scale.data
##  4 other assays present: prediction.score.celltype.l1, prediction.score.celltype.l2, prediction.score.celltype.l3, mnn.reconstructed
##  12 dimensional reductions calculated: integrated_dr, ref.umap, pca, umap.unintegrated, integrated.cca, integrated.rpca, harmony, integrated.mnn, integrated.scvi, umap.cca, umap.scvi, umap.rpca
```

Example 76 (python):
```python
## An object of class Seurat 
## 35789 features across 10434 samples within 5 assays 
## Active assay: RNA (33694 features, 2000 variable features)
##  3 layers present: data, counts, scale.data
##  4 other assays present: prediction.score.celltype.l1, prediction.score.celltype.l2, prediction.score.celltype.l3, mnn.reconstructed
##  12 dimensional reductions calculated: integrated_dr, ref.umap, pca, umap.unintegrated, integrated.cca, integrated.rpca, harmony, integrated.mnn, integrated.scvi, umap.cca, umap.scvi, umap.rpca
```

Example 77 (unknown):
```unknown
normalization.method
```

Example 78 (unknown):
```unknown
IntegrateLayers
```

Example 79 (unknown):
```unknown
options(future.globals.maxSize = 3e+09)
obj <- SCTransform(obj)
obj <- RunPCA(obj, npcs = 30, verbose = F)
obj <- IntegrateLayers(
  object = obj,
  method = RPCAIntegration,
  normalization.method = "SCT",
  verbose = F
)
obj <- FindNeighbors(obj, dims = 1:30, reduction = "integrated.dr")
obj <- FindClusters(obj, resolution = 2)
```

Example 80 (r):
```r
options(future.globals.maxSize = 3e+09)
obj <- SCTransform(obj)
obj <- RunPCA(obj, npcs = 30, verbose = F)
obj <- IntegrateLayers(
  object = obj,
  method = RPCAIntegration,
  normalization.method = "SCT",
  verbose = F
)
obj <- FindNeighbors(obj, dims = 1:30, reduction = "integrated.dr")
obj <- FindClusters(obj, resolution = 2)
```

Example 81 (r):
```r
options(future.globals.maxSize = 3e+09)
obj <- SCTransform(obj)
obj <- RunPCA(obj, npcs = 30, verbose = F)
obj <- IntegrateLayers(
  object = obj,
  method = RPCAIntegration,
  normalization.method = "SCT",
  verbose = F
)
obj <- FindNeighbors(obj, dims = 1:30, reduction = "integrated.dr")
obj <- FindClusters(obj, resolution = 2)
```

Example 82 (unknown):
```unknown
## Modularity Optimizer version 1.3.0 by Ludo Waltman and Nees Jan van Eck
## 
## Number of nodes: 10434
## Number of edges: 449127
## 
## Running Louvain algorithm...
## Maximum modularity in 10 random starts: 0.8354
## Number of communities: 26
## Elapsed time: 1 seconds
```

Example 83 (unknown):
```unknown
## Modularity Optimizer version 1.3.0 by Ludo Waltman and Nees Jan van Eck
## 
## Number of nodes: 10434
## Number of edges: 449127
## 
## Running Louvain algorithm...
## Maximum modularity in 10 random starts: 0.8354
## Number of communities: 26
## Elapsed time: 1 seconds
```

Example 84 (unknown):
```unknown
obj <- RunUMAP(obj, dims = 1:30, reduction = "integrated.dr")
```

Example 85 (r):
```r
obj <- RunUMAP(obj, dims = 1:30, reduction = "integrated.dr")
```

Example 86 (r):
```r
obj <- RunUMAP(obj, dims = 1:30, reduction = "integrated.dr")
```

Example 87 (unknown):
```unknown
sessionInfo()
```

Example 88 (r):
```r
sessionInfo()
```

Example 89 (r):
```r
sessionInfo()
```

Example 90 (unknown):
```unknown
## R version 4.2.2 Patched (2022-11-10 r83330)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.6 LTS
## 
## Matrix products: default
## BLAS:   /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.9.0
## LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.9.0
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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       
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
##  [1] patchwork_1.1.3               ggplot2_3.4.4                
##  [3] Azimuth_0.4.6.9004            shinyBS_0.61.1               
##  [5] SeuratWrappers_0.3.19         thp1.eccite.SeuratData_3.1.5 
##  [7] stxBrain.SeuratData_0.1.1     ssHippo.SeuratData_3.1.4     
##  [9] pbmcsca.SeuratData_3.0.0      pbmcref.SeuratData_1.0.0     
## [11] pbmcMultiome.SeuratData_0.1.4 pbmc3k.SeuratData_3.1.4      
## [13] panc8.SeuratData_3.0.2        ifnb.SeuratData_3.0.0        
## [15] hcabm40k.SeuratData_3.0.0     cbmc.SeuratData_3.1.4        
## [17] bmcite.SeuratData_0.3.0       SeuratData_0.2.2.9001        
## [19] Seurat_5.0.1                  SeuratObject_5.0.1           
## [21] sp_2.1-1                     
## 
## loaded via a namespace (and not attached):
##   [1] rsvd_1.0.5                        ica_1.0-3                        
##   [3] RcppRoll_0.3.0                    Rsamtools_2.14.0                 
##   [5] lmtest_0.9-40                     rprojroot_2.0.3                  
##   [7] crayon_1.5.2                      MASS_7.3-58.2                    
##   [9] rhdf5filters_1.10.1               nlme_3.1-162                     
##  [11] rlang_1.1.1                       XVector_0.38.0                   
##  [13] ROCR_1.0-11                       irlba_2.3.5.1                    
##  [15] filelock_1.0.2                    BiocParallel_1.32.6              
##  [17] rjson_0.2.21                      CNEr_1.34.0                      
##  [19] bit64_4.0.5                       glue_1.6.2                       
##  [21] harmony_1.0.3                     poweRlaw_0.70.6                  
##  [23] sctransform_0.4.1                 vipor_0.4.5                      
##  [25] parallel_4.2.2                    spatstat.sparse_3.0-3            
##  [27] AnnotationDbi_1.60.2              SeuratDisk_0.0.0.9020            
##  [29] BiocGenerics_0.44.0               shinydashboard_0.7.2             
##  [31] dotCall64_1.1-0                   spatstat.geom_3.2-7              
##  [33] tidyselect_1.2.0                  SummarizedExperiment_1.28.0      
##  [35] fitdistrplus_1.1-11               XML_3.99-0.14                    
##  [37] tidyr_1.3.0                       zoo_1.8-12                       
##  [39] GenomicAlignments_1.34.1          xtable_1.8-4                     
##  [41] RcppHNSW_0.5.0                    magrittr_2.0.3                   
##  [43] evaluate_0.22                     scuttle_1.8.4                    
##  [45] cli_3.6.1                         zlibbioc_1.44.0                  
##  [47] miniUI_0.1.1.1                    bslib_0.5.1                      
##  [49] fastmatch_1.1-4                   ensembldb_2.22.0                 
##  [51] fastDummies_1.7.3                 shiny_1.7.5.1                    
##  [53] BiocSingular_1.14.0               xfun_0.40                        
##  [55] cluster_2.1.4                     caTools_1.18.2                   
##  [57] KEGGREST_1.38.0                   tibble_3.2.1                     
##  [59] ggrepel_0.9.4                     listenv_0.9.0                    
##  [61] TFMPvalue_0.0.9                   Biostrings_2.66.0                
##  [63] png_0.1-8                         future_1.33.0                    
##  [65] withr_2.5.2                       bitops_1.0-7                     
##  [67] plyr_1.8.9                        cellranger_1.1.0                 
##  [69] AnnotationFilter_1.22.0           pracma_2.4.2                     
##  [71] pillar_1.9.0                      cachem_1.0.8                     
##  [73] GenomicFeatures_1.50.4            fs_1.6.3                         
##  [75] hdf5r_1.3.8                       DelayedMatrixStats_1.20.0        
##  [77] vctrs_0.6.4                       ellipsis_0.3.2                   
##  [79] generics_0.1.3                    tools_4.2.2                      
##  [81] beeswarm_0.4.0                    munsell_0.5.0                    
##  [83] DelayedArray_0.24.0               fastmap_1.1.1                    
##  [85] compiler_4.2.2                    abind_1.4-5                      
##  [87] httpuv_1.6.12                     rtracklayer_1.58.0               
##  [89] plotly_4.10.3                     GenomeInfoDbData_1.2.9           
##  [91] gridExtra_2.3                     lattice_0.21-9                   
##  [93] deldir_1.0-9                      utf8_1.2.4                       
##  [95] later_1.3.1                       dplyr_1.1.3                      
##  [97] BiocFileCache_2.6.1               jsonlite_1.8.7                   
##  [99] scales_1.2.1                      ScaledMatrix_1.6.0               
## [101] pbapply_1.7-2                     sparseMatrixStats_1.10.0         
## [103] lazyeval_0.2.2                    promises_1.2.1                   
## [105] R.utils_2.12.2                    goftest_1.2-3                    
## [107] spatstat.utils_3.0-4              reticulate_1.34.0                
## [109] rmarkdown_2.25                    pkgdown_2.0.7                    
## [111] cowplot_1.1.1                     textshaping_0.3.6                
## [113] glmGamPoi_1.10.2                  Rtsne_0.16                       
## [115] BSgenome_1.66.3                   Biobase_2.58.0                   
## [117] uwot_0.1.16                       igraph_1.5.1                     
## [119] survival_3.5-7                    ResidualMatrix_1.8.0             
## [121] yaml_2.3.7                        systemfonts_1.0.4                
## [123] htmltools_0.5.6.1                 memoise_2.0.1                    
## [125] BiocIO_1.8.0                      IRanges_2.32.0                   
## [127] viridisLite_0.4.2                 digest_0.6.33                    
## [129] RhpcBLASctl_0.23-42               mime_0.12                        
## [131] rappdirs_0.3.3                    spam_2.10-0                      
## [133] RSQLite_2.3.1                     future.apply_1.11.0              
## [135] remotes_2.4.2.1                   data.table_1.14.8                
## [137] blob_1.2.4                        JASPAR2020_0.99.10               
## [139] S4Vectors_0.36.2                  R.oo_1.25.0                      
## [141] TFBSTools_1.36.0                  ragg_1.2.5                       
## [143] styler_1.10.2                     splines_4.2.2                    
## [145] labeling_0.4.3                    Rhdf5lib_1.20.0                  
## [147] googledrive_2.1.1                 ProtGenerics_1.30.0              
## [149] RCurl_1.98-1.12                   hms_1.1.3                        
## [151] rhdf5_2.42.1                      colorspace_2.1-0                 
## [153] BiocManager_1.30.22               ggbeeswarm_0.7.1                 
## [155] GenomicRanges_1.50.2              Signac_1.12.9000                 
## [157] ggrastr_1.0.1                     sass_0.4.7                       
## [159] Rcpp_1.0.11                       BSgenome.Hsapiens.UCSC.hg38_1.4.5
## [161] RANN_2.6.1                        fansi_1.0.5                      
## [163] tzdb_0.4.0                        parallelly_1.36.0                
## [165] R6_2.5.1                          grid_4.2.2                       
## [167] ggridges_0.5.4                    lifecycle_1.0.3                  
## [169] curl_5.1.0                        googlesheets4_1.1.1              
## [171] leiden_0.4.3                      jquerylib_0.1.4                  
## [173] Matrix_1.6-1.1                    desc_1.4.2                       
## [175] RcppAnnoy_0.0.21                  RColorBrewer_1.1-3               
## [177] spatstat.explore_3.2-5            stringr_1.5.0                    
## [179] R.cache_0.16.0                    htmlwidgets_1.6.2                
## [181] beachmat_2.14.2                   polyclip_1.10-6                  
## [183] biomaRt_2.54.1                    purrr_1.0.2                      
## [185] seqLogo_1.64.0                    globals_0.16.2                   
## [187] spatstat.random_3.2-1             progressr_0.14.0                 
## [189] batchelor_1.14.1                  codetools_0.2-19                 
## [191] matrixStats_1.0.0                 GO.db_3.16.0                     
## [193] gtools_3.9.4                      prettyunits_1.1.1                
## [195] SingleCellExperiment_1.20.1       dbplyr_2.3.4                     
## [197] RSpectra_0.16-1                   R.methodsS3_1.8.2                
## [199] GenomeInfoDb_1.34.9               gtable_0.3.4                     
## [201] DBI_1.1.3                         stats4_4.2.2                     
## [203] tensor_1.5                        httr_1.4.7                       
## [205] highr_0.10                        KernSmooth_2.23-22               
## [207] stringi_1.7.12                    presto_1.0.0                     
## [209] progress_1.2.2                    reshape2_1.4.4                   
## [211] farver_2.1.1                      annotate_1.76.0                  
## [213] DT_0.30                           xml2_1.3.5                       
## [215] EnsDb.Hsapiens.v86_2.99.0         shinyjs_2.1.0                    
## [217] BiocNeighbors_1.16.0              restfulr_0.0.15                  
## [219] readr_2.1.4                       scattermore_1.2                  
## [221] bit_4.0.5                         MatrixGenerics_1.10.0            
## [223] spatstat.data_3.0-3               pkgconfig_2.0.3                  
## [225] gargle_1.5.2                      DirichletMultinomial_1.40.0      
## [227] knitr_1.45
```

Example 91 (unknown):
```unknown
## R version 4.2.2 Patched (2022-11-10 r83330)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.6 LTS
## 
## Matrix products: default
## BLAS:   /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.9.0
## LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.9.0
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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       
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
##  [1] patchwork_1.1.3               ggplot2_3.4.4                
##  [3] Azimuth_0.4.6.9004            shinyBS_0.61.1               
##  [5] SeuratWrappers_0.3.19         thp1.eccite.SeuratData_3.1.5 
##  [7] stxBrain.SeuratData_0.1.1     ssHippo.SeuratData_3.1.4     
##  [9] pbmcsca.SeuratData_3.0.0      pbmcref.SeuratData_1.0.0     
## [11] pbmcMultiome.SeuratData_0.1.4 pbmc3k.SeuratData_3.1.4      
## [13] panc8.SeuratData_3.0.2        ifnb.SeuratData_3.0.0        
## [15] hcabm40k.SeuratData_3.0.0     cbmc.SeuratData_3.1.4        
## [17] bmcite.SeuratData_0.3.0       SeuratData_0.2.2.9001        
## [19] Seurat_5.0.1                  SeuratObject_5.0.1           
## [21] sp_2.1-1                     
## 
## loaded via a namespace (and not attached):
##   [1] rsvd_1.0.5                        ica_1.0-3                        
##   [3] RcppRoll_0.3.0                    Rsamtools_2.14.0                 
##   [5] lmtest_0.9-40                     rprojroot_2.0.3                  
##   [7] crayon_1.5.2                      MASS_7.3-58.2                    
##   [9] rhdf5filters_1.10.1               nlme_3.1-162                     
##  [11] rlang_1.1.1                       XVector_0.38.0                   
##  [13] ROCR_1.0-11                       irlba_2.3.5.1                    
##  [15] filelock_1.0.2                    BiocParallel_1.32.6              
##  [17] rjson_0.2.21                      CNEr_1.34.0                      
##  [19] bit64_4.0.5                       glue_1.6.2                       
##  [21] harmony_1.0.3                     poweRlaw_0.70.6                  
##  [23] sctransform_0.4.1                 vipor_0.4.5                      
##  [25] parallel_4.2.2                    spatstat.sparse_3.0-3            
##  [27] AnnotationDbi_1.60.2              SeuratDisk_0.0.0.9020            
##  [29] BiocGenerics_0.44.0               shinydashboard_0.7.2             
##  [31] dotCall64_1.1-0                   spatstat.geom_3.2-7              
##  [33] tidyselect_1.2.0                  SummarizedExperiment_1.28.0      
##  [35] fitdistrplus_1.1-11               XML_3.99-0.14                    
##  [37] tidyr_1.3.0                       zoo_1.8-12                       
##  [39] GenomicAlignments_1.34.1          xtable_1.8-4                     
##  [41] RcppHNSW_0.5.0                    magrittr_2.0.3                   
##  [43] evaluate_0.22                     scuttle_1.8.4                    
##  [45] cli_3.6.1                         zlibbioc_1.44.0                  
##  [47] miniUI_0.1.1.1                    bslib_0.5.1                      
##  [49] fastmatch_1.1-4                   ensembldb_2.22.0                 
##  [51] fastDummies_1.7.3                 shiny_1.7.5.1                    
##  [53] BiocSingular_1.14.0               xfun_0.40                        
##  [55] cluster_2.1.4                     caTools_1.18.2                   
##  [57] KEGGREST_1.38.0                   tibble_3.2.1                     
##  [59] ggrepel_0.9.4                     listenv_0.9.0                    
##  [61] TFMPvalue_0.0.9                   Biostrings_2.66.0                
##  [63] png_0.1-8                         future_1.33.0                    
##  [65] withr_2.5.2                       bitops_1.0-7                     
##  [67] plyr_1.8.9                        cellranger_1.1.0                 
##  [69] AnnotationFilter_1.22.0           pracma_2.4.2                     
##  [71] pillar_1.9.0                      cachem_1.0.8                     
##  [73] GenomicFeatures_1.50.4            fs_1.6.3                         
##  [75] hdf5r_1.3.8                       DelayedMatrixStats_1.20.0        
##  [77] vctrs_0.6.4                       ellipsis_0.3.2                   
##  [79] generics_0.1.3                    tools_4.2.2                      
##  [81] beeswarm_0.4.0                    munsell_0.5.0                    
##  [83] DelayedArray_0.24.0               fastmap_1.1.1                    
##  [85] compiler_4.2.2                    abind_1.4-5                      
##  [87] httpuv_1.6.12                     rtracklayer_1.58.0               
##  [89] plotly_4.10.3                     GenomeInfoDbData_1.2.9           
##  [91] gridExtra_2.3                     lattice_0.21-9                   
##  [93] deldir_1.0-9                      utf8_1.2.4                       
##  [95] later_1.3.1                       dplyr_1.1.3                      
##  [97] BiocFileCache_2.6.1               jsonlite_1.8.7                   
##  [99] scales_1.2.1                      ScaledMatrix_1.6.0               
## [101] pbapply_1.7-2                     sparseMatrixStats_1.10.0         
## [103] lazyeval_0.2.2                    promises_1.2.1                   
## [105] R.utils_2.12.2                    goftest_1.2-3                    
## [107] spatstat.utils_3.0-4              reticulate_1.34.0                
## [109] rmarkdown_2.25                    pkgdown_2.0.7                    
## [111] cowplot_1.1.1                     textshaping_0.3.6                
## [113] glmGamPoi_1.10.2                  Rtsne_0.16                       
## [115] BSgenome_1.66.3                   Biobase_2.58.0                   
## [117] uwot_0.1.16                       igraph_1.5.1                     
## [119] survival_3.5-7                    ResidualMatrix_1.8.0             
## [121] yaml_2.3.7                        systemfonts_1.0.4                
## [123] htmltools_0.5.6.1                 memoise_2.0.1                    
## [125] BiocIO_1.8.0                      IRanges_2.32.0                   
## [127] viridisLite_0.4.2                 digest_0.6.33                    
## [129] RhpcBLASctl_0.23-42               mime_0.12                        
## [131] rappdirs_0.3.3                    spam_2.10-0                      
## [133] RSQLite_2.3.1                     future.apply_1.11.0              
## [135] remotes_2.4.2.1                   data.table_1.14.8                
## [137] blob_1.2.4                        JASPAR2020_0.99.10               
## [139] S4Vectors_0.36.2                  R.oo_1.25.0                      
## [141] TFBSTools_1.36.0                  ragg_1.2.5                       
## [143] styler_1.10.2                     splines_4.2.2                    
## [145] labeling_0.4.3                    Rhdf5lib_1.20.0                  
## [147] googledrive_2.1.1                 ProtGenerics_1.30.0              
## [149] RCurl_1.98-1.12                   hms_1.1.3                        
## [151] rhdf5_2.42.1                      colorspace_2.1-0                 
## [153] BiocManager_1.30.22               ggbeeswarm_0.7.1                 
## [155] GenomicRanges_1.50.2              Signac_1.12.9000                 
## [157] ggrastr_1.0.1                     sass_0.4.7                       
## [159] Rcpp_1.0.11                       BSgenome.Hsapiens.UCSC.hg38_1.4.5
## [161] RANN_2.6.1                        fansi_1.0.5                      
## [163] tzdb_0.4.0                        parallelly_1.36.0                
## [165] R6_2.5.1                          grid_4.2.2                       
## [167] ggridges_0.5.4                    lifecycle_1.0.3                  
## [169] curl_5.1.0                        googlesheets4_1.1.1              
## [171] leiden_0.4.3                      jquerylib_0.1.4                  
## [173] Matrix_1.6-1.1                    desc_1.4.2                       
## [175] RcppAnnoy_0.0.21                  RColorBrewer_1.1-3               
## [177] spatstat.explore_3.2-5            stringr_1.5.0                    
## [179] R.cache_0.16.0                    htmlwidgets_1.6.2                
## [181] beachmat_2.14.2                   polyclip_1.10-6                  
## [183] biomaRt_2.54.1                    purrr_1.0.2                      
## [185] seqLogo_1.64.0                    globals_0.16.2                   
## [187] spatstat.random_3.2-1             progressr_0.14.0                 
## [189] batchelor_1.14.1                  codetools_0.2-19                 
## [191] matrixStats_1.0.0                 GO.db_3.16.0                     
## [193] gtools_3.9.4                      prettyunits_1.1.1                
## [195] SingleCellExperiment_1.20.1       dbplyr_2.3.4                     
## [197] RSpectra_0.16-1                   R.methodsS3_1.8.2                
## [199] GenomeInfoDb_1.34.9               gtable_0.3.4                     
## [201] DBI_1.1.3                         stats4_4.2.2                     
## [203] tensor_1.5                        httr_1.4.7                       
## [205] highr_0.10                        KernSmooth_2.23-22               
## [207] stringi_1.7.12                    presto_1.0.0                     
## [209] progress_1.2.2                    reshape2_1.4.4                   
## [211] farver_2.1.1                      annotate_1.76.0                  
## [213] DT_0.30                           xml2_1.3.5                       
## [215] EnsDb.Hsapiens.v86_2.99.0         shinyjs_2.1.0                    
## [217] BiocNeighbors_1.16.0              restfulr_0.0.15                  
## [219] readr_2.1.4                       scattermore_1.2                  
## [221] bit_4.0.5                         MatrixGenerics_1.10.0            
## [223] spatstat.data_3.0-3               pkgconfig_2.0.3                  
## [225] gargle_1.5.2                      DirichletMultinomial_1.40.0      
## [227] knitr_1.45
```

---

## New data visualization methods in v3.0

**URL:** http://127.0.0.1:9173/seurat/archive/v3.2/visualization_vignette/index.html

**Contents:**
- New data visualization methods in v3.0
    - Compiled: 2020-10-02
  - Five visualizations of marker feature expression
  - New additions to FeaturePlot
  - Updated and expanded visualization functions
  - Applying themes to plots
  - Interactive plotting features
  - Plotting Accessories

We'll demonstrate visualization techniques in Seurat using our previously computed Seurat object from the 2,700 PBMC tutorial. You can download this dataset from SeuratData

In addition to changes to FeaturePlot, several other plotting functions have been updated and expanded with new features and taking over the role of now-deprecated functions

With Seurat v3.0, all plotting functions return ggplot2-based plots by default, allowing one to easily capture and manipulate plots just like any other ggplot2-based plot.

Seurat utilizes R's plotly graphing library to create interactive plots. This interactive plotting feature works with any ggplot2-based scatter plots (requires a geom_point layer). To use, simply make a ggplot2-based scatter plot (such as DimPlot or FeaturePlot) and pass the resulting plot to HoverLocator

Another interactive feature provided by Seurat is being able to manually select cells for further investigation. We have found this particularly useful for small clusters that do not always separate using unbiased clustering, but which look tantalizingly distinct. You can now select these cells by creating a ggplot2-based scatter plot (such as with DimPlot or FeaturePlot, and passing the returned plot to CellSelector. CellSelector will return a vector with the names of the points selected, so that you can then set them to a new identity class and perform differential expression.

For example, lets pretend that DCs had merged with monocytes in the clustering, but we wanted to see what was unique about them based on their position in the tSNE plot.

We can then change the identity of these cells to turn them into their own mini-cluster.

Using CellSelector to Automatically Assign Cell Identities

In addition to returning a vector of cell names, CellSelector can also take the selected cells and assign a new identity to them, returning a Seurat object with the identity classes already set. This is done by passing the Seurat object used to make the plot into CellSelector, as well as an identity class. As an example, we're going to select the same set of cells as before, and set their identity class to "selected"

Along with new functions add interactive functionality to plots, Seurat provides new accessory functions for manipulating and combining plots.

Plotting multiple plots was previously achieved with the CombinePlot function. We are deprecating this functionality in favor of the patchwork system. Below is a brief demonstration but please see the patchwork package website here for more details and examples.

**Examples:**

Example 1 (r):
```r
SeuratData::InstallData("pbmc3k")
```

Example 2 (r):
```r
SeuratData::InstallData("pbmc3k")
```

Example 3 (r):
```r
library(Seurat)
library(SeuratData)
library(ggplot2)
library(patchwork)
data("pbmc3k.final")
pbmc3k.final$groups <- sample(c("group1", "group2"), size = ncol(pbmc3k.final), replace = TRUE)
features <- c("LYZ", "CCL5", "IL32", "PTPRCAP", "FCGR3A", "PF4")
pbmc3k.final
```

Example 4 (r):
```r
library(Seurat)
library(SeuratData)
library(ggplot2)
library(patchwork)
data("pbmc3k.final")
pbmc3k.final$groups <- sample(c("group1", "group2"), size = ncol(pbmc3k.final), replace = TRUE)
features <- c("LYZ", "CCL5", "IL32", "PTPRCAP", "FCGR3A", "PF4")
pbmc3k.final
```

Example 5 (python):
```python
## An object of class Seurat 
## 13714 features across 2638 samples within 1 assay 
## Active assay: RNA (13714 features, 2000 variable features)
##  2 dimensional reductions calculated: pca, umap
```

Example 6 (python):
```python
## An object of class Seurat 
## 13714 features across 2638 samples within 1 assay 
## Active assay: RNA (13714 features, 2000 variable features)
##  2 dimensional reductions calculated: pca, umap
```

Example 7 (r):
```r
# Ridge plots - from ggridges. Visualize single cell expression distributions in each cluster
RidgePlot(pbmc3k.final, features = features, ncol = 2)
```

Example 8 (r):
```r
# Ridge plots - from ggridges. Visualize single cell expression distributions in each cluster
RidgePlot(pbmc3k.final, features = features, ncol = 2)
```

Example 9 (r):
```r
# Violin plot - Visualize single cell expression distributions in each cluster
VlnPlot(pbmc3k.final, features = features)
```

Example 10 (r):
```r
# Violin plot - Visualize single cell expression distributions in each cluster
VlnPlot(pbmc3k.final, features = features)
```

Example 11 (r):
```r
# Feature plot - visualize feature expression in low-dimensional space
FeaturePlot(pbmc3k.final, features = features)
```

Example 12 (r):
```r
# Feature plot - visualize feature expression in low-dimensional space
FeaturePlot(pbmc3k.final, features = features)
```

Example 13 (r):
```r
# Dot plots - the size of the dot corresponds to the percentage of cells expressing the feature
# in each cluster. The color represents the average expression level
DotPlot(pbmc3k.final, features = features) + RotatedAxis()
```

Example 14 (r):
```r
# Dot plots - the size of the dot corresponds to the percentage of cells expressing the feature
# in each cluster. The color represents the average expression level
DotPlot(pbmc3k.final, features = features) + RotatedAxis()
```

Example 15 (r):
```r
# Single cell heatmap of feature expression
DoHeatmap(subset(pbmc3k.final, downsample = 100), features = features, size = 3)
```

Example 16 (r):
```r
# Single cell heatmap of feature expression
DoHeatmap(subset(pbmc3k.final, downsample = 100), features = features, size = 3)
```

Example 17 (unknown):
```unknown
FeaturePlot
```

Example 18 (r):
```r
# Plot a legend to map colors to expression levels
FeaturePlot(pbmc3k.final, features = "MS4A1")
```

Example 19 (r):
```r
# Plot a legend to map colors to expression levels
FeaturePlot(pbmc3k.final, features = "MS4A1")
```

Example 20 (r):
```r
# Adjust the contrast in the plot
FeaturePlot(pbmc3k.final, features = "MS4A1", min.cutoff = 1, max.cutoff = 3)
```

Example 21 (r):
```r
# Adjust the contrast in the plot
FeaturePlot(pbmc3k.final, features = "MS4A1", min.cutoff = 1, max.cutoff = 3)
```

Example 22 (r):
```r
# Calculate feature-specific contrast levels based on quantiles of non-zero expression.
# Particularly useful when plotting multiple markers
FeaturePlot(pbmc3k.final, features = c("MS4A1", "PTPRCAP"), min.cutoff = "q10", max.cutoff = "q90")
```

Example 23 (r):
```r
# Calculate feature-specific contrast levels based on quantiles of non-zero expression.
# Particularly useful when plotting multiple markers
FeaturePlot(pbmc3k.final, features = c("MS4A1", "PTPRCAP"), min.cutoff = "q10", max.cutoff = "q90")
```

Example 24 (r):
```r
# Visualize co-expression of two features simultaneously
FeaturePlot(pbmc3k.final, features = c("MS4A1", "CD79A"), blend = TRUE)
```

Example 25 (r):
```r
# Visualize co-expression of two features simultaneously
FeaturePlot(pbmc3k.final, features = c("MS4A1", "CD79A"), blend = TRUE)
```

Example 26 (r):
```r
# Split visualization to view expression by groups (replaces FeatureHeatmap)
FeaturePlot(pbmc3k.final, features = c("MS4A1", "CD79A"), split.by = "groups")
```

Example 27 (r):
```r
# Split visualization to view expression by groups (replaces FeatureHeatmap)
FeaturePlot(pbmc3k.final, features = c("MS4A1", "CD79A"), split.by = "groups")
```

Example 28 (unknown):
```unknown
FeaturePlot
```

Example 29 (r):
```r
# Violin plots can also be split on some variable. Simply add the splitting variable to object
# metadata and pass it to the split.by argument
VlnPlot(pbmc3k.final, features = "percent.mt", split.by = "groups")
```

Example 30 (r):
```r
# Violin plots can also be split on some variable. Simply add the splitting variable to object
# metadata and pass it to the split.by argument
VlnPlot(pbmc3k.final, features = "percent.mt", split.by = "groups")
```

Example 31 (r):
```r
# SplitDotPlotGG has been replaced with the `split.by` parameter for DotPlot
DotPlot(pbmc3k.final, features = features, split.by = "groups") + RotatedAxis()
```

Example 32 (r):
```r
# SplitDotPlotGG has been replaced with the `split.by` parameter for DotPlot
DotPlot(pbmc3k.final, features = features, split.by = "groups") + RotatedAxis()
```

Example 33 (r):
```r
# DimPlot replaces TSNEPlot, PCAPlot, etc. In addition, it will plot either 'umap', 'tsne', or
# 'pca' by default, in that order
DimPlot(pbmc3k.final)
```

Example 34 (r):
```r
# DimPlot replaces TSNEPlot, PCAPlot, etc. In addition, it will plot either 'umap', 'tsne', or
# 'pca' by default, in that order
DimPlot(pbmc3k.final)
```

Example 35 (r):
```r
pbmc3k.final.no.umap <- pbmc3k.final
pbmc3k.final.no.umap[["umap"]] <- NULL
DimPlot(pbmc3k.final.no.umap) + RotatedAxis()
```

Example 36 (r):
```r
pbmc3k.final.no.umap <- pbmc3k.final
pbmc3k.final.no.umap[["umap"]] <- NULL
DimPlot(pbmc3k.final.no.umap) + RotatedAxis()
```

Example 37 (r):
```r
# DoHeatmap now shows a grouping bar, splitting the heatmap into groups or clusters. This can be
# changed with the `group.by` parameter
DoHeatmap(pbmc3k.final, features = VariableFeatures(pbmc3k.final)[1:100], cells = 1:500, size = 4, 
    angle = 90) + NoLegend()
```

Example 38 (r):
```r
# DoHeatmap now shows a grouping bar, splitting the heatmap into groups or clusters. This can be
# changed with the `group.by` parameter
DoHeatmap(pbmc3k.final, features = VariableFeatures(pbmc3k.final)[1:100], cells = 1:500, size = 4, 
    angle = 90) + NoLegend()
```

Example 39 (r):
```r
baseplot <- DimPlot(pbmc3k.final, reduction = "umap")
# Add custom labels and titles
baseplot + labs(title = "Clustering of 2,700 pbmc3k.finals")
```

Example 40 (r):
```r
baseplot <- DimPlot(pbmc3k.final, reduction = "umap")
# Add custom labels and titles
baseplot + labs(title = "Clustering of 2,700 pbmc3k.finals")
```

Example 41 (r):
```r
# Use community-created themes, overwriting the default Seurat-applied theme Install ggmin with
# remotes::install_github('sjessa/ggmin')
baseplot + ggmin::theme_powerpoint()
```

Example 42 (r):
```r
# Use community-created themes, overwriting the default Seurat-applied theme Install ggmin with
# remotes::install_github('sjessa/ggmin')
baseplot + ggmin::theme_powerpoint()
```

Example 43 (r):
```r
# Seurat also provides several built-in themes, such as DarkTheme; for more details see
# ?SeuratTheme
baseplot + DarkTheme()
```

Example 44 (r):
```r
# Seurat also provides several built-in themes, such as DarkTheme; for more details see
# ?SeuratTheme
baseplot + DarkTheme()
```

Example 45 (r):
```r
# Chain themes together
baseplot + FontSize(x.title = 20, y.title = 20) + NoLegend()
```

Example 46 (r):
```r
# Chain themes together
baseplot + FontSize(x.title = 20, y.title = 20) + NoLegend()
```

Example 47 (unknown):
```unknown
FeaturePlot
```

Example 48 (unknown):
```unknown
HoverLocator
```

Example 49 (r):
```r
# Include additional data to display alongside cell names by passing in a data frame of
# information Works well when using FetchData
plot <- FeaturePlot(pbmc3k.final, features = "MS4A1")
HoverLocator(plot = plot, information = FetchData(pbmc3k.final, vars = c("ident", "PC_1", "nFeature_RNA")))
```

Example 50 (r):
```r
# Include additional data to display alongside cell names by passing in a data frame of
# information Works well when using FetchData
plot <- FeaturePlot(pbmc3k.final, features = "MS4A1")
HoverLocator(plot = plot, information = FetchData(pbmc3k.final, vars = c("ident", "PC_1", "nFeature_RNA")))
```

Example 51 (unknown):
```unknown
FeaturePlot
```

Example 52 (unknown):
```unknown
CellSelector
```

Example 53 (unknown):
```unknown
CellSelector
```

Example 54 (r):
```r
pbmc3k.final <- RenameIdents(pbmc3k.final, DC = "CD14+ Mono")
plot <- DimPlot(pbmc3k.final, reduction = "umap")
select.cells <- CellSelector(plot = plot)
```

Example 55 (r):
```r
pbmc3k.final <- RenameIdents(pbmc3k.final, DC = "CD14+ Mono")
plot <- DimPlot(pbmc3k.final, reduction = "umap")
select.cells <- CellSelector(plot = plot)
```

Example 56 (r):
```r
head(select.cells)
```

Example 57 (r):
```r
head(select.cells)
```

Example 58 (unknown):
```unknown
## [1] "AAGATTACCGCCTT" "AAGCCATGAACTGC" "AATTACGAATTCCT" "ACCCGTTGCTTCTA"
## [5] "ACGAGGGACAGGAG" "ACGTGATGCCATGA"
```

Example 59 (unknown):
```unknown
## [1] "AAGATTACCGCCTT" "AAGCCATGAACTGC" "AATTACGAATTCCT" "ACCCGTTGCTTCTA"
## [5] "ACGAGGGACAGGAG" "ACGTGATGCCATGA"
```

Example 60 (r):
```r
Idents(pbmc3k.final, cells = select.cells) <- "NewCells"

# Now, we find markers that are specific to the new cells, and find clear DC markers
newcells.markers <- FindMarkers(pbmc3k.final, ident.1 = "NewCells", ident.2 = "CD14+ Mono", min.diff.pct = 0.3, 
    only.pos = TRUE)
head(newcells.markers)
```

Example 61 (r):
```r
Idents(pbmc3k.final, cells = select.cells) <- "NewCells"

# Now, we find markers that are specific to the new cells, and find clear DC markers
newcells.markers <- FindMarkers(pbmc3k.final, ident.1 = "NewCells", ident.2 = "CD14+ Mono", min.diff.pct = 0.3, 
    only.pos = TRUE)
head(newcells.markers)
```

Example 62 (unknown):
```unknown
CellSelector
```

Example 63 (unknown):
```unknown
CellSelector
```

Example 64 (unknown):
```unknown
CellSelector
```

Example 65 (r):
```r
pbmc3k.final <- CellSelector(plot = plot, object = pbmc3k.final, ident = "selected")
```

Example 66 (r):
```r
pbmc3k.final <- CellSelector(plot = plot, object = pbmc3k.final, ident = "selected")
```

Example 67 (r):
```r
levels(pbmc3k.final)
```

Example 68 (r):
```r
levels(pbmc3k.final)
```

Example 69 (unknown):
```unknown
## [1] "selected"     "Naive CD4 T"  "Memory CD4 T" "CD14+ Mono"   "B"           
## [6] "CD8 T"        "FCGR3A+ Mono" "NK"           "Platelet"
```

Example 70 (unknown):
```unknown
## [1] "selected"     "Naive CD4 T"  "Memory CD4 T" "CD14+ Mono"   "B"           
## [6] "CD8 T"        "FCGR3A+ Mono" "NK"           "Platelet"
```

Example 71 (r):
```r
# LabelClusters and LabelPoints will label clusters (a coloring variable) or individual points
# on a ggplot2-based scatter plot
plot <- DimPlot(pbmc3k.final, reduction = "pca") + NoLegend()
LabelClusters(plot = plot, id = "ident")
```

Example 72 (r):
```r
# LabelClusters and LabelPoints will label clusters (a coloring variable) or individual points
# on a ggplot2-based scatter plot
plot <- DimPlot(pbmc3k.final, reduction = "pca") + NoLegend()
LabelClusters(plot = plot, id = "ident")
```

Example 73 (r):
```r
# Both functions support `repel`, which will intelligently stagger labels and draw connecting
# lines from the labels to the points or clusters
LabelPoints(plot = plot, points = TopCells(object = pbmc3k.final[["pca"]]), repel = TRUE)
```

Example 74 (r):
```r
# Both functions support `repel`, which will intelligently stagger labels and draw connecting
# lines from the labels to the points or clusters
LabelPoints(plot = plot, points = TopCells(object = pbmc3k.final[["pca"]]), repel = TRUE)
```

Example 75 (unknown):
```unknown
CombinePlot
```

Example 76 (r):
```r
plot1 <- DimPlot(pbmc3k.final)
plot2 <- FeatureScatter(pbmc3k.final, feature1 = "LYZ", feature2 = "CCL5")
# Combine two plots
plot1 + plot2
```

Example 77 (r):
```r
plot1 <- DimPlot(pbmc3k.final)
plot2 <- FeatureScatter(pbmc3k.final, feature1 = "LYZ", feature2 = "CCL5")
# Combine two plots
plot1 + plot2
```

Example 78 (r):
```r
# Remove the legend from all plots
(plot1 + plot2) & NoLegend()
```

Example 79 (r):
```r
# Remove the legend from all plots
(plot1 + plot2) & NoLegend()
```

---

## Analysis, visualization, and integration of Visium HD spatial datasets with Seurat • Seurat

**URL:** http://127.0.0.1:9173/seurat/articles/weighted_nearest_neighbor_analysis/index.html

**Contents:**
- Weighted Nearest Neighbor Analysis
    - Compiled: October 31, 2023
- WNN analysis of CITE-seq, RNA + ADT
- WNN analysis of 10x Multiome, RNA + ATAC
- Contents

The simultaneous measurement of multiple modalities, known as multimodal analysis, represents an exciting frontier for single-cell genomics and necessitates new computational methods that can define cellular states based on multiple data types. The varying information content of each modality, even across cells in the same dataset, represents a pressing challenge for the analysis and integration of multimodal datasets. In (Hao*, Hao* et al, Cell 2021), we introduce ‘weighted-nearest neighbor’ (WNN) analysis, an unsupervised framework to learn the relative utility of each data type in each cell, enabling an integrative analysis of multiple modalities.

This vignette introduces the WNN workflow for the analysis of multimodal single-cell datasets. The workflow consists of three steps

We demonstrate the use of WNN analysis to two single-cell multimodal technologies: CITE-seq and 10x multiome. We define the cellular states based on both modalities, instead of either individual modality.

We use the CITE-seq dataset from (Stuart*, Butler* et al, Cell 2019), which consists of 30,672 scRNA-seq profiles measured alongside a panel of 25 antibodies from bone marrow. The object contains two assays, RNA and antibody-derived tags (ADT).

To run this vignette please install SeuratData, available on GitHub.

We first perform pre-processing and dimensional reduction on both assays independently. We use standard normalization, but you can also use SCTransform or any alternative method.

For each cell, we calculate its closest neighbors in the dataset based on a weighted combination of RNA and protein similarities. The cell-specific modality weights and multimodal neighbors are calculated in a single function, which takes ~2 minutes to run on this dataset. We specify the dimensionality of each modality (similar to specifying the number of PCs to include in scRNA-seq clustering), but you can vary these settings to see that small changes have minimal effect on the overall results.

We can now use these results for downstream analysis, such as visualization and clustering. For example, we can create a UMAP visualization of the data based on a weighted combination of RNA and protein data We can also perform graph-based clustering and visualize these results on the UMAP, alongside a set of cell annotations.

We can also compute UMAP visualization based on only the RNA and protein data and compare. We find that the RNA analysis is more informative than the ADT analysis in identifying progenitor states (the ADT panel contains markers for differentiated cells), while the converse is true of T cell states (where the ADT analysis outperforms RNA).

We can visualize the expression of canonical marker genes and proteins on the multimodal UMAP, which can assist in verifying the provided annotations:

Finally, we can visualize the modality weights that were learned for each cell. Each of the populations with the highest RNA weights represent progenitor cells, while the populations with the highest protein weights represent T cells. This is in line with our biological expectations, as the antibody panel does not contain markers that can distinguish between different progenitor populations.

Here, we demonstrate the use of WNN analysis to a second multimodal technology, the 10x multiome RNA+ATAC kit. We use a dataset that is publicly available on the 10x website, where paired transcriptomes and ATAC-seq profiles are measured in 10,412 PBMCs.

We use the same WNN methods as we use in the previous tab, where we apply integrated multimodal analysis to a CITE-seq dataset. In this example we will demonstrate how to:

You can download the dataset from the 10x Genomics website here. Please make sure to download the following files:

Finally, in order to run the vignette, make sure the following packages are installed:

We’ll create a Seurat object based on the gene expression data, and then add in the ATAC-seq data as a second assay. You can explore the Signac getting started vignette for more information on the creation and processing of a ChromatinAssay object.

We perform basic QC based on the number of detected molecules for each modality as well as mitochondrial percentage.

We next perform pre-processing and dimensional reduction on both assays independently, using standard approaches for RNA and ATAC-seq data.

We calculate a WNN graph, representing a weighted combination of RNA and ATAC-seq modalities. We use this graph for UMAP visualization and clustering

We annotate the clusters below. Note that you could also annotate the dataset using our supervised mapping pipelines, using either our vignette, or automated web tool, Azimuth.

We can visualize clustering based on gene expression, ATAC-seq, or WNN analysis. The differences are more subtle than in the previous analysis (you can explore the weights, which are more evenly split than in our CITE-seq example), but we find that WNN provides the clearest separation of cell states.

For example, the ATAC-seq data assists in the separation of CD4 and CD8 T cell states. This is due to the presence of multiple loci that exhibit differential accessibility between different T cell subtypes. For example, we can visualize ‘pseudobulk’ tracks of the CD8A locus alongside violin plots of gene expression levels, using tools in the Signac visualization vignette.

Next, we will examine the accessible regions of each cell to determine enriched motifs. As described in the Signac motifs vignette, there are a few ways to do this, but we will use the chromVAR package from the Greenleaf lab. This calculates a per-cell accessibility score for known motifs, and adds these scores as a third assay (chromvar) in the Seurat object.

To continue, please make sure you have the following packages installed.

Install command for all dependencies

Finally, we explore the multimodal dataset to identify key regulators of each cell state. Paired data provides a unique opportunity to identify transcription factors (TFs) that satisfy multiple criteria, helping to narrow down the list of putative regulators to the most likely candidates. We aim to identify TFs whose expression is enriched in multiple cell types in the RNA measurements, but also have enriched accessibility for their motifs in the ATAC measurements.

As an example and positive control, the CCAAT Enhancer Binding Protein (CEBP) family of proteins, including the TF CEBPB, have been repeatedly shown to play important roles in the differentiation and function of myeloid cells including monocytes and dendritic cells. We can see that both the expression of the CEBPB, and the accessibility of the MA0466.2.4 motif (which encodes the binding site for CEBPB), are both enriched in monocytes.

We’d like to quantify this relationship, and search across all cell types to find similar examples. To do so, we will use the presto package to perform fast differential expression. We run two tests: one using gene expression data, and the other using chromVAR motif accessibilities. presto calculates a p-value based on the Wilcox rank sum test, which is also the default test in Seurat, and we restrict our search to TFs that return significant results in both tests.

presto also calculates an “AUC” statistic, which reflects the power of each gene (or motif) to serve as a marker of cell type. A maximum AUC value of 1 indicates a perfect marker. Since the AUC statistic is on the same scale for both genes and motifs, we take the average of the AUC values from the two tests, and use this to rank TFs for each cell type:

We can now compute, and visualize, putative regulators for any cell type. We recover well-established regulators, including TBX21 for NK cells, IRF4 for plasma cells, SOX4 for hematopoietic progenitors, EBF1 and PAX5 for B cells, IRF8 and TCF4 for pDC. We believe that similar strategies can be used to help focus on a set of putative regulators in diverse systems.

Developed by Rahul Satija, Satija Lab and Collaborators.

Site built with pkgdown 2.0.7.

**Examples:**

Example 1 (unknown):
```unknown
vignettes/weighted_nearest_neighbor_analysis.Rmd
```

Example 2 (unknown):
```unknown
weighted_nearest_neighbor_analysis.Rmd
```

Example 3 (unknown):
```unknown
library(Seurat)
library(SeuratData)
library(cowplot)
library(dplyr)
```

Example 4 (r):
```r
library(Seurat)
library(SeuratData)
library(cowplot)
library(dplyr)
```

Example 5 (r):
```r
library(Seurat)
library(SeuratData)
library(cowplot)
library(dplyr)
```

Example 6 (unknown):
```unknown
InstallData("bmcite")
bm <- LoadData(ds = "bmcite")
```

Example 7 (r):
```r
InstallData("bmcite")
bm <- LoadData(ds = "bmcite")
```

Example 8 (r):
```r
InstallData("bmcite")
bm <- LoadData(ds = "bmcite")
```

Example 9 (unknown):
```unknown
DefaultAssay(bm) <- 'RNA'
bm <- NormalizeData(bm) %>% FindVariableFeatures() %>% ScaleData() %>% RunPCA()

DefaultAssay(bm) <- 'ADT'
# we will use all ADT features for dimensional reduction
# we set a dimensional reduction name to avoid overwriting the 
VariableFeatures(bm) <- rownames(bm[["ADT"]])
bm <- NormalizeData(bm, normalization.method = 'CLR', margin = 2) %>% 
  ScaleData() %>% RunPCA(reduction.name = 'apca')
```

Example 10 (r):
```r
DefaultAssay(bm) <- 'RNA'
bm <- NormalizeData(bm) %>% FindVariableFeatures() %>% ScaleData() %>% RunPCA()

DefaultAssay(bm) <- 'ADT'
# we will use all ADT features for dimensional reduction
# we set a dimensional reduction name to avoid overwriting the 
VariableFeatures(bm) <- rownames(bm[["ADT"]])
bm <- NormalizeData(bm, normalization.method = 'CLR', margin = 2) %>% 
  ScaleData() %>% RunPCA(reduction.name = 'apca')
```

Example 11 (r):
```r
DefaultAssay(bm) <- 'RNA'
bm <- NormalizeData(bm) %>% FindVariableFeatures() %>% ScaleData() %>% RunPCA()

DefaultAssay(bm) <- 'ADT'
# we will use all ADT features for dimensional reduction
# we set a dimensional reduction name to avoid overwriting the 
VariableFeatures(bm) <- rownames(bm[["ADT"]])
bm <- NormalizeData(bm, normalization.method = 'CLR', margin = 2) %>% 
  ScaleData() %>% RunPCA(reduction.name = 'apca')
```

Example 12 (unknown):
```unknown
# Identify multimodal neighbors. These will be stored in the neighbors slot, 
# and can be accessed using bm[['weighted.nn']]
# The WNN graph can be accessed at bm[["wknn"]], 
# and the SNN graph used for clustering at bm[["wsnn"]]
# Cell-specific modality weights can be accessed at bm$RNA.weight
bm <- FindMultiModalNeighbors(
  bm, reduction.list = list("pca", "apca"), 
  dims.list = list(1:30, 1:18), modality.weight.name = "RNA.weight"
)
```

Example 13 (r):
```r
# Identify multimodal neighbors. These will be stored in the neighbors slot, 
# and can be accessed using bm[['weighted.nn']]
# The WNN graph can be accessed at bm[["wknn"]], 
# and the SNN graph used for clustering at bm[["wsnn"]]
# Cell-specific modality weights can be accessed at bm$RNA.weight
bm <- FindMultiModalNeighbors(
  bm, reduction.list = list("pca", "apca"), 
  dims.list = list(1:30, 1:18), modality.weight.name = "RNA.weight"
)
```

Example 14 (r):
```r
# Identify multimodal neighbors. These will be stored in the neighbors slot, 
# and can be accessed using bm[['weighted.nn']]
# The WNN graph can be accessed at bm[["wknn"]], 
# and the SNN graph used for clustering at bm[["wsnn"]]
# Cell-specific modality weights can be accessed at bm$RNA.weight
bm <- FindMultiModalNeighbors(
  bm, reduction.list = list("pca", "apca"), 
  dims.list = list(1:30, 1:18), modality.weight.name = "RNA.weight"
)
```

Example 15 (unknown):
```unknown
bm <- RunUMAP(bm, nn.name = "weighted.nn", reduction.name = "wnn.umap", reduction.key = "wnnUMAP_")
bm <- FindClusters(bm, graph.name = "wsnn", algorithm = 3, resolution = 2, verbose = FALSE)
```

Example 16 (r):
```r
bm <- RunUMAP(bm, nn.name = "weighted.nn", reduction.name = "wnn.umap", reduction.key = "wnnUMAP_")
bm <- FindClusters(bm, graph.name = "wsnn", algorithm = 3, resolution = 2, verbose = FALSE)
```

Example 17 (r):
```r
bm <- RunUMAP(bm, nn.name = "weighted.nn", reduction.name = "wnn.umap", reduction.key = "wnnUMAP_")
bm <- FindClusters(bm, graph.name = "wsnn", algorithm = 3, resolution = 2, verbose = FALSE)
```

Example 18 (unknown):
```unknown
p1 <- DimPlot(bm, reduction = 'wnn.umap', label = TRUE, repel = TRUE, label.size = 2.5) + NoLegend()
p2 <- DimPlot(bm, reduction = 'wnn.umap', group.by = 'celltype.l2', label = TRUE, repel = TRUE, label.size = 2.5) + NoLegend()
p1 + p2
```

Example 19 (r):
```r
p1 <- DimPlot(bm, reduction = 'wnn.umap', label = TRUE, repel = TRUE, label.size = 2.5) + NoLegend()
p2 <- DimPlot(bm, reduction = 'wnn.umap', group.by = 'celltype.l2', label = TRUE, repel = TRUE, label.size = 2.5) + NoLegend()
p1 + p2
```

Example 20 (r):
```r
p1 <- DimPlot(bm, reduction = 'wnn.umap', label = TRUE, repel = TRUE, label.size = 2.5) + NoLegend()
p2 <- DimPlot(bm, reduction = 'wnn.umap', group.by = 'celltype.l2', label = TRUE, repel = TRUE, label.size = 2.5) + NoLegend()
p1 + p2
```

Example 21 (unknown):
```unknown
bm <- RunUMAP(bm, reduction = 'pca', dims = 1:30, assay = 'RNA', 
              reduction.name = 'rna.umap', reduction.key = 'rnaUMAP_')
bm <- RunUMAP(bm, reduction = 'apca', dims = 1:18, assay = 'ADT', 
              reduction.name = 'adt.umap', reduction.key = 'adtUMAP_')
```

Example 22 (r):
```r
bm <- RunUMAP(bm, reduction = 'pca', dims = 1:30, assay = 'RNA', 
              reduction.name = 'rna.umap', reduction.key = 'rnaUMAP_')
bm <- RunUMAP(bm, reduction = 'apca', dims = 1:18, assay = 'ADT', 
              reduction.name = 'adt.umap', reduction.key = 'adtUMAP_')
```

Example 23 (r):
```r
bm <- RunUMAP(bm, reduction = 'pca', dims = 1:30, assay = 'RNA', 
              reduction.name = 'rna.umap', reduction.key = 'rnaUMAP_')
bm <- RunUMAP(bm, reduction = 'apca', dims = 1:18, assay = 'ADT', 
              reduction.name = 'adt.umap', reduction.key = 'adtUMAP_')
```

Example 24 (unknown):
```unknown
p3 <- DimPlot(bm, reduction = 'rna.umap', group.by = 'celltype.l2', label = TRUE, 
              repel = TRUE, label.size = 2.5) + NoLegend()
p4 <- DimPlot(bm, reduction = 'adt.umap', group.by = 'celltype.l2', label = TRUE, 
              repel = TRUE, label.size = 2.5) + NoLegend()
p3 + p4
```

Example 25 (r):
```r
p3 <- DimPlot(bm, reduction = 'rna.umap', group.by = 'celltype.l2', label = TRUE, 
              repel = TRUE, label.size = 2.5) + NoLegend()
p4 <- DimPlot(bm, reduction = 'adt.umap', group.by = 'celltype.l2', label = TRUE, 
              repel = TRUE, label.size = 2.5) + NoLegend()
p3 + p4
```

Example 26 (r):
```r
p3 <- DimPlot(bm, reduction = 'rna.umap', group.by = 'celltype.l2', label = TRUE, 
              repel = TRUE, label.size = 2.5) + NoLegend()
p4 <- DimPlot(bm, reduction = 'adt.umap', group.by = 'celltype.l2', label = TRUE, 
              repel = TRUE, label.size = 2.5) + NoLegend()
p3 + p4
```

Example 27 (unknown):
```unknown
p5 <- FeaturePlot(bm, features = c("adt_CD45RA","adt_CD16","adt_CD161"),
                  reduction = 'wnn.umap', max.cutoff = 2, 
                  cols = c("lightgrey","darkgreen"), ncol = 3)
p6 <- FeaturePlot(bm, features = c("rna_TRDC","rna_MPO","rna_AVP"), 
                  reduction = 'wnn.umap', max.cutoff = 3, ncol = 3)
p5 / p6
```

Example 28 (r):
```r
p5 <- FeaturePlot(bm, features = c("adt_CD45RA","adt_CD16","adt_CD161"),
                  reduction = 'wnn.umap', max.cutoff = 2, 
                  cols = c("lightgrey","darkgreen"), ncol = 3)
p6 <- FeaturePlot(bm, features = c("rna_TRDC","rna_MPO","rna_AVP"), 
                  reduction = 'wnn.umap', max.cutoff = 3, ncol = 3)
p5 / p6
```

Example 29 (r):
```r
p5 <- FeaturePlot(bm, features = c("adt_CD45RA","adt_CD16","adt_CD161"),
                  reduction = 'wnn.umap', max.cutoff = 2, 
                  cols = c("lightgrey","darkgreen"), ncol = 3)
p6 <- FeaturePlot(bm, features = c("rna_TRDC","rna_MPO","rna_AVP"), 
                  reduction = 'wnn.umap', max.cutoff = 3, ncol = 3)
p5 / p6
```

Example 30 (unknown):
```unknown
VlnPlot(bm, features = "RNA.weight", group.by = 'celltype.l2', sort = TRUE, pt.size = 0.1) +
  NoLegend()
```

Example 31 (r):
```r
VlnPlot(bm, features = "RNA.weight", group.by = 'celltype.l2', sort = TRUE, pt.size = 0.1) +
  NoLegend()
```

Example 32 (r):
```r
VlnPlot(bm, features = "RNA.weight", group.by = 'celltype.l2', sort = TRUE, pt.size = 0.1) +
  NoLegend()
```

Example 33 (unknown):
```unknown
library(Seurat)
library(Signac)
library(EnsDb.Hsapiens.v86)
library(dplyr)
library(ggplot2)
```

Example 34 (r):
```r
library(Seurat)
library(Signac)
library(EnsDb.Hsapiens.v86)
library(dplyr)
library(ggplot2)
```

Example 35 (r):
```r
library(Seurat)
library(Signac)
library(EnsDb.Hsapiens.v86)
library(dplyr)
library(ggplot2)
```

Example 36 (unknown):
```unknown
# the 10x hdf5 file contains both data types. 
inputdata.10x <- Read10X_h5("../data/pbmc_granulocyte_sorted_10k_filtered_feature_bc_matrix.h5")

# extract RNA and ATAC data
rna_counts <- inputdata.10x$`Gene Expression`
atac_counts <- inputdata.10x$Peaks

# Create Seurat object
pbmc <- CreateSeuratObject(counts = rna_counts)
pbmc[["percent.mt"]] <- PercentageFeatureSet(pbmc, pattern = "^MT-")

# Now add in the ATAC-seq data
# we'll only use peaks in standard chromosomes
grange.counts <- StringToGRanges(rownames(atac_counts), sep = c(":", "-"))
grange.use <- seqnames(grange.counts) %in% standardChromosomes(grange.counts)
atac_counts <- atac_counts[as.vector(grange.use), ]
annotations <- GetGRangesFromEnsDb(ensdb = EnsDb.Hsapiens.v86)
seqlevelsStyle(annotations) <- 'UCSC'
genome(annotations) <- "hg38"

frag.file <- "../data/pbmc_granulocyte_sorted_10k_atac_fragments.tsv.gz"
chrom_assay <- CreateChromatinAssay(
   counts = atac_counts,
   sep = c(":", "-"),
   genome = 'hg38',
   fragments = frag.file,
   min.cells = 10,
   annotation = annotations
 )
pbmc[["ATAC"]] <- chrom_assay
```

Example 37 (r):
```r
# the 10x hdf5 file contains both data types. 
inputdata.10x <- Read10X_h5("../data/pbmc_granulocyte_sorted_10k_filtered_feature_bc_matrix.h5")

# extract RNA and ATAC data
rna_counts <- inputdata.10x$`Gene Expression`
atac_counts <- inputdata.10x$Peaks

# Create Seurat object
pbmc <- CreateSeuratObject(counts = rna_counts)
pbmc[["percent.mt"]] <- PercentageFeatureSet(pbmc, pattern = "^MT-")

# Now add in the ATAC-seq data
# we'll only use peaks in standard chromosomes
grange.counts <- StringToGRanges(rownames(atac_counts), sep = c(":", "-"))
grange.use <- seqnames(grange.counts) %in% standardChromosomes(grange.counts)
atac_counts <- atac_counts[as.vector(grange.use), ]
annotations <- GetGRangesFromEnsDb(ensdb = EnsDb.Hsapiens.v86)
seqlevelsStyle(annotations) <- 'UCSC'
genome(annotations) <- "hg38"

frag.file <- "../data/pbmc_granulocyte_sorted_10k_atac_fragments.tsv.gz"
chrom_assay <- CreateChromatinAssay(
   counts = atac_counts,
   sep = c(":", "-"),
   genome = 'hg38',
   fragments = frag.file,
   min.cells = 10,
   annotation = annotations
 )
pbmc[["ATAC"]] <- chrom_assay
```

Example 38 (r):
```r
# the 10x hdf5 file contains both data types. 
inputdata.10x <- Read10X_h5("../data/pbmc_granulocyte_sorted_10k_filtered_feature_bc_matrix.h5")

# extract RNA and ATAC data
rna_counts <- inputdata.10x$`Gene Expression`
atac_counts <- inputdata.10x$Peaks

# Create Seurat object
pbmc <- CreateSeuratObject(counts = rna_counts)
pbmc[["percent.mt"]] <- PercentageFeatureSet(pbmc, pattern = "^MT-")

# Now add in the ATAC-seq data
# we'll only use peaks in standard chromosomes
grange.counts <- StringToGRanges(rownames(atac_counts), sep = c(":", "-"))
grange.use <- seqnames(grange.counts) %in% standardChromosomes(grange.counts)
atac_counts <- atac_counts[as.vector(grange.use), ]
annotations <- GetGRangesFromEnsDb(ensdb = EnsDb.Hsapiens.v86)
seqlevelsStyle(annotations) <- 'UCSC'
genome(annotations) <- "hg38"

frag.file <- "../data/pbmc_granulocyte_sorted_10k_atac_fragments.tsv.gz"
chrom_assay <- CreateChromatinAssay(
   counts = atac_counts,
   sep = c(":", "-"),
   genome = 'hg38',
   fragments = frag.file,
   min.cells = 10,
   annotation = annotations
 )
pbmc[["ATAC"]] <- chrom_assay
```

Example 39 (unknown):
```unknown
VlnPlot(pbmc, features = c("nCount_ATAC", "nCount_RNA", "percent.mt"), ncol = 3,
  log = TRUE, pt.size = 0) + NoLegend()
```

Example 40 (r):
```r
VlnPlot(pbmc, features = c("nCount_ATAC", "nCount_RNA", "percent.mt"), ncol = 3,
  log = TRUE, pt.size = 0) + NoLegend()
```

Example 41 (r):
```r
VlnPlot(pbmc, features = c("nCount_ATAC", "nCount_RNA", "percent.mt"), ncol = 3,
  log = TRUE, pt.size = 0) + NoLegend()
```

Example 42 (unknown):
```unknown
pbmc <- subset(
  x = pbmc,
  subset = nCount_ATAC < 7e4 &
    nCount_ATAC > 5e3 &
    nCount_RNA < 25000 &
    nCount_RNA > 1000 &
    percent.mt < 20
)
```

Example 43 (r):
```r
pbmc <- subset(
  x = pbmc,
  subset = nCount_ATAC < 7e4 &
    nCount_ATAC > 5e3 &
    nCount_RNA < 25000 &
    nCount_RNA > 1000 &
    percent.mt < 20
)
```

Example 44 (r):
```r
pbmc <- subset(
  x = pbmc,
  subset = nCount_ATAC < 7e4 &
    nCount_ATAC > 5e3 &
    nCount_RNA < 25000 &
    nCount_RNA > 1000 &
    percent.mt < 20
)
```

Example 45 (unknown):
```unknown
# RNA analysis
DefaultAssay(pbmc) <- "RNA"
pbmc <- SCTransform(pbmc, verbose = FALSE) %>% RunPCA() %>% RunUMAP(dims = 1:50, reduction.name = 'umap.rna', reduction.key = 'rnaUMAP_')

# ATAC analysis
# We exclude the first dimension as this is typically correlated with sequencing depth
DefaultAssay(pbmc) <- "ATAC"
pbmc <- RunTFIDF(pbmc)
pbmc <- FindTopFeatures(pbmc, min.cutoff = 'q0')
pbmc <- RunSVD(pbmc)
pbmc <- RunUMAP(pbmc, reduction = 'lsi', dims = 2:50, reduction.name = "umap.atac", reduction.key = "atacUMAP_")
```

Example 46 (r):
```r
# RNA analysis
DefaultAssay(pbmc) <- "RNA"
pbmc <- SCTransform(pbmc, verbose = FALSE) %>% RunPCA() %>% RunUMAP(dims = 1:50, reduction.name = 'umap.rna', reduction.key = 'rnaUMAP_')

# ATAC analysis
# We exclude the first dimension as this is typically correlated with sequencing depth
DefaultAssay(pbmc) <- "ATAC"
pbmc <- RunTFIDF(pbmc)
pbmc <- FindTopFeatures(pbmc, min.cutoff = 'q0')
pbmc <- RunSVD(pbmc)
pbmc <- RunUMAP(pbmc, reduction = 'lsi', dims = 2:50, reduction.name = "umap.atac", reduction.key = "atacUMAP_")
```

Example 47 (r):
```r
# RNA analysis
DefaultAssay(pbmc) <- "RNA"
pbmc <- SCTransform(pbmc, verbose = FALSE) %>% RunPCA() %>% RunUMAP(dims = 1:50, reduction.name = 'umap.rna', reduction.key = 'rnaUMAP_')

# ATAC analysis
# We exclude the first dimension as this is typically correlated with sequencing depth
DefaultAssay(pbmc) <- "ATAC"
pbmc <- RunTFIDF(pbmc)
pbmc <- FindTopFeatures(pbmc, min.cutoff = 'q0')
pbmc <- RunSVD(pbmc)
pbmc <- RunUMAP(pbmc, reduction = 'lsi', dims = 2:50, reduction.name = "umap.atac", reduction.key = "atacUMAP_")
```

Example 48 (unknown):
```unknown
pbmc <- FindMultiModalNeighbors(pbmc, reduction.list = list("pca", "lsi"), dims.list = list(1:50, 2:50))
pbmc <- RunUMAP(pbmc, nn.name = "weighted.nn", reduction.name = "wnn.umap", reduction.key = "wnnUMAP_")
pbmc <- FindClusters(pbmc, graph.name = "wsnn", algorithm = 3, verbose = FALSE)
```

Example 49 (r):
```r
pbmc <- FindMultiModalNeighbors(pbmc, reduction.list = list("pca", "lsi"), dims.list = list(1:50, 2:50))
pbmc <- RunUMAP(pbmc, nn.name = "weighted.nn", reduction.name = "wnn.umap", reduction.key = "wnnUMAP_")
pbmc <- FindClusters(pbmc, graph.name = "wsnn", algorithm = 3, verbose = FALSE)
```

Example 50 (r):
```r
pbmc <- FindMultiModalNeighbors(pbmc, reduction.list = list("pca", "lsi"), dims.list = list(1:50, 2:50))
pbmc <- RunUMAP(pbmc, nn.name = "weighted.nn", reduction.name = "wnn.umap", reduction.key = "wnnUMAP_")
pbmc <- FindClusters(pbmc, graph.name = "wsnn", algorithm = 3, verbose = FALSE)
```

Example 51 (unknown):
```unknown
# perform sub-clustering on cluster 6 to find additional structure
pbmc <- FindSubCluster(pbmc, cluster = 6, graph.name = "wsnn", algorithm = 3)
Idents(pbmc) <- "sub.cluster"
```

Example 52 (r):
```r
# perform sub-clustering on cluster 6 to find additional structure
pbmc <- FindSubCluster(pbmc, cluster = 6, graph.name = "wsnn", algorithm = 3)
Idents(pbmc) <- "sub.cluster"
```

Example 53 (r):
```r
# perform sub-clustering on cluster 6 to find additional structure
pbmc <- FindSubCluster(pbmc, cluster = 6, graph.name = "wsnn", algorithm = 3)
Idents(pbmc) <- "sub.cluster"
```

Example 54 (unknown):
```unknown
# add annotations
pbmc <- RenameIdents(pbmc, '19' = 'pDC','20' = 'HSPC','15' = 'cDC')
pbmc <- RenameIdents(pbmc, '0' = 'CD14 Mono', '9' ='CD14 Mono', '5' = 'CD16 Mono')
pbmc <- RenameIdents(pbmc, '10' = 'Naive B', '11' = 'Intermediate B', '17' = 'Memory B', '21' = 'Plasma')
pbmc <- RenameIdents(pbmc, '7' = 'NK')
pbmc <- RenameIdents(pbmc, '4' = 'CD4 TCM', '13'= "CD4 TEM", '3' = "CD4 TCM", '16' ="Treg", '1' ="CD4 Naive", '14' = "CD4 Naive")
pbmc <- RenameIdents(pbmc, '2' = 'CD8 Naive', '8'= "CD8 Naive", '12' = 'CD8 TEM_1', '6_0' = 'CD8 TEM_2', '6_1' ='CD8 TEM_2', '6_4' ='CD8 TEM_2')
pbmc <- RenameIdents(pbmc, '18' = 'MAIT')
pbmc <- RenameIdents(pbmc, '6_2' ='gdT', '6_3' = 'gdT')
pbmc$celltype <- Idents(pbmc)
```

Example 55 (r):
```r
# add annotations
pbmc <- RenameIdents(pbmc, '19' = 'pDC','20' = 'HSPC','15' = 'cDC')
pbmc <- RenameIdents(pbmc, '0' = 'CD14 Mono', '9' ='CD14 Mono', '5' = 'CD16 Mono')
pbmc <- RenameIdents(pbmc, '10' = 'Naive B', '11' = 'Intermediate B', '17' = 'Memory B', '21' = 'Plasma')
pbmc <- RenameIdents(pbmc, '7' = 'NK')
pbmc <- RenameIdents(pbmc, '4' = 'CD4 TCM', '13'= "CD4 TEM", '3' = "CD4 TCM", '16' ="Treg", '1' ="CD4 Naive", '14' = "CD4 Naive")
pbmc <- RenameIdents(pbmc, '2' = 'CD8 Naive', '8'= "CD8 Naive", '12' = 'CD8 TEM_1', '6_0' = 'CD8 TEM_2', '6_1' ='CD8 TEM_2', '6_4' ='CD8 TEM_2')
pbmc <- RenameIdents(pbmc, '18' = 'MAIT')
pbmc <- RenameIdents(pbmc, '6_2' ='gdT', '6_3' = 'gdT')
pbmc$celltype <- Idents(pbmc)
```

Example 56 (r):
```r
# add annotations
pbmc <- RenameIdents(pbmc, '19' = 'pDC','20' = 'HSPC','15' = 'cDC')
pbmc <- RenameIdents(pbmc, '0' = 'CD14 Mono', '9' ='CD14 Mono', '5' = 'CD16 Mono')
pbmc <- RenameIdents(pbmc, '10' = 'Naive B', '11' = 'Intermediate B', '17' = 'Memory B', '21' = 'Plasma')
pbmc <- RenameIdents(pbmc, '7' = 'NK')
pbmc <- RenameIdents(pbmc, '4' = 'CD4 TCM', '13'= "CD4 TEM", '3' = "CD4 TCM", '16' ="Treg", '1' ="CD4 Naive", '14' = "CD4 Naive")
pbmc <- RenameIdents(pbmc, '2' = 'CD8 Naive', '8'= "CD8 Naive", '12' = 'CD8 TEM_1', '6_0' = 'CD8 TEM_2', '6_1' ='CD8 TEM_2', '6_4' ='CD8 TEM_2')
pbmc <- RenameIdents(pbmc, '18' = 'MAIT')
pbmc <- RenameIdents(pbmc, '6_2' ='gdT', '6_3' = 'gdT')
pbmc$celltype <- Idents(pbmc)
```

Example 57 (unknown):
```unknown
p1 <- DimPlot(pbmc, reduction = "umap.rna", group.by = "celltype", label = TRUE, label.size = 2.5, repel = TRUE) + ggtitle("RNA")
p2 <- DimPlot(pbmc, reduction = "umap.atac", group.by = "celltype", label = TRUE, label.size = 2.5, repel = TRUE) + ggtitle("ATAC")
p3 <- DimPlot(pbmc, reduction = "wnn.umap", group.by = "celltype", label = TRUE, label.size = 2.5, repel = TRUE) + ggtitle("WNN")
p1 + p2 + p3 & NoLegend() & theme(plot.title = element_text(hjust = 0.5))
```

Example 58 (r):
```r
p1 <- DimPlot(pbmc, reduction = "umap.rna", group.by = "celltype", label = TRUE, label.size = 2.5, repel = TRUE) + ggtitle("RNA")
p2 <- DimPlot(pbmc, reduction = "umap.atac", group.by = "celltype", label = TRUE, label.size = 2.5, repel = TRUE) + ggtitle("ATAC")
p3 <- DimPlot(pbmc, reduction = "wnn.umap", group.by = "celltype", label = TRUE, label.size = 2.5, repel = TRUE) + ggtitle("WNN")
p1 + p2 + p3 & NoLegend() & theme(plot.title = element_text(hjust = 0.5))
```

Example 59 (r):
```r
p1 <- DimPlot(pbmc, reduction = "umap.rna", group.by = "celltype", label = TRUE, label.size = 2.5, repel = TRUE) + ggtitle("RNA")
p2 <- DimPlot(pbmc, reduction = "umap.atac", group.by = "celltype", label = TRUE, label.size = 2.5, repel = TRUE) + ggtitle("ATAC")
p3 <- DimPlot(pbmc, reduction = "wnn.umap", group.by = "celltype", label = TRUE, label.size = 2.5, repel = TRUE) + ggtitle("WNN")
p1 + p2 + p3 & NoLegend() & theme(plot.title = element_text(hjust = 0.5))
```

Example 60 (unknown):
```unknown
## to make the visualization easier, subset T cell clusters
celltype.names <- levels(pbmc)
tcell.names <- grep("CD4|CD8|Treg", celltype.names,value = TRUE)
tcells <- subset(pbmc, idents = tcell.names)
CoveragePlot(tcells, region = 'CD8A', features = 'CD8A', assay = 'ATAC', expression.assay = 'SCT', peaks = FALSE)
```

Example 61 (r):
```r
## to make the visualization easier, subset T cell clusters
celltype.names <- levels(pbmc)
tcell.names <- grep("CD4|CD8|Treg", celltype.names,value = TRUE)
tcells <- subset(pbmc, idents = tcell.names)
CoveragePlot(tcells, region = 'CD8A', features = 'CD8A', assay = 'ATAC', expression.assay = 'SCT', peaks = FALSE)
```

Example 62 (r):
```r
## to make the visualization easier, subset T cell clusters
celltype.names <- levels(pbmc)
tcell.names <- grep("CD4|CD8|Treg", celltype.names,value = TRUE)
tcells <- subset(pbmc, idents = tcell.names)
CoveragePlot(tcells, region = 'CD8A', features = 'CD8A', assay = 'ATAC', expression.assay = 'SCT', peaks = FALSE)
```

Example 63 (unknown):
```unknown
remotes::install_github("immunogenomics/presto")
BiocManager::install(c("chromVAR", "TFBSTools", "JASPAR2020", "motifmatchr", "BSgenome.Hsapiens.UCSC.hg38"))
```

Example 64 (r):
```r
remotes::install_github("immunogenomics/presto")
BiocManager::install(c("chromVAR", "TFBSTools", "JASPAR2020", "motifmatchr", "BSgenome.Hsapiens.UCSC.hg38"))
```

Example 65 (r):
```r
remotes::install_github("immunogenomics/presto")
BiocManager::install(c("chromVAR", "TFBSTools", "JASPAR2020", "motifmatchr", "BSgenome.Hsapiens.UCSC.hg38"))
```

Example 66 (unknown):
```unknown
library(chromVAR)
library(JASPAR2020)
library(TFBSTools)
library(motifmatchr)
library(BSgenome.Hsapiens.UCSC.hg38)

# Scan the DNA sequence of each peak for the presence of each motif, and create a Motif object
DefaultAssay(pbmc) <- "ATAC"
pwm_set <- getMatrixSet(x = JASPAR2020, opts = list(species = 9606, all_versions = FALSE))
motif.matrix <- CreateMotifMatrix(features = granges(pbmc), pwm = pwm_set, genome = 'hg38', use.counts = FALSE)
motif.object <- CreateMotifObject(data = motif.matrix, pwm = pwm_set)
pbmc <- SetAssayData(pbmc, assay = 'ATAC', slot = 'motifs', new.data = motif.object)

# Note that this step can take 30-60 minutes 
pbmc <- RunChromVAR(
  object = pbmc,
  genome = BSgenome.Hsapiens.UCSC.hg38
)
```

Example 67 (r):
```r
library(chromVAR)
library(JASPAR2020)
library(TFBSTools)
library(motifmatchr)
library(BSgenome.Hsapiens.UCSC.hg38)

# Scan the DNA sequence of each peak for the presence of each motif, and create a Motif object
DefaultAssay(pbmc) <- "ATAC"
pwm_set <- getMatrixSet(x = JASPAR2020, opts = list(species = 9606, all_versions = FALSE))
motif.matrix <- CreateMotifMatrix(features = granges(pbmc), pwm = pwm_set, genome = 'hg38', use.counts = FALSE)
motif.object <- CreateMotifObject(data = motif.matrix, pwm = pwm_set)
pbmc <- SetAssayData(pbmc, assay = 'ATAC', slot = 'motifs', new.data = motif.object)

# Note that this step can take 30-60 minutes 
pbmc <- RunChromVAR(
  object = pbmc,
  genome = BSgenome.Hsapiens.UCSC.hg38
)
```

Example 68 (r):
```r
library(chromVAR)
library(JASPAR2020)
library(TFBSTools)
library(motifmatchr)
library(BSgenome.Hsapiens.UCSC.hg38)

# Scan the DNA sequence of each peak for the presence of each motif, and create a Motif object
DefaultAssay(pbmc) <- "ATAC"
pwm_set <- getMatrixSet(x = JASPAR2020, opts = list(species = 9606, all_versions = FALSE))
motif.matrix <- CreateMotifMatrix(features = granges(pbmc), pwm = pwm_set, genome = 'hg38', use.counts = FALSE)
motif.object <- CreateMotifObject(data = motif.matrix, pwm = pwm_set)
pbmc <- SetAssayData(pbmc, assay = 'ATAC', slot = 'motifs', new.data = motif.object)

# Note that this step can take 30-60 minutes 
pbmc <- RunChromVAR(
  object = pbmc,
  genome = BSgenome.Hsapiens.UCSC.hg38
)
```

Example 69 (unknown):
```unknown
#returns MA0466.2
motif.name <- ConvertMotifID(pbmc, name = 'CEBPB')
gene_plot <- FeaturePlot(pbmc, features = "sct_CEBPB", reduction = 'wnn.umap')
motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap')
gene_plot | motif_plot
```

Example 70 (r):
```r
#returns MA0466.2
motif.name <- ConvertMotifID(pbmc, name = 'CEBPB')
gene_plot <- FeaturePlot(pbmc, features = "sct_CEBPB", reduction = 'wnn.umap')
motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap')
gene_plot | motif_plot
```

Example 71 (r):
```r
#returns MA0466.2
motif.name <- ConvertMotifID(pbmc, name = 'CEBPB')
gene_plot <- FeaturePlot(pbmc, features = "sct_CEBPB", reduction = 'wnn.umap')
motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap')
gene_plot | motif_plot
```

Example 72 (unknown):
```unknown
markers_rna <- presto:::wilcoxauc.Seurat(X = pbmc, group_by = 'celltype', assay = 'data', seurat_assay = 'SCT')
markers_motifs <- presto:::wilcoxauc.Seurat(X = pbmc, group_by = 'celltype', assay = 'data', seurat_assay = 'chromvar')
motif.names <- markers_motifs$feature
colnames(markers_rna) <- paste0("RNA.", colnames(markers_rna))
colnames(markers_motifs) <- paste0("motif.", colnames(markers_motifs))
markers_rna$gene <- markers_rna$RNA.feature
markers_motifs$gene <- ConvertMotifID(pbmc, id = motif.names)
```

Example 73 (r):
```r
markers_rna <- presto:::wilcoxauc.Seurat(X = pbmc, group_by = 'celltype', assay = 'data', seurat_assay = 'SCT')
markers_motifs <- presto:::wilcoxauc.Seurat(X = pbmc, group_by = 'celltype', assay = 'data', seurat_assay = 'chromvar')
motif.names <- markers_motifs$feature
colnames(markers_rna) <- paste0("RNA.", colnames(markers_rna))
colnames(markers_motifs) <- paste0("motif.", colnames(markers_motifs))
markers_rna$gene <- markers_rna$RNA.feature
markers_motifs$gene <- ConvertMotifID(pbmc, id = motif.names)
```

Example 74 (r):
```r
markers_rna <- presto:::wilcoxauc.Seurat(X = pbmc, group_by = 'celltype', assay = 'data', seurat_assay = 'SCT')
markers_motifs <- presto:::wilcoxauc.Seurat(X = pbmc, group_by = 'celltype', assay = 'data', seurat_assay = 'chromvar')
motif.names <- markers_motifs$feature
colnames(markers_rna) <- paste0("RNA.", colnames(markers_rna))
colnames(markers_motifs) <- paste0("motif.", colnames(markers_motifs))
markers_rna$gene <- markers_rna$RNA.feature
markers_motifs$gene <- ConvertMotifID(pbmc, id = motif.names)
```

Example 75 (javascript):
```javascript
# a simple function to implement the procedure above
topTFs <- function(celltype, padj.cutoff = 1e-2) {
  ctmarkers_rna <- dplyr::filter(
    markers_rna, RNA.group == celltype, RNA.padj < padj.cutoff, RNA.logFC > 0) %>% 
    arrange(-RNA.auc)
  ctmarkers_motif <- dplyr::filter(
    markers_motifs, motif.group == celltype, motif.padj < padj.cutoff, motif.logFC > 0) %>% 
    arrange(-motif.auc)
  top_tfs <- inner_join(
    x = ctmarkers_rna[, c(2, 11, 6, 7)], 
    y = ctmarkers_motif[, c(2, 1, 11, 6, 7)], by = "gene"
  )
  top_tfs$avg_auc <- (top_tfs$RNA.auc + top_tfs$motif.auc) / 2
  top_tfs <- arrange(top_tfs, -avg_auc)
  return(top_tfs)
}
```

Example 76 (r):
```r
# a simple function to implement the procedure above
topTFs <- function(celltype, padj.cutoff = 1e-2) {
  ctmarkers_rna <- dplyr::filter(
    markers_rna, RNA.group == celltype, RNA.padj < padj.cutoff, RNA.logFC > 0) %>% 
    arrange(-RNA.auc)
  ctmarkers_motif <- dplyr::filter(
    markers_motifs, motif.group == celltype, motif.padj < padj.cutoff, motif.logFC > 0) %>% 
    arrange(-motif.auc)
  top_tfs <- inner_join(
    x = ctmarkers_rna[, c(2, 11, 6, 7)], 
    y = ctmarkers_motif[, c(2, 1, 11, 6, 7)], by = "gene"
  )
  top_tfs$avg_auc <- (top_tfs$RNA.auc + top_tfs$motif.auc) / 2
  top_tfs <- arrange(top_tfs, -avg_auc)
  return(top_tfs)
}
```

Example 77 (r):
```r
# a simple function to implement the procedure above
topTFs <- function(celltype, padj.cutoff = 1e-2) {
  ctmarkers_rna <- dplyr::filter(
    markers_rna, RNA.group == celltype, RNA.padj < padj.cutoff, RNA.logFC > 0) %>% 
    arrange(-RNA.auc)
  ctmarkers_motif <- dplyr::filter(
    markers_motifs, motif.group == celltype, motif.padj < padj.cutoff, motif.logFC > 0) %>% 
    arrange(-motif.auc)
  top_tfs <- inner_join(
    x = ctmarkers_rna[, c(2, 11, 6, 7)], 
    y = ctmarkers_motif[, c(2, 1, 11, 6, 7)], by = "gene"
  )
  top_tfs$avg_auc <- (top_tfs$RNA.auc + top_tfs$motif.auc) / 2
  top_tfs <- arrange(top_tfs, -avg_auc)
  return(top_tfs)
}
```

Example 78 (unknown):
```unknown
# identify top markers in NK and visualize
head(topTFs("NK"), 3)
```

Example 79 (r):
```r
# identify top markers in NK and visualize
head(topTFs("NK"), 3)
```

Example 80 (r):
```r
# identify top markers in NK and visualize
head(topTFs("NK"), 3)
```

Example 81 (unknown):
```unknown
##   RNA.group  gene   RNA.auc      RNA.pval motif.group motif.feature motif.auc
## 1        NK TBX21 0.7254543  0.000000e+00          NK      MA0690.1 0.9161365
## 2        NK EOMES 0.5889408  5.394245e-99          NK      MA0800.1 0.9239066
## 3        NK RUNX3 0.7705554 1.256004e-119          NK      MA0684.2 0.6813549
##      motif.pval   avg_auc
## 1 2.177841e-204 0.8207954
## 2 5.165634e-212 0.7564237
## 3  2.486287e-40 0.7259552
```

Example 82 (unknown):
```unknown
##   RNA.group  gene   RNA.auc      RNA.pval motif.group motif.feature motif.auc
## 1        NK TBX21 0.7254543  0.000000e+00          NK      MA0690.1 0.9161365
## 2        NK EOMES 0.5889408  5.394245e-99          NK      MA0800.1 0.9239066
## 3        NK RUNX3 0.7705554 1.256004e-119          NK      MA0684.2 0.6813549
##      motif.pval   avg_auc
## 1 2.177841e-204 0.8207954
## 2 5.165634e-212 0.7564237
## 3  2.486287e-40 0.7259552
```

Example 83 (unknown):
```unknown
motif.name <- ConvertMotifID(pbmc, name = 'TBX21')
gene_plot <- FeaturePlot(pbmc, features = "sct_TBX21", reduction = 'wnn.umap')
motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap')
gene_plot | motif_plot
```

Example 84 (r):
```r
motif.name <- ConvertMotifID(pbmc, name = 'TBX21')
gene_plot <- FeaturePlot(pbmc, features = "sct_TBX21", reduction = 'wnn.umap')
motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap')
gene_plot | motif_plot
```

Example 85 (r):
```r
motif.name <- ConvertMotifID(pbmc, name = 'TBX21')
gene_plot <- FeaturePlot(pbmc, features = "sct_TBX21", reduction = 'wnn.umap')
motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap')
gene_plot | motif_plot
```

Example 86 (unknown):
```unknown
# identify top markers in pDC and visualize
head(topTFs("pDC"), 3)
```

Example 87 (r):
```r
# identify top markers in pDC and visualize
head(topTFs("pDC"), 3)
```

Example 88 (r):
```r
# identify top markers in pDC and visualize
head(topTFs("pDC"), 3)
```

Example 89 (unknown):
```unknown
##   RNA.group gene   RNA.auc      RNA.pval motif.group motif.feature motif.auc
## 1       pDC TCF4 0.9998773 1.881543e-162         pDC      MA0830.2 0.9965481
## 2       pDC IRF8 0.9907541 1.197641e-123         pDC      MA0652.1 0.8833112
## 3       pDC SPIB 0.9113825  0.000000e+00         pDC      MA0081.2 0.9068540
##     motif.pval   avg_auc
## 1 1.785897e-69 0.9982127
## 2 3.982413e-42 0.9370327
## 3 3.083509e-47 0.9091182
```

Example 90 (unknown):
```unknown
##   RNA.group gene   RNA.auc      RNA.pval motif.group motif.feature motif.auc
## 1       pDC TCF4 0.9998773 1.881543e-162         pDC      MA0830.2 0.9965481
## 2       pDC IRF8 0.9907541 1.197641e-123         pDC      MA0652.1 0.8833112
## 3       pDC SPIB 0.9113825  0.000000e+00         pDC      MA0081.2 0.9068540
##     motif.pval   avg_auc
## 1 1.785897e-69 0.9982127
## 2 3.982413e-42 0.9370327
## 3 3.083509e-47 0.9091182
```

Example 91 (unknown):
```unknown
motif.name <- ConvertMotifID(pbmc, name = 'TCF4')
gene_plot <- FeaturePlot(pbmc, features = "sct_TCF4", reduction = 'wnn.umap')
motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap')
gene_plot | motif_plot
```

Example 92 (r):
```r
motif.name <- ConvertMotifID(pbmc, name = 'TCF4')
gene_plot <- FeaturePlot(pbmc, features = "sct_TCF4", reduction = 'wnn.umap')
motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap')
gene_plot | motif_plot
```

Example 93 (r):
```r
motif.name <- ConvertMotifID(pbmc, name = 'TCF4')
gene_plot <- FeaturePlot(pbmc, features = "sct_TCF4", reduction = 'wnn.umap')
motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap')
gene_plot | motif_plot
```

Example 94 (unknown):
```unknown
# identify top markers in HSPC and visualize
head(topTFs("CD16 Mono"),3)
```

Example 95 (r):
```r
# identify top markers in HSPC and visualize
head(topTFs("CD16 Mono"),3)
```

Example 96 (r):
```r
# identify top markers in HSPC and visualize
head(topTFs("CD16 Mono"),3)
```

Example 97 (unknown):
```unknown
##   RNA.group  gene   RNA.auc      RNA.pval motif.group motif.feature motif.auc
## 1 CD16 Mono  TCF7 0.6229004  5.572097e-27   CD16 Mono      MA0769.2 0.6956458
## 2 CD16 Mono  LEF1 0.6244160  1.959810e-27   CD16 Mono      MA0768.1 0.6427922
## 3 CD16 Mono GATA3 0.6853318 1.575081e-132   CD16 Mono      MA0037.3 0.5622475
##     motif.pval   avg_auc
## 1 8.605682e-54 0.6592731
## 2 1.845888e-29 0.6336041
## 3 8.972511e-07 0.6237897
```

Example 98 (unknown):
```unknown
##   RNA.group  gene   RNA.auc      RNA.pval motif.group motif.feature motif.auc
## 1 CD16 Mono  TCF7 0.6229004  5.572097e-27   CD16 Mono      MA0769.2 0.6956458
## 2 CD16 Mono  LEF1 0.6244160  1.959810e-27   CD16 Mono      MA0768.1 0.6427922
## 3 CD16 Mono GATA3 0.6853318 1.575081e-132   CD16 Mono      MA0037.3 0.5622475
##     motif.pval   avg_auc
## 1 8.605682e-54 0.6592731
## 2 1.845888e-29 0.6336041
## 3 8.972511e-07 0.6237897
```

Example 99 (unknown):
```unknown
motif.name <- ConvertMotifID(pbmc, name = 'SPI1')
gene_plot <- FeaturePlot(pbmc, features = "sct_SPI1", reduction = 'wnn.umap')
motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap')
gene_plot | motif_plot
```

Example 100 (r):
```r
motif.name <- ConvertMotifID(pbmc, name = 'SPI1')
gene_plot <- FeaturePlot(pbmc, features = "sct_SPI1", reduction = 'wnn.umap')
motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap')
gene_plot | motif_plot
```

Example 101 (r):
```r
motif.name <- ConvertMotifID(pbmc, name = 'SPI1')
gene_plot <- FeaturePlot(pbmc, features = "sct_SPI1", reduction = 'wnn.umap')
motif_plot <- FeaturePlot(pbmc, features = motif.name, min.cutoff = 0, cols = c("lightgrey", "darkred"), reduction = 'wnn.umap')
gene_plot | motif_plot
```

Example 102 (unknown):
```unknown
# identify top markers in other cell types
head(topTFs("Naive B"), 3)
```

Example 103 (r):
```r
# identify top markers in other cell types
head(topTFs("Naive B"), 3)
```

Example 104 (r):
```r
# identify top markers in other cell types
head(topTFs("Naive B"), 3)
```

Example 105 (unknown):
```unknown
##   RNA.group   gene   RNA.auc      RNA.pval motif.group motif.feature motif.auc
## 1   Naive B   TCF4 0.8350167 8.961289e-239     Naive B      MA0830.2 0.9066328
## 2   Naive B POU2F2 0.6969289  9.622025e-43     Naive B      MA0507.1 0.9740857
## 3   Naive B   EBF1 0.9114260  0.000000e+00     Naive B      MA0154.4 0.7565424
##      motif.pval   avg_auc
## 1 8.987390e-151 0.8708247
## 2 3.336610e-204 0.8355073
## 3  3.662535e-61 0.8339842
```

Example 106 (unknown):
```unknown
##   RNA.group   gene   RNA.auc      RNA.pval motif.group motif.feature motif.auc
## 1   Naive B   TCF4 0.8350167 8.961289e-239     Naive B      MA0830.2 0.9066328
## 2   Naive B POU2F2 0.6969289  9.622025e-43     Naive B      MA0507.1 0.9740857
## 3   Naive B   EBF1 0.9114260  0.000000e+00     Naive B      MA0154.4 0.7565424
##      motif.pval   avg_auc
## 1 8.987390e-151 0.8708247
## 2 3.336610e-204 0.8355073
## 3  3.662535e-61 0.8339842
```

Example 107 (unknown):
```unknown
head(topTFs("HSPC"), 3)
```

Example 108 (r):
```r
head(topTFs("HSPC"), 3)
```

Example 109 (r):
```r
head(topTFs("HSPC"), 3)
```

Example 110 (unknown):
```unknown
##   RNA.group  gene   RNA.auc     RNA.pval motif.group motif.feature motif.auc
## 1      HSPC  SOX4 0.9864425 2.831723e-71        HSPC      MA0867.2 0.6830497
## 2      HSPC GATA2 0.7115385 0.000000e+00        HSPC      MA0036.3 0.8275008
## 3      HSPC MEIS1 0.8254177 0.000000e+00        HSPC      MA0498.2 0.6924225
##     motif.pval   avg_auc
## 1 1.241915e-03 0.8347461
## 2 7.591798e-09 0.7695196
## 3 6.877492e-04 0.7589201
```

Example 111 (unknown):
```unknown
##   RNA.group  gene   RNA.auc     RNA.pval motif.group motif.feature motif.auc
## 1      HSPC  SOX4 0.9864425 2.831723e-71        HSPC      MA0867.2 0.6830497
## 2      HSPC GATA2 0.7115385 0.000000e+00        HSPC      MA0036.3 0.8275008
## 3      HSPC MEIS1 0.8254177 0.000000e+00        HSPC      MA0498.2 0.6924225
##     motif.pval   avg_auc
## 1 1.241915e-03 0.8347461
## 2 7.591798e-09 0.7695196
## 3 6.877492e-04 0.7589201
```

Example 112 (unknown):
```unknown
head(topTFs("Plasma"), 3)
```

Example 113 (r):
```r
head(topTFs("Plasma"), 3)
```

Example 114 (r):
```r
head(topTFs("Plasma"), 3)
```

Example 115 (unknown):
```unknown
##   RNA.group  gene   RNA.auc     RNA.pval motif.group motif.feature motif.auc
## 1    Plasma  IRF4 0.8189420 5.329976e-35      Plasma      MA1419.1 0.9776046
## 2    Plasma MEF2C 0.9108487 3.135227e-12      Plasma      MA0497.1 0.7596637
## 3    Plasma  TCF4 0.8306796 1.041100e-13      Plasma      MA0830.2 0.7840848
##     motif.pval   avg_auc
## 1 2.334627e-12 0.8982733
## 2 1.374353e-04 0.8352562
## 3 3.028306e-05 0.8073822
```

Example 116 (unknown):
```unknown
##   RNA.group  gene   RNA.auc     RNA.pval motif.group motif.feature motif.auc
## 1    Plasma  IRF4 0.8189420 5.329976e-35      Plasma      MA1419.1 0.9776046
## 2    Plasma MEF2C 0.9108487 3.135227e-12      Plasma      MA0497.1 0.7596637
## 3    Plasma  TCF4 0.8306796 1.041100e-13      Plasma      MA0830.2 0.7840848
##     motif.pval   avg_auc
## 1 2.334627e-12 0.8982733
## 2 1.374353e-04 0.8352562
## 3 3.028306e-05 0.8073822
```

Example 117 (unknown):
```unknown
sessionInfo()
```

Example 118 (r):
```r
sessionInfo()
```

Example 119 (r):
```r
sessionInfo()
```

Example 120 (unknown):
```unknown
## R version 4.2.2 Patched (2022-11-10 r83330)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.6 LTS
## 
## Matrix products: default
## BLAS:   /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.9.0
## LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.9.0
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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       
## 
## attached base packages:
## [1] stats4    stats     graphics  grDevices utils     datasets  methods  
## [8] base     
## 
## other attached packages:
##  [1] BSgenome.Hsapiens.UCSC.hg38_1.4.5 BSgenome_1.66.3                  
##  [3] rtracklayer_1.58.0                Biostrings_2.66.0                
##  [5] XVector_0.38.0                    motifmatchr_1.20.0               
##  [7] TFBSTools_1.36.0                  JASPAR2020_0.99.10               
##  [9] chromVAR_1.20.2                   EnsDb.Hsapiens.v86_2.99.0        
## [11] ensembldb_2.22.0                  AnnotationFilter_1.22.0          
## [13] GenomicFeatures_1.50.4            AnnotationDbi_1.60.2             
## [15] Biobase_2.58.0                    GenomicRanges_1.50.2             
## [17] GenomeInfoDb_1.34.9               IRanges_2.32.0                   
## [19] S4Vectors_0.36.2                  BiocGenerics_0.44.0              
## [21] Signac_1.12.9000                  ggplot2_3.4.4                    
## [23] dplyr_1.1.3                       cowplot_1.1.1                    
## [25] thp1.eccite.SeuratData_3.1.5      stxBrain.SeuratData_0.1.1        
## [27] ssHippo.SeuratData_3.1.4          pbmcsca.SeuratData_3.0.0         
## [29] pbmcref.SeuratData_1.0.0          pbmcMultiome.SeuratData_0.1.4    
## [31] pbmc3k.SeuratData_3.1.4           panc8.SeuratData_3.0.2           
## [33] ifnb.SeuratData_3.0.0             hcabm40k.SeuratData_3.0.0        
## [35] cbmc.SeuratData_3.1.4             bmcite.SeuratData_0.3.0          
## [37] SeuratData_0.2.2.9001             Seurat_5.0.0                     
## [39] SeuratObject_5.0.0                sp_2.1-1                         
## 
## loaded via a namespace (and not attached):
##   [1] rappdirs_0.3.3              scattermore_1.2            
##   [3] R.methodsS3_1.8.2           ragg_1.2.5                 
##   [5] nabor_0.5.0                 tidyr_1.3.0                
##   [7] bit64_4.0.5                 knitr_1.45                 
##   [9] R.utils_2.12.2              irlba_2.3.5.1              
##  [11] DelayedArray_0.24.0         rpart_4.1.19               
##  [13] data.table_1.14.8           KEGGREST_1.38.0            
##  [15] RCurl_1.98-1.12             generics_0.1.3             
##  [17] RSQLite_2.3.1               RANN_2.6.1                 
##  [19] future_1.33.0               tzdb_0.4.0                 
##  [21] bit_4.0.5                   spatstat.data_3.0-3        
##  [23] xml2_1.3.5                  httpuv_1.6.12              
##  [25] SummarizedExperiment_1.28.0 DirichletMultinomial_1.40.0
##  [27] xfun_0.40                   hms_1.1.3                  
##  [29] jquerylib_0.1.4             evaluate_0.22              
##  [31] promises_1.2.1              fansi_1.0.5                
##  [33] restfulr_0.0.15             progress_1.2.2             
##  [35] caTools_1.18.2              dbplyr_2.3.4               
##  [37] igraph_1.5.1                DBI_1.1.3                  
##  [39] htmlwidgets_1.6.2           spatstat.geom_3.2-7        
##  [41] purrr_1.0.2                 ellipsis_0.3.2             
##  [43] RSpectra_0.16-1             backports_1.4.1            
##  [45] annotate_1.76.0             sparseMatrixStats_1.10.0   
##  [47] biomaRt_2.54.1              deldir_1.0-9               
##  [49] MatrixGenerics_1.10.0       vctrs_0.6.4                
##  [51] ROCR_1.0-11                 abind_1.4-5                
##  [53] cachem_1.0.8                withr_2.5.2                
##  [55] progressr_0.14.0            presto_1.0.0               
##  [57] checkmate_2.2.0             sctransform_0.4.1          
##  [59] GenomicAlignments_1.34.1    prettyunits_1.1.1          
##  [61] goftest_1.2-3               cluster_2.1.4              
##  [63] seqLogo_1.64.0              dotCall64_1.1-0            
##  [65] lazyeval_0.2.2              crayon_1.5.2               
##  [67] hdf5r_1.3.8                 spatstat.explore_3.2-5     
##  [69] pkgconfig_2.0.3             labeling_0.4.3             
##  [71] nlme_3.1-162                vipor_0.4.5                
##  [73] ProtGenerics_1.30.0         nnet_7.3-18                
##  [75] rlang_1.1.1                 globals_0.16.2             
##  [77] lifecycle_1.0.3             miniUI_0.1.1.1             
##  [79] filelock_1.0.2              fastDummies_1.7.3          
##  [81] BiocFileCache_2.6.1         dichromat_2.0-0.1          
##  [83] ggrastr_1.0.1               rprojroot_2.0.3            
##  [85] polyclip_1.10-6             RcppHNSW_0.5.0             
##  [87] matrixStats_1.0.0           lmtest_0.9-40              
##  [89] Matrix_1.6-1.1              zoo_1.8-12                 
##  [91] base64enc_0.1-3             beeswarm_0.4.0             
##  [93] ggridges_0.5.4              png_0.1-8                  
##  [95] viridisLite_0.4.2           rjson_0.2.21               
##  [97] bitops_1.0-7                R.oo_1.25.0                
##  [99] KernSmooth_2.23-22          spam_2.10-0                
## [101] DelayedMatrixStats_1.20.0   blob_1.2.4                 
## [103] stringr_1.5.0               parallelly_1.36.0          
## [105] spatstat.random_3.2-1       readr_2.1.4                
## [107] CNEr_1.34.0                 scales_1.2.1               
## [109] memoise_2.0.1               magrittr_2.0.3             
## [111] plyr_1.8.9                  ica_1.0-3                  
## [113] zlibbioc_1.44.0             compiler_4.2.2             
## [115] BiocIO_1.8.0                RColorBrewer_1.1-3         
## [117] fitdistrplus_1.1-11         Rsamtools_2.14.0           
## [119] cli_3.6.1                   listenv_0.9.0              
## [121] patchwork_1.1.3             pbapply_1.7-2              
## [123] htmlTable_2.4.1             Formula_1.2-5              
## [125] MASS_7.3-58.2               tidyselect_1.2.0           
## [127] stringi_1.7.12              glmGamPoi_1.10.2           
## [129] textshaping_0.3.6           highr_0.10                 
## [131] yaml_2.3.7                  ggrepel_0.9.4              
## [133] grid_4.2.2                  VariantAnnotation_1.44.1   
## [135] sass_0.4.7                  fastmatch_1.1-4            
## [137] tools_4.2.2                 future.apply_1.11.0        
## [139] parallel_4.2.2              rstudioapi_0.14            
## [141] TFMPvalue_0.0.9             foreign_0.8-84             
## [143] gridExtra_2.3               farver_2.1.1               
## [145] Rtsne_0.16                  digest_0.6.33              
## [147] pracma_2.4.2                shiny_1.7.5.1              
## [149] Rcpp_1.0.11                 later_1.3.1                
## [151] RcppAnnoy_0.0.21            httr_1.4.7                 
## [153] biovizBase_1.46.0           colorspace_2.1-0           
## [155] XML_3.99-0.14               fs_1.6.3                   
## [157] tensor_1.5                  reticulate_1.34.0          
## [159] splines_4.2.2               uwot_0.1.16                
## [161] RcppRoll_0.3.0              spatstat.utils_3.0-4       
## [163] pkgdown_2.0.7               plotly_4.10.3              
## [165] systemfonts_1.0.4           xtable_1.8-4               
## [167] poweRlaw_0.70.6             jsonlite_1.8.7             
## [169] R6_2.5.1                    Hmisc_5.1-1                
## [171] pillar_1.9.0                htmltools_0.5.6.1          
## [173] mime_0.12                   DT_0.30                    
## [175] glue_1.6.2                  fastmap_1.1.1              
## [177] BiocParallel_1.32.6         codetools_0.2-19           
## [179] utf8_1.2.4                  lattice_0.21-9             
## [181] bslib_0.5.1                 spatstat.sparse_3.0-3      
## [183] tibble_3.2.1                curl_5.1.0                 
## [185] ggbeeswarm_0.7.1            leiden_0.4.3               
## [187] gtools_3.9.4                GO.db_3.16.0               
## [189] survival_3.5-7              rmarkdown_2.25             
## [191] desc_1.4.2                  munsell_0.5.0              
## [193] GenomeInfoDbData_1.2.9      reshape2_1.4.4             
## [195] gtable_0.3.4
```

Example 121 (unknown):
```unknown
## R version 4.2.2 Patched (2022-11-10 r83330)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.6 LTS
## 
## Matrix products: default
## BLAS:   /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.9.0
## LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.9.0
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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       
## 
## attached base packages:
## [1] stats4    stats     graphics  grDevices utils     datasets  methods  
## [8] base     
## 
## other attached packages:
##  [1] BSgenome.Hsapiens.UCSC.hg38_1.4.5 BSgenome_1.66.3                  
##  [3] rtracklayer_1.58.0                Biostrings_2.66.0                
##  [5] XVector_0.38.0                    motifmatchr_1.20.0               
##  [7] TFBSTools_1.36.0                  JASPAR2020_0.99.10               
##  [9] chromVAR_1.20.2                   EnsDb.Hsapiens.v86_2.99.0        
## [11] ensembldb_2.22.0                  AnnotationFilter_1.22.0          
## [13] GenomicFeatures_1.50.4            AnnotationDbi_1.60.2             
## [15] Biobase_2.58.0                    GenomicRanges_1.50.2             
## [17] GenomeInfoDb_1.34.9               IRanges_2.32.0                   
## [19] S4Vectors_0.36.2                  BiocGenerics_0.44.0              
## [21] Signac_1.12.9000                  ggplot2_3.4.4                    
## [23] dplyr_1.1.3                       cowplot_1.1.1                    
## [25] thp1.eccite.SeuratData_3.1.5      stxBrain.SeuratData_0.1.1        
## [27] ssHippo.SeuratData_3.1.4          pbmcsca.SeuratData_3.0.0         
## [29] pbmcref.SeuratData_1.0.0          pbmcMultiome.SeuratData_0.1.4    
## [31] pbmc3k.SeuratData_3.1.4           panc8.SeuratData_3.0.2           
## [33] ifnb.SeuratData_3.0.0             hcabm40k.SeuratData_3.0.0        
## [35] cbmc.SeuratData_3.1.4             bmcite.SeuratData_0.3.0          
## [37] SeuratData_0.2.2.9001             Seurat_5.0.0                     
## [39] SeuratObject_5.0.0                sp_2.1-1                         
## 
## loaded via a namespace (and not attached):
##   [1] rappdirs_0.3.3              scattermore_1.2            
##   [3] R.methodsS3_1.8.2           ragg_1.2.5                 
##   [5] nabor_0.5.0                 tidyr_1.3.0                
##   [7] bit64_4.0.5                 knitr_1.45                 
##   [9] R.utils_2.12.2              irlba_2.3.5.1              
##  [11] DelayedArray_0.24.0         rpart_4.1.19               
##  [13] data.table_1.14.8           KEGGREST_1.38.0            
##  [15] RCurl_1.98-1.12             generics_0.1.3             
##  [17] RSQLite_2.3.1               RANN_2.6.1                 
##  [19] future_1.33.0               tzdb_0.4.0                 
##  [21] bit_4.0.5                   spatstat.data_3.0-3        
##  [23] xml2_1.3.5                  httpuv_1.6.12              
##  [25] SummarizedExperiment_1.28.0 DirichletMultinomial_1.40.0
##  [27] xfun_0.40                   hms_1.1.3                  
##  [29] jquerylib_0.1.4             evaluate_0.22              
##  [31] promises_1.2.1              fansi_1.0.5                
##  [33] restfulr_0.0.15             progress_1.2.2             
##  [35] caTools_1.18.2              dbplyr_2.3.4               
##  [37] igraph_1.5.1                DBI_1.1.3                  
##  [39] htmlwidgets_1.6.2           spatstat.geom_3.2-7        
##  [41] purrr_1.0.2                 ellipsis_0.3.2             
##  [43] RSpectra_0.16-1             backports_1.4.1            
##  [45] annotate_1.76.0             sparseMatrixStats_1.10.0   
##  [47] biomaRt_2.54.1              deldir_1.0-9               
##  [49] MatrixGenerics_1.10.0       vctrs_0.6.4                
##  [51] ROCR_1.0-11                 abind_1.4-5                
##  [53] cachem_1.0.8                withr_2.5.2                
##  [55] progressr_0.14.0            presto_1.0.0               
##  [57] checkmate_2.2.0             sctransform_0.4.1          
##  [59] GenomicAlignments_1.34.1    prettyunits_1.1.1          
##  [61] goftest_1.2-3               cluster_2.1.4              
##  [63] seqLogo_1.64.0              dotCall64_1.1-0            
##  [65] lazyeval_0.2.2              crayon_1.5.2               
##  [67] hdf5r_1.3.8                 spatstat.explore_3.2-5     
##  [69] pkgconfig_2.0.3             labeling_0.4.3             
##  [71] nlme_3.1-162                vipor_0.4.5                
##  [73] ProtGenerics_1.30.0         nnet_7.3-18                
##  [75] rlang_1.1.1                 globals_0.16.2             
##  [77] lifecycle_1.0.3             miniUI_0.1.1.1             
##  [79] filelock_1.0.2              fastDummies_1.7.3          
##  [81] BiocFileCache_2.6.1         dichromat_2.0-0.1          
##  [83] ggrastr_1.0.1               rprojroot_2.0.3            
##  [85] polyclip_1.10-6             RcppHNSW_0.5.0             
##  [87] matrixStats_1.0.0           lmtest_0.9-40              
##  [89] Matrix_1.6-1.1              zoo_1.8-12                 
##  [91] base64enc_0.1-3             beeswarm_0.4.0             
##  [93] ggridges_0.5.4              png_0.1-8                  
##  [95] viridisLite_0.4.2           rjson_0.2.21               
##  [97] bitops_1.0-7                R.oo_1.25.0                
##  [99] KernSmooth_2.23-22          spam_2.10-0                
## [101] DelayedMatrixStats_1.20.0   blob_1.2.4                 
## [103] stringr_1.5.0               parallelly_1.36.0          
## [105] spatstat.random_3.2-1       readr_2.1.4                
## [107] CNEr_1.34.0                 scales_1.2.1               
## [109] memoise_2.0.1               magrittr_2.0.3             
## [111] plyr_1.8.9                  ica_1.0-3                  
## [113] zlibbioc_1.44.0             compiler_4.2.2             
## [115] BiocIO_1.8.0                RColorBrewer_1.1-3         
## [117] fitdistrplus_1.1-11         Rsamtools_2.14.0           
## [119] cli_3.6.1                   listenv_0.9.0              
## [121] patchwork_1.1.3             pbapply_1.7-2              
## [123] htmlTable_2.4.1             Formula_1.2-5              
## [125] MASS_7.3-58.2               tidyselect_1.2.0           
## [127] stringi_1.7.12              glmGamPoi_1.10.2           
## [129] textshaping_0.3.6           highr_0.10                 
## [131] yaml_2.3.7                  ggrepel_0.9.4              
## [133] grid_4.2.2                  VariantAnnotation_1.44.1   
## [135] sass_0.4.7                  fastmatch_1.1-4            
## [137] tools_4.2.2                 future.apply_1.11.0        
## [139] parallel_4.2.2              rstudioapi_0.14            
## [141] TFMPvalue_0.0.9             foreign_0.8-84             
## [143] gridExtra_2.3               farver_2.1.1               
## [145] Rtsne_0.16                  digest_0.6.33              
## [147] pracma_2.4.2                shiny_1.7.5.1              
## [149] Rcpp_1.0.11                 later_1.3.1                
## [151] RcppAnnoy_0.0.21            httr_1.4.7                 
## [153] biovizBase_1.46.0           colorspace_2.1-0           
## [155] XML_3.99-0.14               fs_1.6.3                   
## [157] tensor_1.5                  reticulate_1.34.0          
## [159] splines_4.2.2               uwot_0.1.16                
## [161] RcppRoll_0.3.0              spatstat.utils_3.0-4       
## [163] pkgdown_2.0.7               plotly_4.10.3              
## [165] systemfonts_1.0.4           xtable_1.8-4               
## [167] poweRlaw_0.70.6             jsonlite_1.8.7             
## [169] R6_2.5.1                    Hmisc_5.1-1                
## [171] pillar_1.9.0                htmltools_0.5.6.1          
## [173] mime_0.12                   DT_0.30                    
## [175] glue_1.6.2                  fastmap_1.1.1              
## [177] BiocParallel_1.32.6         codetools_0.2-19           
## [179] utf8_1.2.4                  lattice_0.21-9             
## [181] bslib_0.5.1                 spatstat.sparse_3.0-3      
## [183] tibble_3.2.1                curl_5.1.0                 
## [185] ggbeeswarm_0.7.1            leiden_0.4.3               
## [187] gtools_3.9.4                GO.db_3.16.0               
## [189] survival_3.5-7              rmarkdown_2.25             
## [191] desc_1.4.2                  munsell_0.5.0              
## [193] GenomeInfoDbData_1.2.9      reshape2_1.4.4             
## [195] gtable_0.3.4
```

---

## Analysis, visualization, and integration of Visium HD spatial datasets with Seurat • Seurat

**URL:** http://127.0.0.1:9173/seurat/sctransform_vignette.html

**Contents:**
- Using sctransform in Seurat
    - Saket Choudhary, Christoph Hafemeister & Rahul Satija
    - Compiled: 2023-10-31
- Load data and create Seurat object
- Apply sctransform normalization
- Perform dimensionality reduction by PCA and UMAP embedding
- Contents

Biological heterogeneity in single-cell RNA-seq data is often confounded by technical factors including sequencing depth. The number of molecules detected in each cell can vary significantly between cells, even within the same celltype. Interpretation of scRNA-seq data requires effective pre-processing and normalization to remove this technical variability.

In our manuscript we introduce a modeling framework for the normalization and variance stabilization of molecular count data from scRNA-seq experiments. This procedure omits the need for heuristic steps including pseudocount addition or log-transformation and improves common downstream analytical tasks such as variable gene selection, dimensional reduction, and differential expression. We named this method sctransform.

Inspired by important and rigorous work from Lause et al, we released an updated manuscript and updated the sctransform software to a v2 version, which is now the default in Seurat v5.

Why can we choose more PCs when using sctransform?

In the standard Seurat workflow we focus on 10 PCs for this dataset, though we highlight that the results are similar with higher settings for this parameter. Interestingly, we’ve found that when using sctransform, we often benefit by pushing this parameter even higher. We believe this is because the sctransform workflow performs more effective normalization, strongly removing technical effects from the data.

Even after standard log-normalization, variation in sequencing depth is still a confounding factor (see Figure 1), and this effect can subtly influence higher PCs. In sctransform, this effect is substantially mitigated (see Figure 3). This means that higher PCs are more likely to represent subtle, but biologically relevant, sources of heterogeneity – so including them may improve downstream analysis.

In addition, sctransform returns 3,000 variable features by default, instead of 2,000. The rationale is similar, the additional variable features are less likely to be driven by technical differences across cells, and instead may represent more subtle biological fluctuations. In general, we find that results produced with sctransform are less dependent on these parameters (indeed, we achieve nearly identical results when using all genes in the transcriptome, though this does reduce computational efficiency). This can help users generate more robust results, and in addition, enables the application of standard analysis pipelines with identical parameter settings that can quickly be applied to new datasets:

For example, the following code replicates the full end-to-end workflow, in a single command:

Where are normalized values stored for sctransform?

The results of sctransfrom are stored in the “SCT” assay. You can learn more about multi-assay data and commands in Seurat in our vignette, command cheat sheet, or developer guide.

Users can individually annotate clusters based on canonical markers. However, the sctransform normalization reveals sharper biological distinctions compared to the standard Seurat workflow, in a few ways:

Developed by Rahul Satija, Satija Lab and Collaborators.

Site built with pkgdown 2.0.7.

**Examples:**

Example 1 (unknown):
```unknown
vignettes/sctransform_vignette.Rmd
```

Example 2 (unknown):
```unknown
sctransform_vignette.Rmd
```

Example 3 (unknown):
```unknown
sctransform
```

Example 4 (unknown):
```unknown
library(Seurat)
library(ggplot2)
library(sctransform)
```

Example 5 (r):
```r
library(Seurat)
library(ggplot2)
library(sctransform)
```

Example 6 (r):
```r
library(Seurat)
library(ggplot2)
library(sctransform)
```

Example 7 (unknown):
```unknown
pbmc_data <- Read10X(data.dir = "/brahms/shared/vignette-data/pbmc3k/filtered_gene_bc_matrices/hg19/")
pbmc <- CreateSeuratObject(counts = pbmc_data)
```

Example 8 (r):
```r
pbmc_data <- Read10X(data.dir = "/brahms/shared/vignette-data/pbmc3k/filtered_gene_bc_matrices/hg19/")
pbmc <- CreateSeuratObject(counts = pbmc_data)
```

Example 9 (r):
```r
pbmc_data <- Read10X(data.dir = "/brahms/shared/vignette-data/pbmc3k/filtered_gene_bc_matrices/hg19/")
pbmc <- CreateSeuratObject(counts = pbmc_data)
```

Example 10 (unknown):
```unknown
NormalizeData()
```

Example 11 (unknown):
```unknown
ScaleData()
```

Example 12 (unknown):
```unknown
FindVariableFeatures()
```

Example 13 (unknown):
```unknown
vst.flavor = 'v1'
```

Example 14 (unknown):
```unknown
# store mitochondrial percentage in object meta data
pbmc <- PercentageFeatureSet(pbmc, pattern = "^MT-", col.name = "percent.mt")

# run sctransform
pbmc <- SCTransform(pbmc, vars.to.regress = "percent.mt", verbose = FALSE)
```

Example 15 (r):
```r
# store mitochondrial percentage in object meta data
pbmc <- PercentageFeatureSet(pbmc, pattern = "^MT-", col.name = "percent.mt")

# run sctransform
pbmc <- SCTransform(pbmc, vars.to.regress = "percent.mt", verbose = FALSE)
```

Example 16 (r):
```r
# store mitochondrial percentage in object meta data
pbmc <- PercentageFeatureSet(pbmc, pattern = "^MT-", col.name = "percent.mt")

# run sctransform
pbmc <- SCTransform(pbmc, vars.to.regress = "percent.mt", verbose = FALSE)
```

Example 17 (unknown):
```unknown
# These are now standard steps in the Seurat workflow for visualization and clustering
pbmc <- RunPCA(pbmc, verbose = FALSE)
pbmc <- RunUMAP(pbmc, dims = 1:30, verbose = FALSE)

pbmc <- FindNeighbors(pbmc, dims = 1:30, verbose = FALSE)
pbmc <- FindClusters(pbmc, verbose = FALSE)
DimPlot(pbmc, label = TRUE)
```

Example 18 (r):
```r
# These are now standard steps in the Seurat workflow for visualization and clustering
pbmc <- RunPCA(pbmc, verbose = FALSE)
pbmc <- RunUMAP(pbmc, dims = 1:30, verbose = FALSE)

pbmc <- FindNeighbors(pbmc, dims = 1:30, verbose = FALSE)
pbmc <- FindClusters(pbmc, verbose = FALSE)
DimPlot(pbmc, label = TRUE)
```

Example 19 (r):
```r
# These are now standard steps in the Seurat workflow for visualization and clustering
pbmc <- RunPCA(pbmc, verbose = FALSE)
pbmc <- RunUMAP(pbmc, dims = 1:30, verbose = FALSE)

pbmc <- FindNeighbors(pbmc, dims = 1:30, verbose = FALSE)
pbmc <- FindClusters(pbmc, verbose = FALSE)
DimPlot(pbmc, label = TRUE)
```

Example 20 (unknown):
```unknown
pbmc <- CreateSeuratObject(pbmc_data) %>%
    PercentageFeatureSet(pattern = "^MT-", col.name = "percent.mt") %>%
    SCTransform(vars.to.regress = "percent.mt") %>%
    RunPCA() %>%
    FindNeighbors(dims = 1:30) %>%
    RunUMAP(dims = 1:30) %>%
    FindClusters()
```

Example 21 (r):
```r
pbmc <- CreateSeuratObject(pbmc_data) %>%
    PercentageFeatureSet(pattern = "^MT-", col.name = "percent.mt") %>%
    SCTransform(vars.to.regress = "percent.mt") %>%
    RunPCA() %>%
    FindNeighbors(dims = 1:30) %>%
    RunUMAP(dims = 1:30) %>%
    FindClusters()
```

Example 22 (r):
```r
pbmc <- CreateSeuratObject(pbmc_data) %>%
    PercentageFeatureSet(pattern = "^MT-", col.name = "percent.mt") %>%
    SCTransform(vars.to.regress = "percent.mt") %>%
    RunPCA() %>%
    FindNeighbors(dims = 1:30) %>%
    RunUMAP(dims = 1:30) %>%
    FindClusters()
```

Example 23 (unknown):
```unknown
pbmc[["SCT"]]$scale.data
```

Example 24 (unknown):
```unknown
SCTransform()
```

Example 25 (unknown):
```unknown
pbmc[["SCT"]]$counts
```

Example 26 (unknown):
```unknown
pbmc[["SCT"]]$data
```

Example 27 (unknown):
```unknown
# These are now standard steps in the Seurat workflow for visualization and clustering
# Visualize canonical marker genes as violin plots.
VlnPlot(pbmc, features = c("CD8A", "GZMK", "CCL5", "S100A4", "ANXA1", "CCR7", "ISG15", "CD3D"),
    pt.size = 0.2, ncol = 4)
```

Example 28 (r):
```r
# These are now standard steps in the Seurat workflow for visualization and clustering
# Visualize canonical marker genes as violin plots.
VlnPlot(pbmc, features = c("CD8A", "GZMK", "CCL5", "S100A4", "ANXA1", "CCR7", "ISG15", "CD3D"),
    pt.size = 0.2, ncol = 4)
```

Example 29 (r):
```r
# These are now standard steps in the Seurat workflow for visualization and clustering
# Visualize canonical marker genes as violin plots.
VlnPlot(pbmc, features = c("CD8A", "GZMK", "CCL5", "S100A4", "ANXA1", "CCR7", "ISG15", "CD3D"),
    pt.size = 0.2, ncol = 4)
```

Example 30 (unknown):
```unknown
# Visualize canonical marker genes on the sctransform embedding.
FeaturePlot(pbmc, features = c("CD8A", "GZMK", "CCL5", "S100A4", "ANXA1", "CCR7"), pt.size = 0.2,
    ncol = 3)
```

Example 31 (r):
```r
# Visualize canonical marker genes on the sctransform embedding.
FeaturePlot(pbmc, features = c("CD8A", "GZMK", "CCL5", "S100A4", "ANXA1", "CCR7"), pt.size = 0.2,
    ncol = 3)
```

Example 32 (r):
```r
# Visualize canonical marker genes on the sctransform embedding.
FeaturePlot(pbmc, features = c("CD8A", "GZMK", "CCL5", "S100A4", "ANXA1", "CCR7"), pt.size = 0.2,
    ncol = 3)
```

Example 33 (unknown):
```unknown
FeaturePlot(pbmc, features = c("CD3D", "ISG15", "TCL1A", "FCER2", "XCL1", "FCGR3A"), pt.size = 0.2,
    ncol = 3)
```

Example 34 (r):
```r
FeaturePlot(pbmc, features = c("CD3D", "ISG15", "TCL1A", "FCER2", "XCL1", "FCGR3A"), pt.size = 0.2,
    ncol = 3)
```

Example 35 (r):
```r
FeaturePlot(pbmc, features = c("CD3D", "ISG15", "TCL1A", "FCER2", "XCL1", "FCGR3A"), pt.size = 0.2,
    ncol = 3)
```

Example 36 (unknown):
```unknown
sessionInfo()
```

Example 37 (r):
```r
sessionInfo()
```

Example 38 (r):
```r
sessionInfo()
```

Example 39 (unknown):
```unknown
## R version 4.2.2 Patched (2022-11-10 r83330)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.6 LTS
## 
## Matrix products: default
## BLAS:   /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.9.0
## LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.9.0
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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       
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
## [1] sctransform_0.4.1  ggplot2_3.4.4      Seurat_5.0.0       SeuratObject_5.0.0
## [5] sp_2.1-1          
## 
## loaded via a namespace (and not attached):
##   [1] spam_2.10-0                 systemfonts_1.0.4          
##   [3] plyr_1.8.9                  igraph_1.5.1               
##   [5] lazyeval_0.2.2              splines_4.2.2              
##   [7] RcppHNSW_0.5.0              listenv_0.9.0              
##   [9] scattermore_1.2             GenomeInfoDb_1.34.9        
##  [11] digest_0.6.33               htmltools_0.5.6.1          
##  [13] fansi_1.0.5                 magrittr_2.0.3             
##  [15] memoise_2.0.1               tensor_1.5                 
##  [17] cluster_2.1.4               ROCR_1.0-11                
##  [19] globals_0.16.2              matrixStats_1.0.0          
##  [21] R.utils_2.12.2              pkgdown_2.0.7              
##  [23] spatstat.sparse_3.0-3       colorspace_2.1-0           
##  [25] ggrepel_0.9.4               textshaping_0.3.6          
##  [27] xfun_0.40                   dplyr_1.1.3                
##  [29] RCurl_1.98-1.12             jsonlite_1.8.7             
##  [31] progressr_0.14.0            spatstat.data_3.0-3        
##  [33] survival_3.5-7              zoo_1.8-12                 
##  [35] glue_1.6.2                  polyclip_1.10-6            
##  [37] gtable_0.3.4                zlibbioc_1.44.0            
##  [39] XVector_0.38.0              leiden_0.4.3               
##  [41] DelayedArray_0.24.0         future.apply_1.11.0        
##  [43] BiocGenerics_0.44.0         abind_1.4-5                
##  [45] scales_1.2.1                spatstat.random_3.2-1      
##  [47] miniUI_0.1.1.1              Rcpp_1.0.11                
##  [49] viridisLite_0.4.2           xtable_1.8-4               
##  [51] reticulate_1.34.0           dotCall64_1.1-0            
##  [53] stats4_4.2.2                htmlwidgets_1.6.2          
##  [55] httr_1.4.7                  RColorBrewer_1.1-3         
##  [57] ellipsis_0.3.2              ica_1.0-3                  
##  [59] farver_2.1.1                pkgconfig_2.0.3            
##  [61] R.methodsS3_1.8.2           sass_0.4.7                 
##  [63] uwot_0.1.16                 deldir_1.0-9               
##  [65] utf8_1.2.4                  labeling_0.4.3             
##  [67] tidyselect_1.2.0            rlang_1.1.1                
##  [69] reshape2_1.4.4              later_1.3.1                
##  [71] munsell_0.5.0               tools_4.2.2                
##  [73] cachem_1.0.8                cli_3.6.1                  
##  [75] generics_0.1.3              ggridges_0.5.4             
##  [77] evaluate_0.22               stringr_1.5.0              
##  [79] fastmap_1.1.1               yaml_2.3.7                 
##  [81] ragg_1.2.5                  goftest_1.2-3              
##  [83] knitr_1.45                  fs_1.6.3                   
##  [85] fitdistrplus_1.1-11         purrr_1.0.2                
##  [87] RANN_2.6.1                  sparseMatrixStats_1.10.0   
##  [89] pbapply_1.7-2               future_1.33.0              
##  [91] nlme_3.1-162                mime_0.12                  
##  [93] formatR_1.14                ggrastr_1.0.1              
##  [95] R.oo_1.25.0                 compiler_4.2.2             
##  [97] beeswarm_0.4.0              plotly_4.10.3              
##  [99] png_0.1-8                   spatstat.utils_3.0-4       
## [101] tibble_3.2.1                bslib_0.5.1                
## [103] glmGamPoi_1.10.2            stringi_1.7.12             
## [105] highr_0.10                  desc_1.4.2                 
## [107] RSpectra_0.16-1             lattice_0.21-9             
## [109] Matrix_1.6-1.1              vctrs_0.6.4                
## [111] pillar_1.9.0                lifecycle_1.0.3            
## [113] spatstat.geom_3.2-7         lmtest_0.9-40              
## [115] jquerylib_0.1.4             RcppAnnoy_0.0.21           
## [117] bitops_1.0-7                data.table_1.14.8          
## [119] cowplot_1.1.1               irlba_2.3.5.1              
## [121] GenomicRanges_1.50.2        httpuv_1.6.12              
## [123] patchwork_1.1.3             R6_2.5.1                   
## [125] promises_1.2.1              KernSmooth_2.23-22         
## [127] gridExtra_2.3               vipor_0.4.5                
## [129] IRanges_2.32.0              parallelly_1.36.0          
## [131] codetools_0.2-19            fastDummies_1.7.3          
## [133] MASS_7.3-58.2               SummarizedExperiment_1.28.0
## [135] rprojroot_2.0.3             withr_2.5.2                
## [137] GenomeInfoDbData_1.2.9      S4Vectors_0.36.2           
## [139] parallel_4.2.2              grid_4.2.2                 
## [141] tidyr_1.3.0                 DelayedMatrixStats_1.20.0  
## [143] rmarkdown_2.25              MatrixGenerics_1.10.0      
## [145] Rtsne_0.16                  spatstat.explore_3.2-5     
## [147] Biobase_2.58.0              shiny_1.7.5.1              
## [149] ggbeeswarm_0.7.1
```

Example 40 (unknown):
```unknown
## R version 4.2.2 Patched (2022-11-10 r83330)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.6 LTS
## 
## Matrix products: default
## BLAS:   /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.9.0
## LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.9.0
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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       
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
## [1] sctransform_0.4.1  ggplot2_3.4.4      Seurat_5.0.0       SeuratObject_5.0.0
## [5] sp_2.1-1          
## 
## loaded via a namespace (and not attached):
##   [1] spam_2.10-0                 systemfonts_1.0.4          
##   [3] plyr_1.8.9                  igraph_1.5.1               
##   [5] lazyeval_0.2.2              splines_4.2.2              
##   [7] RcppHNSW_0.5.0              listenv_0.9.0              
##   [9] scattermore_1.2             GenomeInfoDb_1.34.9        
##  [11] digest_0.6.33               htmltools_0.5.6.1          
##  [13] fansi_1.0.5                 magrittr_2.0.3             
##  [15] memoise_2.0.1               tensor_1.5                 
##  [17] cluster_2.1.4               ROCR_1.0-11                
##  [19] globals_0.16.2              matrixStats_1.0.0          
##  [21] R.utils_2.12.2              pkgdown_2.0.7              
##  [23] spatstat.sparse_3.0-3       colorspace_2.1-0           
##  [25] ggrepel_0.9.4               textshaping_0.3.6          
##  [27] xfun_0.40                   dplyr_1.1.3                
##  [29] RCurl_1.98-1.12             jsonlite_1.8.7             
##  [31] progressr_0.14.0            spatstat.data_3.0-3        
##  [33] survival_3.5-7              zoo_1.8-12                 
##  [35] glue_1.6.2                  polyclip_1.10-6            
##  [37] gtable_0.3.4                zlibbioc_1.44.0            
##  [39] XVector_0.38.0              leiden_0.4.3               
##  [41] DelayedArray_0.24.0         future.apply_1.11.0        
##  [43] BiocGenerics_0.44.0         abind_1.4-5                
##  [45] scales_1.2.1                spatstat.random_3.2-1      
##  [47] miniUI_0.1.1.1              Rcpp_1.0.11                
##  [49] viridisLite_0.4.2           xtable_1.8-4               
##  [51] reticulate_1.34.0           dotCall64_1.1-0            
##  [53] stats4_4.2.2                htmlwidgets_1.6.2          
##  [55] httr_1.4.7                  RColorBrewer_1.1-3         
##  [57] ellipsis_0.3.2              ica_1.0-3                  
##  [59] farver_2.1.1                pkgconfig_2.0.3            
##  [61] R.methodsS3_1.8.2           sass_0.4.7                 
##  [63] uwot_0.1.16                 deldir_1.0-9               
##  [65] utf8_1.2.4                  labeling_0.4.3             
##  [67] tidyselect_1.2.0            rlang_1.1.1                
##  [69] reshape2_1.4.4              later_1.3.1                
##  [71] munsell_0.5.0               tools_4.2.2                
##  [73] cachem_1.0.8                cli_3.6.1                  
##  [75] generics_0.1.3              ggridges_0.5.4             
##  [77] evaluate_0.22               stringr_1.5.0              
##  [79] fastmap_1.1.1               yaml_2.3.7                 
##  [81] ragg_1.2.5                  goftest_1.2-3              
##  [83] knitr_1.45                  fs_1.6.3                   
##  [85] fitdistrplus_1.1-11         purrr_1.0.2                
##  [87] RANN_2.6.1                  sparseMatrixStats_1.10.0   
##  [89] pbapply_1.7-2               future_1.33.0              
##  [91] nlme_3.1-162                mime_0.12                  
##  [93] formatR_1.14                ggrastr_1.0.1              
##  [95] R.oo_1.25.0                 compiler_4.2.2             
##  [97] beeswarm_0.4.0              plotly_4.10.3              
##  [99] png_0.1-8                   spatstat.utils_3.0-4       
## [101] tibble_3.2.1                bslib_0.5.1                
## [103] glmGamPoi_1.10.2            stringi_1.7.12             
## [105] highr_0.10                  desc_1.4.2                 
## [107] RSpectra_0.16-1             lattice_0.21-9             
## [109] Matrix_1.6-1.1              vctrs_0.6.4                
## [111] pillar_1.9.0                lifecycle_1.0.3            
## [113] spatstat.geom_3.2-7         lmtest_0.9-40              
## [115] jquerylib_0.1.4             RcppAnnoy_0.0.21           
## [117] bitops_1.0-7                data.table_1.14.8          
## [119] cowplot_1.1.1               irlba_2.3.5.1              
## [121] GenomicRanges_1.50.2        httpuv_1.6.12              
## [123] patchwork_1.1.3             R6_2.5.1                   
## [125] promises_1.2.1              KernSmooth_2.23-22         
## [127] gridExtra_2.3               vipor_0.4.5                
## [129] IRanges_2.32.0              parallelly_1.36.0          
## [131] codetools_0.2-19            fastDummies_1.7.3          
## [133] MASS_7.3-58.2               SummarizedExperiment_1.28.0
## [135] rprojroot_2.0.3             withr_2.5.2                
## [137] GenomeInfoDbData_1.2.9      S4Vectors_0.36.2           
## [139] parallel_4.2.2              grid_4.2.2                 
## [141] tidyr_1.3.0                 DelayedMatrixStats_1.20.0  
## [143] rmarkdown_2.25              MatrixGenerics_1.10.0      
## [145] Rtsne_0.16                  spatstat.explore_3.2-5     
## [147] Biobase_2.58.0              shiny_1.7.5.1              
## [149] ggbeeswarm_0.7.1
```

---

## Using Seurat with multi-modal data

**URL:** http://127.0.0.1:9173/seurat/archive/v2.4/multimodal_vignette/index.html

**Contents:**
- Using Seurat with multi-modal data
    - Satija Lab
    - Compiled: 2018-03-24
- Load in the data
  - Setup a Seurat object, and cluster cells based on RNA expression
  - Add the protein expression levels to the Seurat object
  - Visualize protein levels on RNA clusters
  - Identify differentially expressed proteins between clusters
  - Cluster directly on protein levels
  - Loading data from other multi-modal technologies

This vignette demonstrates new features that allow users to analyze and explore multi-modal data with Seurat. While this represents an initial release, we are excited to release significant new functionality for multi-modal datasets in the future.

Here, we analyze a dataset of 8,617 cord blood mononuclear cells (CBMCs), produced with CITE-seq, where we simultaneously measure the single cell transcriptomes alongside the expression of 11 surface proteins, whose levels are quantified with DNA-barcoded antibodies. First, we load in two count matrices : one for the RNA measurements, and one for the antibody-derived tags (ADT). You can download the ADT file here and the RNA file here

The steps below represent a quick clustering of the PBMCs based on the scRNA-seq data. For more detail on individual steps or more advanced options, see our PBMC clustering guided tutorial here

Seurat v2.1 allows you to store information from multiple assays in the same object, as long as the data is multi-modal (collected on the same set of cells). You can use the SetAssayData and GetAssayData accessor functions to add and fetch data from additional assays.

You can use the names of any ADT markers, (i.e. “CITE_CD4”), in FetchData, FeaturePlot, RidgePlot, GenePlot, DoHeatmap, or any other visualization features

You can also run dimensional reduction and graph-based clustering directly on CITE-seq data

The ADT-based clustering yields similar results, but with a few differences

Seurat is also able to analyze data from other multi-modal technologies like REAP-seq. Below we recreate above the same plots that we generated with CITE-seq data, and observe the same qualitative trends. You can download the data from GEO here.

**Examples:**

Example 1 (r):
```r
# Load in the RNA UMI matrix

# Note that this dataset also contains ~5% of mouse cells, which we can use
# as negative controls for the protein measurements. For this reason, the
# gene expression matrix has HUMAN_ or MOUSE_ appended to the beginning of
# each gene.
cbmc.rna <- read.csv("~/Downloads/GSE100866_CBMC_8K_13AB_10X-RNA_umi.csv.gz", 
    sep = ",", header = TRUE, row.names = 1)

# To make life a bit easier going forward, we're going to discard all but
# the top 100 most highly expressed mouse genes, and remove the 'HUMAN_'
# from the CITE-seq prefix
cbmc.rna.collapsed <- CollapseSpeciesExpressionMatrix(cbmc.rna)

# Load in the ADT UMI matrix
cbmc.adt <- read.csv("~/Downloads/GSE100866_CBMC_8K_13AB_10X-ADT_umi.csv.gz", 
    sep = ",", header = TRUE, row.names = 1)

# To avoid any confusion where genes and proteins might have the same name,
# we'll append 'CITE_' to each of the ADT rownames. This is not strictly
# necessary, but it helps for clarity
cbmc.citeseq <- cbmc.adt
rownames(cbmc.citeseq) <- paste0("CITE_", rownames(cbmc.adt))

# Lastly, we observed poor enrichments for CCR5, CCR7, and CD10 - and
# therefore remove them from the matrix (optional)
cbmc.citeseq <- cbmc.citeseq[setdiff(rownames(cbmc.citeseq), c("CITE_CCR5", 
    "CITE_CCR7", "CITE_CD10")), ]
```

Example 2 (r):
```r
# Load in the RNA UMI matrix

# Note that this dataset also contains ~5% of mouse cells, which we can use
# as negative controls for the protein measurements. For this reason, the
# gene expression matrix has HUMAN_ or MOUSE_ appended to the beginning of
# each gene.
cbmc.rna <- read.csv("~/Downloads/GSE100866_CBMC_8K_13AB_10X-RNA_umi.csv.gz", 
    sep = ",", header = TRUE, row.names = 1)

# To make life a bit easier going forward, we're going to discard all but
# the top 100 most highly expressed mouse genes, and remove the 'HUMAN_'
# from the CITE-seq prefix
cbmc.rna.collapsed <- CollapseSpeciesExpressionMatrix(cbmc.rna)

# Load in the ADT UMI matrix
cbmc.adt <- read.csv("~/Downloads/GSE100866_CBMC_8K_13AB_10X-ADT_umi.csv.gz", 
    sep = ",", header = TRUE, row.names = 1)

# To avoid any confusion where genes and proteins might have the same name,
# we'll append 'CITE_' to each of the ADT rownames. This is not strictly
# necessary, but it helps for clarity
cbmc.citeseq <- cbmc.adt
rownames(cbmc.citeseq) <- paste0("CITE_", rownames(cbmc.adt))

# Lastly, we observed poor enrichments for CCR5, CCR7, and CD10 - and
# therefore remove them from the matrix (optional)
cbmc.citeseq <- cbmc.citeseq[setdiff(rownames(cbmc.citeseq), c("CITE_CCR5", 
    "CITE_CCR7", "CITE_CD10")), ]
```

Example 3 (r):
```r
cbmc <- CreateSeuratObject(raw.data = cbmc.rna.collapsed)

# standard log-normalization
cbmc <- NormalizeData(cbmc)

# choose ~1k variable genes
cbmc <- FindVariableGenes(cbmc, do.plot = FALSE, y.cutoff = 0.5)

# standard scaling (no regression)
cbmc <- ScaleData(cbmc, display.progress = FALSE)

# Run PCA, select 13 PCs for tSNE visualization and graph-based clustering
cbmc <- RunPCA(cbmc, pcs.print = 0)
PCElbowPlot(cbmc)
```

Example 4 (r):
```r
cbmc <- CreateSeuratObject(raw.data = cbmc.rna.collapsed)

# standard log-normalization
cbmc <- NormalizeData(cbmc)

# choose ~1k variable genes
cbmc <- FindVariableGenes(cbmc, do.plot = FALSE, y.cutoff = 0.5)

# standard scaling (no regression)
cbmc <- ScaleData(cbmc, display.progress = FALSE)

# Run PCA, select 13 PCs for tSNE visualization and graph-based clustering
cbmc <- RunPCA(cbmc, pcs.print = 0)
PCElbowPlot(cbmc)
```

Example 5 (r):
```r
cbmc <- FindClusters(cbmc, dims.use = 1:13, print.output = FALSE)
cbmc <- RunTSNE(cbmc, dims.use = 1:13)

# Find the markers that define each cluster, and use these to annotate the
# clusters, we use max.cells.per.ident to speed up the process
cbmc.rna.markers <- FindAllMarkers(cbmc, max.cells.per.ident = 100, logfc.threshold = log(2), 
    only.pos = TRUE, min.diff.pct = 0.3, do.print = F)

current.cluster.ids <- 0:15
# Note, for simplicity we are merging two CD14+ Mono clusters (that differ
# in the expression of HLA-DR genes), and two NK clusters (that differ in
# cell cycle stage)
new.cluster.ids <- c("CD4 T", "CD14+ Mono", "CD14+ Mono", "NK", "Mouse", "B", 
    "CD8 T", "CD16+ Mono", "Unknown", "CD34+", "Mk", "Eryth", "DC", "Mouse", 
    "pDC", "NK")
cbmc@ident <- plyr::mapvalues(x = cbmc@ident, from = current.cluster.ids, to = new.cluster.ids)
```

Example 6 (r):
```r
cbmc <- FindClusters(cbmc, dims.use = 1:13, print.output = FALSE)
cbmc <- RunTSNE(cbmc, dims.use = 1:13)

# Find the markers that define each cluster, and use these to annotate the
# clusters, we use max.cells.per.ident to speed up the process
cbmc.rna.markers <- FindAllMarkers(cbmc, max.cells.per.ident = 100, logfc.threshold = log(2), 
    only.pos = TRUE, min.diff.pct = 0.3, do.print = F)

current.cluster.ids <- 0:15
# Note, for simplicity we are merging two CD14+ Mono clusters (that differ
# in the expression of HLA-DR genes), and two NK clusters (that differ in
# cell cycle stage)
new.cluster.ids <- c("CD4 T", "CD14+ Mono", "CD14+ Mono", "NK", "Mouse", "B", 
    "CD8 T", "CD16+ Mono", "Unknown", "CD34+", "Mk", "Eryth", "DC", "Mouse", 
    "pDC", "NK")
cbmc@ident <- plyr::mapvalues(x = cbmc@ident, from = current.cluster.ids, to = new.cluster.ids)
```

Example 7 (r):
```r
TSNEPlot(cbmc, do.label = TRUE, pt.size = 0.5)
```

Example 8 (r):
```r
TSNEPlot(cbmc, do.label = TRUE, pt.size = 0.5)
```

Example 9 (unknown):
```unknown
SetAssayData
```

Example 10 (unknown):
```unknown
GetAssayData
```

Example 11 (r):
```r
# We will define a CITE assay, and store raw data for it. Note that it's
# convenient, but not required, to use the same name as the rowname prefix
# we defined earlier.

# If you are interested in how these data are internally stored, you can
# check out the @assay slot, and the assay class, which is defined in
# multimodal.R Note that RNA data is still stored in its normal slots, but
# can also be accessed using GetAssayData and SetAssayData, using the 'RNA'
# assay

cbmc <- SetAssayData(cbmc, assay.type = "CITE", slot = "raw.data", new.data = cbmc.citeseq)

# Now we can repeat the preprocessing (normalization and scaling) steps that
# we typically run with RNA, but modifying the 'assay.type' argument.  For
# CITE-seq data, we do not recommend typical LogNormalization. Instead, we
# use a centered log-ratio (CLR) normalization, computed independently for
# each gene.  This is a slightly improved procedure from the original
# publication, and we will release more advanced versions of CITE-seq
# normalizations soon.
cbmc <- NormalizeData(cbmc, assay.type = "CITE", normalization.method = "genesCLR")
cbmc <- ScaleData(cbmc, assay.type = "CITE", display.progress = FALSE)
```

Example 12 (r):
```r
# We will define a CITE assay, and store raw data for it. Note that it's
# convenient, but not required, to use the same name as the rowname prefix
# we defined earlier.

# If you are interested in how these data are internally stored, you can
# check out the @assay slot, and the assay class, which is defined in
# multimodal.R Note that RNA data is still stored in its normal slots, but
# can also be accessed using GetAssayData and SetAssayData, using the 'RNA'
# assay

cbmc <- SetAssayData(cbmc, assay.type = "CITE", slot = "raw.data", new.data = cbmc.citeseq)

# Now we can repeat the preprocessing (normalization and scaling) steps that
# we typically run with RNA, but modifying the 'assay.type' argument.  For
# CITE-seq data, we do not recommend typical LogNormalization. Instead, we
# use a centered log-ratio (CLR) normalization, computed independently for
# each gene.  This is a slightly improved procedure from the original
# publication, and we will release more advanced versions of CITE-seq
# normalizations soon.
cbmc <- NormalizeData(cbmc, assay.type = "CITE", normalization.method = "genesCLR")
cbmc <- ScaleData(cbmc, assay.type = "CITE", display.progress = FALSE)
```

Example 13 (r):
```r
# in this plot, protein (ADT) levels are on top, and RNA levels are on the
# bottom
FeaturePlot(cbmc, features.plot = c("CITE_CD3", "CITE_CD11c", "CITE_CD8", "CITE_CD16", 
    "CD3E", "ITGAX", "CD8A", "FCGR3A"), min.cutoff = "q05", max.cutoff = "q95", 
    nCol = 4, cols.use = c("lightgrey", "blue"), pt.size = 0.5)
```

Example 14 (r):
```r
# in this plot, protein (ADT) levels are on top, and RNA levels are on the
# bottom
FeaturePlot(cbmc, features.plot = c("CITE_CD3", "CITE_CD11c", "CITE_CD8", "CITE_CD16", 
    "CD3E", "ITGAX", "CD8A", "FCGR3A"), min.cutoff = "q05", max.cutoff = "q95", 
    nCol = 4, cols.use = c("lightgrey", "blue"), pt.size = 0.5)
```

Example 15 (r):
```r
RidgePlot(cbmc, features.plot = c("CITE_CD3", "CITE_CD11c", "CITE_CD8", "CITE_CD16"), 
    nCol = 2)
```

Example 16 (r):
```r
RidgePlot(cbmc, features.plot = c("CITE_CD3", "CITE_CD11c", "CITE_CD8", "CITE_CD16"), 
    nCol = 2)
```

Example 17 (r):
```r
par(mfrow = c(1, 2))
# Draw ADT scatter plots (like biaxial plots for FACS). Note that you can
# even 'gate' cells if desired by setting do.identify = TRUE
GenePlot(cbmc, gene1 = "CITE_CD19", gene2 = "CITE_CD3", cex = 0.5)

# view relationship between protein and RNA
GenePlot(cbmc, gene1 = "CITE_CD3", gene2 = "CD3E", cex.use = 0.5)
```

Example 18 (r):
```r
par(mfrow = c(1, 2))
# Draw ADT scatter plots (like biaxial plots for FACS). Note that you can
# even 'gate' cells if desired by setting do.identify = TRUE
GenePlot(cbmc, gene1 = "CITE_CD19", gene2 = "CITE_CD3", cex = 0.5)

# view relationship between protein and RNA
GenePlot(cbmc, gene1 = "CITE_CD3", gene2 = "CD3E", cex.use = 0.5)
```

Example 19 (r):
```r
# Let's plot CD4 vs CD8 levels in T cells
tcells <- SubsetData(cbmc, ident.use = c("CD4 T", "CD8 T"))

par(mfrow = c(1, 2))
GenePlot(tcells, gene1 = "CITE_CD4", gene2 = "CITE_CD8", cex = 0.5)

# Let's look at the raw (non-normalized) ADT counts. You can see the values
# are quite high, particularly in comparison to RNA values. This is due to
# the significantl higher protein copy number in cells, which significantly
# reduces 'drop-out' in ADT data
GenePlot(tcells, gene1 = "CITE_CD4", gene2 = "CITE_CD8", use.raw = TRUE, cex = 0.5)
```

Example 20 (r):
```r
# Let's plot CD4 vs CD8 levels in T cells
tcells <- SubsetData(cbmc, ident.use = c("CD4 T", "CD8 T"))

par(mfrow = c(1, 2))
GenePlot(tcells, gene1 = "CITE_CD4", gene2 = "CITE_CD8", cex = 0.5)

# Let's look at the raw (non-normalized) ADT counts. You can see the values
# are quite high, particularly in comparison to RNA values. This is due to
# the significantl higher protein copy number in cells, which significantly
# reduces 'drop-out' in ADT data
GenePlot(tcells, gene1 = "CITE_CD4", gene2 = "CITE_CD8", use.raw = TRUE, cex = 0.5)
```

Example 21 (r):
```r
# If you look a bit more closely, you'll see that our CD8 T cell cluster is
# enriched for CD8 T cells, but still contains many CD4+ CD8- T cells.  This
# is because Naive CD4 and CD8 T cells are quite similar transcriptomically,
# and the RNA dropout levels for CD4 and CD8 are quite high.  This
# demonstrates the challenge of defining subtle immune cell differences from
# scRNA-seq data alone.
```

Example 22 (r):
```r
# If you look a bit more closely, you'll see that our CD8 T cell cluster is
# enriched for CD8 T cells, but still contains many CD4+ CD8- T cells.  This
# is because Naive CD4 and CD8 T cells are quite similar transcriptomically,
# and the RNA dropout levels for CD4 and CD8 are quite high.  This
# demonstrates the challenge of defining subtle immune cell differences from
# scRNA-seq data alone.
```

Example 23 (r):
```r
mono.markers <- FindMarkers(cbmc, "CD14+ Mono", "CD16+ Mono", assay.type = "CITE", 
    logfc.threshold = log(1.5))
head(mono.markers)
```

Example 24 (r):
```r
mono.markers <- FindMarkers(cbmc, "CD14+ Mono", "CD16+ Mono", assay.type = "CITE", 
    logfc.threshold = log(1.5))
head(mono.markers)
```

Example 25 (unknown):
```unknown
##                   p_val  avg_logFC pct.1 pct.2     p_val_adj
## CITE_CD16 5.295377e-114 -1.0542509     1     1 5.295377e-113
## CITE_CD14  6.081424e-56  0.4259318     1     1  6.081424e-55
```

Example 26 (unknown):
```unknown
##                   p_val  avg_logFC pct.1 pct.2     p_val_adj
## CITE_CD16 5.295377e-114 -1.0542509     1     1 5.295377e-113
## CITE_CD14  6.081424e-56  0.4259318     1     1  6.081424e-55
```

Example 27 (r):
```r
# Note that we observe CD14 protein expression only on CD4+ T cells, as has
# been previously observed in the literature
tcell.markers <- FindMarkers(cbmc, ident.1 = "CD4 T", ident.2 = "CD8 T", assay.type = "CITE", 
    logfc.threshold = log(1.5))
head(tcell.markers)
```

Example 28 (r):
```r
# Note that we observe CD14 protein expression only on CD4+ T cells, as has
# been previously observed in the literature
tcell.markers <- FindMarkers(cbmc, ident.1 = "CD4 T", ident.2 = "CD8 T", assay.type = "CITE", 
    logfc.threshold = log(1.5))
head(tcell.markers)
```

Example 29 (unknown):
```unknown
##                   p_val  avg_logFC pct.1 pct.2     p_val_adj
## CITE_CD4  6.920999e-108  1.0355947     1     1 6.920999e-107
## CITE_CD8  8.917315e-107 -2.7302936     1     1 8.917315e-106
## CITE_CD14  2.958142e-98  0.4868748     1     1  2.958142e-97
```

Example 30 (unknown):
```unknown
##                   p_val  avg_logFC pct.1 pct.2     p_val_adj
## CITE_CD4  6.920999e-108  1.0355947     1     1 6.920999e-107
## CITE_CD8  8.917315e-107 -2.7302936     1     1 8.917315e-106
## CITE_CD14  2.958142e-98  0.4868748     1     1  2.958142e-97
```

Example 31 (r):
```r
# Downsample the clusters to a maximum of 300 cells each (makes the heatmap
# easier to see for small clusters)
cbmc.small <- SubsetData(cbmc, max.cells.per.ident = 300)
# Find protein markers for all clusters, and draw a heatmap
adt.markers <- FindAllMarkers(cbmc.small, assay.type = "CITE", only.pos = TRUE, 
    print.bar = F)

DoHeatmap(cbmc.small, genes.use = unique(adt.markers$gene), assay.type = "CITE", 
    slim.col.label = TRUE, remove.key = TRUE, group.label.rot = TRUE)
```

Example 32 (r):
```r
# Downsample the clusters to a maximum of 300 cells each (makes the heatmap
# easier to see for small clusters)
cbmc.small <- SubsetData(cbmc, max.cells.per.ident = 300)
# Find protein markers for all clusters, and draw a heatmap
adt.markers <- FindAllMarkers(cbmc.small, assay.type = "CITE", only.pos = TRUE, 
    print.bar = F)

DoHeatmap(cbmc.small, genes.use = unique(adt.markers$gene), assay.type = "CITE", 
    slim.col.label = TRUE, remove.key = TRUE, group.label.rot = TRUE)
```

Example 33 (r):
```r
# You can see that our unknown cells co-express both myeloid and lymphoid
# markers (true at the RNA level as well). They are likely cell clumps
# (multiplets) that should be discarded. We'll remove the mouse cells now as
# well
cbmc <- SubsetData(cbmc, ident.remove = c("Unknown", "Mouse"))
```

Example 34 (r):
```r
# You can see that our unknown cells co-express both myeloid and lymphoid
# markers (true at the RNA level as well). They are likely cell clumps
# (multiplets) that should be discarded. We'll remove the mouse cells now as
# well
cbmc <- SubsetData(cbmc, ident.remove = c("Unknown", "Mouse"))
```

Example 35 (r):
```r
# We will store the results in a new object, cbmc_cite.
cbmc_cite <- RunPCA(cbmc, pc.genes = rownames(cbmc.citeseq), assay.type = "CITE", 
    pcs.print = 0)
PCAPlot(cbmc_cite, pt.size = 0.5)
```

Example 36 (r):
```r
# We will store the results in a new object, cbmc_cite.
cbmc_cite <- RunPCA(cbmc, pc.genes = rownames(cbmc.citeseq), assay.type = "CITE", 
    pcs.print = 0)
PCAPlot(cbmc_cite, pt.size = 0.5)
```

Example 37 (r):
```r
# Since we only have 10 markers, instead of doing PCA, we'll just use a
# standard euclidean distance matrix here.  Also, this provides a good
# opportunity to demonstrate how to do visualization and clustering using a
# custom distance matrix in Seurat

adt.data <- GetAssayData(cbmc_cite, assay.type = "CITE", slot = "data")
adt.dist <- as.matrix(dist(t(adt.data)))

# Before we recluster the data on ADT levels, we'll stash the RNA cluster
# IDs for later
cbmc_cite <- StashIdent(cbmc_cite, "rnaClusterID")

# Now, we rerun tSNE using our distance matrix defined only on ADT (protein)
# levels.
cbmc_cite <- RunTSNE(cbmc_cite, distance.matrix = adt.dist)

# We can also rerun clustering using the same distance matrix. We'll start
# with a very coarse clustering (resolution=0.2)
cbmc_cite <- FindClusters(cbmc_cite, distance.matrix = adt.dist, print.output = FALSE, 
    resolution = 0.2)

# We can compare the RNA and protein clustering, and use this to annotate
# the protein clustering (we could also of course use FindMarkers)
clustering.table <- table(cbmc_cite@ident, cbmc_cite@meta.data$rnaClusterID)
```

Example 38 (r):
```r
# Since we only have 10 markers, instead of doing PCA, we'll just use a
# standard euclidean distance matrix here.  Also, this provides a good
# opportunity to demonstrate how to do visualization and clustering using a
# custom distance matrix in Seurat

adt.data <- GetAssayData(cbmc_cite, assay.type = "CITE", slot = "data")
adt.dist <- as.matrix(dist(t(adt.data)))

# Before we recluster the data on ADT levels, we'll stash the RNA cluster
# IDs for later
cbmc_cite <- StashIdent(cbmc_cite, "rnaClusterID")

# Now, we rerun tSNE using our distance matrix defined only on ADT (protein)
# levels.
cbmc_cite <- RunTSNE(cbmc_cite, distance.matrix = adt.dist)

# We can also rerun clustering using the same distance matrix. We'll start
# with a very coarse clustering (resolution=0.2)
cbmc_cite <- FindClusters(cbmc_cite, distance.matrix = adt.dist, print.output = FALSE, 
    resolution = 0.2)

# We can compare the RNA and protein clustering, and use this to annotate
# the protein clustering (we could also of course use FindMarkers)
clustering.table <- table(cbmc_cite@ident, cbmc_cite@meta.data$rnaClusterID)
```

Example 39 (r):
```r
current.cluster.ids <- 0:10
# Note, for simplicity we are merging two CD14+ Mono clusters (that differ
# in the expression of HLA-DR genes), and two NK clusters (that differ in
# cell cycle stage)
new.cluster.ids <- c("CD4 T", "CD14+ Mono", "NK", "B", "CD8 T", "CD34+", "Unknown1", 
    "CD16+ Mono", "Unknown2", "pDC", "Unknown3")
cbmc_cite@ident <- plyr::mapvalues(x = cbmc_cite@ident, from = current.cluster.ids, 
    to = new.cluster.ids)

tsne_rnaClusters <- TSNEPlot(cbmc_cite, do.return = TRUE, group.by = "rnaClusterID", 
    pt.size = 0.5)
tsne_rnaClusters <- tsne_rnaClusters + ggtitle("Clustering based on scRNA-seq") + 
    theme(plot.title = element_text(hjust = 0.5))

tsne_adtClusters <- TSNEPlot(cbmc_cite, do.return = TRUE, pt.size = 0.5)
tsne_adtClusters <- tsne_adtClusters + ggtitle("Clustering based on ADT signal") + 
    theme(plot.title = element_text(hjust = 0.5))

# Note: for this comparison, both the RNA and protein clustering are
# visualized on a tSNE generated using the ADT distance matrix.

plot_grid(tsne_rnaClusters, tsne_adtClusters, ncol = 2)
```

Example 40 (r):
```r
current.cluster.ids <- 0:10
# Note, for simplicity we are merging two CD14+ Mono clusters (that differ
# in the expression of HLA-DR genes), and two NK clusters (that differ in
# cell cycle stage)
new.cluster.ids <- c("CD4 T", "CD14+ Mono", "NK", "B", "CD8 T", "CD34+", "Unknown1", 
    "CD16+ Mono", "Unknown2", "pDC", "Unknown3")
cbmc_cite@ident <- plyr::mapvalues(x = cbmc_cite@ident, from = current.cluster.ids, 
    to = new.cluster.ids)

tsne_rnaClusters <- TSNEPlot(cbmc_cite, do.return = TRUE, group.by = "rnaClusterID", 
    pt.size = 0.5)
tsne_rnaClusters <- tsne_rnaClusters + ggtitle("Clustering based on scRNA-seq") + 
    theme(plot.title = element_text(hjust = 0.5))

tsne_adtClusters <- TSNEPlot(cbmc_cite, do.return = TRUE, pt.size = 0.5)
tsne_adtClusters <- tsne_adtClusters + ggtitle("Clustering based on ADT signal") + 
    theme(plot.title = element_text(hjust = 0.5))

# Note: for this comparison, both the RNA and protein clustering are
# visualized on a tSNE generated using the ADT distance matrix.

plot_grid(tsne_rnaClusters, tsne_adtClusters, ncol = 2)
```

Example 41 (r):
```r
tcells <- SubsetData(cbmc_cite, ident.use = c("CD4 T", "CD8 T"))
GenePlot(tcells, gene1 = "CITE_CD4", gene2 = "CITE_CD8", use.raw = F, cex = 0.5)
```

Example 42 (r):
```r
tcells <- SubsetData(cbmc_cite, ident.use = c("CD4 T", "CD8 T"))
GenePlot(tcells, gene1 = "CITE_CD4", gene2 = "CITE_CD8", use.raw = F, cex = 0.5)
```

Example 43 (r):
```r
RidgePlot(cbmc_cite, features.plot = c("CITE_CD11c", "CITE_CD8", "CITE_CD16", 
    "CITE_CD4", "CITE_CD19", "CITE_CD14"), nCol = 2)
```

Example 44 (r):
```r
RidgePlot(cbmc_cite, features.plot = c("CITE_CD11c", "CITE_CD8", "CITE_CD16", 
    "CITE_CD4", "CITE_CD19", "CITE_CD14"), nCol = 2)
```

Example 45 (r):
```r
reap_rna_2 <- read.table("~/Downloads/GSM2685238_mRNA_2_PBMCs_matrix.txt.gz", 
    row.names = 1)
reap_rna_3 <- read.table("~/Downloads/GSM2685239_mRNA_3_PBMCs_matrix.txt.gz", 
    row.names = 1)
reap_protein_2 <- read.table("~/Downloads/GSM2685243_protein_2_PBMCs_matrix.txt.gz", 
    row.names = 1)
reap_protein_3 <- read.table("~/Downloads/GSM2685244_protein_3_PBMCs_matrix.txt.gz", 
    row.names = 1)

reap_rna_combined <- Matrix(as.matrix(cbind(reap_rna_2, reap_rna_3)), sparse = TRUE)
reap_protein_combined <- Matrix(as.matrix(cbind(reap_protein_2, reap_protein_3)), 
    sparse = TRUE)

rownames(reap_protein_combined) <- make.unique(paste0("REAP_", sapply(rownames(reap_protein_combined), 
    ExtractField)))

reap <- CreateSeuratObject(raw.data = reap_rna_combined, min.genes = 250)
reap <- NormalizeData(reap, display.progress = FALSE)
reap <- SetAssayData(reap, assay.type = "REAP", slot = "raw.data", new.data = reap_protein_combined[, 
    reap@cell.names])
reap <- NormalizeData(reap, assay.type = "REAP", normalization.method = "genesCLR", 
    display.progress = FALSE)
par(mfrow = c(1, 3))
GenePlot(reap, gene1 = "REAP_CD19", gene2 = "REAP_CD3", cex.use = 0.5)
GenePlot(reap, gene1 = "REAP_CD4", gene2 = "REAP_CD8a", cex.use = 0.5)
GenePlot(reap, gene1 = "REAP_CD3", gene2 = "CD3E", cex.use = 0.5)
```

Example 46 (r):
```r
reap_rna_2 <- read.table("~/Downloads/GSM2685238_mRNA_2_PBMCs_matrix.txt.gz", 
    row.names = 1)
reap_rna_3 <- read.table("~/Downloads/GSM2685239_mRNA_3_PBMCs_matrix.txt.gz", 
    row.names = 1)
reap_protein_2 <- read.table("~/Downloads/GSM2685243_protein_2_PBMCs_matrix.txt.gz", 
    row.names = 1)
reap_protein_3 <- read.table("~/Downloads/GSM2685244_protein_3_PBMCs_matrix.txt.gz", 
    row.names = 1)

reap_rna_combined <- Matrix(as.matrix(cbind(reap_rna_2, reap_rna_3)), sparse = TRUE)
reap_protein_combined <- Matrix(as.matrix(cbind(reap_protein_2, reap_protein_3)), 
    sparse = TRUE)

rownames(reap_protein_combined) <- make.unique(paste0("REAP_", sapply(rownames(reap_protein_combined), 
    ExtractField)))

reap <- CreateSeuratObject(raw.data = reap_rna_combined, min.genes = 250)
reap <- NormalizeData(reap, display.progress = FALSE)
reap <- SetAssayData(reap, assay.type = "REAP", slot = "raw.data", new.data = reap_protein_combined[, 
    reap@cell.names])
reap <- NormalizeData(reap, assay.type = "REAP", normalization.method = "genesCLR", 
    display.progress = FALSE)
par(mfrow = c(1, 3))
GenePlot(reap, gene1 = "REAP_CD19", gene2 = "REAP_CD3", cex.use = 0.5)
GenePlot(reap, gene1 = "REAP_CD4", gene2 = "REAP_CD8a", cex.use = 0.5)
GenePlot(reap, gene1 = "REAP_CD3", gene2 = "CD3E", cex.use = 0.5)
```

---

## Analysis, visualization, and integration of Visium HD spatial datasets with Seurat • Seurat

**URL:** http://127.0.0.1:9173/seurat/articles/extensions/index.html

**Contents:**
- Seurat Extension Packages
- Signac
- SeuratData
- SeuratWrappers
- SeuratDisk
- Azimuth
- BPCells
- presto
- Contents

In addition to the core Seurat package, we provide several extensions that enhance the functionality and utility of Seurat. A brief description of each is listed below with links to more complete documentation and examples.

Signac is an R toolkit that extends Seurat for the analysis, interpretation, and exploration of single-cell chromatin datasets. The software supports the following features:

For documentation and vignettes, click here.

SeuratData is a mechanism for distributing datasets in the form of Seurat objects using R’s internal package and data management systems. It represents an easy way for users to get access to datasets that are used in the Seurat vignettes. For more information, click here.

In order to facilitate the use of community tools with Seurat, we provide the SeuratWrappers package, which contains code to run other analysis tools on Seurat objects. For a full list of supported packages and vignettes, please see our vignettes page.

The SeuratDisk package introduces the h5Seurat file format for the storage and analysis of multimodal single-cell and spatially-resolved expression experiments. The SeuratDisk package provides functions to save Seurat objects as h5Seurat files, and functions for rapid on-disk conversion between h5Seurat and AnnData formats with the goal of enhancing interoperability between Seurat and Scanpy. For more information, click here

Azimuth is a web application that uses an annotated reference dataset to automate the processing, analysis, and interpretation of a new single-cell RNA-seq experiment. Azimuth leverages a ‘reference-based mapping’ pipeline that inputs a counts matrix of gene expression in single cells, and performs normalization, visualization, cell annotation, and differential expression (biomarker discovery). All results can be explored within the app, and easily downloaded for additional downstream analysis. To use the Azimuth web app, visit the Azimuth website here.

Developed by Greenleaf Lab, BPCells is an R package that allows for computationally efficient single-cell analysis. It utilizes bit-packing compression to store counts matrices on disk and C++ code to cache operations. BPCells is an R package that allows for computationally efficient single-cell analysis. It utilizes bit-packing compression to store counts matrices on disk and C++ code to cache operations.

Developed by Korunsky/Raychaudhari labs, presto performs a fast Wilcoxon rank sum test and auROC analysis. Seurat uses the presto package to perform fast differential expression.

Developed by Rahul Satija, Satija Lab and Collaborators.

Site built with pkgdown 2.0.7.

**Examples:**

Example 1 (unknown):
```unknown
vignettes/extensions.Rmd
```

Example 2 (unknown):
```unknown
extensions.Rmd
```

---

## Analysis, visualization, and integration of Visium HD spatial datasets with Seurat • Seurat

**URL:** http://127.0.0.1:9173/articles_integration_rpca.html

**Contents:**
- Fast integration using reciprocal PCA (RPCA)
    - Compiled: October 31, 2023
- Perform integration
- Modifying the strength of integration
- Performing integration on datasets normalized with SCTransform
- Contents

In this vignette, we present a slightly modified workflow for the integration of scRNA-seq datasets. Instead of utilizing canonical correlation analysis (‘CCA’) to identify anchors, we instead utilize reciprocal PCA (‘RPCA’). When determining anchors between any two datasets using RPCA, we project each dataset into the others PCA space and constrain the anchors by the same mutual neighborhood requirement. The commands for both workflows are largely identical, but the two methods may be applied in different context.

By identifying shared sources of variation between datasets, CCA is well-suited for identifying anchors when cell types are conserved, but there are very substantial differences in gene expression across experiments. CCA-based integration therefore enables integrative analysis when experimental conditions or disease states introduce very strong expression shifts, or when integrating datasets across modalities and species. However, CCA-based integration may also lead to overcorrection, especially when a large proportion of cells are non-overlapping across datasets.

RPCA-based integration runs significantly faster, and also represents a more conservative approach where cells in different biological states are less likely to ‘align’ after integration. We therefore recommend RPCA during integrative analysis where:

Below, we demonstrate the use of reciprocal PCA to align the same stimulated and resting datasets first analyzed in our introduction to scRNA-seq integration vignette. While the list of commands is nearly identical, this workflow requires users to run principal components analysis (PCA) individually on each dataset prior to integration. Users should also set the ‘reduction’ argument to ‘rpca’, when running FindIntegrationAnchors().

We then identify anchors using the FindIntegrationAnchors() function, which takes a list of Seurat objects as input, and use these anchors to integrate the two datasets together with IntegrateData().

Now we can run a single integrated analysis on all cells!

The results show that rpca-based integration is more conservative, and in this case, do not perfectly align a subset of cells (which are naive and memory T cells) across experiments. You can increase the strength of alignment by increasing the k.anchor parameter, which is set to 5 by default. Increasing this parameter to 20 will assist in aligning these populations.

Now that the datasets have been integrated, you can follow the previous steps in the introduction to scRNA-seq integration vignette to identify cell types and cell type-specific responses.

As an additional example, we repeat the analyses performed above, but normalize the datasets using SCTransform. We may choose to set the method parameter to glmGamPoi (install here) in order to enable faster estimation of regression parameters in SCTransform().

Developed by Rahul Satija, Satija Lab and Collaborators.

Site built with pkgdown 2.0.7.

**Examples:**

Example 1 (unknown):
```unknown
vignettes/integration_rpca.Rmd
```

Example 2 (unknown):
```unknown
integration_rpca.Rmd
```

Example 3 (unknown):
```unknown
FindIntegrationAnchors()
```

Example 4 (unknown):
```unknown
library(Seurat)
library(SeuratData)
# install dataset
InstallData("ifnb")
```

Example 5 (r):
```r
library(Seurat)
library(SeuratData)
# install dataset
InstallData("ifnb")
```

Example 6 (r):
```r
library(Seurat)
library(SeuratData)
# install dataset
InstallData("ifnb")
```

Example 7 (javascript):
```javascript
# load dataset
ifnb <- LoadData("ifnb")

# split the dataset into a list of two seurat objects (stim and CTRL)
ifnb.list <- SplitObject(ifnb, split.by = "stim")

# normalize and identify variable features for each dataset independently
ifnb.list <- lapply(X = ifnb.list, FUN = function(x) {
    x <- NormalizeData(x)
    x <- FindVariableFeatures(x, selection.method = "vst", nfeatures = 2000)
})

# select features that are repeatedly variable across datasets for integration run PCA on each
# dataset using these features
features <- SelectIntegrationFeatures(object.list = ifnb.list)
ifnb.list <- lapply(X = ifnb.list, FUN = function(x) {
    x <- ScaleData(x, features = features, verbose = FALSE)
    x <- RunPCA(x, features = features, verbose = FALSE)
})
```

Example 8 (r):
```r
# load dataset
ifnb <- LoadData("ifnb")

# split the dataset into a list of two seurat objects (stim and CTRL)
ifnb.list <- SplitObject(ifnb, split.by = "stim")

# normalize and identify variable features for each dataset independently
ifnb.list <- lapply(X = ifnb.list, FUN = function(x) {
    x <- NormalizeData(x)
    x <- FindVariableFeatures(x, selection.method = "vst", nfeatures = 2000)
})

# select features that are repeatedly variable across datasets for integration run PCA on each
# dataset using these features
features <- SelectIntegrationFeatures(object.list = ifnb.list)
ifnb.list <- lapply(X = ifnb.list, FUN = function(x) {
    x <- ScaleData(x, features = features, verbose = FALSE)
    x <- RunPCA(x, features = features, verbose = FALSE)
})
```

Example 9 (r):
```r
# load dataset
ifnb <- LoadData("ifnb")

# split the dataset into a list of two seurat objects (stim and CTRL)
ifnb.list <- SplitObject(ifnb, split.by = "stim")

# normalize and identify variable features for each dataset independently
ifnb.list <- lapply(X = ifnb.list, FUN = function(x) {
    x <- NormalizeData(x)
    x <- FindVariableFeatures(x, selection.method = "vst", nfeatures = 2000)
})

# select features that are repeatedly variable across datasets for integration run PCA on each
# dataset using these features
features <- SelectIntegrationFeatures(object.list = ifnb.list)
ifnb.list <- lapply(X = ifnb.list, FUN = function(x) {
    x <- ScaleData(x, features = features, verbose = FALSE)
    x <- RunPCA(x, features = features, verbose = FALSE)
})
```

Example 10 (unknown):
```unknown
FindIntegrationAnchors()
```

Example 11 (unknown):
```unknown
IntegrateData()
```

Example 12 (unknown):
```unknown
immune.anchors <- FindIntegrationAnchors(object.list = ifnb.list, anchor.features = features, reduction = "rpca")
```

Example 13 (r):
```r
immune.anchors <- FindIntegrationAnchors(object.list = ifnb.list, anchor.features = features, reduction = "rpca")
```

Example 14 (r):
```r
immune.anchors <- FindIntegrationAnchors(object.list = ifnb.list, anchor.features = features, reduction = "rpca")
```

Example 15 (unknown):
```unknown
# this command creates an 'integrated' data assay
immune.combined <- IntegrateData(anchorset = immune.anchors)
```

Example 16 (r):
```r
# this command creates an 'integrated' data assay
immune.combined <- IntegrateData(anchorset = immune.anchors)
```

Example 17 (r):
```r
# this command creates an 'integrated' data assay
immune.combined <- IntegrateData(anchorset = immune.anchors)
```

Example 18 (unknown):
```unknown
# specify that we will perform downstream analysis on the corrected data note that the
# original unmodified data still resides in the 'RNA' assay
DefaultAssay(immune.combined) <- "integrated"

# Run the standard workflow for visualization and clustering
immune.combined <- ScaleData(immune.combined, verbose = FALSE)
immune.combined <- RunPCA(immune.combined, npcs = 30, verbose = FALSE)
immune.combined <- RunUMAP(immune.combined, reduction = "pca", dims = 1:30)
immune.combined <- FindNeighbors(immune.combined, reduction = "pca", dims = 1:30)
immune.combined <- FindClusters(immune.combined, resolution = 0.5)
```

Example 19 (r):
```r
# specify that we will perform downstream analysis on the corrected data note that the
# original unmodified data still resides in the 'RNA' assay
DefaultAssay(immune.combined) <- "integrated"

# Run the standard workflow for visualization and clustering
immune.combined <- ScaleData(immune.combined, verbose = FALSE)
immune.combined <- RunPCA(immune.combined, npcs = 30, verbose = FALSE)
immune.combined <- RunUMAP(immune.combined, reduction = "pca", dims = 1:30)
immune.combined <- FindNeighbors(immune.combined, reduction = "pca", dims = 1:30)
immune.combined <- FindClusters(immune.combined, resolution = 0.5)
```

Example 20 (r):
```r
# specify that we will perform downstream analysis on the corrected data note that the
# original unmodified data still resides in the 'RNA' assay
DefaultAssay(immune.combined) <- "integrated"

# Run the standard workflow for visualization and clustering
immune.combined <- ScaleData(immune.combined, verbose = FALSE)
immune.combined <- RunPCA(immune.combined, npcs = 30, verbose = FALSE)
immune.combined <- RunUMAP(immune.combined, reduction = "pca", dims = 1:30)
immune.combined <- FindNeighbors(immune.combined, reduction = "pca", dims = 1:30)
immune.combined <- FindClusters(immune.combined, resolution = 0.5)
```

Example 21 (unknown):
```unknown
# Visualization
p1 <- DimPlot(immune.combined, reduction = "umap", group.by = "stim")
p2 <- DimPlot(immune.combined, reduction = "umap", group.by = "seurat_annotations", label = TRUE,
    repel = TRUE)
p1 + p2
```

Example 22 (r):
```r
# Visualization
p1 <- DimPlot(immune.combined, reduction = "umap", group.by = "stim")
p2 <- DimPlot(immune.combined, reduction = "umap", group.by = "seurat_annotations", label = TRUE,
    repel = TRUE)
p1 + p2
```

Example 23 (r):
```r
# Visualization
p1 <- DimPlot(immune.combined, reduction = "umap", group.by = "stim")
p2 <- DimPlot(immune.combined, reduction = "umap", group.by = "seurat_annotations", label = TRUE,
    repel = TRUE)
p1 + p2
```

Example 24 (unknown):
```unknown
immune.anchors <- FindIntegrationAnchors(object.list = ifnb.list, anchor.features = features, reduction = "rpca",
    k.anchor = 20)
immune.combined <- IntegrateData(anchorset = immune.anchors)

immune.combined <- ScaleData(immune.combined, verbose = FALSE)
immune.combined <- RunPCA(immune.combined, npcs = 30, verbose = FALSE)
immune.combined <- RunUMAP(immune.combined, reduction = "pca", dims = 1:30)
immune.combined <- FindNeighbors(immune.combined, reduction = "pca", dims = 1:30)
immune.combined <- FindClusters(immune.combined, resolution = 0.5)
```

Example 25 (r):
```r
immune.anchors <- FindIntegrationAnchors(object.list = ifnb.list, anchor.features = features, reduction = "rpca",
    k.anchor = 20)
immune.combined <- IntegrateData(anchorset = immune.anchors)

immune.combined <- ScaleData(immune.combined, verbose = FALSE)
immune.combined <- RunPCA(immune.combined, npcs = 30, verbose = FALSE)
immune.combined <- RunUMAP(immune.combined, reduction = "pca", dims = 1:30)
immune.combined <- FindNeighbors(immune.combined, reduction = "pca", dims = 1:30)
immune.combined <- FindClusters(immune.combined, resolution = 0.5)
```

Example 26 (r):
```r
immune.anchors <- FindIntegrationAnchors(object.list = ifnb.list, anchor.features = features, reduction = "rpca",
    k.anchor = 20)
immune.combined <- IntegrateData(anchorset = immune.anchors)

immune.combined <- ScaleData(immune.combined, verbose = FALSE)
immune.combined <- RunPCA(immune.combined, npcs = 30, verbose = FALSE)
immune.combined <- RunUMAP(immune.combined, reduction = "pca", dims = 1:30)
immune.combined <- FindNeighbors(immune.combined, reduction = "pca", dims = 1:30)
immune.combined <- FindClusters(immune.combined, resolution = 0.5)
```

Example 27 (unknown):
```unknown
## Modularity Optimizer version 1.3.0 by Ludo Waltman and Nees Jan van Eck
## 
## Number of nodes: 13999
## Number of edges: 594845
## 
## Running Louvain algorithm...
## Maximum modularity in 10 random starts: 0.9098
## Number of communities: 15
## Elapsed time: 2 seconds
```

Example 28 (unknown):
```unknown
## Modularity Optimizer version 1.3.0 by Ludo Waltman and Nees Jan van Eck
## 
## Number of nodes: 13999
## Number of edges: 594845
## 
## Running Louvain algorithm...
## Maximum modularity in 10 random starts: 0.9098
## Number of communities: 15
## Elapsed time: 2 seconds
```

Example 29 (unknown):
```unknown
# Visualization
p1 <- DimPlot(immune.combined, reduction = "umap", group.by = "stim")
p2 <- DimPlot(immune.combined, reduction = "umap", label = TRUE, repel = TRUE)
p1 + p2
```

Example 30 (r):
```r
# Visualization
p1 <- DimPlot(immune.combined, reduction = "umap", group.by = "stim")
p2 <- DimPlot(immune.combined, reduction = "umap", label = TRUE, repel = TRUE)
p1 + p2
```

Example 31 (r):
```r
# Visualization
p1 <- DimPlot(immune.combined, reduction = "umap", group.by = "stim")
p2 <- DimPlot(immune.combined, reduction = "umap", label = TRUE, repel = TRUE)
p1 + p2
```

Example 32 (unknown):
```unknown
library(ggplot2)
plot <- DimPlot(immune.combined, group.by = "stim") + xlab("UMAP 1") + ylab("UMAP 2") + theme(axis.title = element_text(size = 18),
    legend.text = element_text(size = 18)) + guides(colour = guide_legend(override.aes = list(size = 10)))
ggsave(filename = "../output/images/rpca_integration.jpg", height = 7, width = 12, plot = plot,
    quality = 50)
```

Example 33 (r):
```r
library(ggplot2)
plot <- DimPlot(immune.combined, group.by = "stim") + xlab("UMAP 1") + ylab("UMAP 2") + theme(axis.title = element_text(size = 18),
    legend.text = element_text(size = 18)) + guides(colour = guide_legend(override.aes = list(size = 10)))
ggsave(filename = "../output/images/rpca_integration.jpg", height = 7, width = 12, plot = plot,
    quality = 50)
```

Example 34 (r):
```r
library(ggplot2)
plot <- DimPlot(immune.combined, group.by = "stim") + xlab("UMAP 1") + ylab("UMAP 2") + theme(axis.title = element_text(size = 18),
    legend.text = element_text(size = 18)) + guides(colour = guide_legend(override.aes = list(size = 10)))
ggsave(filename = "../output/images/rpca_integration.jpg", height = 7, width = 12, plot = plot,
    quality = 50)
```

Example 35 (unknown):
```unknown
SCTransform()
```

Example 36 (unknown):
```unknown
ifnb <- LoadData("ifnb")
ifnb.list <- SplitObject(ifnb, split.by = "stim")
ifnb.list <- lapply(X = ifnb.list, FUN = SCTransform, method = "glmGamPoi")
features <- SelectIntegrationFeatures(object.list = ifnb.list, nfeatures = 3000)
ifnb.list <- PrepSCTIntegration(object.list = ifnb.list, anchor.features = features)
ifnb.list <- lapply(X = ifnb.list, FUN = RunPCA, features = features)
```

Example 37 (r):
```r
ifnb <- LoadData("ifnb")
ifnb.list <- SplitObject(ifnb, split.by = "stim")
ifnb.list <- lapply(X = ifnb.list, FUN = SCTransform, method = "glmGamPoi")
features <- SelectIntegrationFeatures(object.list = ifnb.list, nfeatures = 3000)
ifnb.list <- PrepSCTIntegration(object.list = ifnb.list, anchor.features = features)
ifnb.list <- lapply(X = ifnb.list, FUN = RunPCA, features = features)
```

Example 38 (r):
```r
ifnb <- LoadData("ifnb")
ifnb.list <- SplitObject(ifnb, split.by = "stim")
ifnb.list <- lapply(X = ifnb.list, FUN = SCTransform, method = "glmGamPoi")
features <- SelectIntegrationFeatures(object.list = ifnb.list, nfeatures = 3000)
ifnb.list <- PrepSCTIntegration(object.list = ifnb.list, anchor.features = features)
ifnb.list <- lapply(X = ifnb.list, FUN = RunPCA, features = features)
```

Example 39 (unknown):
```unknown
immune.anchors <- FindIntegrationAnchors(object.list = ifnb.list, normalization.method = "SCT",
    anchor.features = features, dims = 1:30, reduction = "rpca", k.anchor = 20)
immune.combined.sct <- IntegrateData(anchorset = immune.anchors, normalization.method = "SCT", dims = 1:30)
```

Example 40 (r):
```r
immune.anchors <- FindIntegrationAnchors(object.list = ifnb.list, normalization.method = "SCT",
    anchor.features = features, dims = 1:30, reduction = "rpca", k.anchor = 20)
immune.combined.sct <- IntegrateData(anchorset = immune.anchors, normalization.method = "SCT", dims = 1:30)
```

Example 41 (r):
```r
immune.anchors <- FindIntegrationAnchors(object.list = ifnb.list, normalization.method = "SCT",
    anchor.features = features, dims = 1:30, reduction = "rpca", k.anchor = 20)
immune.combined.sct <- IntegrateData(anchorset = immune.anchors, normalization.method = "SCT", dims = 1:30)
```

Example 42 (unknown):
```unknown
## [1] 1
## [1] 2
```

Example 43 (unknown):
```unknown
## [1] 1
## [1] 2
```

Example 44 (unknown):
```unknown
immune.combined.sct <- RunPCA(immune.combined.sct, verbose = FALSE)
immune.combined.sct <- RunUMAP(immune.combined.sct, reduction = "pca", dims = 1:30)
```

Example 45 (r):
```r
immune.combined.sct <- RunPCA(immune.combined.sct, verbose = FALSE)
immune.combined.sct <- RunUMAP(immune.combined.sct, reduction = "pca", dims = 1:30)
```

Example 46 (r):
```r
immune.combined.sct <- RunPCA(immune.combined.sct, verbose = FALSE)
immune.combined.sct <- RunUMAP(immune.combined.sct, reduction = "pca", dims = 1:30)
```

Example 47 (unknown):
```unknown
# Visualization
p1 <- DimPlot(immune.combined.sct, reduction = "umap", group.by = "stim")
p2 <- DimPlot(immune.combined.sct, reduction = "umap", group.by = "seurat_annotations", label = TRUE,
    repel = TRUE)
p1 + p2
```

Example 48 (r):
```r
# Visualization
p1 <- DimPlot(immune.combined.sct, reduction = "umap", group.by = "stim")
p2 <- DimPlot(immune.combined.sct, reduction = "umap", group.by = "seurat_annotations", label = TRUE,
    repel = TRUE)
p1 + p2
```

Example 49 (r):
```r
# Visualization
p1 <- DimPlot(immune.combined.sct, reduction = "umap", group.by = "stim")
p2 <- DimPlot(immune.combined.sct, reduction = "umap", group.by = "seurat_annotations", label = TRUE,
    repel = TRUE)
p1 + p2
```

Example 50 (unknown):
```unknown
sessionInfo()
```

Example 51 (r):
```r
sessionInfo()
```

Example 52 (r):
```r
sessionInfo()
```

Example 53 (unknown):
```unknown
## R version 4.2.2 Patched (2022-11-10 r83330)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.6 LTS
## 
## Matrix products: default
## BLAS:   /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.9.0
## LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.9.0
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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       
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
##  [1] ggplot2_3.4.4                 thp1.eccite.SeuratData_3.1.5 
##  [3] stxBrain.SeuratData_0.1.1     ssHippo.SeuratData_3.1.4     
##  [5] pbmcsca.SeuratData_3.0.0      pbmcref.SeuratData_1.0.0     
##  [7] pbmcMultiome.SeuratData_0.1.4 pbmc3k.SeuratData_3.1.4      
##  [9] panc8.SeuratData_3.0.2        ifnb.SeuratData_3.0.0        
## [11] hcabm40k.SeuratData_3.0.0     cbmc.SeuratData_3.1.4        
## [13] bmcite.SeuratData_0.3.0       SeuratData_0.2.2.9001        
## [15] Seurat_5.0.0                  SeuratObject_5.0.0           
## [17] sp_2.1-1                     
## 
## loaded via a namespace (and not attached):
##   [1] spam_2.10-0                 systemfonts_1.0.4          
##   [3] plyr_1.8.9                  igraph_1.5.1               
##   [5] lazyeval_0.2.2              splines_4.2.2              
##   [7] RcppHNSW_0.5.0              listenv_0.9.0              
##   [9] scattermore_1.2             GenomeInfoDb_1.34.9        
##  [11] digest_0.6.33               htmltools_0.5.6.1          
##  [13] fansi_1.0.5                 magrittr_2.0.3             
##  [15] memoise_2.0.1               tensor_1.5                 
##  [17] cluster_2.1.4               ROCR_1.0-11                
##  [19] globals_0.16.2              matrixStats_1.0.0          
##  [21] pkgdown_2.0.7               spatstat.sparse_3.0-3      
##  [23] colorspace_2.1-0            rappdirs_0.3.3             
##  [25] ggrepel_0.9.4               textshaping_0.3.6          
##  [27] xfun_0.40                   dplyr_1.1.3                
##  [29] RCurl_1.98-1.12             crayon_1.5.2               
##  [31] jsonlite_1.8.7              progressr_0.14.0           
##  [33] spatstat.data_3.0-3         survival_3.5-7             
##  [35] zoo_1.8-12                  glue_1.6.2                 
##  [37] polyclip_1.10-6             gtable_0.3.4               
##  [39] zlibbioc_1.44.0             XVector_0.38.0             
##  [41] leiden_0.4.3                DelayedArray_0.24.0        
##  [43] future.apply_1.11.0         BiocGenerics_0.44.0        
##  [45] abind_1.4-5                 scales_1.2.1               
##  [47] spatstat.random_3.2-1       miniUI_0.1.1.1             
##  [49] Rcpp_1.0.11                 viridisLite_0.4.2          
##  [51] xtable_1.8-4                reticulate_1.34.0          
##  [53] dotCall64_1.1-0             stats4_4.2.2               
##  [55] htmlwidgets_1.6.2           httr_1.4.7                 
##  [57] RColorBrewer_1.1-3          ellipsis_0.3.2             
##  [59] ica_1.0-3                   farver_2.1.1               
##  [61] pkgconfig_2.0.3             sass_0.4.7                 
##  [63] uwot_0.1.16                 deldir_1.0-9               
##  [65] utf8_1.2.4                  labeling_0.4.3             
##  [67] tidyselect_1.2.0            rlang_1.1.1                
##  [69] reshape2_1.4.4              later_1.3.1                
##  [71] munsell_0.5.0               tools_4.2.2                
##  [73] cachem_1.0.8                cli_3.6.1                  
##  [75] generics_0.1.3              ggridges_0.5.4             
##  [77] evaluate_0.22               stringr_1.5.0              
##  [79] fastmap_1.1.1               yaml_2.3.7                 
##  [81] ragg_1.2.5                  goftest_1.2-3              
##  [83] knitr_1.45                  fs_1.6.3                   
##  [85] fitdistrplus_1.1-11         purrr_1.0.2                
##  [87] RANN_2.6.1                  sparseMatrixStats_1.10.0   
##  [89] pbapply_1.7-2               future_1.33.0              
##  [91] nlme_3.1-162                mime_0.12                  
##  [93] formatR_1.14                compiler_4.2.2             
##  [95] plotly_4.10.3               png_0.1-8                  
##  [97] spatstat.utils_3.0-4        tibble_3.2.1               
##  [99] glmGamPoi_1.10.2            bslib_0.5.1                
## [101] stringi_1.7.12              highr_0.10                 
## [103] desc_1.4.2                  RSpectra_0.16-1            
## [105] lattice_0.21-9              Matrix_1.6-1.1             
## [107] vctrs_0.6.4                 pillar_1.9.0               
## [109] lifecycle_1.0.3             spatstat.geom_3.2-7        
## [111] lmtest_0.9-40               jquerylib_0.1.4            
## [113] RcppAnnoy_0.0.21            bitops_1.0-7               
## [115] data.table_1.14.8           cowplot_1.1.1              
## [117] irlba_2.3.5.1               GenomicRanges_1.50.2       
## [119] httpuv_1.6.12               patchwork_1.1.3            
## [121] R6_2.5.1                    promises_1.2.1             
## [123] KernSmooth_2.23-22          gridExtra_2.3              
## [125] IRanges_2.32.0              parallelly_1.36.0          
## [127] codetools_0.2-19            fastDummies_1.7.3          
## [129] MASS_7.3-58.2               SummarizedExperiment_1.28.0
## [131] rprojroot_2.0.3             withr_2.5.2                
## [133] sctransform_0.4.1           GenomeInfoDbData_1.2.9     
## [135] S4Vectors_0.36.2            parallel_4.2.2             
## [137] grid_4.2.2                  tidyr_1.3.0                
## [139] DelayedMatrixStats_1.20.0   rmarkdown_2.25             
## [141] MatrixGenerics_1.10.0       Rtsne_0.16                 
## [143] spatstat.explore_3.2-5      Biobase_2.58.0             
## [145] shiny_1.7.5.1
```

Example 54 (unknown):
```unknown
## R version 4.2.2 Patched (2022-11-10 r83330)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.6 LTS
## 
## Matrix products: default
## BLAS:   /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.9.0
## LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.9.0
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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       
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
##  [1] ggplot2_3.4.4                 thp1.eccite.SeuratData_3.1.5 
##  [3] stxBrain.SeuratData_0.1.1     ssHippo.SeuratData_3.1.4     
##  [5] pbmcsca.SeuratData_3.0.0      pbmcref.SeuratData_1.0.0     
##  [7] pbmcMultiome.SeuratData_0.1.4 pbmc3k.SeuratData_3.1.4      
##  [9] panc8.SeuratData_3.0.2        ifnb.SeuratData_3.0.0        
## [11] hcabm40k.SeuratData_3.0.0     cbmc.SeuratData_3.1.4        
## [13] bmcite.SeuratData_0.3.0       SeuratData_0.2.2.9001        
## [15] Seurat_5.0.0                  SeuratObject_5.0.0           
## [17] sp_2.1-1                     
## 
## loaded via a namespace (and not attached):
##   [1] spam_2.10-0                 systemfonts_1.0.4          
##   [3] plyr_1.8.9                  igraph_1.5.1               
##   [5] lazyeval_0.2.2              splines_4.2.2              
##   [7] RcppHNSW_0.5.0              listenv_0.9.0              
##   [9] scattermore_1.2             GenomeInfoDb_1.34.9        
##  [11] digest_0.6.33               htmltools_0.5.6.1          
##  [13] fansi_1.0.5                 magrittr_2.0.3             
##  [15] memoise_2.0.1               tensor_1.5                 
##  [17] cluster_2.1.4               ROCR_1.0-11                
##  [19] globals_0.16.2              matrixStats_1.0.0          
##  [21] pkgdown_2.0.7               spatstat.sparse_3.0-3      
##  [23] colorspace_2.1-0            rappdirs_0.3.3             
##  [25] ggrepel_0.9.4               textshaping_0.3.6          
##  [27] xfun_0.40                   dplyr_1.1.3                
##  [29] RCurl_1.98-1.12             crayon_1.5.2               
##  [31] jsonlite_1.8.7              progressr_0.14.0           
##  [33] spatstat.data_3.0-3         survival_3.5-7             
##  [35] zoo_1.8-12                  glue_1.6.2                 
##  [37] polyclip_1.10-6             gtable_0.3.4               
##  [39] zlibbioc_1.44.0             XVector_0.38.0             
##  [41] leiden_0.4.3                DelayedArray_0.24.0        
##  [43] future.apply_1.11.0         BiocGenerics_0.44.0        
##  [45] abind_1.4-5                 scales_1.2.1               
##  [47] spatstat.random_3.2-1       miniUI_0.1.1.1             
##  [49] Rcpp_1.0.11                 viridisLite_0.4.2          
##  [51] xtable_1.8-4                reticulate_1.34.0          
##  [53] dotCall64_1.1-0             stats4_4.2.2               
##  [55] htmlwidgets_1.6.2           httr_1.4.7                 
##  [57] RColorBrewer_1.1-3          ellipsis_0.3.2             
##  [59] ica_1.0-3                   farver_2.1.1               
##  [61] pkgconfig_2.0.3             sass_0.4.7                 
##  [63] uwot_0.1.16                 deldir_1.0-9               
##  [65] utf8_1.2.4                  labeling_0.4.3             
##  [67] tidyselect_1.2.0            rlang_1.1.1                
##  [69] reshape2_1.4.4              later_1.3.1                
##  [71] munsell_0.5.0               tools_4.2.2                
##  [73] cachem_1.0.8                cli_3.6.1                  
##  [75] generics_0.1.3              ggridges_0.5.4             
##  [77] evaluate_0.22               stringr_1.5.0              
##  [79] fastmap_1.1.1               yaml_2.3.7                 
##  [81] ragg_1.2.5                  goftest_1.2-3              
##  [83] knitr_1.45                  fs_1.6.3                   
##  [85] fitdistrplus_1.1-11         purrr_1.0.2                
##  [87] RANN_2.6.1                  sparseMatrixStats_1.10.0   
##  [89] pbapply_1.7-2               future_1.33.0              
##  [91] nlme_3.1-162                mime_0.12                  
##  [93] formatR_1.14                compiler_4.2.2             
##  [95] plotly_4.10.3               png_0.1-8                  
##  [97] spatstat.utils_3.0-4        tibble_3.2.1               
##  [99] glmGamPoi_1.10.2            bslib_0.5.1                
## [101] stringi_1.7.12              highr_0.10                 
## [103] desc_1.4.2                  RSpectra_0.16-1            
## [105] lattice_0.21-9              Matrix_1.6-1.1             
## [107] vctrs_0.6.4                 pillar_1.9.0               
## [109] lifecycle_1.0.3             spatstat.geom_3.2-7        
## [111] lmtest_0.9-40               jquerylib_0.1.4            
## [113] RcppAnnoy_0.0.21            bitops_1.0-7               
## [115] data.table_1.14.8           cowplot_1.1.1              
## [117] irlba_2.3.5.1               GenomicRanges_1.50.2       
## [119] httpuv_1.6.12               patchwork_1.1.3            
## [121] R6_2.5.1                    promises_1.2.1             
## [123] KernSmooth_2.23-22          gridExtra_2.3              
## [125] IRanges_2.32.0              parallelly_1.36.0          
## [127] codetools_0.2-19            fastDummies_1.7.3          
## [129] MASS_7.3-58.2               SummarizedExperiment_1.28.0
## [131] rprojroot_2.0.3             withr_2.5.2                
## [133] sctransform_0.4.1           GenomeInfoDbData_1.2.9     
## [135] S4Vectors_0.36.2            parallel_4.2.2             
## [137] grid_4.2.2                  tidyr_1.3.0                
## [139] DelayedMatrixStats_1.20.0   rmarkdown_2.25             
## [141] MatrixGenerics_1.10.0       Rtsne_0.16                 
## [143] spatstat.explore_3.2-5      Biobase_2.58.0             
## [145] shiny_1.7.5.1
```

---

## Analysis, visualization, and integration of Visium HD spatial datasets with Seurat • Seurat

**URL:** http://127.0.0.1:9173/seurat/visualization_vignette.html

**Contents:**
- Data visualization methods in Seurat
    - Compiled: 2023-10-31
- Five visualizations of marker feature expression
- New additions to FeaturePlot
- Updated and expanded visualization functions
- Applying themes to plots
- Interactive plotting features
- Plotting Accessories
- Contents

We’ll demonstrate visualization techniques in Seurat using our previously computed Seurat object from the 2,700 PBMC tutorial. You can download this dataset from SeuratData

In addition to changes to FeaturePlot(), several other plotting functions have been updated and expanded with new features and taking over the role of now-deprecated functions

With Seurat, all plotting functions return ggplot2-based plots by default, allowing one to easily capture and manipulate plots just like any other ggplot2-based plot.

Seurat utilizes R’s plotly graphing library to create interactive plots. This interactive plotting feature works with any ggplot2-based scatter plots (requires a geom_point layer). To use, simply make a ggplot2-based scatter plot (such as DimPlot() or FeaturePlot()) and pass the resulting plot to HoverLocator()

Another interactive feature provided by Seurat is being able to manually select cells for further investigation. We have found this particularly useful for small clusters that do not always separate using unbiased clustering, but which look tantalizingly distinct. You can now select these cells by creating a ggplot2-based scatter plot (such as with DimPlot() or FeaturePlot(), and passing the returned plot to CellSelector(). CellSelector() will return a vector with the names of the points selected, so that you can then set them to a new identity class and perform differential expression.

For example, let’s pretend that DCs had merged with monocytes in the clustering, but we wanted to see what was unique about them based on their position in the tSNE plot.

We can then change the identity of these cells to turn them into their own mini-cluster.

Using CellSelector to Automatically Assign Cell Identities

In addition to returning a vector of cell names, CellSelector() can also take the selected cells and assign a new identity to them, returning a Seurat object with the identity classes already set. This is done by passing the Seurat object used to make the plot into CellSelector(), as well as an identity class. As an example, we’re going to select the same set of cells as before, and set their identity class to “selected”

Along with new functions add interactive functionality to plots, Seurat provides new accessory functions for manipulating and combining plots.

Plotting multiple plots was previously achieved with the CombinePlot() function. We are deprecating this functionality in favor of the patchwork system. Below is a brief demonstration but please see the patchwork package website here for more details and examples.

Developed by Rahul Satija, Satija Lab and Collaborators.

Site built with pkgdown 2.0.7.

**Examples:**

Example 1 (unknown):
```unknown
vignettes/visualization_vignette.Rmd
```

Example 2 (unknown):
```unknown
visualization_vignette.Rmd
```

Example 3 (unknown):
```unknown
SeuratData::InstallData("pbmc3k")
```

Example 4 (r):
```r
SeuratData::InstallData("pbmc3k")
```

Example 5 (r):
```r
SeuratData::InstallData("pbmc3k")
```

Example 6 (unknown):
```unknown
library(Seurat)
library(SeuratData)
library(ggplot2)
library(patchwork)
pbmc3k.final <- LoadData("pbmc3k", type = "pbmc3k.final")
pbmc3k.final$groups <- sample(c("group1", "group2"), size = ncol(pbmc3k.final), replace = TRUE)
features <- c("LYZ", "CCL5", "IL32", "PTPRCAP", "FCGR3A", "PF4")
pbmc3k.final
```

Example 7 (r):
```r
library(Seurat)
library(SeuratData)
library(ggplot2)
library(patchwork)
pbmc3k.final <- LoadData("pbmc3k", type = "pbmc3k.final")
pbmc3k.final$groups <- sample(c("group1", "group2"), size = ncol(pbmc3k.final), replace = TRUE)
features <- c("LYZ", "CCL5", "IL32", "PTPRCAP", "FCGR3A", "PF4")
pbmc3k.final
```

Example 8 (r):
```r
library(Seurat)
library(SeuratData)
library(ggplot2)
library(patchwork)
pbmc3k.final <- LoadData("pbmc3k", type = "pbmc3k.final")
pbmc3k.final$groups <- sample(c("group1", "group2"), size = ncol(pbmc3k.final), replace = TRUE)
features <- c("LYZ", "CCL5", "IL32", "PTPRCAP", "FCGR3A", "PF4")
pbmc3k.final
```

Example 9 (python):
```python
## An object of class Seurat 
## 13714 features across 2638 samples within 1 assay 
## Active assay: RNA (13714 features, 2000 variable features)
##  3 layers present: data, counts, scale.data
##  2 dimensional reductions calculated: pca, umap
```

Example 10 (python):
```python
## An object of class Seurat 
## 13714 features across 2638 samples within 1 assay 
## Active assay: RNA (13714 features, 2000 variable features)
##  3 layers present: data, counts, scale.data
##  2 dimensional reductions calculated: pca, umap
```

Example 11 (python):
```python
# Ridge plots - from ggridges. Visualize single cell expression distributions in each cluster
RidgePlot(pbmc3k.final, features = features, ncol = 2)
```

Example 12 (r):
```r
# Ridge plots - from ggridges. Visualize single cell expression distributions in each cluster
RidgePlot(pbmc3k.final, features = features, ncol = 2)
```

Example 13 (r):
```r
# Ridge plots - from ggridges. Visualize single cell expression distributions in each cluster
RidgePlot(pbmc3k.final, features = features, ncol = 2)
```

Example 14 (unknown):
```unknown
# Violin plot - Visualize single cell expression distributions in each cluster
VlnPlot(pbmc3k.final, features = features)
```

Example 15 (r):
```r
# Violin plot - Visualize single cell expression distributions in each cluster
VlnPlot(pbmc3k.final, features = features)
```

Example 16 (r):
```r
# Violin plot - Visualize single cell expression distributions in each cluster
VlnPlot(pbmc3k.final, features = features)
```

Example 17 (unknown):
```unknown
# Feature plot - visualize feature expression in low-dimensional space
FeaturePlot(pbmc3k.final, features = features)
```

Example 18 (r):
```r
# Feature plot - visualize feature expression in low-dimensional space
FeaturePlot(pbmc3k.final, features = features)
```

Example 19 (r):
```r
# Feature plot - visualize feature expression in low-dimensional space
FeaturePlot(pbmc3k.final, features = features)
```

Example 20 (unknown):
```unknown
# Dot plots - the size of the dot corresponds to the percentage of cells expressing the
# feature in each cluster. The color represents the average expression level
DotPlot(pbmc3k.final, features = features) + RotatedAxis()
```

Example 21 (r):
```r
# Dot plots - the size of the dot corresponds to the percentage of cells expressing the
# feature in each cluster. The color represents the average expression level
DotPlot(pbmc3k.final, features = features) + RotatedAxis()
```

Example 22 (r):
```r
# Dot plots - the size of the dot corresponds to the percentage of cells expressing the
# feature in each cluster. The color represents the average expression level
DotPlot(pbmc3k.final, features = features) + RotatedAxis()
```

Example 23 (unknown):
```unknown
# Single cell heatmap of feature expression
DoHeatmap(subset(pbmc3k.final, downsample = 100), features = features, size = 3)
```

Example 24 (r):
```r
# Single cell heatmap of feature expression
DoHeatmap(subset(pbmc3k.final, downsample = 100), features = features, size = 3)
```

Example 25 (r):
```r
# Single cell heatmap of feature expression
DoHeatmap(subset(pbmc3k.final, downsample = 100), features = features, size = 3)
```

Example 26 (unknown):
```unknown
FeaturePlot
```

Example 27 (unknown):
```unknown
# Plot a legend to map colors to expression levels
FeaturePlot(pbmc3k.final, features = "MS4A1")
```

Example 28 (r):
```r
# Plot a legend to map colors to expression levels
FeaturePlot(pbmc3k.final, features = "MS4A1")
```

Example 29 (r):
```r
# Plot a legend to map colors to expression levels
FeaturePlot(pbmc3k.final, features = "MS4A1")
```

Example 30 (unknown):
```unknown
# Adjust the contrast in the plot
FeaturePlot(pbmc3k.final, features = "MS4A1", min.cutoff = 1, max.cutoff = 3)
```

Example 31 (r):
```r
# Adjust the contrast in the plot
FeaturePlot(pbmc3k.final, features = "MS4A1", min.cutoff = 1, max.cutoff = 3)
```

Example 32 (r):
```r
# Adjust the contrast in the plot
FeaturePlot(pbmc3k.final, features = "MS4A1", min.cutoff = 1, max.cutoff = 3)
```

Example 33 (unknown):
```unknown
# Calculate feature-specific contrast levels based on quantiles of non-zero expression.
# Particularly useful when plotting multiple markers
FeaturePlot(pbmc3k.final, features = c("MS4A1", "PTPRCAP"), min.cutoff = "q10", max.cutoff = "q90")
```

Example 34 (r):
```r
# Calculate feature-specific contrast levels based on quantiles of non-zero expression.
# Particularly useful when plotting multiple markers
FeaturePlot(pbmc3k.final, features = c("MS4A1", "PTPRCAP"), min.cutoff = "q10", max.cutoff = "q90")
```

Example 35 (r):
```r
# Calculate feature-specific contrast levels based on quantiles of non-zero expression.
# Particularly useful when plotting multiple markers
FeaturePlot(pbmc3k.final, features = c("MS4A1", "PTPRCAP"), min.cutoff = "q10", max.cutoff = "q90")
```

Example 36 (unknown):
```unknown
# Visualize co-expression of two features simultaneously
FeaturePlot(pbmc3k.final, features = c("MS4A1", "CD79A"), blend = TRUE)
```

Example 37 (r):
```r
# Visualize co-expression of two features simultaneously
FeaturePlot(pbmc3k.final, features = c("MS4A1", "CD79A"), blend = TRUE)
```

Example 38 (r):
```r
# Visualize co-expression of two features simultaneously
FeaturePlot(pbmc3k.final, features = c("MS4A1", "CD79A"), blend = TRUE)
```

Example 39 (unknown):
```unknown
# Split visualization to view expression by groups (replaces FeatureHeatmap)
FeaturePlot(pbmc3k.final, features = c("MS4A1", "CD79A"), split.by = "groups")
```

Example 40 (r):
```r
# Split visualization to view expression by groups (replaces FeatureHeatmap)
FeaturePlot(pbmc3k.final, features = c("MS4A1", "CD79A"), split.by = "groups")
```

Example 41 (r):
```r
# Split visualization to view expression by groups (replaces FeatureHeatmap)
FeaturePlot(pbmc3k.final, features = c("MS4A1", "CD79A"), split.by = "groups")
```

Example 42 (unknown):
```unknown
FeaturePlot()
```

Example 43 (python):
```python
# Violin plots can also be split on some variable. Simply add the splitting variable to object
# metadata and pass it to the split.by argument
VlnPlot(pbmc3k.final, features = "percent.mt", split.by = "groups")
```

Example 44 (r):
```r
# Violin plots can also be split on some variable. Simply add the splitting variable to object
# metadata and pass it to the split.by argument
VlnPlot(pbmc3k.final, features = "percent.mt", split.by = "groups")
```

Example 45 (r):
```r
# Violin plots can also be split on some variable. Simply add the splitting variable to object
# metadata and pass it to the split.by argument
VlnPlot(pbmc3k.final, features = "percent.mt", split.by = "groups")
```

Example 46 (unknown):
```unknown
# SplitDotPlotGG has been replaced with the `split.by` parameter for DotPlot
DotPlot(pbmc3k.final, features = features, split.by = "groups") + RotatedAxis()
```

Example 47 (r):
```r
# SplitDotPlotGG has been replaced with the `split.by` parameter for DotPlot
DotPlot(pbmc3k.final, features = features, split.by = "groups") + RotatedAxis()
```

Example 48 (r):
```r
# SplitDotPlotGG has been replaced with the `split.by` parameter for DotPlot
DotPlot(pbmc3k.final, features = features, split.by = "groups") + RotatedAxis()
```

Example 49 (unknown):
```unknown
# DimPlot replaces TSNEPlot, PCAPlot, etc. In addition, it will plot either 'umap', 'tsne', or
# 'pca' by default, in that order
DimPlot(pbmc3k.final)
```

Example 50 (r):
```r
# DimPlot replaces TSNEPlot, PCAPlot, etc. In addition, it will plot either 'umap', 'tsne', or
# 'pca' by default, in that order
DimPlot(pbmc3k.final)
```

Example 51 (r):
```r
# DimPlot replaces TSNEPlot, PCAPlot, etc. In addition, it will plot either 'umap', 'tsne', or
# 'pca' by default, in that order
DimPlot(pbmc3k.final)
```

Example 52 (unknown):
```unknown
pbmc3k.final.no.umap <- pbmc3k.final
pbmc3k.final.no.umap[["umap"]] <- NULL
DimPlot(pbmc3k.final.no.umap) + RotatedAxis()
```

Example 53 (r):
```r
pbmc3k.final.no.umap <- pbmc3k.final
pbmc3k.final.no.umap[["umap"]] <- NULL
DimPlot(pbmc3k.final.no.umap) + RotatedAxis()
```

Example 54 (r):
```r
pbmc3k.final.no.umap <- pbmc3k.final
pbmc3k.final.no.umap[["umap"]] <- NULL
DimPlot(pbmc3k.final.no.umap) + RotatedAxis()
```

Example 55 (unknown):
```unknown
# DoHeatmap now shows a grouping bar, splitting the heatmap into groups or clusters. This can
# be changed with the `group.by` parameter
DoHeatmap(pbmc3k.final, features = VariableFeatures(pbmc3k.final)[1:100], cells = 1:500, size = 4,
    angle = 90) + NoLegend()
```

Example 56 (r):
```r
# DoHeatmap now shows a grouping bar, splitting the heatmap into groups or clusters. This can
# be changed with the `group.by` parameter
DoHeatmap(pbmc3k.final, features = VariableFeatures(pbmc3k.final)[1:100], cells = 1:500, size = 4,
    angle = 90) + NoLegend()
```

Example 57 (r):
```r
# DoHeatmap now shows a grouping bar, splitting the heatmap into groups or clusters. This can
# be changed with the `group.by` parameter
DoHeatmap(pbmc3k.final, features = VariableFeatures(pbmc3k.final)[1:100], cells = 1:500, size = 4,
    angle = 90) + NoLegend()
```

Example 58 (unknown):
```unknown
baseplot <- DimPlot(pbmc3k.final, reduction = "umap")
# Add custom labels and titles
baseplot + labs(title = "Clustering of 2,700 PBMCs")
```

Example 59 (r):
```r
baseplot <- DimPlot(pbmc3k.final, reduction = "umap")
# Add custom labels and titles
baseplot + labs(title = "Clustering of 2,700 PBMCs")
```

Example 60 (r):
```r
baseplot <- DimPlot(pbmc3k.final, reduction = "umap")
# Add custom labels and titles
baseplot + labs(title = "Clustering of 2,700 PBMCs")
```

Example 61 (unknown):
```unknown
# Use community-created themes, overwriting the default Seurat-applied theme Install ggmin
# with remotes::install_github('sjessa/ggmin')
baseplot + ggmin::theme_powerpoint()
```

Example 62 (r):
```r
# Use community-created themes, overwriting the default Seurat-applied theme Install ggmin
# with remotes::install_github('sjessa/ggmin')
baseplot + ggmin::theme_powerpoint()
```

Example 63 (r):
```r
# Use community-created themes, overwriting the default Seurat-applied theme Install ggmin
# with remotes::install_github('sjessa/ggmin')
baseplot + ggmin::theme_powerpoint()
```

Example 64 (unknown):
```unknown
# Seurat also provides several built-in themes, such as DarkTheme; for more details see
# ?SeuratTheme
baseplot + DarkTheme()
```

Example 65 (r):
```r
# Seurat also provides several built-in themes, such as DarkTheme; for more details see
# ?SeuratTheme
baseplot + DarkTheme()
```

Example 66 (r):
```r
# Seurat also provides several built-in themes, such as DarkTheme; for more details see
# ?SeuratTheme
baseplot + DarkTheme()
```

Example 67 (unknown):
```unknown
# Chain themes together
baseplot + FontSize(x.title = 20, y.title = 20) + NoLegend()
```

Example 68 (r):
```r
# Chain themes together
baseplot + FontSize(x.title = 20, y.title = 20) + NoLegend()
```

Example 69 (r):
```r
# Chain themes together
baseplot + FontSize(x.title = 20, y.title = 20) + NoLegend()
```

Example 70 (unknown):
```unknown
FeaturePlot()
```

Example 71 (unknown):
```unknown
HoverLocator()
```

Example 72 (unknown):
```unknown
# Include additional data to display alongside cell names by passing in a data frame of
# information.  Works well when using FetchData
plot <- FeaturePlot(pbmc3k.final, features = "MS4A1")
HoverLocator(plot = plot, information = FetchData(pbmc3k.final, vars = c("ident", "PC_1", "nFeature_RNA")))
```

Example 73 (r):
```r
# Include additional data to display alongside cell names by passing in a data frame of
# information.  Works well when using FetchData
plot <- FeaturePlot(pbmc3k.final, features = "MS4A1")
HoverLocator(plot = plot, information = FetchData(pbmc3k.final, vars = c("ident", "PC_1", "nFeature_RNA")))
```

Example 74 (r):
```r
# Include additional data to display alongside cell names by passing in a data frame of
# information.  Works well when using FetchData
plot <- FeaturePlot(pbmc3k.final, features = "MS4A1")
HoverLocator(plot = plot, information = FetchData(pbmc3k.final, vars = c("ident", "PC_1", "nFeature_RNA")))
```

Example 75 (unknown):
```unknown
FeaturePlot()
```

Example 76 (unknown):
```unknown
CellSelector()
```

Example 77 (unknown):
```unknown
CellSelector()
```

Example 78 (unknown):
```unknown
pbmc3k.final <- RenameIdents(pbmc3k.final, DC = "CD14+ Mono")
plot <- DimPlot(pbmc3k.final, reduction = "umap")
select.cells <- CellSelector(plot = plot)
```

Example 79 (r):
```r
pbmc3k.final <- RenameIdents(pbmc3k.final, DC = "CD14+ Mono")
plot <- DimPlot(pbmc3k.final, reduction = "umap")
select.cells <- CellSelector(plot = plot)
```

Example 80 (r):
```r
pbmc3k.final <- RenameIdents(pbmc3k.final, DC = "CD14+ Mono")
plot <- DimPlot(pbmc3k.final, reduction = "umap")
select.cells <- CellSelector(plot = plot)
```

Example 81 (unknown):
```unknown
head(select.cells)
```

Example 82 (r):
```r
head(select.cells)
```

Example 83 (r):
```r
head(select.cells)
```

Example 84 (unknown):
```unknown
## [1] "AAGATTACCGCCTT" "AAGCCATGAACTGC" "AATTACGAATTCCT" "ACCCGTTGCTTCTA"
## [5] "ACGAGGGACAGGAG" "ACGTGATGCCATGA"
```

Example 85 (unknown):
```unknown
## [1] "AAGATTACCGCCTT" "AAGCCATGAACTGC" "AATTACGAATTCCT" "ACCCGTTGCTTCTA"
## [5] "ACGAGGGACAGGAG" "ACGTGATGCCATGA"
```

Example 86 (unknown):
```unknown
Idents(pbmc3k.final, cells = select.cells) <- "NewCells"

# Now, we find markers that are specific to the new cells, and find clear DC markers
newcells.markers <- FindMarkers(pbmc3k.final, ident.1 = "NewCells", ident.2 = "CD14+ Mono", min.diff.pct = 0.3,
    only.pos = TRUE)
head(newcells.markers)
```

Example 87 (r):
```r
Idents(pbmc3k.final, cells = select.cells) <- "NewCells"

# Now, we find markers that are specific to the new cells, and find clear DC markers
newcells.markers <- FindMarkers(pbmc3k.final, ident.1 = "NewCells", ident.2 = "CD14+ Mono", min.diff.pct = 0.3,
    only.pos = TRUE)
head(newcells.markers)
```

Example 88 (r):
```r
Idents(pbmc3k.final, cells = select.cells) <- "NewCells"

# Now, we find markers that are specific to the new cells, and find clear DC markers
newcells.markers <- FindMarkers(pbmc3k.final, ident.1 = "NewCells", ident.2 = "CD14+ Mono", min.diff.pct = 0.3,
    only.pos = TRUE)
head(newcells.markers)
```

Example 89 (unknown):
```unknown
##                 p_val avg_log2FC pct.1 pct.2    p_val_adj
## FCER1A   3.239004e-69   6.504163 0.800 0.017 4.441970e-65
## SERPINF1 7.761413e-36   5.456560 0.457 0.013 1.064400e-31
## HLA-DQB2 1.721094e-34   4.752397 0.429 0.010 2.360309e-30
## CD1C     2.304106e-33   4.929607 0.514 0.025 3.159851e-29
## ENHO     5.099765e-32   5.076634 0.400 0.010 6.993818e-28
## ITM2C    4.299994e-29   5.660234 0.371 0.010 5.897012e-25
```

Example 90 (unknown):
```unknown
##                 p_val avg_log2FC pct.1 pct.2    p_val_adj
## FCER1A   3.239004e-69   6.504163 0.800 0.017 4.441970e-65
## SERPINF1 7.761413e-36   5.456560 0.457 0.013 1.064400e-31
## HLA-DQB2 1.721094e-34   4.752397 0.429 0.010 2.360309e-30
## CD1C     2.304106e-33   4.929607 0.514 0.025 3.159851e-29
## ENHO     5.099765e-32   5.076634 0.400 0.010 6.993818e-28
## ITM2C    4.299994e-29   5.660234 0.371 0.010 5.897012e-25
```

Example 91 (unknown):
```unknown
CellSelector
```

Example 92 (unknown):
```unknown
CellSelector()
```

Example 93 (unknown):
```unknown
CellSelector()
```

Example 94 (unknown):
```unknown
pbmc3k.final <- CellSelector(plot = plot, object = pbmc3k.final, ident = "selected")
```

Example 95 (r):
```r
pbmc3k.final <- CellSelector(plot = plot, object = pbmc3k.final, ident = "selected")
```

Example 96 (r):
```r
pbmc3k.final <- CellSelector(plot = plot, object = pbmc3k.final, ident = "selected")
```

Example 97 (unknown):
```unknown
levels(pbmc3k.final)
```

Example 98 (r):
```r
levels(pbmc3k.final)
```

Example 99 (r):
```r
levels(pbmc3k.final)
```

Example 100 (unknown):
```unknown
## [1] "selected"     "Naive CD4 T"  "Memory CD4 T" "CD14+ Mono"   "B"           
## [6] "CD8 T"        "FCGR3A+ Mono" "NK"           "Platelet"
```

Example 101 (unknown):
```unknown
## [1] "selected"     "Naive CD4 T"  "Memory CD4 T" "CD14+ Mono"   "B"           
## [6] "CD8 T"        "FCGR3A+ Mono" "NK"           "Platelet"
```

Example 102 (unknown):
```unknown
# LabelClusters and LabelPoints will label clusters (a coloring variable) or individual points
# on a ggplot2-based scatter plot
plot <- DimPlot(pbmc3k.final, reduction = "pca") + NoLegend()
LabelClusters(plot = plot, id = "ident")
```

Example 103 (r):
```r
# LabelClusters and LabelPoints will label clusters (a coloring variable) or individual points
# on a ggplot2-based scatter plot
plot <- DimPlot(pbmc3k.final, reduction = "pca") + NoLegend()
LabelClusters(plot = plot, id = "ident")
```

Example 104 (r):
```r
# LabelClusters and LabelPoints will label clusters (a coloring variable) or individual points
# on a ggplot2-based scatter plot
plot <- DimPlot(pbmc3k.final, reduction = "pca") + NoLegend()
LabelClusters(plot = plot, id = "ident")
```

Example 105 (python):
```python
# Both functions support `repel`, which will intelligently stagger labels and draw connecting
# lines from the labels to the points or clusters
LabelPoints(plot = plot, points = TopCells(object = pbmc3k.final[["pca"]]), repel = TRUE)
```

Example 106 (r):
```r
# Both functions support `repel`, which will intelligently stagger labels and draw connecting
# lines from the labels to the points or clusters
LabelPoints(plot = plot, points = TopCells(object = pbmc3k.final[["pca"]]), repel = TRUE)
```

Example 107 (r):
```r
# Both functions support `repel`, which will intelligently stagger labels and draw connecting
# lines from the labels to the points or clusters
LabelPoints(plot = plot, points = TopCells(object = pbmc3k.final[["pca"]]), repel = TRUE)
```

Example 108 (unknown):
```unknown
CombinePlot()
```

Example 109 (unknown):
```unknown
plot1 <- DimPlot(pbmc3k.final)
# Create scatter plot with the Pearson correlation value as the title
plot2 <- FeatureScatter(pbmc3k.final, feature1 = "LYZ", feature2 = "CCL5")
# Combine two plots
plot1 + plot2
```

Example 110 (r):
```r
plot1 <- DimPlot(pbmc3k.final)
# Create scatter plot with the Pearson correlation value as the title
plot2 <- FeatureScatter(pbmc3k.final, feature1 = "LYZ", feature2 = "CCL5")
# Combine two plots
plot1 + plot2
```

Example 111 (r):
```r
plot1 <- DimPlot(pbmc3k.final)
# Create scatter plot with the Pearson correlation value as the title
plot2 <- FeatureScatter(pbmc3k.final, feature1 = "LYZ", feature2 = "CCL5")
# Combine two plots
plot1 + plot2
```

Example 112 (python):
```python
# Remove the legend from all plots
(plot1 + plot2) & NoLegend()
```

Example 113 (r):
```r
# Remove the legend from all plots
(plot1 + plot2) & NoLegend()
```

Example 114 (r):
```r
# Remove the legend from all plots
(plot1 + plot2) & NoLegend()
```

Example 115 (unknown):
```unknown
sessionInfo()
```

Example 116 (r):
```r
sessionInfo()
```

Example 117 (r):
```r
sessionInfo()
```

Example 118 (unknown):
```unknown
## R version 4.2.2 Patched (2022-11-10 r83330)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.6 LTS
## 
## Matrix products: default
## BLAS:   /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.9.0
## LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.9.0
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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       
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
##  [1] patchwork_1.1.3               ggplot2_3.4.4                
##  [3] thp1.eccite.SeuratData_3.1.5  stxBrain.SeuratData_0.1.1    
##  [5] ssHippo.SeuratData_3.1.4      pbmcsca.SeuratData_3.0.0     
##  [7] pbmcref.SeuratData_1.0.0      pbmcMultiome.SeuratData_0.1.4
##  [9] pbmc3k.SeuratData_3.1.4       panc8.SeuratData_3.0.2       
## [11] ifnb.SeuratData_3.0.0         hcabm40k.SeuratData_3.0.0    
## [13] cbmc.SeuratData_3.1.4         bmcite.SeuratData_0.3.0      
## [15] SeuratData_0.2.2.9001         Seurat_5.0.0                 
## [17] SeuratObject_5.0.0            sp_2.1-1                     
## 
## loaded via a namespace (and not attached):
##   [1] spam_2.10-0            systemfonts_1.0.4      plyr_1.8.9            
##   [4] igraph_1.5.1           lazyeval_0.2.2         splines_4.2.2         
##   [7] RcppHNSW_0.5.0         crosstalk_1.2.0        listenv_0.9.0         
##  [10] scattermore_1.2        digest_0.6.33          htmltools_0.5.6.1     
##  [13] fansi_1.0.5            magrittr_2.0.3         memoise_2.0.1         
##  [16] tensor_1.5             cluster_2.1.4          ROCR_1.0-11           
##  [19] limma_3.54.1           globals_0.16.2         matrixStats_1.0.0     
##  [22] pkgdown_2.0.7          spatstat.sparse_3.0-3  colorspace_2.1-0      
##  [25] rappdirs_0.3.3         ggrepel_0.9.4          textshaping_0.3.6     
##  [28] xfun_0.40              dplyr_1.1.3            crayon_1.5.2          
##  [31] jsonlite_1.8.7         progressr_0.14.0       spatstat.data_3.0-3   
##  [34] survival_3.5-7         zoo_1.8-12             glue_1.6.2            
##  [37] polyclip_1.10-6        gtable_0.3.4           leiden_0.4.3          
##  [40] future.apply_1.11.0    abind_1.4-5            scales_1.2.1          
##  [43] spatstat.random_3.2-1  miniUI_0.1.1.1         Rcpp_1.0.11           
##  [46] viridisLite_0.4.2      xtable_1.8-4           reticulate_1.34.0     
##  [49] dotCall64_1.1-0        ggmin_0.0.0.9000       htmlwidgets_1.6.2     
##  [52] httr_1.4.7             RColorBrewer_1.1-3     ellipsis_0.3.2        
##  [55] ica_1.0-3              farver_2.1.1           pkgconfig_2.0.3       
##  [58] sass_0.4.7             uwot_0.1.16            deldir_1.0-9          
##  [61] utf8_1.2.4             labeling_0.4.3         tidyselect_1.2.0      
##  [64] rlang_1.1.1            reshape2_1.4.4         later_1.3.1           
##  [67] munsell_0.5.0          tools_4.2.2            cachem_1.0.8          
##  [70] cli_3.6.1              generics_0.1.3         ggridges_0.5.4        
##  [73] evaluate_0.22          stringr_1.5.0          fastmap_1.1.1         
##  [76] yaml_2.3.7             ragg_1.2.5             goftest_1.2-3         
##  [79] knitr_1.45             fs_1.6.3               fitdistrplus_1.1-11   
##  [82] purrr_1.0.2            RANN_2.6.1             pbapply_1.7-2         
##  [85] future_1.33.0          nlme_3.1-162           mime_0.12             
##  [88] formatR_1.14           ggrastr_1.0.1          compiler_4.2.2        
##  [91] beeswarm_0.4.0         plotly_4.10.3          png_0.1-8             
##  [94] spatstat.utils_3.0-4   tibble_3.2.1           bslib_0.5.1           
##  [97] stringi_1.7.12         highr_0.10             desc_1.4.2            
## [100] RSpectra_0.16-1        lattice_0.21-9         Matrix_1.6-1.1        
## [103] vctrs_0.6.4            pillar_1.9.0           lifecycle_1.0.3       
## [106] spatstat.geom_3.2-7    lmtest_0.9-40          jquerylib_0.1.4       
## [109] RcppAnnoy_0.0.21       data.table_1.14.8      cowplot_1.1.1         
## [112] irlba_2.3.5.1          httpuv_1.6.12          R6_2.5.1              
## [115] promises_1.2.1         KernSmooth_2.23-22     gridExtra_2.3         
## [118] vipor_0.4.5            parallelly_1.36.0      codetools_0.2-19      
## [121] fastDummies_1.7.3      MASS_7.3-58.2          rprojroot_2.0.3       
## [124] withr_2.5.2            presto_1.0.0           sctransform_0.4.1     
## [127] parallel_4.2.2         grid_4.2.2             tidyr_1.3.0           
## [130] rmarkdown_2.25         Rtsne_0.16             spatstat.explore_3.2-5
## [133] shiny_1.7.5.1          ggbeeswarm_0.7.1
```

Example 119 (unknown):
```unknown
## R version 4.2.2 Patched (2022-11-10 r83330)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.6 LTS
## 
## Matrix products: default
## BLAS:   /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.9.0
## LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.9.0
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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       
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
##  [1] patchwork_1.1.3               ggplot2_3.4.4                
##  [3] thp1.eccite.SeuratData_3.1.5  stxBrain.SeuratData_0.1.1    
##  [5] ssHippo.SeuratData_3.1.4      pbmcsca.SeuratData_3.0.0     
##  [7] pbmcref.SeuratData_1.0.0      pbmcMultiome.SeuratData_0.1.4
##  [9] pbmc3k.SeuratData_3.1.4       panc8.SeuratData_3.0.2       
## [11] ifnb.SeuratData_3.0.0         hcabm40k.SeuratData_3.0.0    
## [13] cbmc.SeuratData_3.1.4         bmcite.SeuratData_0.3.0      
## [15] SeuratData_0.2.2.9001         Seurat_5.0.0                 
## [17] SeuratObject_5.0.0            sp_2.1-1                     
## 
## loaded via a namespace (and not attached):
##   [1] spam_2.10-0            systemfonts_1.0.4      plyr_1.8.9            
##   [4] igraph_1.5.1           lazyeval_0.2.2         splines_4.2.2         
##   [7] RcppHNSW_0.5.0         crosstalk_1.2.0        listenv_0.9.0         
##  [10] scattermore_1.2        digest_0.6.33          htmltools_0.5.6.1     
##  [13] fansi_1.0.5            magrittr_2.0.3         memoise_2.0.1         
##  [16] tensor_1.5             cluster_2.1.4          ROCR_1.0-11           
##  [19] limma_3.54.1           globals_0.16.2         matrixStats_1.0.0     
##  [22] pkgdown_2.0.7          spatstat.sparse_3.0-3  colorspace_2.1-0      
##  [25] rappdirs_0.3.3         ggrepel_0.9.4          textshaping_0.3.6     
##  [28] xfun_0.40              dplyr_1.1.3            crayon_1.5.2          
##  [31] jsonlite_1.8.7         progressr_0.14.0       spatstat.data_3.0-3   
##  [34] survival_3.5-7         zoo_1.8-12             glue_1.6.2            
##  [37] polyclip_1.10-6        gtable_0.3.4           leiden_0.4.3          
##  [40] future.apply_1.11.0    abind_1.4-5            scales_1.2.1          
##  [43] spatstat.random_3.2-1  miniUI_0.1.1.1         Rcpp_1.0.11           
##  [46] viridisLite_0.4.2      xtable_1.8-4           reticulate_1.34.0     
##  [49] dotCall64_1.1-0        ggmin_0.0.0.9000       htmlwidgets_1.6.2     
##  [52] httr_1.4.7             RColorBrewer_1.1-3     ellipsis_0.3.2        
##  [55] ica_1.0-3              farver_2.1.1           pkgconfig_2.0.3       
##  [58] sass_0.4.7             uwot_0.1.16            deldir_1.0-9          
##  [61] utf8_1.2.4             labeling_0.4.3         tidyselect_1.2.0      
##  [64] rlang_1.1.1            reshape2_1.4.4         later_1.3.1           
##  [67] munsell_0.5.0          tools_4.2.2            cachem_1.0.8          
##  [70] cli_3.6.1              generics_0.1.3         ggridges_0.5.4        
##  [73] evaluate_0.22          stringr_1.5.0          fastmap_1.1.1         
##  [76] yaml_2.3.7             ragg_1.2.5             goftest_1.2-3         
##  [79] knitr_1.45             fs_1.6.3               fitdistrplus_1.1-11   
##  [82] purrr_1.0.2            RANN_2.6.1             pbapply_1.7-2         
##  [85] future_1.33.0          nlme_3.1-162           mime_0.12             
##  [88] formatR_1.14           ggrastr_1.0.1          compiler_4.2.2        
##  [91] beeswarm_0.4.0         plotly_4.10.3          png_0.1-8             
##  [94] spatstat.utils_3.0-4   tibble_3.2.1           bslib_0.5.1           
##  [97] stringi_1.7.12         highr_0.10             desc_1.4.2            
## [100] RSpectra_0.16-1        lattice_0.21-9         Matrix_1.6-1.1        
## [103] vctrs_0.6.4            pillar_1.9.0           lifecycle_1.0.3       
## [106] spatstat.geom_3.2-7    lmtest_0.9-40          jquerylib_0.1.4       
## [109] RcppAnnoy_0.0.21       data.table_1.14.8      cowplot_1.1.1         
## [112] irlba_2.3.5.1          httpuv_1.6.12          R6_2.5.1              
## [115] promises_1.2.1         KernSmooth_2.23-22     gridExtra_2.3         
## [118] vipor_0.4.5            parallelly_1.36.0      codetools_0.2-19      
## [121] fastDummies_1.7.3      MASS_7.3-58.2          rprojroot_2.0.3       
## [124] withr_2.5.2            presto_1.0.0           sctransform_0.4.1     
## [127] parallel_4.2.2         grid_4.2.2             tidyr_1.3.0           
## [130] rmarkdown_2.25         Rtsne_0.16             spatstat.explore_3.2-5
## [133] shiny_1.7.5.1          ggbeeswarm_0.7.1
```

---

## PBMC scATAC-seq Vignette

**URL:** http://127.0.0.1:9173/seurat/archive/v3.0/atacseq_integration_vignette/index.html

**Contents:**
- PBMC scATAC-seq Vignette
    - Compiled: June 06, 2019
- Gene activity quantification
- Object setup
- Data preprocessing
- Co-embedding

In this vignette, we demonstrate our new data transfer method in the context of scATAC-seq to

For this example we’ll be working with the 10X PBMC datasets that contain ~10K cells for both scRNA-seq and scATAC-seq. You can download those here: scATAC-seq, scATAC-seq metadata, scRNA-seq

Overall our integration procedure consists of the following steps:

First, we load in the provided peak matrix and collapse the peak matrix to a “gene activity matrix”. Here, we make the simplifying assumption that a gene’s activity can be quantified by simply summing all counts within the gene body + 2kb upstream but our method is compatible with any method that returns a gene by cell matrix (e.g. Cicero).

Next, we’ll set up the Seurat object and store both the original peak counts in the “ATAC” Assay and the gene activity matrix in the “RNA” Assay. As a QC step, we also filter out all cells here with fewer than 5K total counts in the scATAC-seq data, though you may need to modify this threshold for your experiment.

Here, we process the gene activity matrix in order to find anchors between cells in the scATAC-seq dataset and the scRNA-seq dataset.

We also process the peak matrix. Here we perform latent semantic indexing to reduce the dimensionality of the scATAC-seq data. This procedure learns an ‘internal’ structure for the scRNA-seq data, and is important when determining the appropriate weights for the anchors when transferring information. We utilize Latent Semantic Indexing (LSI) to learn the structure of ATAC-seq data, as proposed in Cusanovich et al, Science 2015 and implemented in the RunLSI function. LSI is implemented here by performing computing the term frequency-inverse document frequency (TF-IDF) followed by SVD.

We use all peaks that have at least 100 reads across all cells, and reduce dimensionality to 50. The parameters chosen here are inspired by previous scATAC-seq analyses, and we do not typically change them, but you can do so.

We have previously pre-processed and clustered a scRNA-seq dataset using the standard workflow in Seurat, and provide the object here. You can see that we can identify standard clusters of myeloid and lymphoid PBMCs.

Now, we can identify anchors between the scATAC-seq dataset and the scRNA-seq dataset and use these anchors to transfer the celltype labels we learned from the 10K scRNA-seq data to the scATAC-seq cells.

To transfer the cluster ids, we provide a vector of previously annotated cell type labels for the RNA to the refdata parameter. The output will contain a matrix with predictions and confidence scores for each ATAC-seq cell.

Why do you choose different (non-default) values for reduction and weight.reduction?

In FindTransferAnchors, we typically project the PCA structure from the reference onto the query when transferring between scRNA-seq datasets. However, when transferring across modalities we find that CCA better captures the shared feature correlation structure and therefore set reduction = 'cca' here. Additionally, by default in TransferData we use the same projected PCA structure to compute the weights of the local neighborhood of anchors that influence each cell’s prediction. In the case of scRNA-seq to scATA-seq transfer, we use the low dimensional space learned by computing an LSI on the ATAC-seq data to compute these weights as this better captures the “internal” structure of the ATAC-seq data.

We can then examine the distribution of prediction scores and optionally filter out those cells with low scores. Here, we find that over 95% of the cells receive a score of 0.5 or greater.

We can then view the predicted cell types on a UMAP representation of the scATAC-seq data and find that the transferred labels are highly consistent with the UMAP structure.

After transferring cell type labels, you can then perform downstream analyses on a cell type specific level. For example, you could find sets of enhancers that are specific for certain cell types and look for motif enrichment. While not all of these types of downstream analyses are directly supported in Seurat, stay tuned for updates in this space.

Finally, to visualize all the cells together, we can co-embed the scRNA-seq and scATAC-seq cells in the same low dimensional space. Here, we use the same anchors used earlier to transfer cell type labels to impute RNA-seq values for the scATAC-seq cells. We then merge the measured and imputed scRNA-seq data and run a standard UMAP analysis to visualize all the cells together. Note that this step is for visualization purposes only and is not a necessary part of the data transfer analysis.

Here we plot all cells colored by either their assigned cell type (from the 10K dataset) or their predicted cell type from the data transfer procedure.

How can I further investigate unmatched groups of cells that only appear in one assay?

Upon inspection of the UMAP embeddings, there appeared several groups of cells that appeared to be present only in a single assay. First, the platelet cells appeared only in the scRNA-seq data. These cells are thought to be undergoing biogenesis from megakaryocytes to platelets and therefore either completely lack nuclear material or their chromatin state is uncoupled from their transcriptome. As a result, we would not expect these to align in this analysis.

Additionally, there appeared to be a population next to the B cell progenitors that is composed entirely of scATAC-seq cells and is not integrated well with the scRNA-seq cells. Further examination of the metadata for these cells revealed a high number of reads mapping to blacklisted regions (as provided by the 10x Genomics QC metrics). This suggests that these barcodes could represent dead or dying cells, ambient DNA, or another technical artifact not represented in the scRNA-seq dataset.

How can I evaluate the success of cross-modality integration?

There are several lines of evidence here that give us confidence in this analysis.

Additionally, we have performed a similar analysis, transferring cell type labels from scRNA-seq to scATAC-seq data in the context of the mouse brain and have observed good performance based on similar reasoning to the points above ( Figure 3). These analyses make the assumption that there is generally a positive correlation between chromatin accessibility and gene expression. In cases such as developing systems, where accessibility may not be a good indicator of transcription, the method demonstrated here may not be able to form good anchors and the resulting integration across these specific modalities may be of limited value.

**Examples:**

Example 1 (r):
```r
library(Seurat)
library(ggplot2)
peaks <- Read10X_h5("../data/atac_v1_pbmc_10k_filtered_peak_bc_matrix.h5")
# create a gene activity matrix from the peak matrix and GTF, using chromosomes 1:22, X, and Y.
# Peaks that fall within gene bodies, or 2kb upstream of a gene, are considered
activity.matrix <- CreateGeneActivityMatrix(peak.matrix = peaks, annotation.file = "../data/Homo_sapiens.GRCh37.82.gtf", 
    seq.levels = c(1:22, "X", "Y"), upstream = 2000, verbose = TRUE)
```

Example 2 (r):
```r
library(Seurat)
library(ggplot2)
peaks <- Read10X_h5("../data/atac_v1_pbmc_10k_filtered_peak_bc_matrix.h5")
# create a gene activity matrix from the peak matrix and GTF, using chromosomes 1:22, X, and Y.
# Peaks that fall within gene bodies, or 2kb upstream of a gene, are considered
activity.matrix <- CreateGeneActivityMatrix(peak.matrix = peaks, annotation.file = "../data/Homo_sapiens.GRCh37.82.gtf", 
    seq.levels = c(1:22, "X", "Y"), upstream = 2000, verbose = TRUE)
```

Example 3 (r):
```r
pbmc.atac <- CreateSeuratObject(counts = peaks, assay = "ATAC", project = "10x_ATAC")
pbmc.atac[["ACTIVITY"]] <- CreateAssayObject(counts = activity.matrix)
meta <- read.table("../data/atac_v1_pbmc_10k_singlecell.csv", sep = ",", header = TRUE, row.names = 1, 
    stringsAsFactors = FALSE)
meta <- meta[colnames(pbmc.atac), ]
pbmc.atac <- AddMetaData(pbmc.atac, metadata = meta)
pbmc.atac <- subset(pbmc.atac, subset = nCount_ATAC > 5000)
pbmc.atac$tech <- "atac"
```

Example 4 (r):
```r
pbmc.atac <- CreateSeuratObject(counts = peaks, assay = "ATAC", project = "10x_ATAC")
pbmc.atac[["ACTIVITY"]] <- CreateAssayObject(counts = activity.matrix)
meta <- read.table("../data/atac_v1_pbmc_10k_singlecell.csv", sep = ",", header = TRUE, row.names = 1, 
    stringsAsFactors = FALSE)
meta <- meta[colnames(pbmc.atac), ]
pbmc.atac <- AddMetaData(pbmc.atac, metadata = meta)
pbmc.atac <- subset(pbmc.atac, subset = nCount_ATAC > 5000)
pbmc.atac$tech <- "atac"
```

Example 5 (r):
```r
DefaultAssay(pbmc.atac) <- "ACTIVITY"
pbmc.atac <- FindVariableFeatures(pbmc.atac)
pbmc.atac <- NormalizeData(pbmc.atac)
pbmc.atac <- ScaleData(pbmc.atac)
```

Example 6 (r):
```r
DefaultAssay(pbmc.atac) <- "ACTIVITY"
pbmc.atac <- FindVariableFeatures(pbmc.atac)
pbmc.atac <- NormalizeData(pbmc.atac)
pbmc.atac <- ScaleData(pbmc.atac)
```

Example 7 (r):
```r
DefaultAssay(pbmc.atac) <- "ATAC"
VariableFeatures(pbmc.atac) <- names(which(Matrix::rowSums(pbmc.atac) > 100))
pbmc.atac <- RunLSI(pbmc.atac, n = 50, scale.max = NULL)
pbmc.atac <- RunUMAP(pbmc.atac, reduction = "lsi", dims = 1:50)
```

Example 8 (r):
```r
DefaultAssay(pbmc.atac) <- "ATAC"
VariableFeatures(pbmc.atac) <- names(which(Matrix::rowSums(pbmc.atac) > 100))
pbmc.atac <- RunLSI(pbmc.atac, n = 50, scale.max = NULL)
pbmc.atac <- RunUMAP(pbmc.atac, reduction = "lsi", dims = 1:50)
```

Example 9 (r):
```r
pbmc.rna <- readRDS("../data/pbmc_10k_v3.rds")
pbmc.rna$tech <- "rna"
```

Example 10 (r):
```r
pbmc.rna <- readRDS("../data/pbmc_10k_v3.rds")
pbmc.rna$tech <- "rna"
```

Example 11 (r):
```r
p1 <- DimPlot(pbmc.atac, reduction = "umap") + NoLegend() + ggtitle("scATAC-seq")
p2 <- DimPlot(pbmc.rna, group.by = "celltype", label = TRUE, repel = TRUE) + NoLegend() + ggtitle("scRNA-seq")
CombinePlots(plots = list(p1, p2))
```

Example 12 (r):
```r
p1 <- DimPlot(pbmc.atac, reduction = "umap") + NoLegend() + ggtitle("scATAC-seq")
p2 <- DimPlot(pbmc.rna, group.by = "celltype", label = TRUE, repel = TRUE) + NoLegend() + ggtitle("scRNA-seq")
CombinePlots(plots = list(p1, p2))
```

Example 13 (r):
```r
transfer.anchors <- FindTransferAnchors(reference = pbmc.rna, query = pbmc.atac, features = VariableFeatures(object = pbmc.rna), 
    reference.assay = "RNA", query.assay = "ACTIVITY", reduction = "cca")
```

Example 14 (r):
```r
transfer.anchors <- FindTransferAnchors(reference = pbmc.rna, query = pbmc.atac, features = VariableFeatures(object = pbmc.rna), 
    reference.assay = "RNA", query.assay = "ACTIVITY", reduction = "cca")
```

Example 15 (r):
```r
celltype.predictions <- TransferData(anchorset = transfer.anchors, refdata = pbmc.rna$celltype, 
    weight.reduction = pbmc.atac[["lsi"]])
pbmc.atac <- AddMetaData(pbmc.atac, metadata = celltype.predictions)
```

Example 16 (r):
```r
celltype.predictions <- TransferData(anchorset = transfer.anchors, refdata = pbmc.rna$celltype, 
    weight.reduction = pbmc.atac[["lsi"]])
pbmc.atac <- AddMetaData(pbmc.atac, metadata = celltype.predictions)
```

Example 17 (unknown):
```unknown
FindTransferAnchors
```

Example 18 (unknown):
```unknown
reduction = 'cca'
```

Example 19 (unknown):
```unknown
TransferData
```

Example 20 (r):
```r
hist(pbmc.atac$prediction.score.max)
abline(v = 0.5, col = "red")
```

Example 21 (r):
```r
hist(pbmc.atac$prediction.score.max)
abline(v = 0.5, col = "red")
```

Example 22 (r):
```r
table(pbmc.atac$prediction.score.max > 0.5)
```

Example 23 (r):
```r
table(pbmc.atac$prediction.score.max > 0.5)
```

Example 24 (unknown):
```unknown
## 
## FALSE  TRUE 
##   280  7586
```

Example 25 (unknown):
```unknown
## 
## FALSE  TRUE 
##   280  7586
```

Example 26 (r):
```r
pbmc.atac.filtered <- subset(pbmc.atac, subset = prediction.score.max > 0.5)
pbmc.atac.filtered$predicted.id <- factor(pbmc.atac.filtered$predicted.id, levels = levels(pbmc.rna))  # to make the colors match
p1 <- DimPlot(pbmc.atac.filtered, group.by = "predicted.id", label = TRUE, repel = TRUE) + ggtitle("scATAC-seq cells") + 
    NoLegend() + scale_colour_hue(drop = FALSE)
p2 <- DimPlot(pbmc.rna, group.by = "celltype", label = TRUE, repel = TRUE) + ggtitle("scRNA-seq cells") + 
    NoLegend()
CombinePlots(plots = list(p1, p2))
```

Example 27 (r):
```r
pbmc.atac.filtered <- subset(pbmc.atac, subset = prediction.score.max > 0.5)
pbmc.atac.filtered$predicted.id <- factor(pbmc.atac.filtered$predicted.id, levels = levels(pbmc.rna))  # to make the colors match
p1 <- DimPlot(pbmc.atac.filtered, group.by = "predicted.id", label = TRUE, repel = TRUE) + ggtitle("scATAC-seq cells") + 
    NoLegend() + scale_colour_hue(drop = FALSE)
p2 <- DimPlot(pbmc.rna, group.by = "celltype", label = TRUE, repel = TRUE) + ggtitle("scRNA-seq cells") + 
    NoLegend()
CombinePlots(plots = list(p1, p2))
```

Example 28 (r):
```r
# note that we restrict the imputation to variable genes from scRNA-seq, but could impute the
# full transcriptome if we wanted to
genes.use <- VariableFeatures(pbmc.rna)
refdata <- GetAssayData(pbmc.rna, assay = "RNA", slot = "data")[genes.use, ]

# refdata (input) contains a scRNA-seq expression matrix for the scRNA-seq cells.  imputation
# (output) will contain an imputed scRNA-seq matrix for each of the ATAC cells
imputation <- TransferData(anchorset = transfer.anchors, refdata = refdata, weight.reduction = pbmc.atac[["lsi"]])

# this line adds the imputed data matrix to the pbmc.atac object
pbmc.atac[["RNA"]] <- imputation
coembed <- merge(x = pbmc.rna, y = pbmc.atac)

# Finally, we run PCA and UMAP on this combined object, to visualize the co-embedding of both
# datasets
coembed <- ScaleData(coembed, features = genes.use, do.scale = FALSE)
coembed <- RunPCA(coembed, features = genes.use, verbose = FALSE)
coembed <- RunUMAP(coembed, dims = 1:30)
coembed$celltype <- ifelse(!is.na(coembed$celltype), coembed$celltype, coembed$predicted.id)
```

Example 29 (r):
```r
# note that we restrict the imputation to variable genes from scRNA-seq, but could impute the
# full transcriptome if we wanted to
genes.use <- VariableFeatures(pbmc.rna)
refdata <- GetAssayData(pbmc.rna, assay = "RNA", slot = "data")[genes.use, ]

# refdata (input) contains a scRNA-seq expression matrix for the scRNA-seq cells.  imputation
# (output) will contain an imputed scRNA-seq matrix for each of the ATAC cells
imputation <- TransferData(anchorset = transfer.anchors, refdata = refdata, weight.reduction = pbmc.atac[["lsi"]])

# this line adds the imputed data matrix to the pbmc.atac object
pbmc.atac[["RNA"]] <- imputation
coembed <- merge(x = pbmc.rna, y = pbmc.atac)

# Finally, we run PCA and UMAP on this combined object, to visualize the co-embedding of both
# datasets
coembed <- ScaleData(coembed, features = genes.use, do.scale = FALSE)
coembed <- RunPCA(coembed, features = genes.use, verbose = FALSE)
coembed <- RunUMAP(coembed, dims = 1:30)
coembed$celltype <- ifelse(!is.na(coembed$celltype), coembed$celltype, coembed$predicted.id)
```

Example 30 (r):
```r
p1 <- DimPlot(coembed, group.by = "tech")
p2 <- DimPlot(coembed, group.by = "celltype", label = TRUE, repel = TRUE)
CombinePlots(list(p1, p2))
```

Example 31 (r):
```r
p1 <- DimPlot(coembed, group.by = "tech")
p2 <- DimPlot(coembed, group.by = "celltype", label = TRUE, repel = TRUE)
CombinePlots(list(p1, p2))
```

Example 32 (r):
```r
DimPlot(coembed, split.by = "tech", group.by = "celltype", label = TRUE, repel = TRUE) + NoLegend()
```

Example 33 (r):
```r
DimPlot(coembed, split.by = "tech", group.by = "celltype", label = TRUE, repel = TRUE) + NoLegend()
```

Example 34 (r):
```r
coembed$blacklist_region_fragments[is.na(coembed$blacklist_region_fragments)] <- 0
FeaturePlot(coembed, features = "blacklist_region_fragments", max.cutoff = 500)
```

Example 35 (r):
```r
coembed$blacklist_region_fragments[is.na(coembed$blacklist_region_fragments)] <- 0
FeaturePlot(coembed, features = "blacklist_region_fragments", max.cutoff = 500)
```

---

## Seurat - Dimensional Reduction Vignette • Seurat

**URL:** http://127.0.0.1:9173/seurat/archive/v4.3/dim_reduction_vignette/index.html

**Contents:**
- Seurat - Dimensional Reduction Vignette
    - Compiled: March 27, 2023
- Load in the data
- Explore the new dimensional reduction structure
- Storing a custom dimensional reduction calculation
- Contents

This vignette demonstrates how to store and interact with dimensional reduction information (such as the output from RunPCA()) in Seurat. For demonstration purposes, we will be using the 2,700 PBMC object that is available via the SeuratData package. library(Seurat) library(SeuratData) pbmc <- LoadData("pbmc3k", type = "pbmc3k.final")

In Seurat v3.0, storing and interacting with dimensional reduction information has been generalized and formalized into the DimReduc object. Each dimensional reduction procedure is stored as a DimReduc object in the object@reductions slot as an element of a named list. Accessing these reductions can be done with the [[ operator, calling the name of the reduction desired. For example, after running a principle component analysis with RunPCA(), object[['pca']] will contain the results of the PCA. By adding new elements to the list, users can add additional, and custom, dimensional reductions. Each stored dimensional reduction contains the following slots:cell.embeddings: stores the coordinates for each cell in low-dimensional space.feature.loadings: stores the weight for each feature along each dimension of the embeddingfeature.loadings.projected: Seurat typically calculate the dimensional reduction on a subset of genes (for example, high-variance genes), and then project that structure onto the entire dataset (all genes). The results of that projection (calculated with ProjectDim()) are stored in this slot. Note that the cell loadings will remain unchanged after projection but there are now feature loadings for all featurestdev: The standard deviations of each dimension. Most often used with PCA (storing the square roots of the eigenvalues of the covariance matrix) and can be useful when looking at the drop off in the amount of variance that is explained by each successive dimension.key: Sets the column names for the cell.embeddings and feature.loadings matrices. For example, for PCA, the column names are PC1, PC2, etc., so the key is “PC”.jackstraw: Stores the results of the jackstraw procedure run using this dimensional reduction technique. Currently supported only for PCA.misc: Bonus slot to store any other information you might wantTo access these slots, we provide the Embeddings(),Loadings(), and Stdev() functions pbmc[["pca"]]## A dimensional reduction object with key PC_ ## Number of dimensions: 50 ## Projected dimensional reduction calculated: FALSE ## Jackstraw run: TRUE ## Computed using assay: RNA head(Embeddings(pbmc, reduction = "pca")[, 1:5])## PC_1 PC_2 PC_3 PC_4 PC_5 ## AAACATACAACCAC -4.7296855 -0.5184265 -0.7623220 -2.3156790 -0.07160006 ## AAACATTGAGCTAC -0.5174029 4.5918957 5.9091921 6.9118856 -1.96243034 ## AAACATTGATCAGC -3.1891063 -3.4695154 -0.8313710 -2.0019985 -5.10442765 ## AAACCGTGCTTCCG 12.7933021 0.1007166 0.6310221 -0.3687338 0.21838204 ## AAACCGTGTATGCG -3.1288078 -6.3481412 1.2507776 3.0191026 7.84739502 ## AAACGCACTGGTAC -3.1088963 0.9262125 -0.6482331 -2.3244378 -2.00526763 head(Loadings(pbmc, reduction = "pca")[, 1:5])## PC_1 PC_2 PC_3 PC_4 PC_5 ## PPBP 0.010990202 0.01148426 -0.15176092 0.10403737 0.003299077 ## LYZ 0.116231706 0.01472515 -0.01280613 -0.04414540 0.049906881 ## S100A9 0.115414362 0.01895146 -0.02368853 -0.05787777 0.085382309 ## IGLL5 -0.007987473 0.05454239 0.04901533 0.06694722 0.004603231 ## GNLY -0.015238762 -0.13375626 0.04101340 0.06912322 0.104558611 ## FTL 0.118292572 0.01871142 -0.00984755 -0.01555269 0.038743505 head(Stdev(pbmc, reduction = "pca"))## [1] 7.098420 4.495493 3.872592 3.748859 3.171755 2.545292Seurat provides RunPCA() (pca), and RunTSNE() (tsne), and representing dimensional reduction techniques commonly applied to scRNA-seq data. When using these functions, all slots are filled automatically.We also allow users to add the results of a custom dimensional reduction technique (for example, multi-dimensional scaling (MDS), or zero-inflated factor analysis), that is computed separately. All you need is a matrix with each cell’s coordinates in low-dimensional space, as shown below.

To access these slots, we provide the Embeddings(),Loadings(), and Stdev() functions pbmc[["pca"]]## A dimensional reduction object with key PC_ ## Number of dimensions: 50 ## Projected dimensional reduction calculated: FALSE ## Jackstraw run: TRUE ## Computed using assay: RNA head(Embeddings(pbmc, reduction = "pca")[, 1:5])## PC_1 PC_2 PC_3 PC_4 PC_5 ## AAACATACAACCAC -4.7296855 -0.5184265 -0.7623220 -2.3156790 -0.07160006 ## AAACATTGAGCTAC -0.5174029 4.5918957 5.9091921 6.9118856 -1.96243034 ## AAACATTGATCAGC -3.1891063 -3.4695154 -0.8313710 -2.0019985 -5.10442765 ## AAACCGTGCTTCCG 12.7933021 0.1007166 0.6310221 -0.3687338 0.21838204 ## AAACCGTGTATGCG -3.1288078 -6.3481412 1.2507776 3.0191026 7.84739502 ## AAACGCACTGGTAC -3.1088963 0.9262125 -0.6482331 -2.3244378 -2.00526763 head(Loadings(pbmc, reduction = "pca")[, 1:5])## PC_1 PC_2 PC_3 PC_4 PC_5 ## PPBP 0.010990202 0.01148426 -0.15176092 0.10403737 0.003299077 ## LYZ 0.116231706 0.01472515 -0.01280613 -0.04414540 0.049906881 ## S100A9 0.115414362 0.01895146 -0.02368853 -0.05787777 0.085382309 ## IGLL5 -0.007987473 0.05454239 0.04901533 0.06694722 0.004603231 ## GNLY -0.015238762 -0.13375626 0.04101340 0.06912322 0.104558611 ## FTL 0.118292572 0.01871142 -0.00984755 -0.01555269 0.038743505 head(Stdev(pbmc, reduction = "pca"))## [1] 7.098420 4.495493 3.872592 3.748859 3.171755 2.545292Seurat provides RunPCA() (pca), and RunTSNE() (tsne), and representing dimensional reduction techniques commonly applied to scRNA-seq data. When using these functions, all slots are filled automatically.We also allow users to add the results of a custom dimensional reduction technique (for example, multi-dimensional scaling (MDS), or zero-inflated factor analysis), that is computed separately. All you need is a matrix with each cell’s coordinates in low-dimensional space, as shown below.

Seurat provides RunPCA() (pca), and RunTSNE() (tsne), and representing dimensional reduction techniques commonly applied to scRNA-seq data. When using these functions, all slots are filled automatically.We also allow users to add the results of a custom dimensional reduction technique (for example, multi-dimensional scaling (MDS), or zero-inflated factor analysis), that is computed separately. All you need is a matrix with each cell’s coordinates in low-dimensional space, as shown below.

We also allow users to add the results of a custom dimensional reduction technique (for example, multi-dimensional scaling (MDS), or zero-inflated factor analysis), that is computed separately. All you need is a matrix with each cell’s coordinates in low-dimensional space, as shown below.

Though not incorporated as part of the Seurat package, its easy to run multidimensional scaling (MDS) in R. If you were interested in running MDS and storing the output in your Seurat object: # Before running MDS, we first calculate a distance matrix between all pairs of cells. Here # we use a simple euclidean distance metric on all genes, using scale.data as input d <- dist(t(GetAssayData(pbmc, slot = "scale.data"))) # Run the MDS procedure, k determines the number of dimensions mds <- cmdscale(d = d, k = 2) # cmdscale returns the cell embeddings, we first label the columns to ensure downstream # consistency colnames(mds) <- paste0("MDS_", 1:2) # We will now store this as a custom dimensional reduction called 'mds' pbmc[["mds"]] <- CreateDimReducObject(embeddings = mds, key = "MDS_", assay = DefaultAssay(pbmc)) # We can now use this as you would any other dimensional reduction in all downstream functions DimPlot(pbmc, reduction = "mds", pt.size = 0.5) # If you wold like to observe genes that are strongly correlated with the first MDS coordinate pbmc <- ProjectDim(pbmc, reduction = "mds")## MDS_ 1 ## Positive: CST3, TYROBP, FCER1G, LST1, FTL, AIF1, FTH1, TYMP, FCN1, LYZ ## LGALS1, S100A9, CFD, CD68, SERPINA1, CTSS, IFITM3, SPI1, S100A8, LGALS2 ## Negative: MALAT1, RPS27A, RPS27, RPL3, RPL23A, RPL21, RPL13A, RPS6, RPS3A, RPS3 ## RPL9, LTB, RPSA, CD3D, RPS25, RPS18, PTPRCAP, RPS12, RPL30, RPL31 ## MDS_ 2 ## Positive: NKG7, PRF1, CST7, GZMA, GZMB, B2M, FGFBP2, CTSW, GNLY, HLA-C ## GZMH, SPON2, CD247, FCGR3A, CCL5, HLA-A, CCL4, GZMM, KLRD1, CLIC3 ## Negative: RPL32, RPL18A, HLA-DRA, CD79A, RPL13, MS4A1, RPL11, TCL1A, RPS9, RPL12 ## LINC00926, HLA-DQB1, HLA-DQA1, HLA-DRB1, RPL28, RPS2, S100A8, HLA-DMA, RPL8, RPLP1 # Display the results as a heatmap DimHeatmap(pbmc, reduction = "mds", dims = 1, cells = 500, projected = TRUE, balanced = TRUE) # Explore how the first MDS dimension is distributed across clusters VlnPlot(pbmc, features = "MDS_1") # See how the first MDS dimension is correlated with the first PC dimension FeatureScatter(pbmc, feature1 = "MDS_1", feature2 = "PC_1")Session Info sessionInfo()## R version 4.2.0 (2022-04-22) ## Platform: x86_64-pc-linux-gnu (64-bit) ## Running under: Ubuntu 20.04.5 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/liblapack.so.3 ## ## locale: ## [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C ## [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8 ## [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 ## ## attached base packages: ## [1] stats graphics grDevices utils datasets methods base ## ## other attached packages: ## [1] ggplot2_3.4.1 thp1.eccite.SeuratData_3.1.5 ## [3] stxBrain.SeuratData_0.1.1 ssHippo.SeuratData_3.1.4 ## [5] pbmcsca.SeuratData_3.0.0 pbmcMultiome.SeuratData_0.1.2 ## [7] pbmc3k.SeuratData_3.1.4 panc8.SeuratData_3.0.2 ## [9] ifnb.SeuratData_3.1.0 hcabm40k.SeuratData_3.0.0 ## [11] bmcite.SeuratData_0.3.0 SeuratData_0.2.2 ## [13] SeuratObject_4.1.3 Seurat_4.3.0 ## ## loaded via a namespace (and not attached): ## [1] systemfonts_1.0.4 plyr_1.8.8 igraph_1.4.1 ## [4] lazyeval_0.2.2 sp_1.6-0 splines_4.2.0 ## [7] listenv_0.9.0 scattermore_0.8 digest_0.6.31 ## [10] htmltools_0.5.4 fansi_1.0.4 magrittr_2.0.3 ## [13] memoise_2.0.1 tensor_1.5 cluster_2.1.3 ## [16] ROCR_1.0-11 globals_0.16.2 matrixStats_0.63.0 ## [19] pkgdown_2.0.7 spatstat.sparse_3.0-0 colorspace_2.1-0 ## [22] rappdirs_0.3.3 ggrepel_0.9.3 textshaping_0.3.6 ## [25] xfun_0.37 dplyr_1.1.0 crayon_1.5.2 ## [28] jsonlite_1.8.4 progressr_0.13.0 spatstat.data_3.0-0 ## [31] survival_3.3-1 zoo_1.8-11 glue_1.6.2 ## [34] polyclip_1.10-4 gtable_0.3.1 leiden_0.4.3 ## [37] future.apply_1.10.0 abind_1.4-5 scales_1.2.1 ## [40] spatstat.random_3.1-3 miniUI_0.1.1.1 Rcpp_1.0.10 ## [43] viridisLite_0.4.1 xtable_1.8-4 reticulate_1.28 ## [46] htmlwidgets_1.6.1 httr_1.4.5 RColorBrewer_1.1-3 ## [49] ellipsis_0.3.2 ica_1.0-3 farver_2.1.1 ## [52] pkgconfig_2.0.3 sass_0.4.5 uwot_0.1.14 ## [55] deldir_1.0-6 utf8_1.2.3 tidyselect_1.2.0 ## [58] labeling_0.4.2 rlang_1.0.6 reshape2_1.4.4 ## [61] later_1.3.0 munsell_0.5.0 tools_4.2.0 ## [64] cachem_1.0.7 cli_3.6.0 generics_0.1.3 ## [67] ggridges_0.5.4 evaluate_0.20 stringr_1.5.0 ## [70] fastmap_1.1.1 yaml_2.3.7 ragg_1.2.5 ## [73] goftest_1.2-3 knitr_1.42 fs_1.6.1 ## [76] fitdistrplus_1.1-8 purrr_1.0.1 RANN_2.6.1 ## [79] pbapply_1.7-0 future_1.31.0 nlme_3.1-157 ## [82] mime_0.12 formatR_1.14 compiler_4.2.0 ## [85] plotly_4.10.1 png_0.1-8 spatstat.utils_3.0-1 ## [88] tibble_3.1.8 bslib_0.4.2 stringi_1.7.12 ## [91] highr_0.10 desc_1.4.2 lattice_0.20-45 ## [94] Matrix_1.5-3 vctrs_0.5.2 pillar_1.8.1 ## [97] lifecycle_1.0.3 spatstat.geom_3.0-6 lmtest_0.9-40 ## [100] jquerylib_0.1.4 RcppAnnoy_0.0.20 data.table_1.14.8 ## [103] cowplot_1.1.1 irlba_2.3.5.1 httpuv_1.6.9 ## [106] patchwork_1.1.2 R6_2.5.1 promises_1.2.0.1 ## [109] KernSmooth_2.23-20 gridExtra_2.3 parallelly_1.34.0 ## [112] codetools_0.2-18 MASS_7.3-56 rprojroot_2.0.3 ## [115] withr_2.5.0 sctransform_0.3.5 parallel_4.2.0 ## [118] grid_4.2.0 tidyr_1.3.0 rmarkdown_2.20 ## [121] Rtsne_0.16 spatstat.explore_3.0-6 shiny_1.7.4

# If you wold like to observe genes that are strongly correlated with the first MDS coordinate pbmc <- ProjectDim(pbmc, reduction = "mds")## MDS_ 1 ## Positive: CST3, TYROBP, FCER1G, LST1, FTL, AIF1, FTH1, TYMP, FCN1, LYZ ## LGALS1, S100A9, CFD, CD68, SERPINA1, CTSS, IFITM3, SPI1, S100A8, LGALS2 ## Negative: MALAT1, RPS27A, RPS27, RPL3, RPL23A, RPL21, RPL13A, RPS6, RPS3A, RPS3 ## RPL9, LTB, RPSA, CD3D, RPS25, RPS18, PTPRCAP, RPS12, RPL30, RPL31 ## MDS_ 2 ## Positive: NKG7, PRF1, CST7, GZMA, GZMB, B2M, FGFBP2, CTSW, GNLY, HLA-C ## GZMH, SPON2, CD247, FCGR3A, CCL5, HLA-A, CCL4, GZMM, KLRD1, CLIC3 ## Negative: RPL32, RPL18A, HLA-DRA, CD79A, RPL13, MS4A1, RPL11, TCL1A, RPS9, RPL12 ## LINC00926, HLA-DQB1, HLA-DQA1, HLA-DRB1, RPL28, RPS2, S100A8, HLA-DMA, RPL8, RPLP1 # Display the results as a heatmap DimHeatmap(pbmc, reduction = "mds", dims = 1, cells = 500, projected = TRUE, balanced = TRUE) # Explore how the first MDS dimension is distributed across clusters VlnPlot(pbmc, features = "MDS_1") # See how the first MDS dimension is correlated with the first PC dimension FeatureScatter(pbmc, feature1 = "MDS_1", feature2 = "PC_1")Session Info sessionInfo()## R version 4.2.0 (2022-04-22) ## Platform: x86_64-pc-linux-gnu (64-bit) ## Running under: Ubuntu 20.04.5 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/liblapack.so.3 ## ## locale: ## [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C ## [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8 ## [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 ## ## attached base packages: ## [1] stats graphics grDevices utils datasets methods base ## ## other attached packages: ## [1] ggplot2_3.4.1 thp1.eccite.SeuratData_3.1.5 ## [3] stxBrain.SeuratData_0.1.1 ssHippo.SeuratData_3.1.4 ## [5] pbmcsca.SeuratData_3.0.0 pbmcMultiome.SeuratData_0.1.2 ## [7] pbmc3k.SeuratData_3.1.4 panc8.SeuratData_3.0.2 ## [9] ifnb.SeuratData_3.1.0 hcabm40k.SeuratData_3.0.0 ## [11] bmcite.SeuratData_0.3.0 SeuratData_0.2.2 ## [13] SeuratObject_4.1.3 Seurat_4.3.0 ## ## loaded via a namespace (and not attached): ## [1] systemfonts_1.0.4 plyr_1.8.8 igraph_1.4.1 ## [4] lazyeval_0.2.2 sp_1.6-0 splines_4.2.0 ## [7] listenv_0.9.0 scattermore_0.8 digest_0.6.31 ## [10] htmltools_0.5.4 fansi_1.0.4 magrittr_2.0.3 ## [13] memoise_2.0.1 tensor_1.5 cluster_2.1.3 ## [16] ROCR_1.0-11 globals_0.16.2 matrixStats_0.63.0 ## [19] pkgdown_2.0.7 spatstat.sparse_3.0-0 colorspace_2.1-0 ## [22] rappdirs_0.3.3 ggrepel_0.9.3 textshaping_0.3.6 ## [25] xfun_0.37 dplyr_1.1.0 crayon_1.5.2 ## [28] jsonlite_1.8.4 progressr_0.13.0 spatstat.data_3.0-0 ## [31] survival_3.3-1 zoo_1.8-11 glue_1.6.2 ## [34] polyclip_1.10-4 gtable_0.3.1 leiden_0.4.3 ## [37] future.apply_1.10.0 abind_1.4-5 scales_1.2.1 ## [40] spatstat.random_3.1-3 miniUI_0.1.1.1 Rcpp_1.0.10 ## [43] viridisLite_0.4.1 xtable_1.8-4 reticulate_1.28 ## [46] htmlwidgets_1.6.1 httr_1.4.5 RColorBrewer_1.1-3 ## [49] ellipsis_0.3.2 ica_1.0-3 farver_2.1.1 ## [52] pkgconfig_2.0.3 sass_0.4.5 uwot_0.1.14 ## [55] deldir_1.0-6 utf8_1.2.3 tidyselect_1.2.0 ## [58] labeling_0.4.2 rlang_1.0.6 reshape2_1.4.4 ## [61] later_1.3.0 munsell_0.5.0 tools_4.2.0 ## [64] cachem_1.0.7 cli_3.6.0 generics_0.1.3 ## [67] ggridges_0.5.4 evaluate_0.20 stringr_1.5.0 ## [70] fastmap_1.1.1 yaml_2.3.7 ragg_1.2.5 ## [73] goftest_1.2-3 knitr_1.42 fs_1.6.1 ## [76] fitdistrplus_1.1-8 purrr_1.0.1 RANN_2.6.1 ## [79] pbapply_1.7-0 future_1.31.0 nlme_3.1-157 ## [82] mime_0.12 formatR_1.14 compiler_4.2.0 ## [85] plotly_4.10.1 png_0.1-8 spatstat.utils_3.0-1 ## [88] tibble_3.1.8 bslib_0.4.2 stringi_1.7.12 ## [91] highr_0.10 desc_1.4.2 lattice_0.20-45 ## [94] Matrix_1.5-3 vctrs_0.5.2 pillar_1.8.1 ## [97] lifecycle_1.0.3 spatstat.geom_3.0-6 lmtest_0.9-40 ## [100] jquerylib_0.1.4 RcppAnnoy_0.0.20 data.table_1.14.8 ## [103] cowplot_1.1.1 irlba_2.3.5.1 httpuv_1.6.9 ## [106] patchwork_1.1.2 R6_2.5.1 promises_1.2.0.1 ## [109] KernSmooth_2.23-20 gridExtra_2.3 parallelly_1.34.0 ## [112] codetools_0.2-18 MASS_7.3-56 rprojroot_2.0.3 ## [115] withr_2.5.0 sctransform_0.3.5 parallel_4.2.0 ## [118] grid_4.2.0 tidyr_1.3.0 rmarkdown_2.20 ## [121] Rtsne_0.16 spatstat.explore_3.0-6 shiny_1.7.4

# Explore how the first MDS dimension is distributed across clusters VlnPlot(pbmc, features = "MDS_1") # See how the first MDS dimension is correlated with the first PC dimension FeatureScatter(pbmc, feature1 = "MDS_1", feature2 = "PC_1")Session Info sessionInfo()## R version 4.2.0 (2022-04-22) ## Platform: x86_64-pc-linux-gnu (64-bit) ## Running under: Ubuntu 20.04.5 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/liblapack.so.3 ## ## locale: ## [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C ## [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8 ## [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 ## ## attached base packages: ## [1] stats graphics grDevices utils datasets methods base ## ## other attached packages: ## [1] ggplot2_3.4.1 thp1.eccite.SeuratData_3.1.5 ## [3] stxBrain.SeuratData_0.1.1 ssHippo.SeuratData_3.1.4 ## [5] pbmcsca.SeuratData_3.0.0 pbmcMultiome.SeuratData_0.1.2 ## [7] pbmc3k.SeuratData_3.1.4 panc8.SeuratData_3.0.2 ## [9] ifnb.SeuratData_3.1.0 hcabm40k.SeuratData_3.0.0 ## [11] bmcite.SeuratData_0.3.0 SeuratData_0.2.2 ## [13] SeuratObject_4.1.3 Seurat_4.3.0 ## ## loaded via a namespace (and not attached): ## [1] systemfonts_1.0.4 plyr_1.8.8 igraph_1.4.1 ## [4] lazyeval_0.2.2 sp_1.6-0 splines_4.2.0 ## [7] listenv_0.9.0 scattermore_0.8 digest_0.6.31 ## [10] htmltools_0.5.4 fansi_1.0.4 magrittr_2.0.3 ## [13] memoise_2.0.1 tensor_1.5 cluster_2.1.3 ## [16] ROCR_1.0-11 globals_0.16.2 matrixStats_0.63.0 ## [19] pkgdown_2.0.7 spatstat.sparse_3.0-0 colorspace_2.1-0 ## [22] rappdirs_0.3.3 ggrepel_0.9.3 textshaping_0.3.6 ## [25] xfun_0.37 dplyr_1.1.0 crayon_1.5.2 ## [28] jsonlite_1.8.4 progressr_0.13.0 spatstat.data_3.0-0 ## [31] survival_3.3-1 zoo_1.8-11 glue_1.6.2 ## [34] polyclip_1.10-4 gtable_0.3.1 leiden_0.4.3 ## [37] future.apply_1.10.0 abind_1.4-5 scales_1.2.1 ## [40] spatstat.random_3.1-3 miniUI_0.1.1.1 Rcpp_1.0.10 ## [43] viridisLite_0.4.1 xtable_1.8-4 reticulate_1.28 ## [46] htmlwidgets_1.6.1 httr_1.4.5 RColorBrewer_1.1-3 ## [49] ellipsis_0.3.2 ica_1.0-3 farver_2.1.1 ## [52] pkgconfig_2.0.3 sass_0.4.5 uwot_0.1.14 ## [55] deldir_1.0-6 utf8_1.2.3 tidyselect_1.2.0 ## [58] labeling_0.4.2 rlang_1.0.6 reshape2_1.4.4 ## [61] later_1.3.0 munsell_0.5.0 tools_4.2.0 ## [64] cachem_1.0.7 cli_3.6.0 generics_0.1.3 ## [67] ggridges_0.5.4 evaluate_0.20 stringr_1.5.0 ## [70] fastmap_1.1.1 yaml_2.3.7 ragg_1.2.5 ## [73] goftest_1.2-3 knitr_1.42 fs_1.6.1 ## [76] fitdistrplus_1.1-8 purrr_1.0.1 RANN_2.6.1 ## [79] pbapply_1.7-0 future_1.31.0 nlme_3.1-157 ## [82] mime_0.12 formatR_1.14 compiler_4.2.0 ## [85] plotly_4.10.1 png_0.1-8 spatstat.utils_3.0-1 ## [88] tibble_3.1.8 bslib_0.4.2 stringi_1.7.12 ## [91] highr_0.10 desc_1.4.2 lattice_0.20-45 ## [94] Matrix_1.5-3 vctrs_0.5.2 pillar_1.8.1 ## [97] lifecycle_1.0.3 spatstat.geom_3.0-6 lmtest_0.9-40 ## [100] jquerylib_0.1.4 RcppAnnoy_0.0.20 data.table_1.14.8 ## [103] cowplot_1.1.1 irlba_2.3.5.1 httpuv_1.6.9 ## [106] patchwork_1.1.2 R6_2.5.1 promises_1.2.0.1 ## [109] KernSmooth_2.23-20 gridExtra_2.3 parallelly_1.34.0 ## [112] codetools_0.2-18 MASS_7.3-56 rprojroot_2.0.3 ## [115] withr_2.5.0 sctransform_0.3.5 parallel_4.2.0 ## [118] grid_4.2.0 tidyr_1.3.0 rmarkdown_2.20 ## [121] Rtsne_0.16 spatstat.explore_3.0-6 shiny_1.7.4

# See how the first MDS dimension is correlated with the first PC dimension FeatureScatter(pbmc, feature1 = "MDS_1", feature2 = "PC_1")Session Info sessionInfo()## R version 4.2.0 (2022-04-22) ## Platform: x86_64-pc-linux-gnu (64-bit) ## Running under: Ubuntu 20.04.5 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/liblapack.so.3 ## ## locale: ## [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C ## [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8 ## [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 ## ## attached base packages: ## [1] stats graphics grDevices utils datasets methods base ## ## other attached packages: ## [1] ggplot2_3.4.1 thp1.eccite.SeuratData_3.1.5 ## [3] stxBrain.SeuratData_0.1.1 ssHippo.SeuratData_3.1.4 ## [5] pbmcsca.SeuratData_3.0.0 pbmcMultiome.SeuratData_0.1.2 ## [7] pbmc3k.SeuratData_3.1.4 panc8.SeuratData_3.0.2 ## [9] ifnb.SeuratData_3.1.0 hcabm40k.SeuratData_3.0.0 ## [11] bmcite.SeuratData_0.3.0 SeuratData_0.2.2 ## [13] SeuratObject_4.1.3 Seurat_4.3.0 ## ## loaded via a namespace (and not attached): ## [1] systemfonts_1.0.4 plyr_1.8.8 igraph_1.4.1 ## [4] lazyeval_0.2.2 sp_1.6-0 splines_4.2.0 ## [7] listenv_0.9.0 scattermore_0.8 digest_0.6.31 ## [10] htmltools_0.5.4 fansi_1.0.4 magrittr_2.0.3 ## [13] memoise_2.0.1 tensor_1.5 cluster_2.1.3 ## [16] ROCR_1.0-11 globals_0.16.2 matrixStats_0.63.0 ## [19] pkgdown_2.0.7 spatstat.sparse_3.0-0 colorspace_2.1-0 ## [22] rappdirs_0.3.3 ggrepel_0.9.3 textshaping_0.3.6 ## [25] xfun_0.37 dplyr_1.1.0 crayon_1.5.2 ## [28] jsonlite_1.8.4 progressr_0.13.0 spatstat.data_3.0-0 ## [31] survival_3.3-1 zoo_1.8-11 glue_1.6.2 ## [34] polyclip_1.10-4 gtable_0.3.1 leiden_0.4.3 ## [37] future.apply_1.10.0 abind_1.4-5 scales_1.2.1 ## [40] spatstat.random_3.1-3 miniUI_0.1.1.1 Rcpp_1.0.10 ## [43] viridisLite_0.4.1 xtable_1.8-4 reticulate_1.28 ## [46] htmlwidgets_1.6.1 httr_1.4.5 RColorBrewer_1.1-3 ## [49] ellipsis_0.3.2 ica_1.0-3 farver_2.1.1 ## [52] pkgconfig_2.0.3 sass_0.4.5 uwot_0.1.14 ## [55] deldir_1.0-6 utf8_1.2.3 tidyselect_1.2.0 ## [58] labeling_0.4.2 rlang_1.0.6 reshape2_1.4.4 ## [61] later_1.3.0 munsell_0.5.0 tools_4.2.0 ## [64] cachem_1.0.7 cli_3.6.0 generics_0.1.3 ## [67] ggridges_0.5.4 evaluate_0.20 stringr_1.5.0 ## [70] fastmap_1.1.1 yaml_2.3.7 ragg_1.2.5 ## [73] goftest_1.2-3 knitr_1.42 fs_1.6.1 ## [76] fitdistrplus_1.1-8 purrr_1.0.1 RANN_2.6.1 ## [79] pbapply_1.7-0 future_1.31.0 nlme_3.1-157 ## [82] mime_0.12 formatR_1.14 compiler_4.2.0 ## [85] plotly_4.10.1 png_0.1-8 spatstat.utils_3.0-1 ## [88] tibble_3.1.8 bslib_0.4.2 stringi_1.7.12 ## [91] highr_0.10 desc_1.4.2 lattice_0.20-45 ## [94] Matrix_1.5-3 vctrs_0.5.2 pillar_1.8.1 ## [97] lifecycle_1.0.3 spatstat.geom_3.0-6 lmtest_0.9-40 ## [100] jquerylib_0.1.4 RcppAnnoy_0.0.20 data.table_1.14.8 ## [103] cowplot_1.1.1 irlba_2.3.5.1 httpuv_1.6.9 ## [106] patchwork_1.1.2 R6_2.5.1 promises_1.2.0.1 ## [109] KernSmooth_2.23-20 gridExtra_2.3 parallelly_1.34.0 ## [112] codetools_0.2-18 MASS_7.3-56 rprojroot_2.0.3 ## [115] withr_2.5.0 sctransform_0.3.5 parallel_4.2.0 ## [118] grid_4.2.0 tidyr_1.3.0 rmarkdown_2.20 ## [121] Rtsne_0.16 spatstat.explore_3.0-6 shiny_1.7.4

Session Info sessionInfo()## R version 4.2.0 (2022-04-22) ## Platform: x86_64-pc-linux-gnu (64-bit) ## Running under: Ubuntu 20.04.5 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/liblapack.so.3 ## ## locale: ## [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C ## [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8 ## [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 ## ## attached base packages: ## [1] stats graphics grDevices utils datasets methods base ## ## other attached packages: ## [1] ggplot2_3.4.1 thp1.eccite.SeuratData_3.1.5 ## [3] stxBrain.SeuratData_0.1.1 ssHippo.SeuratData_3.1.4 ## [5] pbmcsca.SeuratData_3.0.0 pbmcMultiome.SeuratData_0.1.2 ## [7] pbmc3k.SeuratData_3.1.4 panc8.SeuratData_3.0.2 ## [9] ifnb.SeuratData_3.1.0 hcabm40k.SeuratData_3.0.0 ## [11] bmcite.SeuratData_0.3.0 SeuratData_0.2.2 ## [13] SeuratObject_4.1.3 Seurat_4.3.0 ## ## loaded via a namespace (and not attached): ## [1] systemfonts_1.0.4 plyr_1.8.8 igraph_1.4.1 ## [4] lazyeval_0.2.2 sp_1.6-0 splines_4.2.0 ## [7] listenv_0.9.0 scattermore_0.8 digest_0.6.31 ## [10] htmltools_0.5.4 fansi_1.0.4 magrittr_2.0.3 ## [13] memoise_2.0.1 tensor_1.5 cluster_2.1.3 ## [16] ROCR_1.0-11 globals_0.16.2 matrixStats_0.63.0 ## [19] pkgdown_2.0.7 spatstat.sparse_3.0-0 colorspace_2.1-0 ## [22] rappdirs_0.3.3 ggrepel_0.9.3 textshaping_0.3.6 ## [25] xfun_0.37 dplyr_1.1.0 crayon_1.5.2 ## [28] jsonlite_1.8.4 progressr_0.13.0 spatstat.data_3.0-0 ## [31] survival_3.3-1 zoo_1.8-11 glue_1.6.2 ## [34] polyclip_1.10-4 gtable_0.3.1 leiden_0.4.3 ## [37] future.apply_1.10.0 abind_1.4-5 scales_1.2.1 ## [40] spatstat.random_3.1-3 miniUI_0.1.1.1 Rcpp_1.0.10 ## [43] viridisLite_0.4.1 xtable_1.8-4 reticulate_1.28 ## [46] htmlwidgets_1.6.1 httr_1.4.5 RColorBrewer_1.1-3 ## [49] ellipsis_0.3.2 ica_1.0-3 farver_2.1.1 ## [52] pkgconfig_2.0.3 sass_0.4.5 uwot_0.1.14 ## [55] deldir_1.0-6 utf8_1.2.3 tidyselect_1.2.0 ## [58] labeling_0.4.2 rlang_1.0.6 reshape2_1.4.4 ## [61] later_1.3.0 munsell_0.5.0 tools_4.2.0 ## [64] cachem_1.0.7 cli_3.6.0 generics_0.1.3 ## [67] ggridges_0.5.4 evaluate_0.20 stringr_1.5.0 ## [70] fastmap_1.1.1 yaml_2.3.7 ragg_1.2.5 ## [73] goftest_1.2-3 knitr_1.42 fs_1.6.1 ## [76] fitdistrplus_1.1-8 purrr_1.0.1 RANN_2.6.1 ## [79] pbapply_1.7-0 future_1.31.0 nlme_3.1-157 ## [82] mime_0.12 formatR_1.14 compiler_4.2.0 ## [85] plotly_4.10.1 png_0.1-8 spatstat.utils_3.0-1 ## [88] tibble_3.1.8 bslib_0.4.2 stringi_1.7.12 ## [91] highr_0.10 desc_1.4.2 lattice_0.20-45 ## [94] Matrix_1.5-3 vctrs_0.5.2 pillar_1.8.1 ## [97] lifecycle_1.0.3 spatstat.geom_3.0-6 lmtest_0.9-40 ## [100] jquerylib_0.1.4 RcppAnnoy_0.0.20 data.table_1.14.8 ## [103] cowplot_1.1.1 irlba_2.3.5.1 httpuv_1.6.9 ## [106] patchwork_1.1.2 R6_2.5.1 promises_1.2.0.1 ## [109] KernSmooth_2.23-20 gridExtra_2.3 parallelly_1.34.0 ## [112] codetools_0.2-18 MASS_7.3-56 rprojroot_2.0.3 ## [115] withr_2.5.0 sctransform_0.3.5 parallel_4.2.0 ## [118] grid_4.2.0 tidyr_1.3.0 rmarkdown_2.20 ## [121] Rtsne_0.16 spatstat.explore_3.0-6 shiny_1.7.4

sessionInfo()## R version 4.2.0 (2022-04-22) ## Platform: x86_64-pc-linux-gnu (64-bit) ## Running under: Ubuntu 20.04.5 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/liblapack.so.3 ## ## locale: ## [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C ## [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8 ## [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 ## ## attached base packages: ## [1] stats graphics grDevices utils datasets methods base ## ## other attached packages: ## [1] ggplot2_3.4.1 thp1.eccite.SeuratData_3.1.5 ## [3] stxBrain.SeuratData_0.1.1 ssHippo.SeuratData_3.1.4 ## [5] pbmcsca.SeuratData_3.0.0 pbmcMultiome.SeuratData_0.1.2 ## [7] pbmc3k.SeuratData_3.1.4 panc8.SeuratData_3.0.2 ## [9] ifnb.SeuratData_3.1.0 hcabm40k.SeuratData_3.0.0 ## [11] bmcite.SeuratData_0.3.0 SeuratData_0.2.2 ## [13] SeuratObject_4.1.3 Seurat_4.3.0 ## ## loaded via a namespace (and not attached): ## [1] systemfonts_1.0.4 plyr_1.8.8 igraph_1.4.1 ## [4] lazyeval_0.2.2 sp_1.6-0 splines_4.2.0 ## [7] listenv_0.9.0 scattermore_0.8 digest_0.6.31 ## [10] htmltools_0.5.4 fansi_1.0.4 magrittr_2.0.3 ## [13] memoise_2.0.1 tensor_1.5 cluster_2.1.3 ## [16] ROCR_1.0-11 globals_0.16.2 matrixStats_0.63.0 ## [19] pkgdown_2.0.7 spatstat.sparse_3.0-0 colorspace_2.1-0 ## [22] rappdirs_0.3.3 ggrepel_0.9.3 textshaping_0.3.6 ## [25] xfun_0.37 dplyr_1.1.0 crayon_1.5.2 ## [28] jsonlite_1.8.4 progressr_0.13.0 spatstat.data_3.0-0 ## [31] survival_3.3-1 zoo_1.8-11 glue_1.6.2 ## [34] polyclip_1.10-4 gtable_0.3.1 leiden_0.4.3 ## [37] future.apply_1.10.0 abind_1.4-5 scales_1.2.1 ## [40] spatstat.random_3.1-3 miniUI_0.1.1.1 Rcpp_1.0.10 ## [43] viridisLite_0.4.1 xtable_1.8-4 reticulate_1.28 ## [46] htmlwidgets_1.6.1 httr_1.4.5 RColorBrewer_1.1-3 ## [49] ellipsis_0.3.2 ica_1.0-3 farver_2.1.1 ## [52] pkgconfig_2.0.3 sass_0.4.5 uwot_0.1.14 ## [55] deldir_1.0-6 utf8_1.2.3 tidyselect_1.2.0 ## [58] labeling_0.4.2 rlang_1.0.6 reshape2_1.4.4 ## [61] later_1.3.0 munsell_0.5.0 tools_4.2.0 ## [64] cachem_1.0.7 cli_3.6.0 generics_0.1.3 ## [67] ggridges_0.5.4 evaluate_0.20 stringr_1.5.0 ## [70] fastmap_1.1.1 yaml_2.3.7 ragg_1.2.5 ## [73] goftest_1.2-3 knitr_1.42 fs_1.6.1 ## [76] fitdistrplus_1.1-8 purrr_1.0.1 RANN_2.6.1 ## [79] pbapply_1.7-0 future_1.31.0 nlme_3.1-157 ## [82] mime_0.12 formatR_1.14 compiler_4.2.0 ## [85] plotly_4.10.1 png_0.1-8 spatstat.utils_3.0-1 ## [88] tibble_3.1.8 bslib_0.4.2 stringi_1.7.12 ## [91] highr_0.10 desc_1.4.2 lattice_0.20-45 ## [94] Matrix_1.5-3 vctrs_0.5.2 pillar_1.8.1 ## [97] lifecycle_1.0.3 spatstat.geom_3.0-6 lmtest_0.9-40 ## [100] jquerylib_0.1.4 RcppAnnoy_0.0.20 data.table_1.14.8 ## [103] cowplot_1.1.1 irlba_2.3.5.1 httpuv_1.6.9 ## [106] patchwork_1.1.2 R6_2.5.1 promises_1.2.0.1 ## [109] KernSmooth_2.23-20 gridExtra_2.3 parallelly_1.34.0 ## [112] codetools_0.2-18 MASS_7.3-56 rprojroot_2.0.3 ## [115] withr_2.5.0 sctransform_0.3.5 parallel_4.2.0 ## [118] grid_4.2.0 tidyr_1.3.0 rmarkdown_2.20 ## [121] Rtsne_0.16 spatstat.explore_3.0-6 shiny_1.7.4

Developed by Paul Hoffman, Satija Lab and Collaborators.

Developed by Paul Hoffman, Satija Lab and Collaborators.

Site built with pkgdown 2.0.7.

Site built with pkgdown 2.0.7.

**Examples:**

Example 1 (unknown):
```unknown
vignettes/dim_reduction_vignette.Rmd
```

Example 2 (unknown):
```unknown
dim_reduction_vignette.Rmd
```

Example 3 (unknown):
```unknown
library(Seurat)
library(SeuratData)
pbmc <- LoadData("pbmc3k", type = "pbmc3k.final")
```

Example 4 (r):
```r
library(Seurat)
library(SeuratData)
pbmc <- LoadData("pbmc3k", type = "pbmc3k.final")
```

Example 5 (r):
```r
library(Seurat)
library(SeuratData)
pbmc <- LoadData("pbmc3k", type = "pbmc3k.final")
```

Example 6 (unknown):
```unknown
object@reductions
```

Example 7 (unknown):
```unknown
object[['pca']]
```

Example 8 (unknown):
```unknown
ProjectDim()
```

Example 9 (unknown):
```unknown
Embeddings()
```

Example 10 (unknown):
```unknown
pbmc[["pca"]]
```

Example 11 (r):
```r
pbmc[["pca"]]
```

Example 12 (r):
```r
pbmc[["pca"]]
```

Example 13 (unknown):
```unknown
## A dimensional reduction object with key PC_ 
##  Number of dimensions: 50 
##  Projected dimensional reduction calculated:  FALSE 
##  Jackstraw run: TRUE 
##  Computed using assay: RNA
```

Example 14 (unknown):
```unknown
## A dimensional reduction object with key PC_ 
##  Number of dimensions: 50 
##  Projected dimensional reduction calculated:  FALSE 
##  Jackstraw run: TRUE 
##  Computed using assay: RNA
```

Example 15 (unknown):
```unknown
head(Embeddings(pbmc, reduction = "pca")[, 1:5])
```

Example 16 (r):
```r
head(Embeddings(pbmc, reduction = "pca")[, 1:5])
```

Example 17 (r):
```r
head(Embeddings(pbmc, reduction = "pca")[, 1:5])
```

Example 18 (unknown):
```unknown
##                      PC_1       PC_2       PC_3       PC_4        PC_5
## AAACATACAACCAC -4.7296855 -0.5184265 -0.7623220 -2.3156790 -0.07160006
## AAACATTGAGCTAC -0.5174029  4.5918957  5.9091921  6.9118856 -1.96243034
## AAACATTGATCAGC -3.1891063 -3.4695154 -0.8313710 -2.0019985 -5.10442765
## AAACCGTGCTTCCG 12.7933021  0.1007166  0.6310221 -0.3687338  0.21838204
## AAACCGTGTATGCG -3.1288078 -6.3481412  1.2507776  3.0191026  7.84739502
## AAACGCACTGGTAC -3.1088963  0.9262125 -0.6482331 -2.3244378 -2.00526763
```

Example 19 (unknown):
```unknown
##                      PC_1       PC_2       PC_3       PC_4        PC_5
## AAACATACAACCAC -4.7296855 -0.5184265 -0.7623220 -2.3156790 -0.07160006
## AAACATTGAGCTAC -0.5174029  4.5918957  5.9091921  6.9118856 -1.96243034
## AAACATTGATCAGC -3.1891063 -3.4695154 -0.8313710 -2.0019985 -5.10442765
## AAACCGTGCTTCCG 12.7933021  0.1007166  0.6310221 -0.3687338  0.21838204
## AAACCGTGTATGCG -3.1288078 -6.3481412  1.2507776  3.0191026  7.84739502
## AAACGCACTGGTAC -3.1088963  0.9262125 -0.6482331 -2.3244378 -2.00526763
```

Example 20 (unknown):
```unknown
head(Loadings(pbmc, reduction = "pca")[, 1:5])
```

Example 21 (r):
```r
head(Loadings(pbmc, reduction = "pca")[, 1:5])
```

Example 22 (r):
```r
head(Loadings(pbmc, reduction = "pca")[, 1:5])
```

Example 23 (unknown):
```unknown
##                PC_1        PC_2        PC_3        PC_4        PC_5
## PPBP    0.010990202  0.01148426 -0.15176092  0.10403737 0.003299077
## LYZ     0.116231706  0.01472515 -0.01280613 -0.04414540 0.049906881
## S100A9  0.115414362  0.01895146 -0.02368853 -0.05787777 0.085382309
## IGLL5  -0.007987473  0.05454239  0.04901533  0.06694722 0.004603231
## GNLY   -0.015238762 -0.13375626  0.04101340  0.06912322 0.104558611
## FTL     0.118292572  0.01871142 -0.00984755 -0.01555269 0.038743505
```

Example 24 (unknown):
```unknown
##                PC_1        PC_2        PC_3        PC_4        PC_5
## PPBP    0.010990202  0.01148426 -0.15176092  0.10403737 0.003299077
## LYZ     0.116231706  0.01472515 -0.01280613 -0.04414540 0.049906881
## S100A9  0.115414362  0.01895146 -0.02368853 -0.05787777 0.085382309
## IGLL5  -0.007987473  0.05454239  0.04901533  0.06694722 0.004603231
## GNLY   -0.015238762 -0.13375626  0.04101340  0.06912322 0.104558611
## FTL     0.118292572  0.01871142 -0.00984755 -0.01555269 0.038743505
```

Example 25 (unknown):
```unknown
head(Stdev(pbmc, reduction = "pca"))
```

Example 26 (r):
```r
head(Stdev(pbmc, reduction = "pca"))
```

Example 27 (r):
```r
head(Stdev(pbmc, reduction = "pca"))
```

Example 28 (unknown):
```unknown
## [1] 7.098420 4.495493 3.872592 3.748859 3.171755 2.545292
```

Example 29 (unknown):
```unknown
## [1] 7.098420 4.495493 3.872592 3.748859 3.171755 2.545292
```

Example 30 (unknown):
```unknown
# Before running MDS, we first calculate a distance matrix between all pairs of cells.  Here
# we use a simple euclidean distance metric on all genes, using scale.data as input
d <- dist(t(GetAssayData(pbmc, slot = "scale.data")))
# Run the MDS procedure, k determines the number of dimensions
mds <- cmdscale(d = d, k = 2)
# cmdscale returns the cell embeddings, we first label the columns to ensure downstream
# consistency
colnames(mds) <- paste0("MDS_", 1:2)
# We will now store this as a custom dimensional reduction called 'mds'
pbmc[["mds"]] <- CreateDimReducObject(embeddings = mds, key = "MDS_", assay = DefaultAssay(pbmc))

# We can now use this as you would any other dimensional reduction in all downstream functions
DimPlot(pbmc, reduction = "mds", pt.size = 0.5)
```

Example 31 (r):
```r
# Before running MDS, we first calculate a distance matrix between all pairs of cells.  Here
# we use a simple euclidean distance metric on all genes, using scale.data as input
d <- dist(t(GetAssayData(pbmc, slot = "scale.data")))
# Run the MDS procedure, k determines the number of dimensions
mds <- cmdscale(d = d, k = 2)
# cmdscale returns the cell embeddings, we first label the columns to ensure downstream
# consistency
colnames(mds) <- paste0("MDS_", 1:2)
# We will now store this as a custom dimensional reduction called 'mds'
pbmc[["mds"]] <- CreateDimReducObject(embeddings = mds, key = "MDS_", assay = DefaultAssay(pbmc))

# We can now use this as you would any other dimensional reduction in all downstream functions
DimPlot(pbmc, reduction = "mds", pt.size = 0.5)
```

Example 32 (r):
```r
# Before running MDS, we first calculate a distance matrix between all pairs of cells.  Here
# we use a simple euclidean distance metric on all genes, using scale.data as input
d <- dist(t(GetAssayData(pbmc, slot = "scale.data")))
# Run the MDS procedure, k determines the number of dimensions
mds <- cmdscale(d = d, k = 2)
# cmdscale returns the cell embeddings, we first label the columns to ensure downstream
# consistency
colnames(mds) <- paste0("MDS_", 1:2)
# We will now store this as a custom dimensional reduction called 'mds'
pbmc[["mds"]] <- CreateDimReducObject(embeddings = mds, key = "MDS_", assay = DefaultAssay(pbmc))

# We can now use this as you would any other dimensional reduction in all downstream functions
DimPlot(pbmc, reduction = "mds", pt.size = 0.5)
```

Example 33 (unknown):
```unknown
# If you wold like to observe genes that are strongly correlated with the first MDS coordinate
pbmc <- ProjectDim(pbmc, reduction = "mds")
```

Example 34 (r):
```r
# If you wold like to observe genes that are strongly correlated with the first MDS coordinate
pbmc <- ProjectDim(pbmc, reduction = "mds")
```

Example 35 (r):
```r
# If you wold like to observe genes that are strongly correlated with the first MDS coordinate
pbmc <- ProjectDim(pbmc, reduction = "mds")
```

Example 36 (unknown):
```unknown
## MDS_ 1 
## Positive:  CST3, TYROBP, FCER1G, LST1, FTL, AIF1, FTH1, TYMP, FCN1, LYZ 
##     LGALS1, S100A9, CFD, CD68, SERPINA1, CTSS, IFITM3, SPI1, S100A8, LGALS2 
## Negative:  MALAT1, RPS27A, RPS27, RPL3, RPL23A, RPL21, RPL13A, RPS6, RPS3A, RPS3 
##     RPL9, LTB, RPSA, CD3D, RPS25, RPS18, PTPRCAP, RPS12, RPL30, RPL31 
## MDS_ 2 
## Positive:  NKG7, PRF1, CST7, GZMA, GZMB, B2M, FGFBP2, CTSW, GNLY, HLA-C 
##     GZMH, SPON2, CD247, FCGR3A, CCL5, HLA-A, CCL4, GZMM, KLRD1, CLIC3 
## Negative:  RPL32, RPL18A, HLA-DRA, CD79A, RPL13, MS4A1, RPL11, TCL1A, RPS9, RPL12 
##     LINC00926, HLA-DQB1, HLA-DQA1, HLA-DRB1, RPL28, RPS2, S100A8, HLA-DMA, RPL8, RPLP1
```

Example 37 (unknown):
```unknown
## MDS_ 1 
## Positive:  CST3, TYROBP, FCER1G, LST1, FTL, AIF1, FTH1, TYMP, FCN1, LYZ 
##     LGALS1, S100A9, CFD, CD68, SERPINA1, CTSS, IFITM3, SPI1, S100A8, LGALS2 
## Negative:  MALAT1, RPS27A, RPS27, RPL3, RPL23A, RPL21, RPL13A, RPS6, RPS3A, RPS3 
##     RPL9, LTB, RPSA, CD3D, RPS25, RPS18, PTPRCAP, RPS12, RPL30, RPL31 
## MDS_ 2 
## Positive:  NKG7, PRF1, CST7, GZMA, GZMB, B2M, FGFBP2, CTSW, GNLY, HLA-C 
##     GZMH, SPON2, CD247, FCGR3A, CCL5, HLA-A, CCL4, GZMM, KLRD1, CLIC3 
## Negative:  RPL32, RPL18A, HLA-DRA, CD79A, RPL13, MS4A1, RPL11, TCL1A, RPS9, RPL12 
##     LINC00926, HLA-DQB1, HLA-DQA1, HLA-DRB1, RPL28, RPS2, S100A8, HLA-DMA, RPL8, RPLP1
```

Example 38 (unknown):
```unknown
# Display the results as a heatmap
DimHeatmap(pbmc, reduction = "mds", dims = 1, cells = 500, projected = TRUE, balanced = TRUE)
```

Example 39 (r):
```r
# Display the results as a heatmap
DimHeatmap(pbmc, reduction = "mds", dims = 1, cells = 500, projected = TRUE, balanced = TRUE)
```

Example 40 (r):
```r
# Display the results as a heatmap
DimHeatmap(pbmc, reduction = "mds", dims = 1, cells = 500, projected = TRUE, balanced = TRUE)
```

Example 41 (unknown):
```unknown
# Explore how the first MDS dimension is distributed across clusters
VlnPlot(pbmc, features = "MDS_1")
```

Example 42 (r):
```r
# Explore how the first MDS dimension is distributed across clusters
VlnPlot(pbmc, features = "MDS_1")
```

Example 43 (r):
```r
# Explore how the first MDS dimension is distributed across clusters
VlnPlot(pbmc, features = "MDS_1")
```

Example 44 (unknown):
```unknown
# See how the first MDS dimension is correlated with the first PC dimension
FeatureScatter(pbmc, feature1 = "MDS_1", feature2 = "PC_1")
```

Example 45 (r):
```r
# See how the first MDS dimension is correlated with the first PC dimension
FeatureScatter(pbmc, feature1 = "MDS_1", feature2 = "PC_1")
```

Example 46 (r):
```r
# See how the first MDS dimension is correlated with the first PC dimension
FeatureScatter(pbmc, feature1 = "MDS_1", feature2 = "PC_1")
```

Example 47 (unknown):
```unknown
sessionInfo()
```

Example 48 (r):
```r
sessionInfo()
```

Example 49 (r):
```r
sessionInfo()
```

Example 50 (unknown):
```unknown
## R version 4.2.0 (2022-04-22)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.5 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/liblapack.so.3
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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       
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
##  [1] ggplot2_3.4.1                 thp1.eccite.SeuratData_3.1.5 
##  [3] stxBrain.SeuratData_0.1.1     ssHippo.SeuratData_3.1.4     
##  [5] pbmcsca.SeuratData_3.0.0      pbmcMultiome.SeuratData_0.1.2
##  [7] pbmc3k.SeuratData_3.1.4       panc8.SeuratData_3.0.2       
##  [9] ifnb.SeuratData_3.1.0         hcabm40k.SeuratData_3.0.0    
## [11] bmcite.SeuratData_0.3.0       SeuratData_0.2.2             
## [13] SeuratObject_4.1.3            Seurat_4.3.0                 
## 
## loaded via a namespace (and not attached):
##   [1] systemfonts_1.0.4      plyr_1.8.8             igraph_1.4.1          
##   [4] lazyeval_0.2.2         sp_1.6-0               splines_4.2.0         
##   [7] listenv_0.9.0          scattermore_0.8        digest_0.6.31         
##  [10] htmltools_0.5.4        fansi_1.0.4            magrittr_2.0.3        
##  [13] memoise_2.0.1          tensor_1.5             cluster_2.1.3         
##  [16] ROCR_1.0-11            globals_0.16.2         matrixStats_0.63.0    
##  [19] pkgdown_2.0.7          spatstat.sparse_3.0-0  colorspace_2.1-0      
##  [22] rappdirs_0.3.3         ggrepel_0.9.3          textshaping_0.3.6     
##  [25] xfun_0.37              dplyr_1.1.0            crayon_1.5.2          
##  [28] jsonlite_1.8.4         progressr_0.13.0       spatstat.data_3.0-0   
##  [31] survival_3.3-1         zoo_1.8-11             glue_1.6.2            
##  [34] polyclip_1.10-4        gtable_0.3.1           leiden_0.4.3          
##  [37] future.apply_1.10.0    abind_1.4-5            scales_1.2.1          
##  [40] spatstat.random_3.1-3  miniUI_0.1.1.1         Rcpp_1.0.10           
##  [43] viridisLite_0.4.1      xtable_1.8-4           reticulate_1.28       
##  [46] htmlwidgets_1.6.1      httr_1.4.5             RColorBrewer_1.1-3    
##  [49] ellipsis_0.3.2         ica_1.0-3              farver_2.1.1          
##  [52] pkgconfig_2.0.3        sass_0.4.5             uwot_0.1.14           
##  [55] deldir_1.0-6           utf8_1.2.3             tidyselect_1.2.0      
##  [58] labeling_0.4.2         rlang_1.0.6            reshape2_1.4.4        
##  [61] later_1.3.0            munsell_0.5.0          tools_4.2.0           
##  [64] cachem_1.0.7           cli_3.6.0              generics_0.1.3        
##  [67] ggridges_0.5.4         evaluate_0.20          stringr_1.5.0         
##  [70] fastmap_1.1.1          yaml_2.3.7             ragg_1.2.5            
##  [73] goftest_1.2-3          knitr_1.42             fs_1.6.1              
##  [76] fitdistrplus_1.1-8     purrr_1.0.1            RANN_2.6.1            
##  [79] pbapply_1.7-0          future_1.31.0          nlme_3.1-157          
##  [82] mime_0.12              formatR_1.14           compiler_4.2.0        
##  [85] plotly_4.10.1          png_0.1-8              spatstat.utils_3.0-1  
##  [88] tibble_3.1.8           bslib_0.4.2            stringi_1.7.12        
##  [91] highr_0.10             desc_1.4.2             lattice_0.20-45       
##  [94] Matrix_1.5-3           vctrs_0.5.2            pillar_1.8.1          
##  [97] lifecycle_1.0.3        spatstat.geom_3.0-6    lmtest_0.9-40         
## [100] jquerylib_0.1.4        RcppAnnoy_0.0.20       data.table_1.14.8     
## [103] cowplot_1.1.1          irlba_2.3.5.1          httpuv_1.6.9          
## [106] patchwork_1.1.2        R6_2.5.1               promises_1.2.0.1      
## [109] KernSmooth_2.23-20     gridExtra_2.3          parallelly_1.34.0     
## [112] codetools_0.2-18       MASS_7.3-56            rprojroot_2.0.3       
## [115] withr_2.5.0            sctransform_0.3.5      parallel_4.2.0        
## [118] grid_4.2.0             tidyr_1.3.0            rmarkdown_2.20        
## [121] Rtsne_0.16             spatstat.explore_3.0-6 shiny_1.7.4
```

Example 51 (unknown):
```unknown
## R version 4.2.0 (2022-04-22)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.5 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/liblapack.so.3
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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       
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
##  [1] ggplot2_3.4.1                 thp1.eccite.SeuratData_3.1.5 
##  [3] stxBrain.SeuratData_0.1.1     ssHippo.SeuratData_3.1.4     
##  [5] pbmcsca.SeuratData_3.0.0      pbmcMultiome.SeuratData_0.1.2
##  [7] pbmc3k.SeuratData_3.1.4       panc8.SeuratData_3.0.2       
##  [9] ifnb.SeuratData_3.1.0         hcabm40k.SeuratData_3.0.0    
## [11] bmcite.SeuratData_0.3.0       SeuratData_0.2.2             
## [13] SeuratObject_4.1.3            Seurat_4.3.0                 
## 
## loaded via a namespace (and not attached):
##   [1] systemfonts_1.0.4      plyr_1.8.8             igraph_1.4.1          
##   [4] lazyeval_0.2.2         sp_1.6-0               splines_4.2.0         
##   [7] listenv_0.9.0          scattermore_0.8        digest_0.6.31         
##  [10] htmltools_0.5.4        fansi_1.0.4            magrittr_2.0.3        
##  [13] memoise_2.0.1          tensor_1.5             cluster_2.1.3         
##  [16] ROCR_1.0-11            globals_0.16.2         matrixStats_0.63.0    
##  [19] pkgdown_2.0.7          spatstat.sparse_3.0-0  colorspace_2.1-0      
##  [22] rappdirs_0.3.3         ggrepel_0.9.3          textshaping_0.3.6     
##  [25] xfun_0.37              dplyr_1.1.0            crayon_1.5.2          
##  [28] jsonlite_1.8.4         progressr_0.13.0       spatstat.data_3.0-0   
##  [31] survival_3.3-1         zoo_1.8-11             glue_1.6.2            
##  [34] polyclip_1.10-4        gtable_0.3.1           leiden_0.4.3          
##  [37] future.apply_1.10.0    abind_1.4-5            scales_1.2.1          
##  [40] spatstat.random_3.1-3  miniUI_0.1.1.1         Rcpp_1.0.10           
##  [43] viridisLite_0.4.1      xtable_1.8-4           reticulate_1.28       
##  [46] htmlwidgets_1.6.1      httr_1.4.5             RColorBrewer_1.1-3    
##  [49] ellipsis_0.3.2         ica_1.0-3              farver_2.1.1          
##  [52] pkgconfig_2.0.3        sass_0.4.5             uwot_0.1.14           
##  [55] deldir_1.0-6           utf8_1.2.3             tidyselect_1.2.0      
##  [58] labeling_0.4.2         rlang_1.0.6            reshape2_1.4.4        
##  [61] later_1.3.0            munsell_0.5.0          tools_4.2.0           
##  [64] cachem_1.0.7           cli_3.6.0              generics_0.1.3        
##  [67] ggridges_0.5.4         evaluate_0.20          stringr_1.5.0         
##  [70] fastmap_1.1.1          yaml_2.3.7             ragg_1.2.5            
##  [73] goftest_1.2-3          knitr_1.42             fs_1.6.1              
##  [76] fitdistrplus_1.1-8     purrr_1.0.1            RANN_2.6.1            
##  [79] pbapply_1.7-0          future_1.31.0          nlme_3.1-157          
##  [82] mime_0.12              formatR_1.14           compiler_4.2.0        
##  [85] plotly_4.10.1          png_0.1-8              spatstat.utils_3.0-1  
##  [88] tibble_3.1.8           bslib_0.4.2            stringi_1.7.12        
##  [91] highr_0.10             desc_1.4.2             lattice_0.20-45       
##  [94] Matrix_1.5-3           vctrs_0.5.2            pillar_1.8.1          
##  [97] lifecycle_1.0.3        spatstat.geom_3.0-6    lmtest_0.9-40         
## [100] jquerylib_0.1.4        RcppAnnoy_0.0.20       data.table_1.14.8     
## [103] cowplot_1.1.1          irlba_2.3.5.1          httpuv_1.6.9          
## [106] patchwork_1.1.2        R6_2.5.1               promises_1.2.0.1      
## [109] KernSmooth_2.23-20     gridExtra_2.3          parallelly_1.34.0     
## [112] codetools_0.2-18       MASS_7.3-56            rprojroot_2.0.3       
## [115] withr_2.5.0            sctransform_0.3.5      parallel_4.2.0        
## [118] grid_4.2.0             tidyr_1.3.0            rmarkdown_2.20        
## [121] Rtsne_0.16             spatstat.explore_3.0-6 shiny_1.7.4
```

---

## Analysis, visualization, and integration of Visium HD spatial datasets with Seurat • Seurat

**URL:** http://127.0.0.1:9173/seurat/cell_cycle_vignette.html

**Contents:**
- Cell-Cycle Scoring and Regression
    - Compiled: 2023-10-31
- Assign Cell-Cycle Scores
- Regress out cell cycle scores during data scaling
- Alternate Workflow
- Contents

We demonstrate how to mitigate the effects of cell cycle heterogeneity in scRNA-seq data by calculating cell cycle phase scores based on canonical markers, and regressing these out of the data during pre-processing. We demonstrate this on a dataset of murine hematopoietic progenitors (Nestorowa et al., Blood 2016).You can download the files needed to run this vignette here.

If we run a PCA on our object, using the variable genes we found in FindVariableFeatures() above, we see that while most of the variance can be explained by lineage, PC8 and PC10 are split on cell-cycle genes including TOP2A and MKI67. We will attempt to regress this signal from the data, so that cell-cycle heterogeneity does not contribute to PCA or downstream analysis.

First, we assign each cell a score, based on its expression of G2/M and S phase markers. These marker sets should be anticorrelated in their expression levels, and cells expressing neither are likely not cycling and in G1 phase.

We assign scores in the CellCycleScoring() function, which stores S and G2/M scores in object meta data, along with the predicted classification of each cell in either G2M, S or G1 phase. CellCycleScoring() can also set the identity of the Seurat object to the cell-cycle phase by passing set.ident = TRUE (the original identities are stored as old.ident). Please note that Seurat does not use the discrete classifications (G2M/G1/S) in downstream cell cycle regression. Instead, it uses the quantitative scores for G2M and S phase. However, we provide our predicted classifications in case they are of interest.

We score single cells based on the scoring strategy described in Tirosh et al. 2016. See ?AddModuleScore() in Seurat for more information, this function can be used to calculate supervised module scores for any gene list.

We now attempt to subtract (‘regress out’) this source of heterogeneity from the data. For users of Seurat v1.4, this was implemented in RegressOut. However, as the results of this procedure are stored in the scaled data slot (therefore overwriting the output of ScaleData()), we now merge this functionality into the ScaleData() function itself.

For each gene, Seurat models the relationship between gene expression and the S and G2M cell cycle scores. The scaled residuals of this model represent a ‘corrected’ expression matrix, that can be used downstream for dimensional reduction.

As the best cell cycle markers are extremely well conserved across tissues and species, we have found this procedure to work robustly and reliably on diverse datasets.

The procedure above removes all signal associated with cell cycle. In some cases, we’ve found that this can negatively impact downstream analysis, particularly in differentiating processes (like murine hematopoiesis), where stem cells are quiescent and differentiated cells are proliferating (or vice versa). In this case, regressing out all cell cycle effects can blur the distinction between stem and progenitor cells as well.

As an alternative, we suggest regressing out the difference between the G2M and S phase scores. This means that signals separating non-cycling cells and cycling cells will be maintained, but differences in cell cycle phase among proliferating cells (which are often uninteresting), will be regressed out of the data

Developed by Rahul Satija, Satija Lab and Collaborators.

Site built with pkgdown 2.0.7.

**Examples:**

Example 1 (unknown):
```unknown
vignettes/cell_cycle_vignette.Rmd
```

Example 2 (unknown):
```unknown
cell_cycle_vignette.Rmd
```

Example 3 (python):
```python
library(Seurat)

# Read in the expression matrix The first row is a header row, the first column is rownames
exp.mat <- read.table(file = "/brahms/shared/vignette-data/cell_cycle_vignette_files/nestorawa_forcellcycle_expressionMatrix.txt",
    header = TRUE, as.is = TRUE, row.names = 1)

# A list of cell cycle markers, from Tirosh et al, 2015, is loaded with Seurat.  We can
# segregate this list into markers of G2/M phase and markers of S phase
s.genes <- cc.genes$s.genes
g2m.genes <- cc.genes$g2m.genes

# Create our Seurat object and complete the initalization steps
marrow <- CreateSeuratObject(counts = Matrix::Matrix(as.matrix(exp.mat), sparse = T))
marrow <- NormalizeData(marrow)
marrow <- FindVariableFeatures(marrow, selection.method = "vst")
marrow <- ScaleData(marrow, features = rownames(marrow))
```

Example 4 (r):
```r
library(Seurat)

# Read in the expression matrix The first row is a header row, the first column is rownames
exp.mat <- read.table(file = "/brahms/shared/vignette-data/cell_cycle_vignette_files/nestorawa_forcellcycle_expressionMatrix.txt",
    header = TRUE, as.is = TRUE, row.names = 1)

# A list of cell cycle markers, from Tirosh et al, 2015, is loaded with Seurat.  We can
# segregate this list into markers of G2/M phase and markers of S phase
s.genes <- cc.genes$s.genes
g2m.genes <- cc.genes$g2m.genes

# Create our Seurat object and complete the initalization steps
marrow <- CreateSeuratObject(counts = Matrix::Matrix(as.matrix(exp.mat), sparse = T))
marrow <- NormalizeData(marrow)
marrow <- FindVariableFeatures(marrow, selection.method = "vst")
marrow <- ScaleData(marrow, features = rownames(marrow))
```

Example 5 (r):
```r
library(Seurat)

# Read in the expression matrix The first row is a header row, the first column is rownames
exp.mat <- read.table(file = "/brahms/shared/vignette-data/cell_cycle_vignette_files/nestorawa_forcellcycle_expressionMatrix.txt",
    header = TRUE, as.is = TRUE, row.names = 1)

# A list of cell cycle markers, from Tirosh et al, 2015, is loaded with Seurat.  We can
# segregate this list into markers of G2/M phase and markers of S phase
s.genes <- cc.genes$s.genes
g2m.genes <- cc.genes$g2m.genes

# Create our Seurat object and complete the initalization steps
marrow <- CreateSeuratObject(counts = Matrix::Matrix(as.matrix(exp.mat), sparse = T))
marrow <- NormalizeData(marrow)
marrow <- FindVariableFeatures(marrow, selection.method = "vst")
marrow <- ScaleData(marrow, features = rownames(marrow))
```

Example 6 (unknown):
```unknown
FindVariableFeatures()
```

Example 7 (unknown):
```unknown
marrow <- RunPCA(marrow, features = VariableFeatures(marrow), ndims.print = 6:10, nfeatures.print = 10)
```

Example 8 (r):
```r
marrow <- RunPCA(marrow, features = VariableFeatures(marrow), ndims.print = 6:10, nfeatures.print = 10)
```

Example 9 (r):
```r
marrow <- RunPCA(marrow, features = VariableFeatures(marrow), ndims.print = 6:10, nfeatures.print = 10)
```

Example 10 (unknown):
```unknown
## PC_ 6 
## Positive:  SELL, ARL6IP1, CCL9, CD34, ADGRL4, BPIFC, NUSAP1, FAM64A, CD244, C030034L19RIK 
## Negative:  LY6C2, AA467197, CYBB, MGST2, ITGB2, PF4, CD74, ATP1B1, GP1BB, TREM3 
## PC_ 7 
## Positive:  F13A1, LY86, CFP, IRF8, CSF1R, TIFAB, IFI209, CCR2, TNS4, MS4A6C 
## Negative:  HDC, CPA3, PGLYRP1, MS4A3, NKG7, UBE2C, CCNB1, NUSAP1, PLK1, FUT8 
## PC_ 8 
## Positive:  NUSAP1, UBE2C, KIF23, PLK1, CENPF, FAM64A, CCNB1, H2AFX, ID2, CDC20 
## Negative:  WFDC17, SLC35D3, ADGRL4, VLDLR, CD33, H2AFY, P2RY14, IFI206, CCL9, CD34 
## PC_ 9 
## Positive:  IGKC, JCHAIN, LY6D, MZB1, CD74, IGLC2, FCRLA, IGKV4-50, IGHM, IGHV9-1 
## Negative:  SLC2A6, HBA-A1, HBA-A2, IGHV8-7, FCER1G, F13A1, HBB-BS, PLD4, HBB-BT, IGFBP4 
## PC_ 10 
## Positive:  H2AFX, FAM64A, ZFP383, NUSAP1, CDC25B, CENPF, GBP10, TOP2A, GBP6, GFRA1 
## Negative:  CTSW, XKRX, PRR5L, RORA, MBOAT4, A630014C17RIK, ZFP105, COL9A3, CLEC2I, TRAT1
```

Example 11 (unknown):
```unknown
## PC_ 6 
## Positive:  SELL, ARL6IP1, CCL9, CD34, ADGRL4, BPIFC, NUSAP1, FAM64A, CD244, C030034L19RIK 
## Negative:  LY6C2, AA467197, CYBB, MGST2, ITGB2, PF4, CD74, ATP1B1, GP1BB, TREM3 
## PC_ 7 
## Positive:  F13A1, LY86, CFP, IRF8, CSF1R, TIFAB, IFI209, CCR2, TNS4, MS4A6C 
## Negative:  HDC, CPA3, PGLYRP1, MS4A3, NKG7, UBE2C, CCNB1, NUSAP1, PLK1, FUT8 
## PC_ 8 
## Positive:  NUSAP1, UBE2C, KIF23, PLK1, CENPF, FAM64A, CCNB1, H2AFX, ID2, CDC20 
## Negative:  WFDC17, SLC35D3, ADGRL4, VLDLR, CD33, H2AFY, P2RY14, IFI206, CCL9, CD34 
## PC_ 9 
## Positive:  IGKC, JCHAIN, LY6D, MZB1, CD74, IGLC2, FCRLA, IGKV4-50, IGHM, IGHV9-1 
## Negative:  SLC2A6, HBA-A1, HBA-A2, IGHV8-7, FCER1G, F13A1, HBB-BS, PLD4, HBB-BT, IGFBP4 
## PC_ 10 
## Positive:  H2AFX, FAM64A, ZFP383, NUSAP1, CDC25B, CENPF, GBP10, TOP2A, GBP6, GFRA1 
## Negative:  CTSW, XKRX, PRR5L, RORA, MBOAT4, A630014C17RIK, ZFP105, COL9A3, CLEC2I, TRAT1
```

Example 12 (unknown):
```unknown
DimHeatmap(marrow, dims = c(8, 10))
```

Example 13 (r):
```r
DimHeatmap(marrow, dims = c(8, 10))
```

Example 14 (r):
```r
DimHeatmap(marrow, dims = c(8, 10))
```

Example 15 (unknown):
```unknown
CellCycleScoring()
```

Example 16 (unknown):
```unknown
CellCycleScoring()
```

Example 17 (unknown):
```unknown
set.ident = TRUE
```

Example 18 (unknown):
```unknown
marrow <- CellCycleScoring(marrow, s.features = s.genes, g2m.features = g2m.genes, set.ident = TRUE)

# view cell cycle scores and phase assignments
head(marrow[[]])
```

Example 19 (r):
```r
marrow <- CellCycleScoring(marrow, s.features = s.genes, g2m.features = g2m.genes, set.ident = TRUE)

# view cell cycle scores and phase assignments
head(marrow[[]])
```

Example 20 (r):
```r
marrow <- CellCycleScoring(marrow, s.features = s.genes, g2m.features = g2m.genes, set.ident = TRUE)

# view cell cycle scores and phase assignments
head(marrow[[]])
```

Example 21 (unknown):
```unknown
##          orig.ident nCount_RNA nFeature_RNA     S.Score  G2M.Score Phase
## Prog_013       Prog    2563089        10211 -0.14248691 -0.4680395    G1
## Prog_019       Prog    3030620         9991 -0.16915786  0.5851766   G2M
## Prog_031       Prog    1293487        10192 -0.34627038 -0.3971879    G1
## Prog_037       Prog    1357987         9599 -0.44270212  0.6820229   G2M
## Prog_008       Prog    4079891        10540  0.55854051  0.1284359     S
## Prog_014       Prog    2569783        10788  0.07116218  0.3166073   G2M
##          old.ident
## Prog_013      Prog
## Prog_019      Prog
## Prog_031      Prog
## Prog_037      Prog
## Prog_008      Prog
## Prog_014      Prog
```

Example 22 (unknown):
```unknown
##          orig.ident nCount_RNA nFeature_RNA     S.Score  G2M.Score Phase
## Prog_013       Prog    2563089        10211 -0.14248691 -0.4680395    G1
## Prog_019       Prog    3030620         9991 -0.16915786  0.5851766   G2M
## Prog_031       Prog    1293487        10192 -0.34627038 -0.3971879    G1
## Prog_037       Prog    1357987         9599 -0.44270212  0.6820229   G2M
## Prog_008       Prog    4079891        10540  0.55854051  0.1284359     S
## Prog_014       Prog    2569783        10788  0.07116218  0.3166073   G2M
##          old.ident
## Prog_013      Prog
## Prog_019      Prog
## Prog_031      Prog
## Prog_037      Prog
## Prog_008      Prog
## Prog_014      Prog
```

Example 23 (unknown):
```unknown
# Visualize the distribution of cell cycle markers across
RidgePlot(marrow, features = c("PCNA", "TOP2A", "MCM6", "MKI67"), ncol = 2)
```

Example 24 (r):
```r
# Visualize the distribution of cell cycle markers across
RidgePlot(marrow, features = c("PCNA", "TOP2A", "MCM6", "MKI67"), ncol = 2)
```

Example 25 (r):
```r
# Visualize the distribution of cell cycle markers across
RidgePlot(marrow, features = c("PCNA", "TOP2A", "MCM6", "MKI67"), ncol = 2)
```

Example 26 (unknown):
```unknown
# Running a PCA on cell cycle genes reveals, unsurprisingly, that cells separate entirely by
# phase
marrow <- RunPCA(marrow, features = c(s.genes, g2m.genes))
DimPlot(marrow)
```

Example 27 (r):
```r
# Running a PCA on cell cycle genes reveals, unsurprisingly, that cells separate entirely by
# phase
marrow <- RunPCA(marrow, features = c(s.genes, g2m.genes))
DimPlot(marrow)
```

Example 28 (r):
```r
# Running a PCA on cell cycle genes reveals, unsurprisingly, that cells separate entirely by
# phase
marrow <- RunPCA(marrow, features = c(s.genes, g2m.genes))
DimPlot(marrow)
```

Example 29 (unknown):
```unknown
library(ggplot2)
plot <- DimPlot(marrow) + theme(axis.title = element_text(size = 18), legend.text = element_text(size = 18)) +
    guides(colour = guide_legend(override.aes = list(size = 10)))
ggsave(filename = "../output/images/cell_cycle_vignette.jpg", height = 7, width = 12, plot = plot,
    quality = 50)
```

Example 30 (r):
```r
library(ggplot2)
plot <- DimPlot(marrow) + theme(axis.title = element_text(size = 18), legend.text = element_text(size = 18)) +
    guides(colour = guide_legend(override.aes = list(size = 10)))
ggsave(filename = "../output/images/cell_cycle_vignette.jpg", height = 7, width = 12, plot = plot,
    quality = 50)
```

Example 31 (r):
```r
library(ggplot2)
plot <- DimPlot(marrow) + theme(axis.title = element_text(size = 18), legend.text = element_text(size = 18)) +
    guides(colour = guide_legend(override.aes = list(size = 10)))
ggsave(filename = "../output/images/cell_cycle_vignette.jpg", height = 7, width = 12, plot = plot,
    quality = 50)
```

Example 32 (unknown):
```unknown
?AddModuleScore()
```

Example 33 (unknown):
```unknown
ScaleData()
```

Example 34 (unknown):
```unknown
ScaleData()
```

Example 35 (unknown):
```unknown
marrow <- ScaleData(marrow, vars.to.regress = c("S.Score", "G2M.Score"), features = rownames(marrow))
```

Example 36 (r):
```r
marrow <- ScaleData(marrow, vars.to.regress = c("S.Score", "G2M.Score"), features = rownames(marrow))
```

Example 37 (r):
```r
marrow <- ScaleData(marrow, vars.to.regress = c("S.Score", "G2M.Score"), features = rownames(marrow))
```

Example 38 (unknown):
```unknown
# Now, a PCA on the variable genes no longer returns components associated with cell cycle
marrow <- RunPCA(marrow, features = VariableFeatures(marrow), nfeatures.print = 10)
```

Example 39 (r):
```r
# Now, a PCA on the variable genes no longer returns components associated with cell cycle
marrow <- RunPCA(marrow, features = VariableFeatures(marrow), nfeatures.print = 10)
```

Example 40 (r):
```r
# Now, a PCA on the variable genes no longer returns components associated with cell cycle
marrow <- RunPCA(marrow, features = VariableFeatures(marrow), nfeatures.print = 10)
```

Example 41 (unknown):
```unknown
## PC_ 1 
## Positive:  BLVRB, CAR2, KLF1, AQP1, CES2G, ERMAP, CAR1, FAM132A, RHD, SPHK1 
## Negative:  TMSB4X, H2AFY, CORO1A, PLAC8, EMB, MPO, PRTN3, CD34, LCP1, BC035044 
## PC_ 2 
## Positive:  ANGPT1, ADGRG1, MEIS1, ITGA2B, MPL, DAPP1, APOE, RAB37, GATA2, F2R 
## Negative:  LY6C2, ELANE, HP, IGSF6, ANXA3, CTSG, CLEC12A, TIFAB, SLPI, ALAS1 
## PC_ 3 
## Positive:  APOE, GATA2, NKG7, MUC13, MS4A3, RAB44, HDC, CPA3, FCGR3, TUBA8 
## Negative:  FLT3, DNTT, LSP1, WFDC17, MYL10, GIMAP6, LAX1, GPR171, TBXA2R, SATB1 
## PC_ 4 
## Positive:  CSRP3, ST8SIA6, DNTT, MPEG1, SCIN, LGALS1, CMAH, RGL1, APOE, MFSD2B 
## Negative:  PROCR, MPL, HLF, MMRN1, SERPINA3G, ESAM, GSTM1, D630039A03RIK, MYL10, LY6A 
## PC_ 5 
## Positive:  CPA3, LMO4, IKZF2, IFITM1, FUT8, MS4A2, SIGLECF, CSRP3, HDC, RAB44 
## Negative:  PF4, GP1BB, SDPR, F2RL2, RAB27B, SLC14A1, TREML1, PBX1, F2R, TUBA8
```

Example 42 (unknown):
```unknown
## PC_ 1 
## Positive:  BLVRB, CAR2, KLF1, AQP1, CES2G, ERMAP, CAR1, FAM132A, RHD, SPHK1 
## Negative:  TMSB4X, H2AFY, CORO1A, PLAC8, EMB, MPO, PRTN3, CD34, LCP1, BC035044 
## PC_ 2 
## Positive:  ANGPT1, ADGRG1, MEIS1, ITGA2B, MPL, DAPP1, APOE, RAB37, GATA2, F2R 
## Negative:  LY6C2, ELANE, HP, IGSF6, ANXA3, CTSG, CLEC12A, TIFAB, SLPI, ALAS1 
## PC_ 3 
## Positive:  APOE, GATA2, NKG7, MUC13, MS4A3, RAB44, HDC, CPA3, FCGR3, TUBA8 
## Negative:  FLT3, DNTT, LSP1, WFDC17, MYL10, GIMAP6, LAX1, GPR171, TBXA2R, SATB1 
## PC_ 4 
## Positive:  CSRP3, ST8SIA6, DNTT, MPEG1, SCIN, LGALS1, CMAH, RGL1, APOE, MFSD2B 
## Negative:  PROCR, MPL, HLF, MMRN1, SERPINA3G, ESAM, GSTM1, D630039A03RIK, MYL10, LY6A 
## PC_ 5 
## Positive:  CPA3, LMO4, IKZF2, IFITM1, FUT8, MS4A2, SIGLECF, CSRP3, HDC, RAB44 
## Negative:  PF4, GP1BB, SDPR, F2RL2, RAB27B, SLC14A1, TREML1, PBX1, F2R, TUBA8
```

Example 43 (unknown):
```unknown
# When running a PCA on only cell cycle genes, cells no longer separate by cell-cycle phase
marrow <- RunPCA(marrow, features = c(s.genes, g2m.genes))
DimPlot(marrow)
```

Example 44 (r):
```r
# When running a PCA on only cell cycle genes, cells no longer separate by cell-cycle phase
marrow <- RunPCA(marrow, features = c(s.genes, g2m.genes))
DimPlot(marrow)
```

Example 45 (r):
```r
# When running a PCA on only cell cycle genes, cells no longer separate by cell-cycle phase
marrow <- RunPCA(marrow, features = c(s.genes, g2m.genes))
DimPlot(marrow)
```

Example 46 (unknown):
```unknown
marrow$CC.Difference <- marrow$S.Score - marrow$G2M.Score
marrow <- ScaleData(marrow, vars.to.regress = "CC.Difference", features = rownames(marrow))
```

Example 47 (r):
```r
marrow$CC.Difference <- marrow$S.Score - marrow$G2M.Score
marrow <- ScaleData(marrow, vars.to.regress = "CC.Difference", features = rownames(marrow))
```

Example 48 (r):
```r
marrow$CC.Difference <- marrow$S.Score - marrow$G2M.Score
marrow <- ScaleData(marrow, vars.to.regress = "CC.Difference", features = rownames(marrow))
```

Example 49 (unknown):
```unknown
# cell cycle effects strongly mitigated in PCA
marrow <- RunPCA(marrow, features = VariableFeatures(marrow), nfeatures.print = 10)
```

Example 50 (r):
```r
# cell cycle effects strongly mitigated in PCA
marrow <- RunPCA(marrow, features = VariableFeatures(marrow), nfeatures.print = 10)
```

Example 51 (r):
```r
# cell cycle effects strongly mitigated in PCA
marrow <- RunPCA(marrow, features = VariableFeatures(marrow), nfeatures.print = 10)
```

Example 52 (unknown):
```unknown
## PC_ 1 
## Positive:  BLVRB, KLF1, ERMAP, FAM132A, CAR2, RHD, CES2G, SPHK1, AQP1, SLC38A5 
## Negative:  TMSB4X, CORO1A, PLAC8, H2AFY, LAPTM5, CD34, LCP1, TMEM176B, IGFBP4, EMB 
## PC_ 2 
## Positive:  APOE, GATA2, RAB37, ANGPT1, ADGRG1, MEIS1, MPL, F2R, PDZK1IP1, DAPP1 
## Negative:  CTSG, ELANE, LY6C2, HP, CLEC12A, ANXA3, IGSF6, TIFAB, SLPI, MPO 
## PC_ 3 
## Positive:  APOE, GATA2, NKG7, MUC13, ITGA2B, TUBA8, CPA3, RAB44, SLC18A2, CD9 
## Negative:  DNTT, FLT3, WFDC17, LSP1, MYL10, LAX1, GIMAP6, IGHM, CD24A, MN1 
## PC_ 4 
## Positive:  CSRP3, ST8SIA6, SCIN, LGALS1, APOE, ITGB7, MFSD2B, RGL1, DNTT, IGHV1-23 
## Negative:  MPL, MMRN1, PROCR, HLF, SERPINA3G, ESAM, PTGS1, D630039A03RIK, NDN, PPIC 
## PC_ 5 
## Positive:  GP1BB, PF4, SDPR, F2RL2, TREML1, RAB27B, SLC14A1, PBX1, PLEK, TUBA8 
## Negative:  HDC, LMO4, CSRP3, IFITM1, FCGR3, HLF, CPA3, PROCR, PGLYRP1, IKZF2
```

Example 53 (unknown):
```unknown
## PC_ 1 
## Positive:  BLVRB, KLF1, ERMAP, FAM132A, CAR2, RHD, CES2G, SPHK1, AQP1, SLC38A5 
## Negative:  TMSB4X, CORO1A, PLAC8, H2AFY, LAPTM5, CD34, LCP1, TMEM176B, IGFBP4, EMB 
## PC_ 2 
## Positive:  APOE, GATA2, RAB37, ANGPT1, ADGRG1, MEIS1, MPL, F2R, PDZK1IP1, DAPP1 
## Negative:  CTSG, ELANE, LY6C2, HP, CLEC12A, ANXA3, IGSF6, TIFAB, SLPI, MPO 
## PC_ 3 
## Positive:  APOE, GATA2, NKG7, MUC13, ITGA2B, TUBA8, CPA3, RAB44, SLC18A2, CD9 
## Negative:  DNTT, FLT3, WFDC17, LSP1, MYL10, LAX1, GIMAP6, IGHM, CD24A, MN1 
## PC_ 4 
## Positive:  CSRP3, ST8SIA6, SCIN, LGALS1, APOE, ITGB7, MFSD2B, RGL1, DNTT, IGHV1-23 
## Negative:  MPL, MMRN1, PROCR, HLF, SERPINA3G, ESAM, PTGS1, D630039A03RIK, NDN, PPIC 
## PC_ 5 
## Positive:  GP1BB, PF4, SDPR, F2RL2, TREML1, RAB27B, SLC14A1, PBX1, PLEK, TUBA8 
## Negative:  HDC, LMO4, CSRP3, IFITM1, FCGR3, HLF, CPA3, PROCR, PGLYRP1, IKZF2
```

Example 54 (python):
```python
# when running a PCA on cell cycle genes, actively proliferating cells remain distinct from G1
# cells however, within actively proliferating cells, G2M and S phase cells group together
marrow <- RunPCA(marrow, features = c(s.genes, g2m.genes))
DimPlot(marrow)
```

Example 55 (r):
```r
# when running a PCA on cell cycle genes, actively proliferating cells remain distinct from G1
# cells however, within actively proliferating cells, G2M and S phase cells group together
marrow <- RunPCA(marrow, features = c(s.genes, g2m.genes))
DimPlot(marrow)
```

Example 56 (r):
```r
# when running a PCA on cell cycle genes, actively proliferating cells remain distinct from G1
# cells however, within actively proliferating cells, G2M and S phase cells group together
marrow <- RunPCA(marrow, features = c(s.genes, g2m.genes))
DimPlot(marrow)
```

Example 57 (unknown):
```unknown
sessionInfo()
```

Example 58 (r):
```r
sessionInfo()
```

Example 59 (r):
```r
sessionInfo()
```

Example 60 (unknown):
```unknown
## R version 4.2.2 Patched (2022-11-10 r83330)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.6 LTS
## 
## Matrix products: default
## BLAS:   /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.9.0
## LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.9.0
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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       
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
## [1] ggplot2_3.4.4      Seurat_5.0.0       SeuratObject_5.0.0 sp_2.1-1          
## 
## loaded via a namespace (and not attached):
##   [1] ggbeeswarm_0.7.1       Rtsne_0.16             colorspace_2.1-0      
##   [4] deldir_1.0-9           ellipsis_0.3.2         ggridges_0.5.4        
##   [7] rprojroot_2.0.3        RcppHNSW_0.5.0         fs_1.6.3              
##  [10] spatstat.data_3.0-3    farver_2.1.1           leiden_0.4.3          
##  [13] listenv_0.9.0          ggrepel_0.9.4          RSpectra_0.16-1       
##  [16] fansi_1.0.5            codetools_0.2-19       splines_4.2.2         
##  [19] cachem_1.0.8           knitr_1.45             polyclip_1.10-6       
##  [22] spam_2.10-0            jsonlite_1.8.7         ica_1.0-3             
##  [25] cluster_2.1.4          png_0.1-8              uwot_0.1.16           
##  [28] spatstat.sparse_3.0-3  sctransform_0.4.1      shiny_1.7.5.1         
##  [31] compiler_4.2.2         httr_1.4.7             Matrix_1.6-1.1        
##  [34] fastmap_1.1.1          lazyeval_0.2.2         cli_3.6.1             
##  [37] later_1.3.1            formatR_1.14           htmltools_0.5.6.1     
##  [40] tools_4.2.2            igraph_1.5.1           dotCall64_1.1-0       
##  [43] gtable_0.3.4           glue_1.6.2             reshape2_1.4.4        
##  [46] RANN_2.6.1             dplyr_1.1.3            Rcpp_1.0.11           
##  [49] scattermore_1.2        jquerylib_0.1.4        pkgdown_2.0.7         
##  [52] vctrs_0.6.4            nlme_3.1-162           spatstat.explore_3.2-5
##  [55] progressr_0.14.0       lmtest_0.9-40          spatstat.random_3.2-1 
##  [58] xfun_0.40              stringr_1.5.0          globals_0.16.2        
##  [61] mime_0.12              miniUI_0.1.1.1         lifecycle_1.0.3       
##  [64] irlba_2.3.5.1          goftest_1.2-3          future_1.33.0         
##  [67] MASS_7.3-58.2          zoo_1.8-12             scales_1.2.1          
##  [70] spatstat.utils_3.0-4   ragg_1.2.5             promises_1.2.1        
##  [73] parallel_4.2.2         RColorBrewer_1.1-3     yaml_2.3.7            
##  [76] gridExtra_2.3          memoise_2.0.1          reticulate_1.34.0     
##  [79] pbapply_1.7-2          ggrastr_1.0.1          sass_0.4.7            
##  [82] stringi_1.7.12         highr_0.10             desc_1.4.2            
##  [85] fastDummies_1.7.3      rlang_1.1.1            pkgconfig_2.0.3       
##  [88] systemfonts_1.0.4      matrixStats_1.0.0      evaluate_0.22         
##  [91] lattice_0.21-9         tensor_1.5             ROCR_1.0-11           
##  [94] purrr_1.0.2            labeling_0.4.3         patchwork_1.1.3       
##  [97] htmlwidgets_1.6.2      cowplot_1.1.1          tidyselect_1.2.0      
## [100] parallelly_1.36.0      RcppAnnoy_0.0.21       plyr_1.8.9            
## [103] magrittr_2.0.3         R6_2.5.1               generics_0.1.3        
## [106] withr_2.5.2            pillar_1.9.0           fitdistrplus_1.1-11   
## [109] abind_1.4-5            survival_3.5-7         tibble_3.2.1          
## [112] future.apply_1.11.0    KernSmooth_2.23-22     utf8_1.2.4            
## [115] spatstat.geom_3.2-7    plotly_4.10.3          rmarkdown_2.25        
## [118] grid_4.2.2             data.table_1.14.8      digest_0.6.33         
## [121] xtable_1.8-4           tidyr_1.3.0            httpuv_1.6.12         
## [124] textshaping_0.3.6      munsell_0.5.0          beeswarm_0.4.0        
## [127] viridisLite_0.4.2      vipor_0.4.5            bslib_0.5.1
```

Example 61 (unknown):
```unknown
## R version 4.2.2 Patched (2022-11-10 r83330)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.6 LTS
## 
## Matrix products: default
## BLAS:   /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.9.0
## LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.9.0
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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       
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
## [1] ggplot2_3.4.4      Seurat_5.0.0       SeuratObject_5.0.0 sp_2.1-1          
## 
## loaded via a namespace (and not attached):
##   [1] ggbeeswarm_0.7.1       Rtsne_0.16             colorspace_2.1-0      
##   [4] deldir_1.0-9           ellipsis_0.3.2         ggridges_0.5.4        
##   [7] rprojroot_2.0.3        RcppHNSW_0.5.0         fs_1.6.3              
##  [10] spatstat.data_3.0-3    farver_2.1.1           leiden_0.4.3          
##  [13] listenv_0.9.0          ggrepel_0.9.4          RSpectra_0.16-1       
##  [16] fansi_1.0.5            codetools_0.2-19       splines_4.2.2         
##  [19] cachem_1.0.8           knitr_1.45             polyclip_1.10-6       
##  [22] spam_2.10-0            jsonlite_1.8.7         ica_1.0-3             
##  [25] cluster_2.1.4          png_0.1-8              uwot_0.1.16           
##  [28] spatstat.sparse_3.0-3  sctransform_0.4.1      shiny_1.7.5.1         
##  [31] compiler_4.2.2         httr_1.4.7             Matrix_1.6-1.1        
##  [34] fastmap_1.1.1          lazyeval_0.2.2         cli_3.6.1             
##  [37] later_1.3.1            formatR_1.14           htmltools_0.5.6.1     
##  [40] tools_4.2.2            igraph_1.5.1           dotCall64_1.1-0       
##  [43] gtable_0.3.4           glue_1.6.2             reshape2_1.4.4        
##  [46] RANN_2.6.1             dplyr_1.1.3            Rcpp_1.0.11           
##  [49] scattermore_1.2        jquerylib_0.1.4        pkgdown_2.0.7         
##  [52] vctrs_0.6.4            nlme_3.1-162           spatstat.explore_3.2-5
##  [55] progressr_0.14.0       lmtest_0.9-40          spatstat.random_3.2-1 
##  [58] xfun_0.40              stringr_1.5.0          globals_0.16.2        
##  [61] mime_0.12              miniUI_0.1.1.1         lifecycle_1.0.3       
##  [64] irlba_2.3.5.1          goftest_1.2-3          future_1.33.0         
##  [67] MASS_7.3-58.2          zoo_1.8-12             scales_1.2.1          
##  [70] spatstat.utils_3.0-4   ragg_1.2.5             promises_1.2.1        
##  [73] parallel_4.2.2         RColorBrewer_1.1-3     yaml_2.3.7            
##  [76] gridExtra_2.3          memoise_2.0.1          reticulate_1.34.0     
##  [79] pbapply_1.7-2          ggrastr_1.0.1          sass_0.4.7            
##  [82] stringi_1.7.12         highr_0.10             desc_1.4.2            
##  [85] fastDummies_1.7.3      rlang_1.1.1            pkgconfig_2.0.3       
##  [88] systemfonts_1.0.4      matrixStats_1.0.0      evaluate_0.22         
##  [91] lattice_0.21-9         tensor_1.5             ROCR_1.0-11           
##  [94] purrr_1.0.2            labeling_0.4.3         patchwork_1.1.3       
##  [97] htmlwidgets_1.6.2      cowplot_1.1.1          tidyselect_1.2.0      
## [100] parallelly_1.36.0      RcppAnnoy_0.0.21       plyr_1.8.9            
## [103] magrittr_2.0.3         R6_2.5.1               generics_0.1.3        
## [106] withr_2.5.2            pillar_1.9.0           fitdistrplus_1.1-11   
## [109] abind_1.4-5            survival_3.5-7         tibble_3.2.1          
## [112] future.apply_1.11.0    KernSmooth_2.23-22     utf8_1.2.4            
## [115] spatstat.geom_3.2-7    plotly_4.10.3          rmarkdown_2.25        
## [118] grid_4.2.2             data.table_1.14.8      digest_0.6.33         
## [121] xtable_1.8-4           tidyr_1.3.0            httpuv_1.6.12         
## [124] textshaping_0.3.6      munsell_0.5.0          beeswarm_0.4.0        
## [127] viridisLite_0.4.2      vipor_0.4.5            bslib_0.5.1
```

---

## Using Seurat with multi-modal data

**URL:** http://127.0.0.1:9173/seurat/archive/v3.1/multimodal_vignette/index.html

**Contents:**
- Using Seurat with multi-modal data
    - Compiled: 2020-04-17
  - Load in the data
  - Setup a Seurat object, and cluster cells based on RNA expression
  - Add the protein expression levels to the Seurat object
  - Visualize protein levels on RNA clusters
  - Identify differentially expressed proteins between clusters
  - Cluster directly on protein levels
  - Loading data from 10X multi-modal experiments

This vignette demonstrates new features that allow users to analyze and explore multi-modal data with Seurat. While this represents an initial release, we are excited to release significant new functionality for multi-modal datasets in the future.

Here, we analyze a dataset of 8,617 cord blood mononuclear cells (CBMCs), produced with CITE-seq, where we simultaneously measure the single cell transcriptomes alongside the expression of 11 surface proteins, whose levels are quantified with DNA-barcoded antibodies. First, we load in two count matrices : one for the RNA measurements, and one for the antibody-derived tags (ADT). You can download the ADT file here and the RNA file here

The steps below represent a quick clustering of the PBMCs based on the scRNA-seq data. For more detail on individual steps or more advanced options, see our PBMC clustering guided tutorial here

Seurat v3.0 allows you to store information from multiple assays in the same object, as long as the data is multi-modal (collected on the same set of cells). You can use the SetAssayData and GetAssayData accessor functions to add and fetch data from additional assays.

You can use the names of any ADT markers, (i.e. “adt_CD4”), in FetchData, FeaturePlot, RidgePlot, FeatureScatter, DoHeatmap, or any other visualization features

If you look a bit more closely, you’ll see that our CD8 T cell cluster is enriched for CD8 T cells, but still contains many CD4+ CD8- T cells. This is because Naive CD4 and CD8 T cells are quite similar transcriptomically, and the RNA dropout levels for CD4 and CD8 are quite high. This demonstrates the challenge of defining subtle immune cell differences from scRNA-seq data alone.

You can also run dimensional reduction and graph-based clustering directly on CITE-seq data

The ADT-based clustering yields similar results, but with a few differences

Seurat is also able to analyze data from multi-modal 10X experiments processed using CellRanger v3; as an example, we recreate the plots above using a dataset of 7,900 peripheral blood mononuclear cells (PBMC), freely available from 10X Genomics here.

**Examples:**

Example 1 (r):
```r
library(Seurat)
library(ggplot2)
library(patchwork)
```

Example 2 (r):
```r
library(Seurat)
library(ggplot2)
library(patchwork)
```

Example 3 (r):
```r
# Load in the RNA UMI matrix

# Note that this dataset also contains ~5% of mouse cells, which we can use as negative controls
# for the protein measurements. For this reason, the gene expression matrix has HUMAN_ or MOUSE_
# appended to the beginning of each gene.
cbmc.rna <- as.sparse(read.csv(file = "../data/GSE100866_CBMC_8K_13AB_10X-RNA_umi.csv.gz", sep = ",", 
    header = TRUE, row.names = 1))

# To make life a bit easier going forward, we're going to discard all but the top 100 most
# highly expressed mouse genes, and remove the 'HUMAN_' from the CITE-seq prefix
cbmc.rna <- CollapseSpeciesExpressionMatrix(cbmc.rna)

# Load in the ADT UMI matrix
cbmc.adt <- as.sparse(read.csv(file = "../data/GSE100866_CBMC_8K_13AB_10X-ADT_umi.csv.gz", sep = ",", 
    header = TRUE, row.names = 1))

# When adding multimodal data to Seurat, it's okay to have duplicate feature names. Each set of
# modal data (eg. RNA, ADT, etc.) is stored in its own Assay object.  One of these Assay objects
# is called the 'default assay', meaning it's used for all analyses and visualization.  To pull
# data from an assay that isn't the default, you can specify a key that's linked to an assay for
# feature pulling.  To see all keys for all objects, use the Key function.  Lastly, we observed
# poor enrichments for CCR5, CCR7, and CD10 - and therefore remove them from the matrix
# (optional)
cbmc.adt <- cbmc.adt[setdiff(rownames(x = cbmc.adt), c("CCR5", "CCR7", "CD10")), ]
```

Example 4 (r):
```r
# Load in the RNA UMI matrix

# Note that this dataset also contains ~5% of mouse cells, which we can use as negative controls
# for the protein measurements. For this reason, the gene expression matrix has HUMAN_ or MOUSE_
# appended to the beginning of each gene.
cbmc.rna <- as.sparse(read.csv(file = "../data/GSE100866_CBMC_8K_13AB_10X-RNA_umi.csv.gz", sep = ",", 
    header = TRUE, row.names = 1))

# To make life a bit easier going forward, we're going to discard all but the top 100 most
# highly expressed mouse genes, and remove the 'HUMAN_' from the CITE-seq prefix
cbmc.rna <- CollapseSpeciesExpressionMatrix(cbmc.rna)

# Load in the ADT UMI matrix
cbmc.adt <- as.sparse(read.csv(file = "../data/GSE100866_CBMC_8K_13AB_10X-ADT_umi.csv.gz", sep = ",", 
    header = TRUE, row.names = 1))

# When adding multimodal data to Seurat, it's okay to have duplicate feature names. Each set of
# modal data (eg. RNA, ADT, etc.) is stored in its own Assay object.  One of these Assay objects
# is called the 'default assay', meaning it's used for all analyses and visualization.  To pull
# data from an assay that isn't the default, you can specify a key that's linked to an assay for
# feature pulling.  To see all keys for all objects, use the Key function.  Lastly, we observed
# poor enrichments for CCR5, CCR7, and CD10 - and therefore remove them from the matrix
# (optional)
cbmc.adt <- cbmc.adt[setdiff(rownames(x = cbmc.adt), c("CCR5", "CCR7", "CD10")), ]
```

Example 5 (r):
```r
cbmc <- CreateSeuratObject(counts = cbmc.rna)

# standard log-normalization
cbmc <- NormalizeData(cbmc)

# choose ~1k variable features
cbmc <- FindVariableFeatures(cbmc)

# standard scaling (no regression)
cbmc <- ScaleData(cbmc)

# Run PCA, select 13 PCs for tSNE visualization and graph-based clustering
cbmc <- RunPCA(cbmc, verbose = FALSE)
ElbowPlot(cbmc, ndims = 50)
```

Example 6 (r):
```r
cbmc <- CreateSeuratObject(counts = cbmc.rna)

# standard log-normalization
cbmc <- NormalizeData(cbmc)

# choose ~1k variable features
cbmc <- FindVariableFeatures(cbmc)

# standard scaling (no regression)
cbmc <- ScaleData(cbmc)

# Run PCA, select 13 PCs for tSNE visualization and graph-based clustering
cbmc <- RunPCA(cbmc, verbose = FALSE)
ElbowPlot(cbmc, ndims = 50)
```

Example 7 (r):
```r
cbmc <- FindNeighbors(cbmc, dims = 1:25)
cbmc <- FindClusters(cbmc, resolution = 0.8)
cbmc <- RunTSNE(cbmc, dims = 1:25, method = "FIt-SNE")

# Find the markers that define each cluster, and use these to annotate the clusters, we use
# max.cells.per.ident to speed up the process
cbmc.rna.markers <- FindAllMarkers(cbmc, max.cells.per.ident = 100, min.diff.pct = 0.3, only.pos = TRUE)
```

Example 8 (r):
```r
cbmc <- FindNeighbors(cbmc, dims = 1:25)
cbmc <- FindClusters(cbmc, resolution = 0.8)
cbmc <- RunTSNE(cbmc, dims = 1:25, method = "FIt-SNE")

# Find the markers that define each cluster, and use these to annotate the clusters, we use
# max.cells.per.ident to speed up the process
cbmc.rna.markers <- FindAllMarkers(cbmc, max.cells.per.ident = 100, min.diff.pct = 0.3, only.pos = TRUE)
```

Example 9 (r):
```r
# Note, for simplicity we are merging two CD14+ Monocyte clusters (that differ in expression of
# HLA-DR genes) and NK clusters (that differ in cell cycle stage)
new.cluster.ids <- c("Memory CD4 T", "CD14+ Mono", "Naive CD4 T", "NK", "CD14+ Mono", "Mouse", "B", 
    "CD8 T", "CD16+ Mono", "T/Mono doublets", "NK", "CD34+", "Multiplets", "Mouse", "Eryth", "Mk", 
    "Mouse", "DC", "pDCs")
names(new.cluster.ids) <- levels(cbmc)
cbmc <- RenameIdents(cbmc, new.cluster.ids)
```

Example 10 (r):
```r
# Note, for simplicity we are merging two CD14+ Monocyte clusters (that differ in expression of
# HLA-DR genes) and NK clusters (that differ in cell cycle stage)
new.cluster.ids <- c("Memory CD4 T", "CD14+ Mono", "Naive CD4 T", "NK", "CD14+ Mono", "Mouse", "B", 
    "CD8 T", "CD16+ Mono", "T/Mono doublets", "NK", "CD34+", "Multiplets", "Mouse", "Eryth", "Mk", 
    "Mouse", "DC", "pDCs")
names(new.cluster.ids) <- levels(cbmc)
cbmc <- RenameIdents(cbmc, new.cluster.ids)
```

Example 11 (r):
```r
DimPlot(cbmc, label = TRUE) + NoLegend()
```

Example 12 (r):
```r
DimPlot(cbmc, label = TRUE) + NoLegend()
```

Example 13 (unknown):
```unknown
SetAssayData
```

Example 14 (unknown):
```unknown
GetAssayData
```

Example 15 (r):
```r
# We will define an ADT assay, and store raw counts for it

# If you are interested in how these data are internally stored, you can check out the Assay
# class, which is defined in objects.R; note that all single-cell expression data, including RNA
# data, are still stored in Assay objects, and can also be accessed using GetAssayData
cbmc[["ADT"]] <- CreateAssayObject(counts = cbmc.adt)

# Now we can repeat the preprocessing (normalization and scaling) steps that we typically run
# with RNA, but modifying the 'assay' argument.  For CITE-seq data, we do not recommend typical
# LogNormalization. Instead, we use a centered log-ratio (CLR) normalization, computed
# independently for each feature.  This is a slightly improved procedure from the original
# publication, and we will release more advanced versions of CITE-seq normalizations soon.
cbmc <- NormalizeData(cbmc, assay = "ADT", normalization.method = "CLR")
cbmc <- ScaleData(cbmc, assay = "ADT")
```

Example 16 (r):
```r
# We will define an ADT assay, and store raw counts for it

# If you are interested in how these data are internally stored, you can check out the Assay
# class, which is defined in objects.R; note that all single-cell expression data, including RNA
# data, are still stored in Assay objects, and can also be accessed using GetAssayData
cbmc[["ADT"]] <- CreateAssayObject(counts = cbmc.adt)

# Now we can repeat the preprocessing (normalization and scaling) steps that we typically run
# with RNA, but modifying the 'assay' argument.  For CITE-seq data, we do not recommend typical
# LogNormalization. Instead, we use a centered log-ratio (CLR) normalization, computed
# independently for each feature.  This is a slightly improved procedure from the original
# publication, and we will release more advanced versions of CITE-seq normalizations soon.
cbmc <- NormalizeData(cbmc, assay = "ADT", normalization.method = "CLR")
cbmc <- ScaleData(cbmc, assay = "ADT")
```

Example 17 (r):
```r
# in this plot, protein (ADT) levels are on top, and RNA levels are on the bottom
FeaturePlot(cbmc, features = c("adt_CD3", "adt_CD11c", "adt_CD8", "adt_CD16", "CD3E", "ITGAX", "CD8A", 
    "FCGR3A"), min.cutoff = "q05", max.cutoff = "q95", ncol = 4)
```

Example 18 (r):
```r
# in this plot, protein (ADT) levels are on top, and RNA levels are on the bottom
FeaturePlot(cbmc, features = c("adt_CD3", "adt_CD11c", "adt_CD8", "adt_CD16", "CD3E", "ITGAX", "CD8A", 
    "FCGR3A"), min.cutoff = "q05", max.cutoff = "q95", ncol = 4)
```

Example 19 (r):
```r
RidgePlot(cbmc, features = c("adt_CD3", "adt_CD11c", "adt_CD8", "adt_CD16"), ncol = 2)
```

Example 20 (r):
```r
RidgePlot(cbmc, features = c("adt_CD3", "adt_CD11c", "adt_CD8", "adt_CD16"), ncol = 2)
```

Example 21 (r):
```r
# Draw ADT scatter plots (like biaxial plots for FACS). Note that you can even 'gate' cells if
# desired by using HoverLocator and FeatureLocator
FeatureScatter(cbmc, feature1 = "adt_CD19", feature2 = "adt_CD3")
```

Example 22 (r):
```r
# Draw ADT scatter plots (like biaxial plots for FACS). Note that you can even 'gate' cells if
# desired by using HoverLocator and FeatureLocator
FeatureScatter(cbmc, feature1 = "adt_CD19", feature2 = "adt_CD3")
```

Example 23 (r):
```r
# view relationship between protein and RNA
FeatureScatter(cbmc, feature1 = "adt_CD3", feature2 = "CD3E")
```

Example 24 (r):
```r
# view relationship between protein and RNA
FeatureScatter(cbmc, feature1 = "adt_CD3", feature2 = "CD3E")
```

Example 25 (r):
```r
# Let's plot CD4 vs CD8 levels in T cells
tcells <- subset(cbmc, idents = c("Naive CD4 T", "Memory CD4 T", "CD8 T"))
FeatureScatter(tcells, feature1 = "adt_CD4", feature2 = "adt_CD8")
```

Example 26 (r):
```r
# Let's plot CD4 vs CD8 levels in T cells
tcells <- subset(cbmc, idents = c("Naive CD4 T", "Memory CD4 T", "CD8 T"))
FeatureScatter(tcells, feature1 = "adt_CD4", feature2 = "adt_CD8")
```

Example 27 (r):
```r
# # Let's look at the raw (non-normalized) ADT counts. You can see the values are quite high,
# particularly in comparison to RNA values. This is due to the significantly higher protein copy
# number in cells, which significantly reduces 'drop-out' in ADT data
FeatureScatter(tcells, feature1 = "adt_CD4", feature2 = "adt_CD8", slot = "counts")
```

Example 28 (r):
```r
# # Let's look at the raw (non-normalized) ADT counts. You can see the values are quite high,
# particularly in comparison to RNA values. This is due to the significantly higher protein copy
# number in cells, which significantly reduces 'drop-out' in ADT data
FeatureScatter(tcells, feature1 = "adt_CD4", feature2 = "adt_CD8", slot = "counts")
```

Example 29 (r):
```r
saveRDS(cbmc, file = "../output/cbmc.rds")
```

Example 30 (r):
```r
saveRDS(cbmc, file = "../output/cbmc.rds")
```

Example 31 (r):
```r
# Downsample the clusters to a maximum of 300 cells each (makes the heatmap easier to see for
# small clusters)
cbmc.small <- subset(cbmc, downsample = 300)

# Find protein markers for all clusters, and draw a heatmap
adt.markers <- FindAllMarkers(cbmc.small, assay = "ADT", only.pos = TRUE)
DoHeatmap(cbmc.small, features = unique(adt.markers$gene), assay = "ADT", angle = 90) + NoLegend()
```

Example 32 (r):
```r
# Downsample the clusters to a maximum of 300 cells each (makes the heatmap easier to see for
# small clusters)
cbmc.small <- subset(cbmc, downsample = 300)

# Find protein markers for all clusters, and draw a heatmap
adt.markers <- FindAllMarkers(cbmc.small, assay = "ADT", only.pos = TRUE)
DoHeatmap(cbmc.small, features = unique(adt.markers$gene), assay = "ADT", angle = 90) + NoLegend()
```

Example 33 (r):
```r
# You can see that our unknown cells co-express both myeloid and lymphoid markers (true at the
# RNA level as well). They are likely cell clumps (multiplets) that should be discarded. We'll
# remove the mouse cells now as well
cbmc <- subset(cbmc, idents = c("Multiplets", "Mouse"), invert = TRUE)
```

Example 34 (r):
```r
# You can see that our unknown cells co-express both myeloid and lymphoid markers (true at the
# RNA level as well). They are likely cell clumps (multiplets) that should be discarded. We'll
# remove the mouse cells now as well
cbmc <- subset(cbmc, idents = c("Multiplets", "Mouse"), invert = TRUE)
```

Example 35 (r):
```r
# Because we're going to be working with the ADT data extensively, we're going to switch the
# default assay to the 'CITE' assay.  This will cause all functions to use ADT data by default,
# rather than requiring us to specify it each time
DefaultAssay(cbmc) <- "ADT"
cbmc <- RunPCA(cbmc, features = rownames(cbmc), reduction.name = "pca_adt", reduction.key = "pca_adt_", 
    verbose = FALSE)
DimPlot(cbmc, reduction = "pca_adt")
```

Example 36 (r):
```r
# Because we're going to be working with the ADT data extensively, we're going to switch the
# default assay to the 'CITE' assay.  This will cause all functions to use ADT data by default,
# rather than requiring us to specify it each time
DefaultAssay(cbmc) <- "ADT"
cbmc <- RunPCA(cbmc, features = rownames(cbmc), reduction.name = "pca_adt", reduction.key = "pca_adt_", 
    verbose = FALSE)
DimPlot(cbmc, reduction = "pca_adt")
```

Example 37 (r):
```r
# Since we only have 10 markers, instead of doing PCA, we'll just use a standard euclidean
# distance matrix here.  Also, this provides a good opportunity to demonstrate how to do
# visualization and clustering using a custom distance matrix in Seurat
adt.data <- GetAssayData(cbmc, slot = "data")
adt.dist <- dist(t(adt.data))

# Before we recluster the data on ADT levels, we'll stash the RNA cluster IDs for later
cbmc[["rnaClusterID"]] <- Idents(cbmc)

# Now, we rerun tSNE using our distance matrix defined only on ADT (protein) levels.
cbmc[["tsne_adt"]] <- RunTSNE(adt.dist, assay = "ADT", reduction.key = "adtTSNE_")
cbmc[["adt_snn"]] <- FindNeighbors(adt.dist)$snn
cbmc <- FindClusters(cbmc, resolution = 0.2, graph.name = "adt_snn")

# We can compare the RNA and protein clustering, and use this to annotate the protein clustering
# (we could also of course use FindMarkers)
clustering.table <- table(Idents(cbmc), cbmc$rnaClusterID)
clustering.table
```

Example 38 (r):
```r
# Since we only have 10 markers, instead of doing PCA, we'll just use a standard euclidean
# distance matrix here.  Also, this provides a good opportunity to demonstrate how to do
# visualization and clustering using a custom distance matrix in Seurat
adt.data <- GetAssayData(cbmc, slot = "data")
adt.dist <- dist(t(adt.data))

# Before we recluster the data on ADT levels, we'll stash the RNA cluster IDs for later
cbmc[["rnaClusterID"]] <- Idents(cbmc)

# Now, we rerun tSNE using our distance matrix defined only on ADT (protein) levels.
cbmc[["tsne_adt"]] <- RunTSNE(adt.dist, assay = "ADT", reduction.key = "adtTSNE_")
cbmc[["adt_snn"]] <- FindNeighbors(adt.dist)$snn
cbmc <- FindClusters(cbmc, resolution = 0.2, graph.name = "adt_snn")

# We can compare the RNA and protein clustering, and use this to annotate the protein clustering
# (we could also of course use FindMarkers)
clustering.table <- table(Idents(cbmc), cbmc$rnaClusterID)
clustering.table
```

Example 39 (r):
```r
new.cluster.ids <- c("CD4 T", "CD14+ Mono", "NK", "B", "CD8 T", "NK", "CD34+", "T/Mono doublets", 
    "CD16+ Mono", "pDCs", "B")
names(new.cluster.ids) <- levels(cbmc)
cbmc <- RenameIdents(cbmc, new.cluster.ids)

tsne_rnaClusters <- DimPlot(cbmc, reduction = "tsne_adt", group.by = "rnaClusterID") + NoLegend()
tsne_rnaClusters <- tsne_rnaClusters + ggtitle("Clustering based on scRNA-seq") + theme(plot.title = element_text(hjust = 0.5))
tsne_rnaClusters <- LabelClusters(plot = tsne_rnaClusters, id = "rnaClusterID", size = 4)

tsne_adtClusters <- DimPlot(cbmc, reduction = "tsne_adt", pt.size = 0.5) + NoLegend()
tsne_adtClusters <- tsne_adtClusters + ggtitle("Clustering based on ADT signal") + theme(plot.title = element_text(hjust = 0.5))
tsne_adtClusters <- LabelClusters(plot = tsne_adtClusters, id = "ident", size = 4)

# Note: for this comparison, both the RNA and protein clustering are visualized on a tSNE
# generated using the ADT distance matrix.
wrap_plots(list(tsne_rnaClusters, tsne_adtClusters), ncol = 2)
```

Example 40 (r):
```r
new.cluster.ids <- c("CD4 T", "CD14+ Mono", "NK", "B", "CD8 T", "NK", "CD34+", "T/Mono doublets", 
    "CD16+ Mono", "pDCs", "B")
names(new.cluster.ids) <- levels(cbmc)
cbmc <- RenameIdents(cbmc, new.cluster.ids)

tsne_rnaClusters <- DimPlot(cbmc, reduction = "tsne_adt", group.by = "rnaClusterID") + NoLegend()
tsne_rnaClusters <- tsne_rnaClusters + ggtitle("Clustering based on scRNA-seq") + theme(plot.title = element_text(hjust = 0.5))
tsne_rnaClusters <- LabelClusters(plot = tsne_rnaClusters, id = "rnaClusterID", size = 4)

tsne_adtClusters <- DimPlot(cbmc, reduction = "tsne_adt", pt.size = 0.5) + NoLegend()
tsne_adtClusters <- tsne_adtClusters + ggtitle("Clustering based on ADT signal") + theme(plot.title = element_text(hjust = 0.5))
tsne_adtClusters <- LabelClusters(plot = tsne_adtClusters, id = "ident", size = 4)

# Note: for this comparison, both the RNA and protein clustering are visualized on a tSNE
# generated using the ADT distance matrix.
wrap_plots(list(tsne_rnaClusters, tsne_adtClusters), ncol = 2)
```

Example 41 (r):
```r
tcells <- subset(cbmc, idents = c("CD4 T", "CD8 T"))
FeatureScatter(tcells, feature1 = "CD4", feature2 = "CD8")
```

Example 42 (r):
```r
tcells <- subset(cbmc, idents = c("CD4 T", "CD8 T"))
FeatureScatter(tcells, feature1 = "CD4", feature2 = "CD8")
```

Example 43 (r):
```r
RidgePlot(cbmc, features = c("adt_CD11c", "adt_CD8", "adt_CD16", "adt_CD4", "adt_CD19", "adt_CD14"), 
    ncol = 2)
```

Example 44 (r):
```r
RidgePlot(cbmc, features = c("adt_CD11c", "adt_CD8", "adt_CD16", "adt_CD4", "adt_CD19", "adt_CD14"), 
    ncol = 2)
```

Example 45 (r):
```r
saveRDS(cbmc, file = "../output/cbmc_multimodal.rds")
```

Example 46 (r):
```r
saveRDS(cbmc, file = "../output/cbmc_multimodal.rds")
```

Example 47 (r):
```r
pbmc10k.data <- Read10X(data.dir = "../data/pbmc10k/filtered_feature_bc_matrix/")
rownames(x = pbmc10k.data[["Antibody Capture"]]) <- gsub(pattern = "_[control_]*TotalSeqB", replacement = "", 
    x = rownames(x = pbmc10k.data[["Antibody Capture"]]))

pbmc10k <- CreateSeuratObject(counts = pbmc10k.data[["Gene Expression"]], min.cells = 3, min.features = 200)
pbmc10k <- NormalizeData(pbmc10k)
pbmc10k[["ADT"]] <- CreateAssayObject(pbmc10k.data[["Antibody Capture"]][, colnames(x = pbmc10k)])
pbmc10k <- NormalizeData(pbmc10k, assay = "ADT", normalization.method = "CLR")

plot1 <- FeatureScatter(pbmc10k, feature1 = "adt_CD19", feature2 = "adt_CD3", pt.size = 1)
plot2 <- FeatureScatter(pbmc10k, feature1 = "adt_CD4", feature2 = "adt_CD8a", pt.size = 1)
plot3 <- FeatureScatter(pbmc10k, feature1 = "adt_CD3", feature2 = "CD3E", pt.size = 1)
(plot1 + plot2 + plot3) & NoLegend()
```

Example 48 (r):
```r
pbmc10k.data <- Read10X(data.dir = "../data/pbmc10k/filtered_feature_bc_matrix/")
rownames(x = pbmc10k.data[["Antibody Capture"]]) <- gsub(pattern = "_[control_]*TotalSeqB", replacement = "", 
    x = rownames(x = pbmc10k.data[["Antibody Capture"]]))

pbmc10k <- CreateSeuratObject(counts = pbmc10k.data[["Gene Expression"]], min.cells = 3, min.features = 200)
pbmc10k <- NormalizeData(pbmc10k)
pbmc10k[["ADT"]] <- CreateAssayObject(pbmc10k.data[["Antibody Capture"]][, colnames(x = pbmc10k)])
pbmc10k <- NormalizeData(pbmc10k, assay = "ADT", normalization.method = "CLR")

plot1 <- FeatureScatter(pbmc10k, feature1 = "adt_CD19", feature2 = "adt_CD3", pt.size = 1)
plot2 <- FeatureScatter(pbmc10k, feature1 = "adt_CD4", feature2 = "adt_CD8a", pt.size = 1)
plot3 <- FeatureScatter(pbmc10k, feature1 = "adt_CD3", feature2 = "CD3E", pt.size = 1)
(plot1 + plot2 + plot3) & NoLegend()
```

---

## Differential expression testing

**URL:** http://127.0.0.1:9173/seurat/archive/v3.2/de_vignette/index.html

**Contents:**
- Differential expression testing
    - Compiled: 2020-10-02
  - Load in the data
  - Perform default differential expression tests
  - Prefilter features or cells to increase the speed of DE testing
  - Perform DE analysis using alternative tests
  - Acknowledgements

This vignette highlights some example workflows for performing differential expression in Seurat. For demonstration purposes, we will be using the 2,700 PBMC object that is created in the first guided tutorial. You can download the pre-computed object here.

The bulk of Seurat's differential expression features can be accessed through the FindMarkers function. As a default, Seurat performs differential expression based on the non-parameteric Wilcoxon rank sum test. This replaces the previous default test ('bimod'). To test for differential expression between two specific groups of cells, specify the ident.1 and ident.2 parameters.

The results data frame has the following columns :

If the ident.2 parameter is omitted or set to NULL, FindMarkers will test for differentially expressed features between the group specified by ident.1 and all other cells.

To increase the speed of marker discovery, particularly for large datasets, Seurat allows for pre-filtering of features or cells. For example, features that are very infrequently detected in either group of cells, or features that are expressed at similar average levels, are unlikely to be differentially expressed. Example use cases of the min.pct, logfc.threshold, min.diff.pct, and max.cells.per.ident parameters are demonstrated below.

The following differential expression tests are currently supported:

For MAST and DESeq2 please ensure that these packages are installed separately in order to use them as part of Seurat. Once installed, use the test.use parameter can be used to specify which DE test to use.

We thank the authors of the MAST and DESeq2 packages for their kind assistance and advice. We also point users to the following study by Charlotte Soneson and Mark Robinson, which performs careful and extensive evaluation of methods for single cell differential expression testing.

**Examples:**

Example 1 (r):
```r
library(Seurat)
pbmc <- readRDS(file = "../data/pbmc3k_final.rds")
```

Example 2 (r):
```r
library(Seurat)
pbmc <- readRDS(file = "../data/pbmc3k_final.rds")
```

Example 3 (unknown):
```unknown
FindMarkers
```

Example 4 (r):
```r
# list options for groups to perform differential expression on
levels(pbmc)
```

Example 5 (r):
```r
# list options for groups to perform differential expression on
levels(pbmc)
```

Example 6 (unknown):
```unknown
## [1] "Naive CD4 T"  "Memory CD4 T" "CD14+ Mono"   "B"            "CD8 T"       
## [6] "FCGR3A+ Mono" "NK"           "DC"           "Platelet"
```

Example 7 (unknown):
```unknown
## [1] "Naive CD4 T"  "Memory CD4 T" "CD14+ Mono"   "B"            "CD8 T"       
## [6] "FCGR3A+ Mono" "NK"           "DC"           "Platelet"
```

Example 8 (r):
```r
# Find differentially expressed features between CD14+ and FCGR3A+ Monocytes
monocyte.de.markers <- FindMarkers(pbmc, ident.1 = "CD14+ Mono", ident.2 = "FCGR3A+ Mono")
# view results
head(monocyte.de.markers)
```

Example 9 (r):
```r
# Find differentially expressed features between CD14+ and FCGR3A+ Monocytes
monocyte.de.markers <- FindMarkers(pbmc, ident.1 = "CD14+ Mono", ident.2 = "FCGR3A+ Mono")
# view results
head(monocyte.de.markers)
```

Example 10 (unknown):
```unknown
FindMarkers
```

Example 11 (r):
```r
# Find differentially expressed features between CD14+ Monocytes and all other cells, only
# search for positive markers
monocyte.de.markers <- FindMarkers(pbmc, ident.1 = "CD14+ Mono", ident.2 = NULL, only.pos = TRUE)
# view results
head(monocyte.de.markers)
```

Example 12 (r):
```r
# Find differentially expressed features between CD14+ Monocytes and all other cells, only
# search for positive markers
monocyte.de.markers <- FindMarkers(pbmc, ident.1 = "CD14+ Mono", ident.2 = NULL, only.pos = TRUE)
# view results
head(monocyte.de.markers)
```

Example 13 (unknown):
```unknown
logfc.threshold
```

Example 14 (unknown):
```unknown
min.diff.pct
```

Example 15 (unknown):
```unknown
max.cells.per.ident
```

Example 16 (r):
```r
# Pre-filter features that are detected at <50% frequency in either CD14+ Monocytes or FCGR3A+
# Monocytes
head(FindMarkers(pbmc, ident.1 = "CD14+ Mono", ident.2 = "FCGR3A+ Mono", min.pct = 0.5))
```

Example 17 (r):
```r
# Pre-filter features that are detected at <50% frequency in either CD14+ Monocytes or FCGR3A+
# Monocytes
head(FindMarkers(pbmc, ident.1 = "CD14+ Mono", ident.2 = "FCGR3A+ Mono", min.pct = 0.5))
```

Example 18 (r):
```r
# Pre-filter features that have less than a two-fold change between the average expression of
# CD14+ Monocytes vs FCGR3A+ Monocytes
head(FindMarkers(pbmc, ident.1 = "CD14+ Mono", ident.2 = "FCGR3A+ Mono", logfc.threshold = log(2)))
```

Example 19 (r):
```r
# Pre-filter features that have less than a two-fold change between the average expression of
# CD14+ Monocytes vs FCGR3A+ Monocytes
head(FindMarkers(pbmc, ident.1 = "CD14+ Mono", ident.2 = "FCGR3A+ Mono", logfc.threshold = log(2)))
```

Example 20 (r):
```r
# Pre-filter features whose detection percentages across the two groups are similar (within
# 0.25)
head(FindMarkers(pbmc, ident.1 = "CD14+ Mono", ident.2 = "FCGR3A+ Mono", min.diff.pct = 0.25))
```

Example 21 (r):
```r
# Pre-filter features whose detection percentages across the two groups are similar (within
# 0.25)
head(FindMarkers(pbmc, ident.1 = "CD14+ Mono", ident.2 = "FCGR3A+ Mono", min.diff.pct = 0.25))
```

Example 22 (r):
```r
# Increasing min.pct, logfc.threshold, and min.diff.pct, will increase the speed of DE testing,
# but could also miss features that are prefiltered

# Subsample each group to a maximum of 200 cells. Can be very useful for large clusters, or
# computationally-intensive DE tests
head(FindMarkers(pbmc, ident.1 = "CD14+ Mono", ident.2 = "FCGR3A+ Mono", max.cells.per.ident = 200))
```

Example 23 (r):
```r
# Increasing min.pct, logfc.threshold, and min.diff.pct, will increase the speed of DE testing,
# but could also miss features that are prefiltered

# Subsample each group to a maximum of 200 cells. Can be very useful for large clusters, or
# computationally-intensive DE tests
head(FindMarkers(pbmc, ident.1 = "CD14+ Mono", ident.2 = "FCGR3A+ Mono", max.cells.per.ident = 200))
```

Example 24 (r):
```r
# Test for DE features using the MAST package
head(FindMarkers(pbmc, ident.1 = "CD14+ Mono", ident.2 = "FCGR3A+ Mono", test.use = "MAST"))
```

Example 25 (r):
```r
# Test for DE features using the MAST package
head(FindMarkers(pbmc, ident.1 = "CD14+ Mono", ident.2 = "FCGR3A+ Mono", test.use = "MAST"))
```

Example 26 (r):
```r
# Test for DE features using the DESeq2 package. Throws an error if DESeq2 has not already been
# installed Note that the DESeq2 workflows can be computationally intensive for large datasets,
# but are incompatible with some feature pre-filtering options We therefore suggest initially
# limiting the number of cells used for testing
head(FindMarkers(pbmc, ident.1 = "CD14+ Mono", ident.2 = "FCGR3A+ Mono", test.use = "DESeq2", max.cells.per.ident = 50))
```

Example 27 (r):
```r
# Test for DE features using the DESeq2 package. Throws an error if DESeq2 has not already been
# installed Note that the DESeq2 workflows can be computationally intensive for large datasets,
# but are incompatible with some feature pre-filtering options We therefore suggest initially
# limiting the number of cells used for testing
head(FindMarkers(pbmc, ident.1 = "CD14+ Mono", ident.2 = "FCGR3A+ Mono", test.use = "DESeq2", max.cells.per.ident = 50))
```

---

## Demultiplexing with hashtag oligos (HTOs)

**URL:** http://127.0.0.1:9173/seurat/archive/v3.0/hashing_vignette/index.html

**Contents:**
- Demultiplexing with hashtag oligos (HTOs)
    - Compiled: 2019-06-24
- 8-HTO dataset from human PBMCs
  - Basic setup
  - Adding HTO data as an independent assay
  - Demultiplex cells based on HTO enrichment
  - Visualize demultiplexing results
- 12-HTO dataset from four human cell lines
  - Create Seurat object, add HTO data and perform normalization
  - Demultiplex data
  - Visualize demultiplexing results
  - Visualize RNA clustering

Developed in collaboration with the Technology Innovation Group at NYGC, Cell Hashing uses oligo-tagged antibodies against ubuquitously expressed surface proteins to place a “sample barcode” on each single cell, enabling different samples to be multiplexed together and run in a single experiment. For more information, please refer to this paper.

This vignette will give a brief demonstration on how to work with data produced with Cell Hashing in Seurat. Applied to two datasets, we can successfully demultiplex cells to their the original sample-of-origin, and identify cross-sample doublets.

Setup Seurat object and add in the HTO data

You can read more about working with multi-modal data here

Here we use the Seurat function HTODemux() to assign single cells back to their sample origins.

Output from running HTODemux() is saved in the object metadata. We can visualize how many cells are classified as singlets, doublets and negative/ambiguous cells.

Visualize enrichment for selected HTOs with ridge plots

Visualize pairs of HTO signals to confirm mutual exclusivity in singlets

Compare number of UMIs for singlets, doublets and negative cells

Generate a two dimensional tSNE embedding for HTOs.Here we are grouping cells by singlets and doublets for simplicity.

Create an HTO heatmap, based on Figure 1C in the Cell Hashing paper.

Cluster and visualize cells using the usual scRNA-seq workflow, and examine for the potential presence of batch effects.

Distribution of selected HTOs grouped by classification, displayed by ridge plots

Visualize HTO signals in a heatmap

**Examples:**

Example 1 (r):
```r
library(Seurat)
```

Example 2 (r):
```r
library(Seurat)
```

Example 3 (r):
```r
# Load in the UMI matrix
pbmc.umis <- readRDS("../data/pbmc_umi_mtx.rds")

# For generating a hashtag count matrix from FASTQ files, please refer to
# https://github.com/Hoohm/CITE-seq-Count.  Load in the HTO count matrix
pbmc.htos <- readRDS("../data/pbmc_hto_mtx.rds")

# Select cell barcodes detected by both RNA and HTO In the example datasets we have already
# filtered the cells for you, but perform this step for clarity.
joint.bcs <- intersect(colnames(pbmc.umis), colnames(pbmc.htos))

# Subset RNA and HTO counts by joint cell barcodes
pbmc.umis <- pbmc.umis[, joint.bcs]
pbmc.htos <- as.matrix(pbmc.htos[, joint.bcs])

# Confirm that the HTO have the correct names
rownames(pbmc.htos)
```

Example 4 (r):
```r
# Load in the UMI matrix
pbmc.umis <- readRDS("../data/pbmc_umi_mtx.rds")

# For generating a hashtag count matrix from FASTQ files, please refer to
# https://github.com/Hoohm/CITE-seq-Count.  Load in the HTO count matrix
pbmc.htos <- readRDS("../data/pbmc_hto_mtx.rds")

# Select cell barcodes detected by both RNA and HTO In the example datasets we have already
# filtered the cells for you, but perform this step for clarity.
joint.bcs <- intersect(colnames(pbmc.umis), colnames(pbmc.htos))

# Subset RNA and HTO counts by joint cell barcodes
pbmc.umis <- pbmc.umis[, joint.bcs]
pbmc.htos <- as.matrix(pbmc.htos[, joint.bcs])

# Confirm that the HTO have the correct names
rownames(pbmc.htos)
```

Example 5 (unknown):
```unknown
## [1] "HTO_A" "HTO_B" "HTO_C" "HTO_D" "HTO_E" "HTO_F" "HTO_G" "HTO_H"
```

Example 6 (unknown):
```unknown
## [1] "HTO_A" "HTO_B" "HTO_C" "HTO_D" "HTO_E" "HTO_F" "HTO_G" "HTO_H"
```

Example 7 (r):
```r
# Setup Seurat object
pbmc.hashtag <- CreateSeuratObject(counts = pbmc.umis)

# Normalize RNA data with log normalization
pbmc.hashtag <- NormalizeData(pbmc.hashtag)
# Find and scale variable features
pbmc.hashtag <- FindVariableFeatures(pbmc.hashtag, selection.method = "mean.var.plot")
pbmc.hashtag <- ScaleData(pbmc.hashtag, features = VariableFeatures(pbmc.hashtag))
```

Example 8 (r):
```r
# Setup Seurat object
pbmc.hashtag <- CreateSeuratObject(counts = pbmc.umis)

# Normalize RNA data with log normalization
pbmc.hashtag <- NormalizeData(pbmc.hashtag)
# Find and scale variable features
pbmc.hashtag <- FindVariableFeatures(pbmc.hashtag, selection.method = "mean.var.plot")
pbmc.hashtag <- ScaleData(pbmc.hashtag, features = VariableFeatures(pbmc.hashtag))
```

Example 9 (r):
```r
# Add HTO data as a new assay independent from RNA
pbmc.hashtag[["HTO"]] <- CreateAssayObject(counts = pbmc.htos)
# Normalize HTO data, here we use centered log-ratio (CLR) transformation
pbmc.hashtag <- NormalizeData(pbmc.hashtag, assay = "HTO", normalization.method = "CLR")
```

Example 10 (r):
```r
# Add HTO data as a new assay independent from RNA
pbmc.hashtag[["HTO"]] <- CreateAssayObject(counts = pbmc.htos)
# Normalize HTO data, here we use centered log-ratio (CLR) transformation
pbmc.hashtag <- NormalizeData(pbmc.hashtag, assay = "HTO", normalization.method = "CLR")
```

Example 11 (r):
```r
# If you have a very large dataset we suggest using k_function = 'clara'. This is a k-medoid
# clustering function for large applications You can also play with additional parameters (see
# documentation for HTODemux()) to adjust the threshold for classification Here we are using the
# default settings
pbmc.hashtag <- HTODemux(pbmc.hashtag, assay = "HTO", positive.quantile = 0.99)
```

Example 12 (r):
```r
# If you have a very large dataset we suggest using k_function = 'clara'. This is a k-medoid
# clustering function for large applications You can also play with additional parameters (see
# documentation for HTODemux()) to adjust the threshold for classification Here we are using the
# default settings
pbmc.hashtag <- HTODemux(pbmc.hashtag, assay = "HTO", positive.quantile = 0.99)
```

Example 13 (r):
```r
# Global classification results
table(pbmc.hashtag$HTO_classification.global)
```

Example 14 (r):
```r
# Global classification results
table(pbmc.hashtag$HTO_classification.global)
```

Example 15 (javascript):
```javascript
## 
##  Doublet Negative  Singlet 
##     2598      346    13972
```

Example 16 (javascript):
```javascript
## 
##  Doublet Negative  Singlet 
##     2598      346    13972
```

Example 17 (r):
```r
# Group cells based on the max HTO signal
Idents(pbmc.hashtag) <- "HTO_maxID"
RidgePlot(pbmc.hashtag, assay = "HTO", features = rownames(pbmc.hashtag[["HTO"]])[1:2], ncol = 2)
```

Example 18 (r):
```r
# Group cells based on the max HTO signal
Idents(pbmc.hashtag) <- "HTO_maxID"
RidgePlot(pbmc.hashtag, assay = "HTO", features = rownames(pbmc.hashtag[["HTO"]])[1:2], ncol = 2)
```

Example 19 (r):
```r
FeatureScatter(pbmc.hashtag, feature1 = "hto_HTO-A", feature2 = "hto_HTO-B")
```

Example 20 (r):
```r
FeatureScatter(pbmc.hashtag, feature1 = "hto_HTO-A", feature2 = "hto_HTO-B")
```

Example 21 (r):
```r
Idents(pbmc.hashtag) <- "HTO_classification.global"
VlnPlot(pbmc.hashtag, features = "nCount_RNA", pt.size = 0.1, log = TRUE)
```

Example 22 (r):
```r
Idents(pbmc.hashtag) <- "HTO_classification.global"
VlnPlot(pbmc.hashtag, features = "nCount_RNA", pt.size = 0.1, log = TRUE)
```

Example 23 (r):
```r
# First, we will remove negative cells from the object
pbmc.hashtag.subset <- subset(pbmc.hashtag, idents = "Negative", invert = TRUE)

# Calculate a distance matrix using HTO
hto.dist.mtx <- as.matrix(dist(t(GetAssayData(object = pbmc.hashtag.subset, assay = "HTO"))))

# Calculate tSNE embeddings with a distance matrix
pbmc.hashtag.subset <- RunTSNE(pbmc.hashtag.subset, distance.matrix = hto.dist.mtx, perplexity = 100)
DimPlot(pbmc.hashtag.subset)
```

Example 24 (r):
```r
# First, we will remove negative cells from the object
pbmc.hashtag.subset <- subset(pbmc.hashtag, idents = "Negative", invert = TRUE)

# Calculate a distance matrix using HTO
hto.dist.mtx <- as.matrix(dist(t(GetAssayData(object = pbmc.hashtag.subset, assay = "HTO"))))

# Calculate tSNE embeddings with a distance matrix
pbmc.hashtag.subset <- RunTSNE(pbmc.hashtag.subset, distance.matrix = hto.dist.mtx, perplexity = 100)
DimPlot(pbmc.hashtag.subset)
```

Example 25 (r):
```r
# You can also visualize the more detailed classification result by running Idents(object) <-
# 'HTO_classification' beofre plotting. Here, you can see that each of the small clouds on the
# tSNE plot corresponds to one of the 28 possible doublet combinations.
```

Example 26 (r):
```r
# You can also visualize the more detailed classification result by running Idents(object) <-
# 'HTO_classification' beofre plotting. Here, you can see that each of the small clouds on the
# tSNE plot corresponds to one of the 28 possible doublet combinations.
```

Example 27 (r):
```r
# To increase the efficiency of plotting, you can subsample cells using the num.cells argument
HTOHeatmap(pbmc.hashtag, assay = "HTO", ncells = 5000)
```

Example 28 (r):
```r
# To increase the efficiency of plotting, you can subsample cells using the num.cells argument
HTOHeatmap(pbmc.hashtag, assay = "HTO", ncells = 5000)
```

Example 29 (r):
```r
# Extract the singlets
pbmc.singlet <- subset(pbmc.hashtag, idents = "Singlet")

# Select the top 1000 most variable features
pbmc.singlet <- FindVariableFeatures(pbmc.singlet, selection.method = "mean.var.plot")

# Scaling RNA data, we only scale the variable features here for efficiency
pbmc.singlet <- ScaleData(pbmc.singlet, features = VariableFeatures(pbmc.singlet))

# Run PCA
pbmc.singlet <- RunPCA(pbmc.singlet, features = VariableFeatures(pbmc.singlet))
```

Example 30 (r):
```r
# Extract the singlets
pbmc.singlet <- subset(pbmc.hashtag, idents = "Singlet")

# Select the top 1000 most variable features
pbmc.singlet <- FindVariableFeatures(pbmc.singlet, selection.method = "mean.var.plot")

# Scaling RNA data, we only scale the variable features here for efficiency
pbmc.singlet <- ScaleData(pbmc.singlet, features = VariableFeatures(pbmc.singlet))

# Run PCA
pbmc.singlet <- RunPCA(pbmc.singlet, features = VariableFeatures(pbmc.singlet))
```

Example 31 (unknown):
```unknown
## PC_ 1 
## Positive:  LYZ, S100A9, S100A8, FOS, CST3, AIF1, TYROBP, LST1, RP11-1143G9.4, FCER1G 
##     LGALS1, FTL, FTH1, VCAN, LGALS2, CFD, MS4A6A, CSTA, CD14, CYBB 
##     HLA-DRA, CD36, RP11-290F20.3, GCA, CD74, RBP7, SGK1, JUND, G0S2, IFITM3 
## Negative:  CCL5, NKG7, GNLY, B2M, RPL3, KLRB1, PRF1, KLRD1, GZMB, KLRF1 
##     GZMM, FGFBP2, CCL4, CMC1, CD2, TRDC, RPL21, CD247, CD69, SPON2 
##     GZMK, CLIC3, KLRG1, TRGC2, HOPX, C12orf75, ZAP70, RPS4X, TRGC1, MATK 
## PC_ 2 
## Positive:  IGHM, RPS8, CD79A, RPL21, IGHD, MS4A1, LINC00926, HLA-DRA, CD74, TCL1A 
##     IGLC3, IGLC2, RPS4X, VPREB3, RPL3, RP11-693J15.5, IGJ, FCER2, MEF2C, AFF3 
##     BCL11A, AC096579.7, IGHA1, IGLL5, AL928768.3, PIM2, IGHG1, MOUSE-mt-Nd1, MOUSE-mt-Cytb, MOUSE-mt-Nd4 
## Negative:  GNLY, NKG7, CCL5, GZMB, KLRF1, PRF1, KLRD1, FGFBP2, SPON2, CLIC3 
##     B2M, TYROBP, CCL4, FCER1G, KLRB1, CMC1, TRDC, HOPX, MYOM2, LGALS1 
##     FCGR3A, GZMM, FCRL6, CD247, KLRC1, S1PR5, MATK, TRGC1, APMAP, TTC38 
## PC_ 3 
## Positive:  MOUSE-Rpl41, MOUSE-Actb, MOUSE-Rpl35, MOUSE-S100a6, MOUSE-mt-Cytb, MOUSE-Lgals1, MOUSE-mt-Nd4, MOUSE-Rps8, MOUSE-Malat1, MOUSE-mt-Nd1 
##     MOUSE-Rplp1, MOUSE-Fth1, MOUSE-Rpl37, MOUSE-Rpl37a, MOUSE-Rpl18a, MOUSE-Rps29, MOUSE-Rpl13, MOUSE-Rps2, MOUSE-Ftl1, MOUSE-Rps28 
##     MOUSE-Tmsb10, MOUSE-Rps27, MOUSE-S100a4, MOUSE-Rps18, MOUSE-Rps5, MOUSE-Rpl13a, MOUSE-Gm10260, MOUSE-Fau, MOUSE-Rpl3, MOUSE-Rplp0 
## Negative:  RPL21, RPS8, B2M, RPL3, RPS4X, CD74, HLA-DRA, IGHM, CD79A, LINC00926 
##     IGJ, IGHD, MS4A1, IGLC2, TCL1A, MEF2C, VPREB3, FTH1, IGLC3, FTL 
##     RP11-693J15.5, PPP3CA, RP11-138A9.2, AFF3, PIM2, FCER2, IGHA1, BCL11A, CD69, RNU1-59P 
## PC_ 4 
## Positive:  RPL21, RPS8, RPL3, RPS4X, CD8B, CD2, GZMK, PIM2, DUSP2, B2M 
##     RP11-138A9.2, LYAR, S100A8, ZAP70, AIF1, MOUSE-Rpl18a, RBP7, MOUSE-S100a6, VCAN, MOUSE-Rps23 
##     PRDM1, S100A9, MOUSE-Lgals1, STAT4, MOUSE-Rps16, MOUSE-Rps3a1, MOUSE-Rps5, MOUSE-Rps8, G0S2, MOUSE-Rps19 
## Negative:  CD74, IGHM, HLA-DRA, IGHD, CD79A, MS4A1, TCL1A, LINC00926, IGLC3, IGLC2 
##     MEF2C, VPREB3, GNLY, IGJ, GZMB, RP11-693J15.5, FCER2, KLRF1, NKG7, BCL11A 
##     CLIC3, PRF1, SPON2, FGFBP2, AFF3, KLRD1, AC096579.7, CCL4, MYOM2, PLEK 
## PC_ 5 
## Positive:  VCAN, S100A8, S100A9, FOS, RP11-1143G9.4, CD14, CD36, LYZ, MS4A6A, LGALS2 
##     RBP7, CCL5, GZMK, DUSP2, G0S2, JUND, SGK1, TRGC2, RNU1-59P, KLRG1 
##     RNVU1-19, ALOX5AP, LYAR, KLRB1, NKG7, CMC1, GCA, CD69, IGHM, TRGC1 
## Negative:  FCGR3A, RP11-290F20.3, IFITM3, LYPD2, LST1, FCER1G, AIF1, CFD, FTH1, CST3 
##     FTL, TYROBP, SOX4, RPL21, MYOM2, RPS4X, B2M, LGALS1, PLEK, MEF2C 
##     HLA-DRA, SPON2, CLIC3, RPL3, APOBEC3C, PTGDS, CD74, S100B, GZMB, MOUSE-Rps29
```

Example 32 (unknown):
```unknown
## PC_ 1 
## Positive:  LYZ, S100A9, S100A8, FOS, CST3, AIF1, TYROBP, LST1, RP11-1143G9.4, FCER1G 
##     LGALS1, FTL, FTH1, VCAN, LGALS2, CFD, MS4A6A, CSTA, CD14, CYBB 
##     HLA-DRA, CD36, RP11-290F20.3, GCA, CD74, RBP7, SGK1, JUND, G0S2, IFITM3 
## Negative:  CCL5, NKG7, GNLY, B2M, RPL3, KLRB1, PRF1, KLRD1, GZMB, KLRF1 
##     GZMM, FGFBP2, CCL4, CMC1, CD2, TRDC, RPL21, CD247, CD69, SPON2 
##     GZMK, CLIC3, KLRG1, TRGC2, HOPX, C12orf75, ZAP70, RPS4X, TRGC1, MATK 
## PC_ 2 
## Positive:  IGHM, RPS8, CD79A, RPL21, IGHD, MS4A1, LINC00926, HLA-DRA, CD74, TCL1A 
##     IGLC3, IGLC2, RPS4X, VPREB3, RPL3, RP11-693J15.5, IGJ, FCER2, MEF2C, AFF3 
##     BCL11A, AC096579.7, IGHA1, IGLL5, AL928768.3, PIM2, IGHG1, MOUSE-mt-Nd1, MOUSE-mt-Cytb, MOUSE-mt-Nd4 
## Negative:  GNLY, NKG7, CCL5, GZMB, KLRF1, PRF1, KLRD1, FGFBP2, SPON2, CLIC3 
##     B2M, TYROBP, CCL4, FCER1G, KLRB1, CMC1, TRDC, HOPX, MYOM2, LGALS1 
##     FCGR3A, GZMM, FCRL6, CD247, KLRC1, S1PR5, MATK, TRGC1, APMAP, TTC38 
## PC_ 3 
## Positive:  MOUSE-Rpl41, MOUSE-Actb, MOUSE-Rpl35, MOUSE-S100a6, MOUSE-mt-Cytb, MOUSE-Lgals1, MOUSE-mt-Nd4, MOUSE-Rps8, MOUSE-Malat1, MOUSE-mt-Nd1 
##     MOUSE-Rplp1, MOUSE-Fth1, MOUSE-Rpl37, MOUSE-Rpl37a, MOUSE-Rpl18a, MOUSE-Rps29, MOUSE-Rpl13, MOUSE-Rps2, MOUSE-Ftl1, MOUSE-Rps28 
##     MOUSE-Tmsb10, MOUSE-Rps27, MOUSE-S100a4, MOUSE-Rps18, MOUSE-Rps5, MOUSE-Rpl13a, MOUSE-Gm10260, MOUSE-Fau, MOUSE-Rpl3, MOUSE-Rplp0 
## Negative:  RPL21, RPS8, B2M, RPL3, RPS4X, CD74, HLA-DRA, IGHM, CD79A, LINC00926 
##     IGJ, IGHD, MS4A1, IGLC2, TCL1A, MEF2C, VPREB3, FTH1, IGLC3, FTL 
##     RP11-693J15.5, PPP3CA, RP11-138A9.2, AFF3, PIM2, FCER2, IGHA1, BCL11A, CD69, RNU1-59P 
## PC_ 4 
## Positive:  RPL21, RPS8, RPL3, RPS4X, CD8B, CD2, GZMK, PIM2, DUSP2, B2M 
##     RP11-138A9.2, LYAR, S100A8, ZAP70, AIF1, MOUSE-Rpl18a, RBP7, MOUSE-S100a6, VCAN, MOUSE-Rps23 
##     PRDM1, S100A9, MOUSE-Lgals1, STAT4, MOUSE-Rps16, MOUSE-Rps3a1, MOUSE-Rps5, MOUSE-Rps8, G0S2, MOUSE-Rps19 
## Negative:  CD74, IGHM, HLA-DRA, IGHD, CD79A, MS4A1, TCL1A, LINC00926, IGLC3, IGLC2 
##     MEF2C, VPREB3, GNLY, IGJ, GZMB, RP11-693J15.5, FCER2, KLRF1, NKG7, BCL11A 
##     CLIC3, PRF1, SPON2, FGFBP2, AFF3, KLRD1, AC096579.7, CCL4, MYOM2, PLEK 
## PC_ 5 
## Positive:  VCAN, S100A8, S100A9, FOS, RP11-1143G9.4, CD14, CD36, LYZ, MS4A6A, LGALS2 
##     RBP7, CCL5, GZMK, DUSP2, G0S2, JUND, SGK1, TRGC2, RNU1-59P, KLRG1 
##     RNVU1-19, ALOX5AP, LYAR, KLRB1, NKG7, CMC1, GCA, CD69, IGHM, TRGC1 
## Negative:  FCGR3A, RP11-290F20.3, IFITM3, LYPD2, LST1, FCER1G, AIF1, CFD, FTH1, CST3 
##     FTL, TYROBP, SOX4, RPL21, MYOM2, RPS4X, B2M, LGALS1, PLEK, MEF2C 
##     HLA-DRA, SPON2, CLIC3, RPL3, APOBEC3C, PTGDS, CD74, S100B, GZMB, MOUSE-Rps29
```

Example 33 (r):
```r
# We select the top 10 PCs for clustering and tSNE based on PCElbowPlot
pbmc.singlet <- FindNeighbors(pbmc.singlet, reduction = "pca", dims = 1:10)
pbmc.singlet <- FindClusters(pbmc.singlet, resolution = 0.6)
```

Example 34 (r):
```r
# We select the top 10 PCs for clustering and tSNE based on PCElbowPlot
pbmc.singlet <- FindNeighbors(pbmc.singlet, reduction = "pca", dims = 1:10)
pbmc.singlet <- FindClusters(pbmc.singlet, resolution = 0.6)
```

Example 35 (unknown):
```unknown
## Modularity Optimizer version 1.3.0 by Ludo Waltman and Nees Jan van Eck
## 
## Number of nodes: 13972
## Number of edges: 450324
## 
## Running Louvain algorithm...
## Maximum modularity in 10 random starts: 0.8983
## Number of communities: 18
## Elapsed time: 2 seconds
```

Example 36 (unknown):
```unknown
## Modularity Optimizer version 1.3.0 by Ludo Waltman and Nees Jan van Eck
## 
## Number of nodes: 13972
## Number of edges: 450324
## 
## Running Louvain algorithm...
## Maximum modularity in 10 random starts: 0.8983
## Number of communities: 18
## Elapsed time: 2 seconds
```

Example 37 (r):
```r
pbmc.singlet <- RunTSNE(pbmc.singlet, reduction = "pca", dims = 1:10)

# Projecting singlet identities on TSNE visualization
DimPlot(pbmc.singlet, group.by = "HTO_classification")
```

Example 38 (r):
```r
pbmc.singlet <- RunTSNE(pbmc.singlet, reduction = "pca", dims = 1:10)

# Projecting singlet identities on TSNE visualization
DimPlot(pbmc.singlet, group.by = "HTO_classification")
```

Example 39 (r):
```r
# Read in UMI count matrix for RNA
hto12.umis <- readRDS("../data/hto12_umi_mtx.rds")

# Read in HTO count matrix
hto12.htos <- readRDS("../data/hto12_hto_mtx.rds")

# Select cell barcodes detected in both RNA and HTO
cells.use <- intersect(rownames(hto12.htos), colnames(hto12.umis))

# Create Seurat object and add HTO data
hto12 <- CreateSeuratObject(counts = hto12.umis[, cells.use], min.features = 300)
hto12[["HTO"]] <- CreateAssayObject(counts = t(x = hto12.htos[colnames(hto12), 1:12]))

# Normalize data
hto12 <- NormalizeData(hto12)
hto12 <- NormalizeData(hto12, assay = "HTO", normalization.method = "CLR")
```

Example 40 (r):
```r
# Read in UMI count matrix for RNA
hto12.umis <- readRDS("../data/hto12_umi_mtx.rds")

# Read in HTO count matrix
hto12.htos <- readRDS("../data/hto12_hto_mtx.rds")

# Select cell barcodes detected in both RNA and HTO
cells.use <- intersect(rownames(hto12.htos), colnames(hto12.umis))

# Create Seurat object and add HTO data
hto12 <- CreateSeuratObject(counts = hto12.umis[, cells.use], min.features = 300)
hto12[["HTO"]] <- CreateAssayObject(counts = t(x = hto12.htos[colnames(hto12), 1:12]))

# Normalize data
hto12 <- NormalizeData(hto12)
hto12 <- NormalizeData(hto12, assay = "HTO", normalization.method = "CLR")
```

Example 41 (r):
```r
hto12 <- HTODemux(hto12, assay = "HTO", positive.quantile = 0.99)
```

Example 42 (r):
```r
hto12 <- HTODemux(hto12, assay = "HTO", positive.quantile = 0.99)
```

Example 43 (r):
```r
RidgePlot(hto12, assay = "HTO", features = c("HEK-A", "K562-B", "KG1-A", "THP1-C"), ncol = 2)
```

Example 44 (r):
```r
RidgePlot(hto12, assay = "HTO", features = c("HEK-A", "K562-B", "KG1-A", "THP1-C"), ncol = 2)
```

Example 45 (r):
```r
HTOHeatmap(hto12, assay = "HTO")
```

Example 46 (r):
```r
HTOHeatmap(hto12, assay = "HTO")
```

Example 47 (r):
```r
# Remove the negative cells
hto12 <- subset(hto12, idents = "Negative", invert = TRUE)

# Run PCA on most variable features
hto12 <- FindVariableFeatures(hto12, selection.method = "mean.var.plot")
hto12 <- ScaleData(hto12, features = VariableFeatures(hto12))
hto12 <- RunPCA(hto12)
```

Example 48 (r):
```r
# Remove the negative cells
hto12 <- subset(hto12, idents = "Negative", invert = TRUE)

# Run PCA on most variable features
hto12 <- FindVariableFeatures(hto12, selection.method = "mean.var.plot")
hto12 <- ScaleData(hto12, features = VariableFeatures(hto12))
hto12 <- RunPCA(hto12)
```

Example 49 (unknown):
```unknown
## PC_ 1 
## Positive:  MDK, ID3, XIST, CKB, HES4, YDJC, HBG1, HIST1H2BK, HBG2, HSPA1A 
##     HMBS, NMU, GYPA, HBE1, HBZ, BLVRB, HBA1, HIST1H1C, MYL4, RFESD 
##     HBA2, RP11-462G2.1, PRAME, GYPB, SDF2L1, PHF19, HIST1H2BJ, HEMGN, HIST1H2AC, UROD 
## Negative:  GMFG, RPS4Y1, AIF1, ARHGDIB, TMSB4X, VAMP8, B2M, S100A4, CD74, IGFBP7 
##     LST1, SRGN, CLEC11A, NUCB2, EIF1AY, CAPG, HLA-DRA, HLA-DRB1, PSMB8, ALOX5AP 
##     LGALS1, CYP1B1, PRSS57, HPGDS, PLAC8, RAC2, CORO1A, PYCARD, CD37, NCF4 
## PC_ 2 
## Positive:  ITM2A, HLA-DRA, PRSS57, HPGDS, PTPRCAP, HLA-DPA1, HOPX, CD74, HLA-DPB1, DSCC1 
##     CD34, CYP1B1, SPINT2, C19orf77, CTSW, IL2RG, IFI16, RP11-354E11.2, RAB27B, SLC9A3R1 
##     HLA-DMA, CLEC2B, IQGAP2, UBE2L6, KIAA0125, SAMSN1, TSTD1, C12orf75, ICAM3, GATA2 
## Negative:  AZU1, ELANE, PRTN3, CHI3L1, CITED4, CAP1, PPT1, CFD, CTSG, LYST 
##     S100A6, CSTA, MS4A3, SLPI, MNDA, PPCS, NFYC, RNASE2, PPP1R27, SMAP2 
##     BMP8B, TREM2, APLP2, MS4A6A, IRF8, FCGRT, DHRS9, SLC44A1, AGT, ZMPSTE24 
## PC_ 3 
## Positive:  HBG1, HBG2, GYPA, HBE1, MYL4, RP11-462G2.1, PRAME, HBA1, HBZ, GTSF1 
##     GYPB, HBA2, BLVRB, HEMGN, HIST1H1C, RFESD, HIST1H2AC, HIST1H2BK, NMU, HIST1H2BJ 
##     RHAG, ALAS2, HBD, PHF19, PAGE1, SNCG, TNNI3, SLC25A37, JUNB, RP11-301G19.1 
## Negative:  NGFRAP1, S100A10, CDKN2A, VIM, UCHL1, CNN3, CALD1, ZNF503, DMKN, XIST 
##     PLS3, RP6-24A23.7, TSC22D3, ID4, SOX4, HOTAIRM1, TUBB2B, NEFL, UBE2C, ID3 
##     CSRP2, HSPA1A, PMAIP1, HES4, ID2, HSPA1B, HAND1, C12orf75, SLIT2, EIF4A1 
## PC_ 4 
## Positive:  HSD17B4, PLEK, HPGDS, HGF, PRSS57, ADCYAP1, CA2, CST7, MT-ND3, ALS2 
##     CSF2RB, LINC01088, DBI, MT-ND2, MT-RNR2, CALR, MT-CYB, DTWD2, DSCC1, IKZF2 
##     SNTB1, BACE2, AE000661.37, SLA, MT-CO1, CD84, RP11-317J10.2, RP11-643A5.2, RAB32, CLEC11A 
## Negative:  REG4, LTB, CYTIP, NRP2, ALDH1A1, DUSP6, S100B, SLC9A3R1, RAMP1, HOPX 
##     ABI3, VCAN, CYTL1, CYP1B1, GNG11, SQLE, SLC2A5, SAMSN1, PTPRC, CALCRL 
##     LAPTM5, HPGD, C10orf54, MTSS1, LY96, ANGPT2, GSN, C6orf141, C10orf128, TIMP1 
## PC_ 5 
## Positive:  CST3, TYROBP, S100A9, FCER1A, IFI6, IFI30, GRN, FCER1G, NPC2, S100A8 
##     APOE, NUPR1, ASAH1, SH3BGRL3, DBI, SPP1, HLA-C, ALOX5AP, CTSD, ANXA1 
##     GLIPR1, CTSS, AP1S2, B2M, TIMP1, S100A11, APOC1, LYZ, RNF130, RP11-354E11.2 
## Negative:  C6orf141, CTSG, HOPX, CLDN10, RASGRP2, REG4, MS4A3, NRP2, NUCB2, LTB 
##     SLC2A5, PRTN3, DNAJC15, MLC1, PPP1R27, MT-ND5, MYC, SPINK2, BMP8B, PTPRCAP 
##     GNG11, SATB1, SERPINB2, MTSS1, RAMP1, CYTIP, STOM, KIAA0125, GLYATL2, ALDH1A1
```

Example 50 (unknown):
```unknown
## PC_ 1 
## Positive:  MDK, ID3, XIST, CKB, HES4, YDJC, HBG1, HIST1H2BK, HBG2, HSPA1A 
##     HMBS, NMU, GYPA, HBE1, HBZ, BLVRB, HBA1, HIST1H1C, MYL4, RFESD 
##     HBA2, RP11-462G2.1, PRAME, GYPB, SDF2L1, PHF19, HIST1H2BJ, HEMGN, HIST1H2AC, UROD 
## Negative:  GMFG, RPS4Y1, AIF1, ARHGDIB, TMSB4X, VAMP8, B2M, S100A4, CD74, IGFBP7 
##     LST1, SRGN, CLEC11A, NUCB2, EIF1AY, CAPG, HLA-DRA, HLA-DRB1, PSMB8, ALOX5AP 
##     LGALS1, CYP1B1, PRSS57, HPGDS, PLAC8, RAC2, CORO1A, PYCARD, CD37, NCF4 
## PC_ 2 
## Positive:  ITM2A, HLA-DRA, PRSS57, HPGDS, PTPRCAP, HLA-DPA1, HOPX, CD74, HLA-DPB1, DSCC1 
##     CD34, CYP1B1, SPINT2, C19orf77, CTSW, IL2RG, IFI16, RP11-354E11.2, RAB27B, SLC9A3R1 
##     HLA-DMA, CLEC2B, IQGAP2, UBE2L6, KIAA0125, SAMSN1, TSTD1, C12orf75, ICAM3, GATA2 
## Negative:  AZU1, ELANE, PRTN3, CHI3L1, CITED4, CAP1, PPT1, CFD, CTSG, LYST 
##     S100A6, CSTA, MS4A3, SLPI, MNDA, PPCS, NFYC, RNASE2, PPP1R27, SMAP2 
##     BMP8B, TREM2, APLP2, MS4A6A, IRF8, FCGRT, DHRS9, SLC44A1, AGT, ZMPSTE24 
## PC_ 3 
## Positive:  HBG1, HBG2, GYPA, HBE1, MYL4, RP11-462G2.1, PRAME, HBA1, HBZ, GTSF1 
##     GYPB, HBA2, BLVRB, HEMGN, HIST1H1C, RFESD, HIST1H2AC, HIST1H2BK, NMU, HIST1H2BJ 
##     RHAG, ALAS2, HBD, PHF19, PAGE1, SNCG, TNNI3, SLC25A37, JUNB, RP11-301G19.1 
## Negative:  NGFRAP1, S100A10, CDKN2A, VIM, UCHL1, CNN3, CALD1, ZNF503, DMKN, XIST 
##     PLS3, RP6-24A23.7, TSC22D3, ID4, SOX4, HOTAIRM1, TUBB2B, NEFL, UBE2C, ID3 
##     CSRP2, HSPA1A, PMAIP1, HES4, ID2, HSPA1B, HAND1, C12orf75, SLIT2, EIF4A1 
## PC_ 4 
## Positive:  HSD17B4, PLEK, HPGDS, HGF, PRSS57, ADCYAP1, CA2, CST7, MT-ND3, ALS2 
##     CSF2RB, LINC01088, DBI, MT-ND2, MT-RNR2, CALR, MT-CYB, DTWD2, DSCC1, IKZF2 
##     SNTB1, BACE2, AE000661.37, SLA, MT-CO1, CD84, RP11-317J10.2, RP11-643A5.2, RAB32, CLEC11A 
## Negative:  REG4, LTB, CYTIP, NRP2, ALDH1A1, DUSP6, S100B, SLC9A3R1, RAMP1, HOPX 
##     ABI3, VCAN, CYTL1, CYP1B1, GNG11, SQLE, SLC2A5, SAMSN1, PTPRC, CALCRL 
##     LAPTM5, HPGD, C10orf54, MTSS1, LY96, ANGPT2, GSN, C6orf141, C10orf128, TIMP1 
## PC_ 5 
## Positive:  CST3, TYROBP, S100A9, FCER1A, IFI6, IFI30, GRN, FCER1G, NPC2, S100A8 
##     APOE, NUPR1, ASAH1, SH3BGRL3, DBI, SPP1, HLA-C, ALOX5AP, CTSD, ANXA1 
##     GLIPR1, CTSS, AP1S2, B2M, TIMP1, S100A11, APOC1, LYZ, RNF130, RP11-354E11.2 
## Negative:  C6orf141, CTSG, HOPX, CLDN10, RASGRP2, REG4, MS4A3, NRP2, NUCB2, LTB 
##     SLC2A5, PRTN3, DNAJC15, MLC1, PPP1R27, MT-ND5, MYC, SPINK2, BMP8B, PTPRCAP 
##     GNG11, SATB1, SERPINB2, MTSS1, RAMP1, CYTIP, STOM, KIAA0125, GLYATL2, ALDH1A1
```

Example 51 (r):
```r
hto12 <- RunTSNE(hto12, dims = 1:5, perplexity = 100)
DimPlot(hto12) + NoLegend()
```

Example 52 (r):
```r
hto12 <- RunTSNE(hto12, dims = 1:5, perplexity = 100)
DimPlot(hto12) + NoLegend()
```

---

## Analysis, visualization, and integration of Visium HD spatial datasets with Seurat • Seurat

**URL:** http://127.0.0.1:9173/articles_seurat5_integration_bridge.html

**Contents:**
- Dictionary Learning for cross-modality integration
    - Compiled: October 31, 2023
    - Azimuth ATAC for Bridge Integration
  - Load the bridge, query, and reference datasets
- Preprocessing/normalization for all datasets
  - Map scATAC-seq dataset using bridge integration
  - Assessing the mapping
- Contents

In the same way that read mapping tools have transformed genome sequence analysis, the ability to map new datasets to established references represents an exciting opportunity for the field of single-cell genomics. Along with others in the community, we have developed tools to map and interpret query datasets, and have also constructed a set of scRNA-seq datasets for diverse mammalian tissues.

A key challenge is to extend this reference mapping framework to technologies that do not measure gene expression, even if the underlying reference is based on scRNA-seq. In Hao et al, Nat Biotechnol 2023, we introduce ‘bridge integration’, which enables the mapping of complementary technologies (like scATAC-seq, scDNAme, CyTOF), onto scRNA-seq references, using a ‘multi-omic’ dataset as a molecular bridge. In this vignette, we demonstrate how to map an scATAC-seq dataset of human PBMC, onto our previously constructed PBMC reference. We use a publicly available 10x multiome dataset, which simultaneously measures gene expression and chromatin accessibility in the same cell, as a bridge dataset.

In this vignette we demonstrate:

Users can now automatically run bridge integration for PBMC and Bone Marrow scATAC-seq queries with the newly released Azimuth ATAC workflow on the Azimuth website or in R. For more details on running locally in R, see the section on ATAC data in this vignette.

We start by loading a 10x multiome dataset, consisting of ~12,000 PBMC from a healthy donor. The dataset measures RNA-seq and ATAC-seq in the same cell, and is available for download from 10x Genomics here. We follow the loading instructions from the Signac package vignettes. Note that when using Signac, please make sure you are using the latest version of Bioconductor, as users have reported errors when using older BioC versions.

Load and setup the 10x multiome object

The scATAC-seq query dataset represents ~10,000 PBMC from a healthy donor, and is available for download here. We load in the peak/cell matrix, store the path to the fragments file, and add gene annotations to the object, following the steps as with the ATAC data in the multiome experiment.

We note that it is important to quantify the same set of genomic features in the query dataset as are quantified in the multi-omic bridge. We therefore requantify the set of scATAC-seq peaks using the FeatureMatrix command. This is also described in the Signac vignettes and shown below.

Load and setup the 10x scATAC-seq query

We load the reference (download here) from our recent paper. This reference is stored as an h5Seurat file, a format that enables on-disk storage of multimodal Seurat objects (more details on h5Seurat and SeuratDisk can be found here).

What if I want to use my own reference dataset?

As an alternative to using a pre-built reference, you can also use your own reference. To demonstrate, you can download a scRNA-seq dataset of 23,837 human PBMC here, which we have already annotated.

When using your own reference, set reference.reduction = "pca" in the PrepareBridgeReference function.

Prior to performing bridge integration, we normalize and pre-process each of the datasets (note that the reference has already been normalized). We normalize gene expression data using sctransform, and ATAC data using TF-IDF.

Now that we have the reference, query, and bridge datasets set up, we can begin integration. The bridge dataset enables translation between the scRNA-seq reference and the scATAC-seq query, effectively augmenting the reference so that it can map a new data type. We call this an extended reference, and first set it up. Note that you can save the results of this function and map multiple scATAC-seq datasets without having to rerun.

First, we drop the first dimension of the ATAC reduction.

Now, we can directly find anchors between the extended reference and query objects. We use the FindBridgeTransferAnchors function, which translates the query dataset using the same dictionary as was used to translate the reference, and then identifies anchors in this space. The function is meant to mimic our FindTransferAnchors function, but to identify correspondences across modalities.

Once we have identified anchors, we can map the query dataset onto the reference. The MapQuery function is the same as we have previously introduced for reference mapping . It transfers cell annotations from the reference dataset, and also visualizes the query dataset on a previously computed UMAP embedding. Since our reference dataset contains cell type annotations at three levels of resolution (l1 - l3), we can transfer each level to the query dataset.

Now we can visualize the results, plotting the scATAC-seq cells based on their predicted annotations, on the reference UMAP embedding. You can see that each scATAC-seq cell has been assigned a cell name based on the scRNA-seq defined cell ontology.

To assess the mapping and cell type predictions, we will first see if the predicted cell type labels are concordant with an unsupervised analysis of the scATAC-seq dataset. We follow the standard unsupervised processing workflow for scATAC-seq data:

Now, we visualize the predicted cluster labels on the unsupervised UMAP emebdding. We can see that predicted cluster labels (from the scRNA-seq reference) are concordant with the structure of the scATAC-seq data. However, there are some cell types (i.e. Treg), that do not appear to separate in unsupervised analysis. These may be prediction errors, or cases where the reference mapping provides additional resolution.

Lastly, we validate the predicted cell types for the scATAC-seq data by examining their chromatin accessibility profiles at canonical loci. We use the CoveragePlot function to visualize accessibility patterns at the CD8A, FOXP3, and RORC, after grouping cells by their predicted labels. We see expected patterns in each case. For example, the PAX5 locus exhibits peaks that are accessible exclusively in B cells, and the CD8A locus shows the same in CD8 T cell subsets. Similarly, the accessibility of FOXP3, a canonical marker of regulatory T cells (Tregs), in predicted Tregs provides strong support for the accuracy of our prediction.

Developed by Rahul Satija, Satija Lab and Collaborators.

Site built with pkgdown 2.0.7.

**Examples:**

Example 1 (unknown):
```unknown
vignettes/seurat5_integration_bridge.Rmd
```

Example 2 (unknown):
```unknown
seurat5_integration_bridge.Rmd
```

Example 3 (unknown):
```unknown
library(Seurat)
library(Signac)
library(EnsDb.Hsapiens.v86)
library(dplyr)
library(ggplot2)
```

Example 4 (r):
```r
library(Seurat)
library(Signac)
library(EnsDb.Hsapiens.v86)
library(dplyr)
library(ggplot2)
```

Example 5 (r):
```r
library(Seurat)
library(Signac)
library(EnsDb.Hsapiens.v86)
library(dplyr)
library(ggplot2)
```

Example 6 (unknown):
```unknown
# the 10x hdf5 file contains both data types.
inputdata.10x <- Read10X_h5("/brahms/hartmana/vignette_data/pbmc_cellranger_arc_2/pbmc_granulocyte_sorted_10k_filtered_feature_bc_matrix.h5")
# extract RNA and ATAC data
rna_counts <- inputdata.10x$`Gene Expression`
atac_counts <- inputdata.10x$Peaks
# Create Seurat object
obj.multi <- CreateSeuratObject(counts = rna_counts)
# Get % of mitochondrial genes
obj.multi[["percent.mt"]] <- PercentageFeatureSet(obj.multi, pattern = "^MT-")

# add the ATAC-seq assay
grange.counts <- StringToGRanges(rownames(atac_counts), sep = c(":", "-"))
grange.use <- seqnames(grange.counts) %in% standardChromosomes(grange.counts)
atac_counts <- atac_counts[as.vector(grange.use), ]
# Get gene annotations
annotations <- GetGRangesFromEnsDb(ensdb = EnsDb.Hsapiens.v86)
# Change style to UCSC
seqlevelsStyle(annotations) <- 'UCSC'
genome(annotations) <- "hg38"
# File with ATAC per fragment information file
frag.file <- "/brahms/hartmana/vignette_data/pbmc_cellranger_arc_2/pbmc_granulocyte_sorted_10k_atac_fragments.tsv.gz"
# Add in ATAC-seq data as ChromatinAssay object
chrom_assay <- CreateChromatinAssay(
  counts = atac_counts,
  sep = c(":", "-"),
  genome = 'hg38',
  fragments = frag.file,
  min.cells = 10,
  annotation = annotations
)
# Add the ATAC assay to the multiome object
obj.multi[["ATAC"]] <- chrom_assay
# Filter ATAC data based on QC metrics
obj.multi <- subset(
  x = obj.multi,
  subset = nCount_ATAC < 7e4 &
    nCount_ATAC > 5e3 &
    nCount_RNA < 25000 &
    nCount_RNA > 1000 &
    percent.mt < 20
)
```

Example 7 (r):
```r
# the 10x hdf5 file contains both data types.
inputdata.10x <- Read10X_h5("/brahms/hartmana/vignette_data/pbmc_cellranger_arc_2/pbmc_granulocyte_sorted_10k_filtered_feature_bc_matrix.h5")
# extract RNA and ATAC data
rna_counts <- inputdata.10x$`Gene Expression`
atac_counts <- inputdata.10x$Peaks
# Create Seurat object
obj.multi <- CreateSeuratObject(counts = rna_counts)
# Get % of mitochondrial genes
obj.multi[["percent.mt"]] <- PercentageFeatureSet(obj.multi, pattern = "^MT-")

# add the ATAC-seq assay
grange.counts <- StringToGRanges(rownames(atac_counts), sep = c(":", "-"))
grange.use <- seqnames(grange.counts) %in% standardChromosomes(grange.counts)
atac_counts <- atac_counts[as.vector(grange.use), ]
# Get gene annotations
annotations <- GetGRangesFromEnsDb(ensdb = EnsDb.Hsapiens.v86)
# Change style to UCSC
seqlevelsStyle(annotations) <- 'UCSC'
genome(annotations) <- "hg38"
# File with ATAC per fragment information file
frag.file <- "/brahms/hartmana/vignette_data/pbmc_cellranger_arc_2/pbmc_granulocyte_sorted_10k_atac_fragments.tsv.gz"
# Add in ATAC-seq data as ChromatinAssay object
chrom_assay <- CreateChromatinAssay(
  counts = atac_counts,
  sep = c(":", "-"),
  genome = 'hg38',
  fragments = frag.file,
  min.cells = 10,
  annotation = annotations
)
# Add the ATAC assay to the multiome object
obj.multi[["ATAC"]] <- chrom_assay
# Filter ATAC data based on QC metrics
obj.multi <- subset(
  x = obj.multi,
  subset = nCount_ATAC < 7e4 &
    nCount_ATAC > 5e3 &
    nCount_RNA < 25000 &
    nCount_RNA > 1000 &
    percent.mt < 20
)
```

Example 8 (r):
```r
# the 10x hdf5 file contains both data types.
inputdata.10x <- Read10X_h5("/brahms/hartmana/vignette_data/pbmc_cellranger_arc_2/pbmc_granulocyte_sorted_10k_filtered_feature_bc_matrix.h5")
# extract RNA and ATAC data
rna_counts <- inputdata.10x$`Gene Expression`
atac_counts <- inputdata.10x$Peaks
# Create Seurat object
obj.multi <- CreateSeuratObject(counts = rna_counts)
# Get % of mitochondrial genes
obj.multi[["percent.mt"]] <- PercentageFeatureSet(obj.multi, pattern = "^MT-")

# add the ATAC-seq assay
grange.counts <- StringToGRanges(rownames(atac_counts), sep = c(":", "-"))
grange.use <- seqnames(grange.counts) %in% standardChromosomes(grange.counts)
atac_counts <- atac_counts[as.vector(grange.use), ]
# Get gene annotations
annotations <- GetGRangesFromEnsDb(ensdb = EnsDb.Hsapiens.v86)
# Change style to UCSC
seqlevelsStyle(annotations) <- 'UCSC'
genome(annotations) <- "hg38"
# File with ATAC per fragment information file
frag.file <- "/brahms/hartmana/vignette_data/pbmc_cellranger_arc_2/pbmc_granulocyte_sorted_10k_atac_fragments.tsv.gz"
# Add in ATAC-seq data as ChromatinAssay object
chrom_assay <- CreateChromatinAssay(
  counts = atac_counts,
  sep = c(":", "-"),
  genome = 'hg38',
  fragments = frag.file,
  min.cells = 10,
  annotation = annotations
)
# Add the ATAC assay to the multiome object
obj.multi[["ATAC"]] <- chrom_assay
# Filter ATAC data based on QC metrics
obj.multi <- subset(
  x = obj.multi,
  subset = nCount_ATAC < 7e4 &
    nCount_ATAC > 5e3 &
    nCount_RNA < 25000 &
    nCount_RNA > 1000 &
    percent.mt < 20
)
```

Example 9 (unknown):
```unknown
FeatureMatrix
```

Example 10 (unknown):
```unknown
# Load ATAC dataset
atac_pbmc_data <- Read10X_h5(filename = "/brahms/hartmana/vignette_data/10k_PBMC_ATAC_nextgem_Chromium_X_filtered_peak_bc_matrix.h5") 
fragpath <- "/brahms/hartmana/vignette_data/10k_PBMC_ATAC_nextgem_Chromium_X_fragments.tsv.gz"
# Get gene annotations
annotation <- GetGRangesFromEnsDb(ensdb = EnsDb.Hsapiens.v86)
# Change to UCSC style 
seqlevelsStyle(annotation) <- 'UCSC'
# Create ChromatinAssay for ATAC data
atac_pbmc_assay <- CreateChromatinAssay(
  counts = atac_pbmc_data,
  sep = c(":", "-"),
  fragments = fragpath,
  annotation = annotation
)
# Requantify query ATAC to have same features as multiome ATAC dataset
requant_multiome_ATAC <- FeatureMatrix(
  fragments = Fragments(atac_pbmc_assay),
  features = granges(obj.multi[['ATAC']]),
  cells = Cells(atac_pbmc_assay)
)
# Create assay with requantified ATAC data
ATAC_assay <- CreateChromatinAssay(
  counts = requant_multiome_ATAC,
  fragments = fragpath,
  annotation = annotation
)
# Create Seurat sbject
obj.atac  <- CreateSeuratObject(counts = ATAC_assay,assay = 'ATAC')
obj.atac[['peak.orig']] <- atac_pbmc_assay
obj.atac <- subset(obj.atac, subset = nCount_ATAC < 7e4 & nCount_ATAC > 2000)
```

Example 11 (r):
```r
# Load ATAC dataset
atac_pbmc_data <- Read10X_h5(filename = "/brahms/hartmana/vignette_data/10k_PBMC_ATAC_nextgem_Chromium_X_filtered_peak_bc_matrix.h5") 
fragpath <- "/brahms/hartmana/vignette_data/10k_PBMC_ATAC_nextgem_Chromium_X_fragments.tsv.gz"
# Get gene annotations
annotation <- GetGRangesFromEnsDb(ensdb = EnsDb.Hsapiens.v86)
# Change to UCSC style 
seqlevelsStyle(annotation) <- 'UCSC'
# Create ChromatinAssay for ATAC data
atac_pbmc_assay <- CreateChromatinAssay(
  counts = atac_pbmc_data,
  sep = c(":", "-"),
  fragments = fragpath,
  annotation = annotation
)
# Requantify query ATAC to have same features as multiome ATAC dataset
requant_multiome_ATAC <- FeatureMatrix(
  fragments = Fragments(atac_pbmc_assay),
  features = granges(obj.multi[['ATAC']]),
  cells = Cells(atac_pbmc_assay)
)
# Create assay with requantified ATAC data
ATAC_assay <- CreateChromatinAssay(
  counts = requant_multiome_ATAC,
  fragments = fragpath,
  annotation = annotation
)
# Create Seurat sbject
obj.atac  <- CreateSeuratObject(counts = ATAC_assay,assay = 'ATAC')
obj.atac[['peak.orig']] <- atac_pbmc_assay
obj.atac <- subset(obj.atac, subset = nCount_ATAC < 7e4 & nCount_ATAC > 2000)
```

Example 12 (r):
```r
# Load ATAC dataset
atac_pbmc_data <- Read10X_h5(filename = "/brahms/hartmana/vignette_data/10k_PBMC_ATAC_nextgem_Chromium_X_filtered_peak_bc_matrix.h5") 
fragpath <- "/brahms/hartmana/vignette_data/10k_PBMC_ATAC_nextgem_Chromium_X_fragments.tsv.gz"
# Get gene annotations
annotation <- GetGRangesFromEnsDb(ensdb = EnsDb.Hsapiens.v86)
# Change to UCSC style 
seqlevelsStyle(annotation) <- 'UCSC'
# Create ChromatinAssay for ATAC data
atac_pbmc_assay <- CreateChromatinAssay(
  counts = atac_pbmc_data,
  sep = c(":", "-"),
  fragments = fragpath,
  annotation = annotation
)
# Requantify query ATAC to have same features as multiome ATAC dataset
requant_multiome_ATAC <- FeatureMatrix(
  fragments = Fragments(atac_pbmc_assay),
  features = granges(obj.multi[['ATAC']]),
  cells = Cells(atac_pbmc_assay)
)
# Create assay with requantified ATAC data
ATAC_assay <- CreateChromatinAssay(
  counts = requant_multiome_ATAC,
  fragments = fragpath,
  annotation = annotation
)
# Create Seurat sbject
obj.atac  <- CreateSeuratObject(counts = ATAC_assay,assay = 'ATAC')
obj.atac[['peak.orig']] <- atac_pbmc_assay
obj.atac <- subset(obj.atac, subset = nCount_ATAC < 7e4 & nCount_ATAC > 2000)
```

Example 13 (unknown):
```unknown
obj.rna <- readRDS("/brahms/haoy/seurat4_pbmc/pbmc_multimodal_2023.rds")
```

Example 14 (r):
```r
obj.rna <- readRDS("/brahms/haoy/seurat4_pbmc/pbmc_multimodal_2023.rds")
```

Example 15 (r):
```r
obj.rna <- readRDS("/brahms/haoy/seurat4_pbmc/pbmc_multimodal_2023.rds")
```

Example 16 (unknown):
```unknown
obj.rna = readRDS("/path/to/reference.rds")
obj.rna = SCTransform(object = obj.rna) %>%
  RunPCA() %>%
  RunUMAP(dims = 1:50, return.model = TRUE)
```

Example 17 (r):
```r
obj.rna = readRDS("/path/to/reference.rds")
obj.rna = SCTransform(object = obj.rna) %>%
  RunPCA() %>%
  RunUMAP(dims = 1:50, return.model = TRUE)
```

Example 18 (r):
```r
obj.rna = readRDS("/path/to/reference.rds")
obj.rna = SCTransform(object = obj.rna) %>%
  RunPCA() %>%
  RunUMAP(dims = 1:50, return.model = TRUE)
```

Example 19 (unknown):
```unknown
reference.reduction = "pca"
```

Example 20 (unknown):
```unknown
PrepareBridgeReference
```

Example 21 (unknown):
```unknown
# normalize multiome RNA
DefaultAssay(obj.multi) <- "RNA"
obj.multi <- SCTransform(obj.multi, verbose = FALSE)
# normalize multiome ATAC
DefaultAssay(obj.multi) <- "ATAC"
obj.multi <- RunTFIDF(obj.multi)
obj.multi <- FindTopFeatures(obj.multi, min.cutoff = "q0")
# normalize query
obj.atac <- RunTFIDF(obj.atac)
```

Example 22 (r):
```r
# normalize multiome RNA
DefaultAssay(obj.multi) <- "RNA"
obj.multi <- SCTransform(obj.multi, verbose = FALSE)
# normalize multiome ATAC
DefaultAssay(obj.multi) <- "ATAC"
obj.multi <- RunTFIDF(obj.multi)
obj.multi <- FindTopFeatures(obj.multi, min.cutoff = "q0")
# normalize query
obj.atac <- RunTFIDF(obj.atac)
```

Example 23 (r):
```r
# normalize multiome RNA
DefaultAssay(obj.multi) <- "RNA"
obj.multi <- SCTransform(obj.multi, verbose = FALSE)
# normalize multiome ATAC
DefaultAssay(obj.multi) <- "ATAC"
obj.multi <- RunTFIDF(obj.multi)
obj.multi <- FindTopFeatures(obj.multi, min.cutoff = "q0")
# normalize query
obj.atac <- RunTFIDF(obj.atac)
```

Example 24 (unknown):
```unknown
dims.atac <- 2:50
dims.rna <- 1:50
DefaultAssay(obj.multi) <-  "RNA"
DefaultAssay(obj.rna) <- "SCT"
obj.rna.ext <- PrepareBridgeReference(
  reference = obj.rna, bridge = obj.multi,
  reference.reduction = "spca", reference.dims = dims.rna,
  normalization.method = "SCT")
```

Example 25 (r):
```r
dims.atac <- 2:50
dims.rna <- 1:50
DefaultAssay(obj.multi) <-  "RNA"
DefaultAssay(obj.rna) <- "SCT"
obj.rna.ext <- PrepareBridgeReference(
  reference = obj.rna, bridge = obj.multi,
  reference.reduction = "spca", reference.dims = dims.rna,
  normalization.method = "SCT")
```

Example 26 (r):
```r
dims.atac <- 2:50
dims.rna <- 1:50
DefaultAssay(obj.multi) <-  "RNA"
DefaultAssay(obj.rna) <- "SCT"
obj.rna.ext <- PrepareBridgeReference(
  reference = obj.rna, bridge = obj.multi,
  reference.reduction = "spca", reference.dims = dims.rna,
  normalization.method = "SCT")
```

Example 27 (unknown):
```unknown
FindBridgeTransferAnchors
```

Example 28 (unknown):
```unknown
FindTransferAnchors
```

Example 29 (unknown):
```unknown
bridge.anchor <- FindBridgeTransferAnchors(
  extended.reference = obj.rna.ext, query = obj.atac,
  reduction = "lsiproject", dims = dims.atac)
```

Example 30 (r):
```r
bridge.anchor <- FindBridgeTransferAnchors(
  extended.reference = obj.rna.ext, query = obj.atac,
  reduction = "lsiproject", dims = dims.atac)
```

Example 31 (r):
```r
bridge.anchor <- FindBridgeTransferAnchors(
  extended.reference = obj.rna.ext, query = obj.atac,
  reduction = "lsiproject", dims = dims.atac)
```

Example 32 (unknown):
```unknown
obj.atac <- MapQuery(
  anchorset = bridge.anchor, reference = obj.rna.ext,
  query = obj.atac,
  refdata = list(
    l1 = "celltype.l1",
    l2 = "celltype.l2",
    l3 = "celltype.l3"),
  reduction.model = "wnn.umap")
```

Example 33 (r):
```r
obj.atac <- MapQuery(
  anchorset = bridge.anchor, reference = obj.rna.ext,
  query = obj.atac,
  refdata = list(
    l1 = "celltype.l1",
    l2 = "celltype.l2",
    l3 = "celltype.l3"),
  reduction.model = "wnn.umap")
```

Example 34 (r):
```r
obj.atac <- MapQuery(
  anchorset = bridge.anchor, reference = obj.rna.ext,
  query = obj.atac,
  refdata = list(
    l1 = "celltype.l1",
    l2 = "celltype.l2",
    l3 = "celltype.l3"),
  reduction.model = "wnn.umap")
```

Example 35 (unknown):
```unknown
DimPlot(
  obj.atac, group.by = "predicted.l2",
  reduction = "ref.umap", label = TRUE
) + ggtitle("ATAC") + NoLegend()
```

Example 36 (r):
```r
DimPlot(
  obj.atac, group.by = "predicted.l2",
  reduction = "ref.umap", label = TRUE
) + ggtitle("ATAC") + NoLegend()
```

Example 37 (r):
```r
DimPlot(
  obj.atac, group.by = "predicted.l2",
  reduction = "ref.umap", label = TRUE
) + ggtitle("ATAC") + NoLegend()
```

Example 38 (unknown):
```unknown
obj.atac <- FindTopFeatures(obj.atac, min.cutoff = "q0")
obj.atac <- RunSVD(obj.atac)
obj.atac <- RunUMAP(obj.atac, reduction = "lsi", dims = 2:50)
```

Example 39 (r):
```r
obj.atac <- FindTopFeatures(obj.atac, min.cutoff = "q0")
obj.atac <- RunSVD(obj.atac)
obj.atac <- RunUMAP(obj.atac, reduction = "lsi", dims = 2:50)
```

Example 40 (r):
```r
obj.atac <- FindTopFeatures(obj.atac, min.cutoff = "q0")
obj.atac <- RunSVD(obj.atac)
obj.atac <- RunUMAP(obj.atac, reduction = "lsi", dims = 2:50)
```

Example 41 (unknown):
```unknown
DimPlot(obj.atac, group.by = "predicted.l2", reduction = "umap", label = FALSE)
```

Example 42 (r):
```r
DimPlot(obj.atac, group.by = "predicted.l2", reduction = "umap", label = FALSE)
```

Example 43 (r):
```r
DimPlot(obj.atac, group.by = "predicted.l2", reduction = "umap", label = FALSE)
```

Example 44 (unknown):
```unknown
CoveragePlot
```

Example 45 (unknown):
```unknown
CoveragePlot(
  obj.atac, region  = "PAX5", group.by = "predicted.l1",
  idents = c("B", "CD4 T", "Mono", "NK"), window = 200,
  extend.upstream = -150000)
```

Example 46 (r):
```r
CoveragePlot(
  obj.atac, region  = "PAX5", group.by = "predicted.l1",
  idents = c("B", "CD4 T", "Mono", "NK"), window = 200,
  extend.upstream = -150000)
```

Example 47 (r):
```r
CoveragePlot(
  obj.atac, region  = "PAX5", group.by = "predicted.l1",
  idents = c("B", "CD4 T", "Mono", "NK"), window = 200,
  extend.upstream = -150000)
```

Example 48 (unknown):
```unknown
CoveragePlot(
  obj.atac, region = "CD8A", group.by = "predicted.l2",
  idents = c("CD8 Naive", "CD4 Naive", "CD4 TCM", "CD8 TCM"),
  extend.downstream = 5000, extend.upstream = 5000)
```

Example 49 (r):
```r
CoveragePlot(
  obj.atac, region = "CD8A", group.by = "predicted.l2",
  idents = c("CD8 Naive", "CD4 Naive", "CD4 TCM", "CD8 TCM"),
  extend.downstream = 5000, extend.upstream = 5000)
```

Example 50 (r):
```r
CoveragePlot(
  obj.atac, region = "CD8A", group.by = "predicted.l2",
  idents = c("CD8 Naive", "CD4 Naive", "CD4 TCM", "CD8 TCM"),
  extend.downstream = 5000, extend.upstream = 5000)
```

Example 51 (unknown):
```unknown
CoveragePlot(
  obj.atac, region = "FOXP3", group.by = "predicted.l2",
  idents = c( "CD4 Naive", "CD4 TCM", "CD4 TEM", "Treg"),
  extend.downstream = 0, extend.upstream = 0)
```

Example 52 (r):
```r
CoveragePlot(
  obj.atac, region = "FOXP3", group.by = "predicted.l2",
  idents = c( "CD4 Naive", "CD4 TCM", "CD4 TEM", "Treg"),
  extend.downstream = 0, extend.upstream = 0)
```

Example 53 (r):
```r
CoveragePlot(
  obj.atac, region = "FOXP3", group.by = "predicted.l2",
  idents = c( "CD4 Naive", "CD4 TCM", "CD4 TEM", "Treg"),
  extend.downstream = 0, extend.upstream = 0)
```

Example 54 (unknown):
```unknown
CoveragePlot(
  obj.atac, region = "RORC", group.by = "predicted.l2",
  idents = c("CD8 Naive", "CD8 TEM", "CD8 TCM", "MAIT"),
  extend.downstream = 5000, extend.upstream = 5000)
```

Example 55 (r):
```r
CoveragePlot(
  obj.atac, region = "RORC", group.by = "predicted.l2",
  idents = c("CD8 Naive", "CD8 TEM", "CD8 TCM", "MAIT"),
  extend.downstream = 5000, extend.upstream = 5000)
```

Example 56 (r):
```r
CoveragePlot(
  obj.atac, region = "RORC", group.by = "predicted.l2",
  idents = c("CD8 Naive", "CD8 TEM", "CD8 TCM", "MAIT"),
  extend.downstream = 5000, extend.upstream = 5000)
```

Example 57 (unknown):
```unknown
sessionInfo()
```

Example 58 (r):
```r
sessionInfo()
```

Example 59 (r):
```r
sessionInfo()
```

Example 60 (unknown):
```unknown
## R version 4.2.2 Patched (2022-11-10 r83330)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.6 LTS
## 
## Matrix products: default
## BLAS:   /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.9.0
## LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.9.0
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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       
## 
## attached base packages:
## [1] stats4    stats     graphics  grDevices utils     datasets  methods  
## [8] base     
## 
## other attached packages:
##  [1] ggplot2_3.4.4             dplyr_1.1.3              
##  [3] EnsDb.Hsapiens.v86_2.99.0 ensembldb_2.22.0         
##  [5] AnnotationFilter_1.22.0   GenomicFeatures_1.50.4   
##  [7] AnnotationDbi_1.60.2      Biobase_2.58.0           
##  [9] GenomicRanges_1.50.2      GenomeInfoDb_1.34.9      
## [11] IRanges_2.32.0            S4Vectors_0.36.2         
## [13] BiocGenerics_0.44.0       Signac_1.12.9000         
## [15] Seurat_5.0.0              SeuratObject_5.0.0       
## [17] sp_2.1-1                 
## 
## loaded via a namespace (and not attached):
##   [1] rappdirs_0.3.3              rtracklayer_1.58.0         
##   [3] scattermore_1.2             R.methodsS3_1.8.2          
##   [5] ragg_1.2.5                  tidyr_1.3.0                
##   [7] bit64_4.0.5                 knitr_1.45                 
##   [9] irlba_2.3.5.1               DelayedArray_0.24.0        
##  [11] R.utils_2.12.2              styler_1.10.2              
##  [13] data.table_1.14.8           rpart_4.1.19               
##  [15] KEGGREST_1.38.0             RCurl_1.98-1.12            
##  [17] generics_0.1.3              cowplot_1.1.1              
##  [19] RSQLite_2.3.1               RANN_2.6.1                 
##  [21] future_1.33.0               bit_4.0.5                  
##  [23] spatstat.data_3.0-3         xml2_1.3.5                 
##  [25] httpuv_1.6.12               SummarizedExperiment_1.28.0
##  [27] xfun_0.40                   hms_1.1.3                  
##  [29] jquerylib_0.1.4             evaluate_0.22              
##  [31] promises_1.2.1              fansi_1.0.5                
##  [33] restfulr_0.0.15             progress_1.2.2             
##  [35] dbplyr_2.3.4                igraph_1.5.1               
##  [37] DBI_1.1.3                   htmlwidgets_1.6.2          
##  [39] spatstat.geom_3.2-7         purrr_1.0.2                
##  [41] ellipsis_0.3.2              RSpectra_0.16-1            
##  [43] backports_1.4.1             biomaRt_2.54.1             
##  [45] deldir_1.0-9                sparseMatrixStats_1.10.0   
##  [47] MatrixGenerics_1.10.0       vctrs_0.6.4                
##  [49] ROCR_1.0-11                 abind_1.4-5                
##  [51] cachem_1.0.8                withr_2.5.2                
##  [53] BSgenome_1.66.3             progressr_0.14.0           
##  [55] checkmate_2.2.0             sctransform_0.4.1          
##  [57] GenomicAlignments_1.34.1    prettyunits_1.1.1          
##  [59] goftest_1.2-3               cluster_2.1.4              
##  [61] dotCall64_1.1-0             lazyeval_0.2.2             
##  [63] crayon_1.5.2                hdf5r_1.3.8                
##  [65] spatstat.explore_3.2-5      pkgconfig_2.0.3            
##  [67] labeling_0.4.3              nlme_3.1-162               
##  [69] ProtGenerics_1.30.0         nnet_7.3-18                
##  [71] rlang_1.1.1                 globals_0.16.2             
##  [73] lifecycle_1.0.3             miniUI_0.1.1.1             
##  [75] filelock_1.0.2              fastDummies_1.7.3          
##  [77] BiocFileCache_2.6.1         dichromat_2.0-0.1          
##  [79] rprojroot_2.0.3             polyclip_1.10-6            
##  [81] RcppHNSW_0.5.0              matrixStats_1.0.0          
##  [83] lmtest_0.9-40               Matrix_1.6-1.1             
##  [85] zoo_1.8-12                  base64enc_0.1-3            
##  [87] ggridges_0.5.4              png_0.1-8                  
##  [89] viridisLite_0.4.2           rjson_0.2.21               
##  [91] bitops_1.0-7                R.oo_1.25.0                
##  [93] KernSmooth_2.23-22          spam_2.10-0                
##  [95] Biostrings_2.66.0           blob_1.2.4                 
##  [97] DelayedMatrixStats_1.20.0   stringr_1.5.0              
##  [99] parallelly_1.36.0           spatstat.random_3.2-1      
## [101] R.cache_0.16.0              scales_1.2.1               
## [103] memoise_2.0.1               magrittr_2.0.3             
## [105] plyr_1.8.9                  ica_1.0-3                  
## [107] zlibbioc_1.44.0             compiler_4.2.2             
## [109] BiocIO_1.8.0                RColorBrewer_1.1-3         
## [111] fitdistrplus_1.1-11         Rsamtools_2.14.0           
## [113] cli_3.6.1                   XVector_0.38.0             
## [115] listenv_0.9.0               patchwork_1.1.3            
## [117] pbapply_1.7-2               htmlTable_2.4.1            
## [119] Formula_1.2-5               MASS_7.3-58.2              
## [121] tidyselect_1.2.0            stringi_1.7.12             
## [123] textshaping_0.3.6           glmGamPoi_1.10.2           
## [125] highr_0.10                  yaml_2.3.7                 
## [127] ggrepel_0.9.4               grid_4.2.2                 
## [129] sass_0.4.7                  VariantAnnotation_1.44.1   
## [131] fastmatch_1.1-4             tools_4.2.2                
## [133] future.apply_1.11.0         parallel_4.2.2             
## [135] rstudioapi_0.14             foreign_0.8-84             
## [137] gridExtra_2.3               farver_2.1.1               
## [139] Rtsne_0.16                  digest_0.6.33              
## [141] shiny_1.7.5.1               Rcpp_1.0.11                
## [143] later_1.3.1                 RcppAnnoy_0.0.21           
## [145] httr_1.4.7                  biovizBase_1.46.0          
## [147] colorspace_2.1-0            XML_3.99-0.14              
## [149] fs_1.6.3                    tensor_1.5                 
## [151] reticulate_1.34.0           splines_4.2.2              
## [153] uwot_0.1.16                 RcppRoll_0.3.0             
## [155] spatstat.utils_3.0-4        pkgdown_2.0.7              
## [157] plotly_4.10.3               systemfonts_1.0.4          
## [159] xtable_1.8-4                jsonlite_1.8.7             
## [161] R6_2.5.1                    Hmisc_5.1-1                
## [163] pillar_1.9.0                htmltools_0.5.6.1          
## [165] mime_0.12                   glue_1.6.2                 
## [167] fastmap_1.1.1               BiocParallel_1.32.6        
## [169] codetools_0.2-19            utf8_1.2.4                 
## [171] lattice_0.21-9              bslib_0.5.1                
## [173] spatstat.sparse_3.0-3       tibble_3.2.1               
## [175] curl_5.1.0                  leiden_0.4.3               
## [177] survival_3.5-7              rmarkdown_2.25             
## [179] desc_1.4.2                  munsell_0.5.0              
## [181] GenomeInfoDbData_1.2.9      reshape2_1.4.4             
## [183] gtable_0.3.4
```

Example 61 (unknown):
```unknown
## R version 4.2.2 Patched (2022-11-10 r83330)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.6 LTS
## 
## Matrix products: default
## BLAS:   /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.9.0
## LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.9.0
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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       
## 
## attached base packages:
## [1] stats4    stats     graphics  grDevices utils     datasets  methods  
## [8] base     
## 
## other attached packages:
##  [1] ggplot2_3.4.4             dplyr_1.1.3              
##  [3] EnsDb.Hsapiens.v86_2.99.0 ensembldb_2.22.0         
##  [5] AnnotationFilter_1.22.0   GenomicFeatures_1.50.4   
##  [7] AnnotationDbi_1.60.2      Biobase_2.58.0           
##  [9] GenomicRanges_1.50.2      GenomeInfoDb_1.34.9      
## [11] IRanges_2.32.0            S4Vectors_0.36.2         
## [13] BiocGenerics_0.44.0       Signac_1.12.9000         
## [15] Seurat_5.0.0              SeuratObject_5.0.0       
## [17] sp_2.1-1                 
## 
## loaded via a namespace (and not attached):
##   [1] rappdirs_0.3.3              rtracklayer_1.58.0         
##   [3] scattermore_1.2             R.methodsS3_1.8.2          
##   [5] ragg_1.2.5                  tidyr_1.3.0                
##   [7] bit64_4.0.5                 knitr_1.45                 
##   [9] irlba_2.3.5.1               DelayedArray_0.24.0        
##  [11] R.utils_2.12.2              styler_1.10.2              
##  [13] data.table_1.14.8           rpart_4.1.19               
##  [15] KEGGREST_1.38.0             RCurl_1.98-1.12            
##  [17] generics_0.1.3              cowplot_1.1.1              
##  [19] RSQLite_2.3.1               RANN_2.6.1                 
##  [21] future_1.33.0               bit_4.0.5                  
##  [23] spatstat.data_3.0-3         xml2_1.3.5                 
##  [25] httpuv_1.6.12               SummarizedExperiment_1.28.0
##  [27] xfun_0.40                   hms_1.1.3                  
##  [29] jquerylib_0.1.4             evaluate_0.22              
##  [31] promises_1.2.1              fansi_1.0.5                
##  [33] restfulr_0.0.15             progress_1.2.2             
##  [35] dbplyr_2.3.4                igraph_1.5.1               
##  [37] DBI_1.1.3                   htmlwidgets_1.6.2          
##  [39] spatstat.geom_3.2-7         purrr_1.0.2                
##  [41] ellipsis_0.3.2              RSpectra_0.16-1            
##  [43] backports_1.4.1             biomaRt_2.54.1             
##  [45] deldir_1.0-9                sparseMatrixStats_1.10.0   
##  [47] MatrixGenerics_1.10.0       vctrs_0.6.4                
##  [49] ROCR_1.0-11                 abind_1.4-5                
##  [51] cachem_1.0.8                withr_2.5.2                
##  [53] BSgenome_1.66.3             progressr_0.14.0           
##  [55] checkmate_2.2.0             sctransform_0.4.1          
##  [57] GenomicAlignments_1.34.1    prettyunits_1.1.1          
##  [59] goftest_1.2-3               cluster_2.1.4              
##  [61] dotCall64_1.1-0             lazyeval_0.2.2             
##  [63] crayon_1.5.2                hdf5r_1.3.8                
##  [65] spatstat.explore_3.2-5      pkgconfig_2.0.3            
##  [67] labeling_0.4.3              nlme_3.1-162               
##  [69] ProtGenerics_1.30.0         nnet_7.3-18                
##  [71] rlang_1.1.1                 globals_0.16.2             
##  [73] lifecycle_1.0.3             miniUI_0.1.1.1             
##  [75] filelock_1.0.2              fastDummies_1.7.3          
##  [77] BiocFileCache_2.6.1         dichromat_2.0-0.1          
##  [79] rprojroot_2.0.3             polyclip_1.10-6            
##  [81] RcppHNSW_0.5.0              matrixStats_1.0.0          
##  [83] lmtest_0.9-40               Matrix_1.6-1.1             
##  [85] zoo_1.8-12                  base64enc_0.1-3            
##  [87] ggridges_0.5.4              png_0.1-8                  
##  [89] viridisLite_0.4.2           rjson_0.2.21               
##  [91] bitops_1.0-7                R.oo_1.25.0                
##  [93] KernSmooth_2.23-22          spam_2.10-0                
##  [95] Biostrings_2.66.0           blob_1.2.4                 
##  [97] DelayedMatrixStats_1.20.0   stringr_1.5.0              
##  [99] parallelly_1.36.0           spatstat.random_3.2-1      
## [101] R.cache_0.16.0              scales_1.2.1               
## [103] memoise_2.0.1               magrittr_2.0.3             
## [105] plyr_1.8.9                  ica_1.0-3                  
## [107] zlibbioc_1.44.0             compiler_4.2.2             
## [109] BiocIO_1.8.0                RColorBrewer_1.1-3         
## [111] fitdistrplus_1.1-11         Rsamtools_2.14.0           
## [113] cli_3.6.1                   XVector_0.38.0             
## [115] listenv_0.9.0               patchwork_1.1.3            
## [117] pbapply_1.7-2               htmlTable_2.4.1            
## [119] Formula_1.2-5               MASS_7.3-58.2              
## [121] tidyselect_1.2.0            stringi_1.7.12             
## [123] textshaping_0.3.6           glmGamPoi_1.10.2           
## [125] highr_0.10                  yaml_2.3.7                 
## [127] ggrepel_0.9.4               grid_4.2.2                 
## [129] sass_0.4.7                  VariantAnnotation_1.44.1   
## [131] fastmatch_1.1-4             tools_4.2.2                
## [133] future.apply_1.11.0         parallel_4.2.2             
## [135] rstudioapi_0.14             foreign_0.8-84             
## [137] gridExtra_2.3               farver_2.1.1               
## [139] Rtsne_0.16                  digest_0.6.33              
## [141] shiny_1.7.5.1               Rcpp_1.0.11                
## [143] later_1.3.1                 RcppAnnoy_0.0.21           
## [145] httr_1.4.7                  biovizBase_1.46.0          
## [147] colorspace_2.1-0            XML_3.99-0.14              
## [149] fs_1.6.3                    tensor_1.5                 
## [151] reticulate_1.34.0           splines_4.2.2              
## [153] uwot_0.1.16                 RcppRoll_0.3.0             
## [155] spatstat.utils_3.0-4        pkgdown_2.0.7              
## [157] plotly_4.10.3               systemfonts_1.0.4          
## [159] xtable_1.8-4                jsonlite_1.8.7             
## [161] R6_2.5.1                    Hmisc_5.1-1                
## [163] pillar_1.9.0                htmltools_0.5.6.1          
## [165] mime_0.12                   glue_1.6.2                 
## [167] fastmap_1.1.1               BiocParallel_1.32.6        
## [169] codetools_0.2-19            utf8_1.2.4                 
## [171] lattice_0.21-9              bslib_0.5.1                
## [173] spatstat.sparse_3.0-3       tibble_3.2.1               
## [175] curl_5.1.0                  leiden_0.4.3               
## [177] survival_3.5-7              rmarkdown_2.25             
## [179] desc_1.4.2                  munsell_0.5.0              
## [181] GenomeInfoDbData_1.2.9      reshape2_1.4.4             
## [183] gtable_0.3.4
```

---

## New data visualization methods in v2.0

**URL:** http://127.0.0.1:9173/seurat/archive/v2.4/visualization_vignette/index.html

**Contents:**
- New data visualization methods in v2.0
    - Paul Hoffman
    - Compiled: 2018-03-24
  - Five visualizations of marker gene expression
  - New additions to FeaturePlot
  - Interactive plotting features

We’ll demonstrate visualization techniques in Seurat using our previously computed Seurat object from the 2,700 PBMC tutorial. You can download that here

Seurat utilizes R’s plotly graphing library to create interactive plots. Just pass do.hover = TRUE to FeaturePlot, CellPlot, GenePlot, or DimPlot and its extensions (includes PCAPlot, TSNEPlot, etc.)

Manually select cells for further investigation. We have found this particularly useful for small clusters that do not always separate using unbiased clustering, but which look tantalizingly distinct. You can now select these cells by passing do.identify = TRUE to FeaturePlot or DimPlot and its extensions (includes PCAPlot, TSNEPlot, etc.). You can then set them to a new identity class and perform differential expression.

For example, lets pretend that DCs had merged with monocytes in the clustering, but we wanted to see what was unique about them based on their position in the tSNE plot.

We can then use SetIdent to turn these cells into their own mini-cluster.

**Examples:**

Example 1 (r):
```r
library(Seurat)
pbmc <- readRDS(file = "~/Downloads/seurat_resources/pbmc3k_final.rds")
pbmc
```

Example 2 (r):
```r
library(Seurat)
pbmc <- readRDS(file = "~/Downloads/seurat_resources/pbmc3k_final.rds")
pbmc
```

Example 3 (python):
```python
## An object of class seurat in project 10X_PBMC 
##  13714 genes across 2638 samples.
```

Example 4 (python):
```python
## An object of class seurat in project 10X_PBMC 
##  13714 genes across 2638 samples.
```

Example 5 (r):
```r
features.plot <- c("LYZ", "CCL5", "IL32", "PTPRCAP", "FCGR3A", "PF4")
# Ridge plots - from ggridges. Visualize single cell expression
# distributions in each cluster
RidgePlot(object = pbmc, features.plot = features.plot, nCol = 2)
```

Example 6 (r):
```r
features.plot <- c("LYZ", "CCL5", "IL32", "PTPRCAP", "FCGR3A", "PF4")
# Ridge plots - from ggridges. Visualize single cell expression
# distributions in each cluster
RidgePlot(object = pbmc, features.plot = features.plot, nCol = 2)
```

Example 7 (r):
```r
# Violin plots. Visualize single cell expression distributions in each
# cluster
VlnPlot(object = pbmc, features.plot = features.plot, x.lab.rot = TRUE)
```

Example 8 (r):
```r
# Violin plots. Visualize single cell expression distributions in each
# cluster
VlnPlot(object = pbmc, features.plot = features.plot, x.lab.rot = TRUE)
```

Example 9 (r):
```r
# Dot plots - the size of the dot corresponds to the percentage of cells
# expressing the gene in each cluster. The color represents the average
# expression level
DotPlot(object = pbmc, genes.plot = features.plot, plot.legend = TRUE)
```

Example 10 (r):
```r
# Dot plots - the size of the dot corresponds to the percentage of cells
# expressing the gene in each cluster. The color represents the average
# expression level
DotPlot(object = pbmc, genes.plot = features.plot, plot.legend = TRUE)
```

Example 11 (r):
```r
# Feature plot - visualize gene expression in low-dimensional space
FeaturePlot(object = pbmc, features.plot = features.plot, cols.use = c("lightgrey", 
    "blue"))
```

Example 12 (r):
```r
# Feature plot - visualize gene expression in low-dimensional space
FeaturePlot(object = pbmc, features.plot = features.plot, cols.use = c("lightgrey", 
    "blue"))
```

Example 13 (r):
```r
# Single cell heatmap of gene expression
DoHeatmap(object = SubsetData(object = pbmc, max.cells.per.ident = 100), genes.use = features.plot, 
    slim.col.label = TRUE, group.label.rot = TRUE)
```

Example 14 (r):
```r
# Single cell heatmap of gene expression
DoHeatmap(object = SubsetData(object = pbmc, max.cells.per.ident = 100), genes.use = features.plot, 
    slim.col.label = TRUE, group.label.rot = TRUE)
```

Example 15 (r):
```r
# Plot a legend to map colors to expression levels
FeaturePlot(object = pbmc, features.plot = "MS4A1", no.legend = FALSE)
```

Example 16 (r):
```r
# Plot a legend to map colors to expression levels
FeaturePlot(object = pbmc, features.plot = "MS4A1", no.legend = FALSE)
```

Example 17 (r):
```r
# Adjust the contrast in the plot
FeaturePlot(object = pbmc, features.plot = "MS4A1", no.legend = FALSE, min.cutoff = 1, 
    max.cutoff = 3)
```

Example 18 (r):
```r
# Adjust the contrast in the plot
FeaturePlot(object = pbmc, features.plot = "MS4A1", no.legend = FALSE, min.cutoff = 1, 
    max.cutoff = 3)
```

Example 19 (r):
```r
# Calculate gene-specific contrast levels based on quantiles of non-zero
# expression. Particularly useful when plotting multiple markers
FeaturePlot(object = pbmc, features.plot = c("MS4A1", "PTPRCAP"), no.legend = FALSE, 
    min.cutoff = "q10", max.cutoff = "q90")
```

Example 20 (r):
```r
# Calculate gene-specific contrast levels based on quantiles of non-zero
# expression. Particularly useful when plotting multiple markers
FeaturePlot(object = pbmc, features.plot = c("MS4A1", "PTPRCAP"), no.legend = FALSE, 
    min.cutoff = "q10", max.cutoff = "q90")
```

Example 21 (r):
```r
# Visualize co-expression of two genes simultaneously. in beta mode (data is
# currently discretized, will be placed on a continuous scale soon)
FeaturePlot(object = pbmc, features.plot = c("MS4A1", "CD79A"), cols.use = c("grey", 
    "red", "blue", "green"), overlay = TRUE, no.legend = FALSE)
```

Example 22 (r):
```r
# Visualize co-expression of two genes simultaneously. in beta mode (data is
# currently discretized, will be placed on a continuous scale soon)
FeaturePlot(object = pbmc, features.plot = c("MS4A1", "CD79A"), cols.use = c("grey", 
    "red", "blue", "green"), overlay = TRUE, no.legend = FALSE)
```

Example 23 (r):
```r
# Inspire fear and awe at your next lab meeting.
FeaturePlot(object = pbmc, features.plot = c("MS4A1", "PTPRCAP"), no.legend = FALSE, 
    min.cutoff = "q10", max.cutoff = "q90", dark.theme = TRUE)
```

Example 24 (r):
```r
# Inspire fear and awe at your next lab meeting.
FeaturePlot(object = pbmc, features.plot = c("MS4A1", "PTPRCAP"), no.legend = FALSE, 
    min.cutoff = "q10", max.cutoff = "q90", dark.theme = TRUE)
```

Example 25 (r):
```r
# Dark themes are also available with the `DarkTheme` function, and can be
# added to any ggplot2-based plot.
```

Example 26 (r):
```r
# Dark themes are also available with the `DarkTheme` function, and can be
# added to any ggplot2-based plot.
```

Example 27 (unknown):
```unknown
do.hover = TRUE
```

Example 28 (unknown):
```unknown
FeaturePlot
```

Example 29 (r):
```r
# Include additional data to display alongside cell names in data.hover
FeaturePlot(object = pbmc, features.plot = "MS4A1", do.hover = TRUE, data.hover = c("ident", 
    "PC1", "nGene"))
```

Example 30 (r):
```r
# Include additional data to display alongside cell names in data.hover
FeaturePlot(object = pbmc, features.plot = "MS4A1", do.hover = TRUE, data.hover = c("ident", 
    "PC1", "nGene"))
```

Example 31 (unknown):
```unknown
do.identify = TRUE
```

Example 32 (unknown):
```unknown
FeaturePlot
```

Example 33 (r):
```r
pbmc <- RenameIdent(object = pbmc, old.ident.name = "Dendritic cells", new.ident.name = "CD14+ Monocytes")
select.cells <- TSNEPlot(object = pbmc, do.identify = TRUE)
```

Example 34 (r):
```r
pbmc <- RenameIdent(object = pbmc, old.ident.name = "Dendritic cells", new.ident.name = "CD14+ Monocytes")
select.cells <- TSNEPlot(object = pbmc, do.identify = TRUE)
```

Example 35 (r):
```r
head(select.cells)
```

Example 36 (r):
```r
head(select.cells)
```

Example 37 (unknown):
```unknown
## [1] "AAGATTACCGCCTT" "AAGCCATGAACTGC" "AATGCGTGGACGGA" "AATTACGAATTCCT"
## [5] "ACGAGGGACAGGAG" "ACGTGATGCCATGA"
```

Example 38 (unknown):
```unknown
## [1] "AAGATTACCGCCTT" "AAGCCATGAACTGC" "AATGCGTGGACGGA" "AATTACGAATTCCT"
## [5] "ACGAGGGACAGGAG" "ACGTGATGCCATGA"
```

Example 39 (r):
```r
pbmc <- SetIdent(object = pbmc, cells.use = select.cells, ident.use = "NewCells")

# Now, we find markers that are specific to the new cells, and find clear DC
# markers
newcells.markers <- FindMarkers(object = pbmc, ident.1 = "NewCells", ident.2 = "CD14+ Monocytes", 
    min.diff.pct = 0.3, only.pos = TRUE)
head(x = newcells.markers)
```

Example 40 (r):
```r
pbmc <- SetIdent(object = pbmc, cells.use = select.cells, ident.use = "NewCells")

# Now, we find markers that are specific to the new cells, and find clear DC
# markers
newcells.markers <- FindMarkers(object = pbmc, ident.1 = "NewCells", ident.2 = "CD14+ Monocytes", 
    min.diff.pct = 0.3, only.pos = TRUE)
head(x = newcells.markers)
```

Example 41 (unknown):
```unknown
##                 p_val avg_logFC pct.1 pct.2    p_val_adj
## FCER1A   1.665710e-81 2.7128605 0.853 0.010 2.284354e-77
## HLA-DQB2 2.742465e-35 0.6859660 0.441 0.010 3.761017e-31
## CD1C     3.486797e-34 1.2535693 0.529 0.025 4.781794e-30
## SERPINF1 1.190504e-33 1.0475813 0.441 0.013 1.632658e-29
## ENHO     9.227248e-33 0.9701464 0.412 0.010 1.265425e-28
## CLEC10A  2.448149e-32 1.5865036 0.735 0.073 3.357391e-28
```

Example 42 (unknown):
```unknown
##                 p_val avg_logFC pct.1 pct.2    p_val_adj
## FCER1A   1.665710e-81 2.7128605 0.853 0.010 2.284354e-77
## HLA-DQB2 2.742465e-35 0.6859660 0.441 0.010 3.761017e-31
## CD1C     3.486797e-34 1.2535693 0.529 0.025 4.781794e-30
## SERPINF1 1.190504e-33 1.0475813 0.441 0.013 1.632658e-29
## ENHO     9.227248e-33 0.9701464 0.412 0.010 1.265425e-28
## CLEC10A  2.448149e-32 1.5865036 0.735 0.073 3.357391e-28
```

---

## Analysis, visualization, and integration of Visium HD spatial datasets with Seurat • Seurat

**URL:** http://127.0.0.1:9173/articles_announcements.html

**Contents:**
- News
- Changes in Seurat v5
- Contents

We are excited to release Seurat v5 on CRAN, where it is now the default version for new installs. Seurat v5 is designed to be backwards compatible with Seurat v4 so existing code will continue to run, but we have made some changes to the software that will affect user results. We note that users who aim to reproduce their previous workflows in Seurat v4 can still install this version using the instructions on our install page.

In particular, we have made changes to:

Seurat Object and Assay class: Seurat v5 now includes support for additional assay and data types, including on-disk matrices. To facilitate this, we have introduced an updated Seurat v5 assay. Users can check out this [vignette for more information]. Briefly, Seurat v5 assays store data in layers (previously referred to as ‘slots’).

For example, these layers can store: raw counts (layer='counts'), normalized data (layer='data'), or z-scored/variance-stabilized data (layer='scale.data').

Data can be accessed using the $ accessor (i.e. obj[["RNA"]]$counts), or the `LayerData function (i.e. LayerData(obj, assay="RNA", layer='counts').

We’ve designed these updates to minimize changes for users. Existing Seurat functions and workflows from v4 continue to work in v5. For example, the command GetAssayData(obj, assay="RNA", slot='counts'), will run successfully in both Seurat v4 and Seurat v5.

Integration workflow: Seurat v5 introduces a streamlined integration and data transfer workflows that performs integration in low-dimensional space, and improves speed and memory efficiency. The results of integration are not identical between the two workflows, but users can still run the v4 integration workflow in Seurat v5 if they wish.

In previous versions of Seurat, the integration workflow required a list of multiple Seurat objects as input. In Seurat v5, all the data can be kept as a single object, but prior to integration, users can simply split the layers. See our introduction to integration vignette for more information.

Differential expression: Seurat v5 now uses the presto package (from the Korunsky and Raychaudhari labs), when available, to perform differential expression analysis. Using presto can dramatically speed up DE testing, and we encourage users to install it. In addition, in Seurat v5 we implement a pseudocount (when calculating log-FC) at the group level instead of the cell level. As a result, users will observe higher logFC estimates in v5 - but should note that these estimates may be more unstable - particularly for genes that are very lowly expressed in one of the two groups. We gratefully acknowledge feedback from the McCarthy and Pachter labs on this topic.

Pseudobulk analysis: Once a single-cell dataset has been analyzed to annotate cell subpopulations, pseudobulk analyses (i.e. aggregating together cells within a given subpopulation and sample) can reduce noise, improve quantification of lowly expressed genes, and reduce the size of the data matrix. In Seurat v5, we encourage the use of the AggregateExpression function to perform pseudobulk analysis. Check out our differential expression vignette as well as our pancreatic/healthy PBMC comparison, for examples of how to use AggregateExpression to perform robust differential expression of scRNA-seq data from multiple different conditions.

Developed by Rahul Satija, Satija Lab and Collaborators.

Site built with pkgdown 2.0.7.

**Examples:**

Example 1 (unknown):
```unknown
vignettes/announcements.Rmd
```

Example 2 (unknown):
```unknown
announcements.Rmd
```

Example 3 (unknown):
```unknown
(layer='counts')
```

Example 4 (unknown):
```unknown
(layer='data')
```

Example 5 (unknown):
```unknown
(layer='scale.data')
```

Example 6 (unknown):
```unknown
obj[["RNA"]]$counts
```

Example 7 (unknown):
```unknown
LayerData(obj, assay="RNA", layer='counts')
```

Example 8 (unknown):
```unknown
GetAssayData(obj, assay="RNA", slot='counts')
```

Example 9 (unknown):
```unknown
SCTransform
```

Example 10 (unknown):
```unknown
vst.flavor = "v1"
```

Example 11 (unknown):
```unknown
SCTransform
```

Example 12 (unknown):
```unknown
AggregateExpression
```

Example 13 (unknown):
```unknown
AggregateExpression
```

---

## Introduction to SCTransform, v2 regularization • Seurat

**URL:** http://127.0.0.1:9173/seurat/archive/v4.3/sctransform_v2_vignette/index.html

**Contents:**
- Introduction to SCTransform, v2 regularization
    - Compiled: January 17, 2024
- TL;DR
- Introduction
- Install sctransform
- Setup the Seurat objects
- Perform normalization and dimensionality reduction
- Perform integration using pearson residuals
- Perform an integrated analysis
- Identify differential expressed genes across conditions
  - Identify conserved cell type markers
- Contents

We recently introduced sctransform to perform normalization and variance stabilization of scRNA-seq datasets. We now release an updated version (‘v2’), based on our broad analysis of 59 scRNA-seq datasets spanning a range of technologies, systems, and sequencing depths. This update improves speed and memory consumption, the stability of parameter estimates, the identification of variable features, and the the ability to perform downstream differential expression analyses.

Users can install sctransform v2 from CRAN (sctransform v0.3.3+) and invoke the use of the updated method via the vst.flavor argument.

Heterogeneity in single-cell RNA-seq (scRNA-seq) data is driven by multiple sources, including biological variation in cellular state as well as technical variation introduced during experimental processing. In Choudhary and Satija, 2021 we provide a set of recommendations for modeling variation in scRNA-seq data, particularly when using generalized linear models or likelihood-based approaches for preprocessing and downstream analysis.

In this vignette, we use sctransform v2 based workflow to perform a comparative analysis of human immune cells (PBMC) in either a resting or interferon-stimulated state. In this vignette we apply sctransform-v2 based normalization to perform the following tasks:

We will install sctransform v2 from CRAN. We will also install the glmGamPoi package which substantially improves the speed of the learning procedure.

The dataset is available through our SeuratData package.

To perform normalization, we invoke SCTransform with an additional flag vst.flavor="v2" to invoke the v2 regularization. This provides some improvements over our original approach first introduced in Hafemeister and Satija, 2019.

To perform integration using the pearson residuals calculated above, we use the PrepSCTIntegration() function after selecting a list of informative features using SelectIntegrationFeatures():

To integrate the two datasets, we use the FindIntegrationAnchors() function, which takes a list of Seurat objects as input, and use these anchors to integrate the two datasets together with IntegrateData().

Now we can run a single integrated analysis on all cells:

To visualize the two conditions side-by-side, we can use the split.by argument to show each condition colored by cluster.

We can also visualize the distribution of annotated celltypes across control and stimulated datasets:

Using the normalized datasets with known celltype annotation, we can ask what genes change in different conditions for cells of the same type. First, we create a column in the meta.data slot to hold both the cell type and stimulation information and switch the current ident to that column.

To run differential expression, we make use of ‘corrected counts’ that are stored in the data slot of the the SCT assay. Corrected counts are obtained by setting the sequencing depth for all the cells to a fixed value and reversing the learned regularized negative-binomial regression model. Prior to performing differential expression, we first run PrepSCTFindMarkers, which ensures that the fixed value is set properly. Then we use FindMarkers(assay="SCT") to find differentially expressed genes. Here, we aim to identify genes that are differently expressed between stimulated and control B cells.

If running on a subset of the original object after running PrepSCTFindMarkers(), FindMarkers() should be invoked with recorrect_umi = FALSE to use the existing corrected counts:

We can also use the corrected counts for visualization:

To identify canonical cell type marker genes that are conserved across conditions, we provide the FindConservedMarkers() function. This function performs differential gene expression testing for each dataset/group and combines the p-values using meta-analysis methods from the MetaDE R package. For example, we can identify genes that are conserved markers irrespective of stimulation condition in NK cells. Note that the PrepSCTFindMarkers command does not to be rerun here.

Developed by Rahul Satija, Satija Lab and Collaborators.

Site built with pkgdown 2.0.7.

**Examples:**

Example 1 (unknown):
```unknown
vignettes/sctransform_v2_vignette.Rmd
```

Example 2 (unknown):
```unknown
sctransform_v2_vignette.Rmd
```

Example 3 (unknown):
```unknown
# install sctransform >= 0.3.3
install.packages("sctransform")
# invoke sctransform - requires Seurat>=4.1
object <- SCTransform(object, vst.flavor = "v2")
```

Example 4 (r):
```r
# install sctransform >= 0.3.3
install.packages("sctransform")
# invoke sctransform - requires Seurat>=4.1
object <- SCTransform(object, vst.flavor = "v2")
```

Example 5 (r):
```r
# install sctransform >= 0.3.3
install.packages("sctransform")
# invoke sctransform - requires Seurat>=4.1
object <- SCTransform(object, vst.flavor = "v2")
```

Example 6 (python):
```python
# install glmGamPoi
if (!requireNamespace("BiocManager", quietly = TRUE)) install.packages("BiocManager")
BiocManager::install("glmGamPoi")
# install sctransform from Github
install.packages("sctransform")
```

Example 7 (r):
```r
# install glmGamPoi
if (!requireNamespace("BiocManager", quietly = TRUE)) install.packages("BiocManager")
BiocManager::install("glmGamPoi")
# install sctransform from Github
install.packages("sctransform")
```

Example 8 (r):
```r
# install glmGamPoi
if (!requireNamespace("BiocManager", quietly = TRUE)) install.packages("BiocManager")
BiocManager::install("glmGamPoi")
# install sctransform from Github
install.packages("sctransform")
```

Example 9 (unknown):
```unknown
library(Seurat)
library(SeuratData)
library(patchwork)
library(dplyr)
library(ggplot2)
```

Example 10 (r):
```r
library(Seurat)
library(SeuratData)
library(patchwork)
library(dplyr)
library(ggplot2)
```

Example 11 (r):
```r
library(Seurat)
library(SeuratData)
library(patchwork)
library(dplyr)
library(ggplot2)
```

Example 12 (unknown):
```unknown
# install dataset
InstallData("ifnb")
```

Example 13 (r):
```r
# install dataset
InstallData("ifnb")
```

Example 14 (r):
```r
# install dataset
InstallData("ifnb")
```

Example 15 (unknown):
```unknown
# load dataset
ifnb <- LoadData("ifnb")

# split the dataset into a list of two seurat objects (stim and CTRL)
ifnb.list <- SplitObject(ifnb, split.by = "stim")

ctrl <- ifnb.list[["CTRL"]]
stim <- ifnb.list[["STIM"]]
```

Example 16 (r):
```r
# load dataset
ifnb <- LoadData("ifnb")

# split the dataset into a list of two seurat objects (stim and CTRL)
ifnb.list <- SplitObject(ifnb, split.by = "stim")

ctrl <- ifnb.list[["CTRL"]]
stim <- ifnb.list[["STIM"]]
```

Example 17 (r):
```r
# load dataset
ifnb <- LoadData("ifnb")

# split the dataset into a list of two seurat objects (stim and CTRL)
ifnb.list <- SplitObject(ifnb, split.by = "stim")

ctrl <- ifnb.list[["CTRL"]]
stim <- ifnb.list[["STIM"]]
```

Example 18 (unknown):
```unknown
SCTransform
```

Example 19 (unknown):
```unknown
vst.flavor="v2"
```

Example 20 (unknown):
```unknown
# normalize and run dimensionality reduction on control dataset
ctrl <- SCTransform(ctrl, vst.flavor = "v2", verbose = FALSE) %>%
    RunPCA(npcs = 30, verbose = FALSE) %>%
    RunUMAP(reduction = "pca", dims = 1:30, verbose = FALSE) %>%
    FindNeighbors(reduction = "pca", dims = 1:30, verbose = FALSE) %>%
    FindClusters(resolution = 0.7, verbose = FALSE)

p1 <- DimPlot(ctrl, label = T, repel = T) + ggtitle("Unsupervised clustering")
p2 <- DimPlot(ctrl, label = T, repel = T, group.by = "seurat_annotations") + ggtitle("Annotated celltypes")

p1 | p2
```

Example 21 (r):
```r
# normalize and run dimensionality reduction on control dataset
ctrl <- SCTransform(ctrl, vst.flavor = "v2", verbose = FALSE) %>%
    RunPCA(npcs = 30, verbose = FALSE) %>%
    RunUMAP(reduction = "pca", dims = 1:30, verbose = FALSE) %>%
    FindNeighbors(reduction = "pca", dims = 1:30, verbose = FALSE) %>%
    FindClusters(resolution = 0.7, verbose = FALSE)

p1 <- DimPlot(ctrl, label = T, repel = T) + ggtitle("Unsupervised clustering")
p2 <- DimPlot(ctrl, label = T, repel = T, group.by = "seurat_annotations") + ggtitle("Annotated celltypes")

p1 | p2
```

Example 22 (r):
```r
# normalize and run dimensionality reduction on control dataset
ctrl <- SCTransform(ctrl, vst.flavor = "v2", verbose = FALSE) %>%
    RunPCA(npcs = 30, verbose = FALSE) %>%
    RunUMAP(reduction = "pca", dims = 1:30, verbose = FALSE) %>%
    FindNeighbors(reduction = "pca", dims = 1:30, verbose = FALSE) %>%
    FindClusters(resolution = 0.7, verbose = FALSE)

p1 <- DimPlot(ctrl, label = T, repel = T) + ggtitle("Unsupervised clustering")
p2 <- DimPlot(ctrl, label = T, repel = T, group.by = "seurat_annotations") + ggtitle("Annotated celltypes")

p1 | p2
```

Example 23 (unknown):
```unknown
PrepSCTIntegration()
```

Example 24 (unknown):
```unknown
SelectIntegrationFeatures()
```

Example 25 (unknown):
```unknown
stim <- SCTransform(stim, vst.flavor = "v2", verbose = FALSE) %>%
    RunPCA(npcs = 30, verbose = FALSE)
ifnb.list <- list(ctrl = ctrl, stim = stim)
features <- SelectIntegrationFeatures(object.list = ifnb.list, nfeatures = 3000)
ifnb.list <- PrepSCTIntegration(object.list = ifnb.list, anchor.features = features)
```

Example 26 (r):
```r
stim <- SCTransform(stim, vst.flavor = "v2", verbose = FALSE) %>%
    RunPCA(npcs = 30, verbose = FALSE)
ifnb.list <- list(ctrl = ctrl, stim = stim)
features <- SelectIntegrationFeatures(object.list = ifnb.list, nfeatures = 3000)
ifnb.list <- PrepSCTIntegration(object.list = ifnb.list, anchor.features = features)
```

Example 27 (r):
```r
stim <- SCTransform(stim, vst.flavor = "v2", verbose = FALSE) %>%
    RunPCA(npcs = 30, verbose = FALSE)
ifnb.list <- list(ctrl = ctrl, stim = stim)
features <- SelectIntegrationFeatures(object.list = ifnb.list, nfeatures = 3000)
ifnb.list <- PrepSCTIntegration(object.list = ifnb.list, anchor.features = features)
```

Example 28 (unknown):
```unknown
FindIntegrationAnchors()
```

Example 29 (unknown):
```unknown
IntegrateData()
```

Example 30 (unknown):
```unknown
immune.anchors <- FindIntegrationAnchors(object.list = ifnb.list, normalization.method = "SCT",
    anchor.features = features)
immune.combined.sct <- IntegrateData(anchorset = immune.anchors, normalization.method = "SCT")
```

Example 31 (r):
```r
immune.anchors <- FindIntegrationAnchors(object.list = ifnb.list, normalization.method = "SCT",
    anchor.features = features)
immune.combined.sct <- IntegrateData(anchorset = immune.anchors, normalization.method = "SCT")
```

Example 32 (r):
```r
immune.anchors <- FindIntegrationAnchors(object.list = ifnb.list, normalization.method = "SCT",
    anchor.features = features)
immune.combined.sct <- IntegrateData(anchorset = immune.anchors, normalization.method = "SCT")
```

Example 33 (unknown):
```unknown
## [1] 1
## [1] 2
```

Example 34 (unknown):
```unknown
## [1] 1
## [1] 2
```

Example 35 (unknown):
```unknown
immune.combined.sct <- RunPCA(immune.combined.sct, verbose = FALSE)
immune.combined.sct <- RunUMAP(immune.combined.sct, reduction = "pca", dims = 1:30, verbose = FALSE)
immune.combined.sct <- FindNeighbors(immune.combined.sct, reduction = "pca", dims = 1:30)
immune.combined.sct <- FindClusters(immune.combined.sct, resolution = 0.3)
```

Example 36 (r):
```r
immune.combined.sct <- RunPCA(immune.combined.sct, verbose = FALSE)
immune.combined.sct <- RunUMAP(immune.combined.sct, reduction = "pca", dims = 1:30, verbose = FALSE)
immune.combined.sct <- FindNeighbors(immune.combined.sct, reduction = "pca", dims = 1:30)
immune.combined.sct <- FindClusters(immune.combined.sct, resolution = 0.3)
```

Example 37 (r):
```r
immune.combined.sct <- RunPCA(immune.combined.sct, verbose = FALSE)
immune.combined.sct <- RunUMAP(immune.combined.sct, reduction = "pca", dims = 1:30, verbose = FALSE)
immune.combined.sct <- FindNeighbors(immune.combined.sct, reduction = "pca", dims = 1:30)
immune.combined.sct <- FindClusters(immune.combined.sct, resolution = 0.3)
```

Example 38 (unknown):
```unknown
DimPlot(immune.combined.sct, reduction = "umap", split.by = "stim")
```

Example 39 (r):
```r
DimPlot(immune.combined.sct, reduction = "umap", split.by = "stim")
```

Example 40 (r):
```r
DimPlot(immune.combined.sct, reduction = "umap", split.by = "stim")
```

Example 41 (unknown):
```unknown
p1 <- DimPlot(immune.combined.sct, reduction = "umap", group.by = "stim")
p2 <- DimPlot(immune.combined.sct, reduction = "umap", group.by = "seurat_clusters", label = TRUE,
    repel = TRUE)
p3 <- DimPlot(immune.combined.sct, reduction = "umap", group.by = "seurat_annotations", label = TRUE,
    repel = TRUE)
p1 | p2 | p3
```

Example 42 (r):
```r
p1 <- DimPlot(immune.combined.sct, reduction = "umap", group.by = "stim")
p2 <- DimPlot(immune.combined.sct, reduction = "umap", group.by = "seurat_clusters", label = TRUE,
    repel = TRUE)
p3 <- DimPlot(immune.combined.sct, reduction = "umap", group.by = "seurat_annotations", label = TRUE,
    repel = TRUE)
p1 | p2 | p3
```

Example 43 (r):
```r
p1 <- DimPlot(immune.combined.sct, reduction = "umap", group.by = "stim")
p2 <- DimPlot(immune.combined.sct, reduction = "umap", group.by = "seurat_clusters", label = TRUE,
    repel = TRUE)
p3 <- DimPlot(immune.combined.sct, reduction = "umap", group.by = "seurat_annotations", label = TRUE,
    repel = TRUE)
p1 | p2 | p3
```

Example 44 (unknown):
```unknown
immune.combined.sct$celltype.stim <- paste(immune.combined.sct$seurat_annotations, immune.combined.sct$stim,
    sep = "_")
Idents(immune.combined.sct) <- "celltype.stim"
```

Example 45 (r):
```r
immune.combined.sct$celltype.stim <- paste(immune.combined.sct$seurat_annotations, immune.combined.sct$stim,
    sep = "_")
Idents(immune.combined.sct) <- "celltype.stim"
```

Example 46 (r):
```r
immune.combined.sct$celltype.stim <- paste(immune.combined.sct$seurat_annotations, immune.combined.sct$stim,
    sep = "_")
Idents(immune.combined.sct) <- "celltype.stim"
```

Example 47 (unknown):
```unknown
PrepSCTFindMarkers
```

Example 48 (unknown):
```unknown
FindMarkers(assay="SCT")
```

Example 49 (unknown):
```unknown
immune.combined.sct <- PrepSCTFindMarkers(immune.combined.sct)

b.interferon.response <- FindMarkers(immune.combined.sct, assay = "SCT", ident.1 = "B_STIM", ident.2 = "B_CTRL",
    verbose = FALSE)
head(b.interferon.response, n = 15)
```

Example 50 (r):
```r
immune.combined.sct <- PrepSCTFindMarkers(immune.combined.sct)

b.interferon.response <- FindMarkers(immune.combined.sct, assay = "SCT", ident.1 = "B_STIM", ident.2 = "B_CTRL",
    verbose = FALSE)
head(b.interferon.response, n = 15)
```

Example 51 (r):
```r
immune.combined.sct <- PrepSCTFindMarkers(immune.combined.sct)

b.interferon.response <- FindMarkers(immune.combined.sct, assay = "SCT", ident.1 = "B_STIM", ident.2 = "B_CTRL",
    verbose = FALSE)
head(b.interferon.response, n = 15)
```

Example 52 (unknown):
```unknown
##                 p_val avg_log2FC pct.1 pct.2     p_val_adj
## ISG15   1.505693e-159  5.1598904 0.998 0.229 2.003475e-155
## IFIT3   4.128835e-154  6.2281506 0.961 0.052 5.493827e-150
## IFI6    2.479595e-153  5.6463400 0.965 0.076 3.299349e-149
## ISG20   9.385626e-152  3.1715979 1.000 0.666 1.248851e-147
## IFIT1   2.447118e-139  6.2614957 0.904 0.029 3.256136e-135
## MX1     2.111961e-124  4.1490465 0.900 0.115 2.810175e-120
## LY6E    2.930420e-122  3.9278136 0.898 0.150 3.899217e-118
## TNFSF10 1.104024e-112  6.8254288 0.785 0.020 1.469014e-108
## IFIT2   3.491368e-108  5.5668205 0.783 0.037 4.645615e-104
## B2M      3.405403e-98  0.6074989 1.000 1.000  4.531229e-94
## IRF7     1.114291e-96  3.3721350 0.834 0.187  1.482675e-92
## PLSCR1   3.364901e-96  4.0217697 0.783 0.111  4.477338e-92
## UBE2L6   1.155610e-85  2.6732717 0.849 0.295  1.537655e-81
## CXCL10   5.689834e-84  8.0923962 0.639 0.010  7.570893e-80
## PSMB9    2.304426e-81  1.8684260 0.937 0.568  3.066269e-77
```

Example 53 (unknown):
```unknown
##                 p_val avg_log2FC pct.1 pct.2     p_val_adj
## ISG15   1.505693e-159  5.1598904 0.998 0.229 2.003475e-155
## IFIT3   4.128835e-154  6.2281506 0.961 0.052 5.493827e-150
## IFI6    2.479595e-153  5.6463400 0.965 0.076 3.299349e-149
## ISG20   9.385626e-152  3.1715979 1.000 0.666 1.248851e-147
## IFIT1   2.447118e-139  6.2614957 0.904 0.029 3.256136e-135
## MX1     2.111961e-124  4.1490465 0.900 0.115 2.810175e-120
## LY6E    2.930420e-122  3.9278136 0.898 0.150 3.899217e-118
## TNFSF10 1.104024e-112  6.8254288 0.785 0.020 1.469014e-108
## IFIT2   3.491368e-108  5.5668205 0.783 0.037 4.645615e-104
## B2M      3.405403e-98  0.6074989 1.000 1.000  4.531229e-94
## IRF7     1.114291e-96  3.3721350 0.834 0.187  1.482675e-92
## PLSCR1   3.364901e-96  4.0217697 0.783 0.111  4.477338e-92
## UBE2L6   1.155610e-85  2.6732717 0.849 0.295  1.537655e-81
## CXCL10   5.689834e-84  8.0923962 0.639 0.010  7.570893e-80
## PSMB9    2.304426e-81  1.8684260 0.937 0.568  3.066269e-77
```

Example 54 (unknown):
```unknown
PrepSCTFindMarkers()
```

Example 55 (unknown):
```unknown
FindMarkers()
```

Example 56 (unknown):
```unknown
recorrect_umi = FALSE
```

Example 57 (unknown):
```unknown
immune.combined.sct.subset <- subset(immune.combined.sct, idents = c("B_STIM", "B_CTRL"))
b.interferon.response.subset <- FindMarkers(immune.combined.sct.subset, assay = "SCT", ident.1 = "B_STIM",
    ident.2 = "B_CTRL", verbose = FALSE, recorrect_umi = FALSE)
```

Example 58 (r):
```r
immune.combined.sct.subset <- subset(immune.combined.sct, idents = c("B_STIM", "B_CTRL"))
b.interferon.response.subset <- FindMarkers(immune.combined.sct.subset, assay = "SCT", ident.1 = "B_STIM",
    ident.2 = "B_CTRL", verbose = FALSE, recorrect_umi = FALSE)
```

Example 59 (r):
```r
immune.combined.sct.subset <- subset(immune.combined.sct, idents = c("B_STIM", "B_CTRL"))
b.interferon.response.subset <- FindMarkers(immune.combined.sct.subset, assay = "SCT", ident.1 = "B_STIM",
    ident.2 = "B_CTRL", verbose = FALSE, recorrect_umi = FALSE)
```

Example 60 (unknown):
```unknown
Idents(immune.combined.sct) <- "seurat_annotations"
DefaultAssay(immune.combined.sct) <- "SCT"
FeaturePlot(immune.combined.sct, features = c("CD3D", "GNLY", "IFI6"), split.by = "stim", max.cutoff = 3,
    cols = c("grey", "red"))
```

Example 61 (r):
```r
Idents(immune.combined.sct) <- "seurat_annotations"
DefaultAssay(immune.combined.sct) <- "SCT"
FeaturePlot(immune.combined.sct, features = c("CD3D", "GNLY", "IFI6"), split.by = "stim", max.cutoff = 3,
    cols = c("grey", "red"))
```

Example 62 (r):
```r
Idents(immune.combined.sct) <- "seurat_annotations"
DefaultAssay(immune.combined.sct) <- "SCT"
FeaturePlot(immune.combined.sct, features = c("CD3D", "GNLY", "IFI6"), split.by = "stim", max.cutoff = 3,
    cols = c("grey", "red"))
```

Example 63 (unknown):
```unknown
plots <- VlnPlot(immune.combined.sct, features = c("LYZ", "ISG15", "CXCL10"), split.by = "stim",
    group.by = "seurat_annotations", pt.size = 0, combine = FALSE)
wrap_plots(plots = plots, ncol = 1)
```

Example 64 (r):
```r
plots <- VlnPlot(immune.combined.sct, features = c("LYZ", "ISG15", "CXCL10"), split.by = "stim",
    group.by = "seurat_annotations", pt.size = 0, combine = FALSE)
wrap_plots(plots = plots, ncol = 1)
```

Example 65 (r):
```r
plots <- VlnPlot(immune.combined.sct, features = c("LYZ", "ISG15", "CXCL10"), split.by = "stim",
    group.by = "seurat_annotations", pt.size = 0, combine = FALSE)
wrap_plots(plots = plots, ncol = 1)
```

Example 66 (unknown):
```unknown
FindConservedMarkers()
```

Example 67 (unknown):
```unknown
PrepSCTFindMarkers
```

Example 68 (unknown):
```unknown
nk.markers <- FindConservedMarkers(immune.combined.sct, assay = "SCT", ident.1 = "NK", grouping.var = "stim",
    verbose = FALSE)
head(nk.markers)
```

Example 69 (r):
```r
nk.markers <- FindConservedMarkers(immune.combined.sct, assay = "SCT", ident.1 = "NK", grouping.var = "stim",
    verbose = FALSE)
head(nk.markers)
```

Example 70 (r):
```r
nk.markers <- FindConservedMarkers(immune.combined.sct, assay = "SCT", ident.1 = "NK", grouping.var = "stim",
    verbose = FALSE)
head(nk.markers)
```

Example 71 (unknown):
```unknown
##       CTRL_p_val CTRL_avg_log2FC CTRL_pct.1 CTRL_pct.2 CTRL_p_val_adj
## GNLY           0        6.678447      0.943      0.045              0
## NKG7           0        5.190647      0.953      0.080              0
## GZMB           0        4.821619      0.839      0.043              0
## CLIC3          0        5.504544      0.601      0.024              0
## CTSW           0        5.088893      0.537      0.029              0
## KLRD1          0        5.110949      0.507      0.019              0
##       STIM_p_val STIM_avg_log2FC STIM_pct.1 STIM_pct.2 STIM_p_val_adj max_pval
## GNLY           0        6.308521      0.956      0.056              0        0
## NKG7           0        4.846749      0.950      0.077              0        0
## GZMB           0        4.958283      0.897      0.058              0        0
## CLIC3          0        5.265345      0.623      0.030              0        0
## CTSW           0        5.099038      0.592      0.035              0        0
## KLRD1          0        4.817659      0.555      0.026              0        0
##       minimump_p_val
## GNLY               0
## NKG7               0
## GZMB               0
## CLIC3              0
## CTSW               0
## KLRD1              0
```

Example 72 (unknown):
```unknown
##       CTRL_p_val CTRL_avg_log2FC CTRL_pct.1 CTRL_pct.2 CTRL_p_val_adj
## GNLY           0        6.678447      0.943      0.045              0
## NKG7           0        5.190647      0.953      0.080              0
## GZMB           0        4.821619      0.839      0.043              0
## CLIC3          0        5.504544      0.601      0.024              0
## CTSW           0        5.088893      0.537      0.029              0
## KLRD1          0        5.110949      0.507      0.019              0
##       STIM_p_val STIM_avg_log2FC STIM_pct.1 STIM_pct.2 STIM_p_val_adj max_pval
## GNLY           0        6.308521      0.956      0.056              0        0
## NKG7           0        4.846749      0.950      0.077              0        0
## GZMB           0        4.958283      0.897      0.058              0        0
## CLIC3          0        5.265345      0.623      0.030              0        0
## CTSW           0        5.099038      0.592      0.035              0        0
## KLRD1          0        4.817659      0.555      0.026              0        0
##       minimump_p_val
## GNLY               0
## NKG7               0
## GZMB               0
## CLIC3              0
## CTSW               0
## KLRD1              0
```

Example 73 (unknown):
```unknown
sessionInfo()
```

Example 74 (r):
```r
sessionInfo()
```

Example 75 (r):
```r
sessionInfo()
```

Example 76 (unknown):
```unknown
## R version 4.2.2 Patched (2022-11-10 r83330)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.6 LTS
## 
## Matrix products: default
## BLAS:   /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.9.0
## LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.9.0
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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       
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
##  [1] ggplot2_3.4.4                  dplyr_1.1.4                   
##  [3] patchwork_1.1.3                thp1.eccite.SeuratData_3.1.5  
##  [5] stxBrain.SeuratData_0.1.1      ssHippo.SeuratData_3.1.4      
##  [7] pbmcsca.SeuratData_3.0.0       pbmcref.SeuratData_1.0.0      
##  [9] pbmcMultiome.SeuratData_0.1.4  pbmc3k.SeuratData_3.1.4       
## [11] panc8.SeuratData_3.0.2         ifnb.SeuratData_3.0.0         
## [13] hcabm40k.SeuratData_3.0.0      cbmc.SeuratData_3.1.4         
## [15] bonemarrowref.SeuratData_1.0.0 bmcite.SeuratData_0.3.0       
## [17] SeuratData_0.2.2.9001          Seurat_5.0.1.9001             
## [19] SeuratObject_5.0.1             sp_2.1-2                      
## 
## loaded via a namespace (and not attached):
##   [1] utf8_1.2.4                  spatstat.explore_3.2-5     
##   [3] reticulate_1.34.0           tidyselect_1.2.0           
##   [5] htmlwidgets_1.6.4           grid_4.2.2                 
##   [7] Rtsne_0.17                  munsell_0.5.0              
##   [9] mutoss_0.1-13               codetools_0.2-19           
##  [11] ragg_1.2.7                  ica_1.0-3                  
##  [13] future_1.33.0               miniUI_0.1.1.1             
##  [15] withr_2.5.2                 spatstat.random_3.2-2      
##  [17] colorspace_2.1-0            progressr_0.14.0           
##  [19] Biobase_2.58.0              highr_0.10                 
##  [21] knitr_1.45                  stats4_4.2.2               
##  [23] ROCR_1.0-11                 tensor_1.5                 
##  [25] listenv_0.9.0               Rdpack_2.6                 
##  [27] MatrixGenerics_1.10.0       labeling_0.4.3             
##  [29] GenomeInfoDbData_1.2.9      mnormt_2.1.1               
##  [31] polyclip_1.10-6             farver_2.1.1               
##  [33] rprojroot_2.0.4             TH.data_1.1-2              
##  [35] parallelly_1.36.0           vctrs_0.6.5                
##  [37] generics_0.1.3              xfun_0.41                  
##  [39] R6_2.5.1                    GenomeInfoDb_1.34.9        
##  [41] ggbeeswarm_0.7.2            bitops_1.0-7               
##  [43] spatstat.utils_3.0-4        cachem_1.0.8               
##  [45] DelayedArray_0.24.0         promises_1.2.1             
##  [47] scales_1.3.0                multcomp_1.4-25            
##  [49] beeswarm_0.4.0              gtable_0.3.4               
##  [51] globals_0.16.2              goftest_1.2-3              
##  [53] spam_2.10-0                 sandwich_3.1-0             
##  [55] rlang_1.1.2                 systemfonts_1.0.5          
##  [57] splines_4.2.2               lazyeval_0.2.2             
##  [59] spatstat.geom_3.2-7         BiocManager_1.30.22        
##  [61] yaml_2.3.8                  reshape2_1.4.4             
##  [63] abind_1.4-5                 httpuv_1.6.13              
##  [65] tools_4.2.2                 ellipsis_0.3.2             
##  [67] jquerylib_0.1.4             RColorBrewer_1.1-3         
##  [69] BiocGenerics_0.44.0         ggridges_0.5.5             
##  [71] TFisher_0.2.0               Rcpp_1.0.11                
##  [73] plyr_1.8.9                  sparseMatrixStats_1.10.0   
##  [75] zlibbioc_1.44.0             purrr_1.0.2                
##  [77] RCurl_1.98-1.13             deldir_2.0-2               
##  [79] pbapply_1.7-2               cowplot_1.1.2              
##  [81] S4Vectors_0.36.2            zoo_1.8-12                 
##  [83] SummarizedExperiment_1.28.0 ggrepel_0.9.4              
##  [85] cluster_2.1.6               fs_1.6.3                   
##  [87] magrittr_2.0.3              data.table_1.14.10         
##  [89] RSpectra_0.16-1             glmGamPoi_1.10.2           
##  [91] scattermore_1.2             lmtest_0.9-40              
##  [93] RANN_2.6.1                  mvtnorm_1.2-4              
##  [95] fitdistrplus_1.1-11         matrixStats_1.1.0          
##  [97] mime_0.12                   evaluate_0.23              
##  [99] xtable_1.8-4                fastDummies_1.7.3          
## [101] IRanges_2.32.0              gridExtra_2.3              
## [103] compiler_4.2.2              tibble_3.2.1               
## [105] KernSmooth_2.23-22          crayon_1.5.2               
## [107] htmltools_0.5.7             later_1.3.2                
## [109] tidyr_1.3.0                 formatR_1.14               
## [111] MASS_7.3-58.2               rappdirs_0.3.3             
## [113] Matrix_1.6-4                cli_3.6.2                  
## [115] rbibutils_2.2.16            qqconf_1.3.2               
## [117] metap_1.9                   parallel_4.2.2             
## [119] dotCall64_1.1-1             igraph_1.6.0               
## [121] GenomicRanges_1.50.2        pkgconfig_2.0.3            
## [123] sn_2.1.1                    pkgdown_2.0.7              
## [125] numDeriv_2016.8-1.1         plotly_4.10.3              
## [127] spatstat.sparse_3.0-3       vipor_0.4.5                
## [129] bslib_0.6.1                 multtest_2.54.0            
## [131] XVector_0.38.0              stringr_1.5.1              
## [133] digest_0.6.33               sctransform_0.4.1          
## [135] RcppAnnoy_0.0.21            spatstat.data_3.0-3        
## [137] rmarkdown_2.25              leiden_0.4.3.1             
## [139] uwot_0.1.16                 DelayedMatrixStats_1.20.0  
## [141] shiny_1.8.0                 lifecycle_1.0.4            
## [143] nlme_3.1-162                jsonlite_1.8.8             
## [145] limma_3.54.2                desc_1.4.2                 
## [147] viridisLite_0.4.2           fansi_1.0.6                
## [149] pillar_1.9.0                lattice_0.21-9             
## [151] plotrix_3.8-4               ggrastr_1.0.2              
## [153] fastmap_1.1.1               httr_1.4.7                 
## [155] survival_3.5-7              glue_1.6.2                 
## [157] png_0.1-8                   presto_1.0.0               
## [159] stringi_1.8.3               sass_0.4.8                 
## [161] textshaping_0.3.7           RcppHNSW_0.5.0             
## [163] memoise_2.0.1               mathjaxr_1.6-0             
## [165] irlba_2.3.5.1               future.apply_1.11.0
```

Example 77 (unknown):
```unknown
## R version 4.2.2 Patched (2022-11-10 r83330)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.6 LTS
## 
## Matrix products: default
## BLAS:   /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.9.0
## LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.9.0
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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       
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
##  [1] ggplot2_3.4.4                  dplyr_1.1.4                   
##  [3] patchwork_1.1.3                thp1.eccite.SeuratData_3.1.5  
##  [5] stxBrain.SeuratData_0.1.1      ssHippo.SeuratData_3.1.4      
##  [7] pbmcsca.SeuratData_3.0.0       pbmcref.SeuratData_1.0.0      
##  [9] pbmcMultiome.SeuratData_0.1.4  pbmc3k.SeuratData_3.1.4       
## [11] panc8.SeuratData_3.0.2         ifnb.SeuratData_3.0.0         
## [13] hcabm40k.SeuratData_3.0.0      cbmc.SeuratData_3.1.4         
## [15] bonemarrowref.SeuratData_1.0.0 bmcite.SeuratData_0.3.0       
## [17] SeuratData_0.2.2.9001          Seurat_5.0.1.9001             
## [19] SeuratObject_5.0.1             sp_2.1-2                      
## 
## loaded via a namespace (and not attached):
##   [1] utf8_1.2.4                  spatstat.explore_3.2-5     
##   [3] reticulate_1.34.0           tidyselect_1.2.0           
##   [5] htmlwidgets_1.6.4           grid_4.2.2                 
##   [7] Rtsne_0.17                  munsell_0.5.0              
##   [9] mutoss_0.1-13               codetools_0.2-19           
##  [11] ragg_1.2.7                  ica_1.0-3                  
##  [13] future_1.33.0               miniUI_0.1.1.1             
##  [15] withr_2.5.2                 spatstat.random_3.2-2      
##  [17] colorspace_2.1-0            progressr_0.14.0           
##  [19] Biobase_2.58.0              highr_0.10                 
##  [21] knitr_1.45                  stats4_4.2.2               
##  [23] ROCR_1.0-11                 tensor_1.5                 
##  [25] listenv_0.9.0               Rdpack_2.6                 
##  [27] MatrixGenerics_1.10.0       labeling_0.4.3             
##  [29] GenomeInfoDbData_1.2.9      mnormt_2.1.1               
##  [31] polyclip_1.10-6             farver_2.1.1               
##  [33] rprojroot_2.0.4             TH.data_1.1-2              
##  [35] parallelly_1.36.0           vctrs_0.6.5                
##  [37] generics_0.1.3              xfun_0.41                  
##  [39] R6_2.5.1                    GenomeInfoDb_1.34.9        
##  [41] ggbeeswarm_0.7.2            bitops_1.0-7               
##  [43] spatstat.utils_3.0-4        cachem_1.0.8               
##  [45] DelayedArray_0.24.0         promises_1.2.1             
##  [47] scales_1.3.0                multcomp_1.4-25            
##  [49] beeswarm_0.4.0              gtable_0.3.4               
##  [51] globals_0.16.2              goftest_1.2-3              
##  [53] spam_2.10-0                 sandwich_3.1-0             
##  [55] rlang_1.1.2                 systemfonts_1.0.5          
##  [57] splines_4.2.2               lazyeval_0.2.2             
##  [59] spatstat.geom_3.2-7         BiocManager_1.30.22        
##  [61] yaml_2.3.8                  reshape2_1.4.4             
##  [63] abind_1.4-5                 httpuv_1.6.13              
##  [65] tools_4.2.2                 ellipsis_0.3.2             
##  [67] jquerylib_0.1.4             RColorBrewer_1.1-3         
##  [69] BiocGenerics_0.44.0         ggridges_0.5.5             
##  [71] TFisher_0.2.0               Rcpp_1.0.11                
##  [73] plyr_1.8.9                  sparseMatrixStats_1.10.0   
##  [75] zlibbioc_1.44.0             purrr_1.0.2                
##  [77] RCurl_1.98-1.13             deldir_2.0-2               
##  [79] pbapply_1.7-2               cowplot_1.1.2              
##  [81] S4Vectors_0.36.2            zoo_1.8-12                 
##  [83] SummarizedExperiment_1.28.0 ggrepel_0.9.4              
##  [85] cluster_2.1.6               fs_1.6.3                   
##  [87] magrittr_2.0.3              data.table_1.14.10         
##  [89] RSpectra_0.16-1             glmGamPoi_1.10.2           
##  [91] scattermore_1.2             lmtest_0.9-40              
##  [93] RANN_2.6.1                  mvtnorm_1.2-4              
##  [95] fitdistrplus_1.1-11         matrixStats_1.1.0          
##  [97] mime_0.12                   evaluate_0.23              
##  [99] xtable_1.8-4                fastDummies_1.7.3          
## [101] IRanges_2.32.0              gridExtra_2.3              
## [103] compiler_4.2.2              tibble_3.2.1               
## [105] KernSmooth_2.23-22          crayon_1.5.2               
## [107] htmltools_0.5.7             later_1.3.2                
## [109] tidyr_1.3.0                 formatR_1.14               
## [111] MASS_7.3-58.2               rappdirs_0.3.3             
## [113] Matrix_1.6-4                cli_3.6.2                  
## [115] rbibutils_2.2.16            qqconf_1.3.2               
## [117] metap_1.9                   parallel_4.2.2             
## [119] dotCall64_1.1-1             igraph_1.6.0               
## [121] GenomicRanges_1.50.2        pkgconfig_2.0.3            
## [123] sn_2.1.1                    pkgdown_2.0.7              
## [125] numDeriv_2016.8-1.1         plotly_4.10.3              
## [127] spatstat.sparse_3.0-3       vipor_0.4.5                
## [129] bslib_0.6.1                 multtest_2.54.0            
## [131] XVector_0.38.0              stringr_1.5.1              
## [133] digest_0.6.33               sctransform_0.4.1          
## [135] RcppAnnoy_0.0.21            spatstat.data_3.0-3        
## [137] rmarkdown_2.25              leiden_0.4.3.1             
## [139] uwot_0.1.16                 DelayedMatrixStats_1.20.0  
## [141] shiny_1.8.0                 lifecycle_1.0.4            
## [143] nlme_3.1-162                jsonlite_1.8.8             
## [145] limma_3.54.2                desc_1.4.2                 
## [147] viridisLite_0.4.2           fansi_1.0.6                
## [149] pillar_1.9.0                lattice_0.21-9             
## [151] plotrix_3.8-4               ggrastr_1.0.2              
## [153] fastmap_1.1.1               httr_1.4.7                 
## [155] survival_3.5-7              glue_1.6.2                 
## [157] png_0.1-8                   presto_1.0.0               
## [159] stringi_1.8.3               sass_0.4.8                 
## [161] textshaping_0.3.7           RcppHNSW_0.5.0             
## [163] memoise_2.0.1               mathjaxr_1.6-0             
## [165] irlba_2.3.5.1               future.apply_1.11.0
```

---

## Analysis, visualization, and integration of Visium HD spatial datasets with Seurat • Seurat

**URL:** http://127.0.0.1:9173/seurat/articles/parsebio_sketch_integration/index.html

**Contents:**
- Sketch integration using a 1 million cell dataset from Parse Biosciences
    - Compiled: 2023-11-15
- Create a Seurat object containing data from 24 patients
- Sample representative cells from each dataset
- Perform integration on the sketched cells across samples
- Integrate the full datasets
- Compare healthy and diabetic samples
- Contents

The recent increase in publicly available single-cell datasets poses a significant challenge for integrative analysis. For example, multiple tissues have now been profiled across dozens of studies, representing hundreds of individuals and millions of cells. In Hao et al, 2023 proposed a dictionary learning based method, atomic sketch integration, could also enable efficient and large-scale integrative analysis. Our procedure enables the integration of large compendiums of datasets without ever needing to load the full scale of data into memory. In our manuscript we use atomic sketch integration to integrate millions of scRNA-seq from human lung and human PBMC.

In this vignette, we demonstrate how to use atomic sketch integration to harmonize scRNA-seq experiments 1M cells, though we have used this procedure to integrate datasets of 10M+ cells as well. We analyze a dataset from Parse Biosciences, in which PBMC from 24 human samples (12 healthy donors, 12 Type-1 diabetes donors), which is available here.

Prior to running this vignette, please install Seurat v5, as well as the BPCells package, which we use for on-disk storage. You can read more about using BPCells in Seurat v5 here. We also recommend reading the Sketch-based analysis in Seurat v5 vignette, which introduces the concept of on-disk and in-memory storage in Seurat v5.

We downloaded the original dataset and donor metadata from Parse Biosciences. While the BPCells package can work directly with h5ad files, for optimal performance, we converted the dataset to the compressed sparse format used by BPCells, as described here. We create a Seurat object for this dataset. Since the input to CreateSeuratObject is a BPCells matrix, the data remains on-disk and is not loaded into memory. After creating the object, we split the dataset into 24 layers, one for each sample (i.e. patient), to facilitate integration.

Inspired by pioneering work aiming to identify ‘sketches’ of scRNA-seq data, our first step is to sample a representative set of cells from each dataset. We compute a leverage score (estimate of ‘statistical leverage’) for each cell, which helps to identify cells that are likely to be member of rare subpopulations and ensure that these are included in our representative sample. Importantly, the estimation of leverage scores only requires data normalization, can be computed efficiently for sparse datasets, and does not require any intensive computation or dimensional reduction steps. We load each object separately, perform basic preprocessing (normalization and variable feature selection), and select and store 5,000 representative cells from each dataset. Since there are 24 datasets, the sketched dataset now contains 120,000 cells. These cells are stored in a new sketch assay, and are loaded in-memory.

Next we perform integrative analysis on the ‘atoms’ from each of the datasets. Here, we perform integration using the streamlined Seurat v5 integration worfklow, and utilize the reference-based RPCAIntegration method. The function performs all corrections in low-dimensional space (rather than on the expression values themselves) to further improve speed and memory usage, and outputs a merged Seurat object where all cells have been placed in an integrated low-dimensional space (stored as integrated.rpca). However, we emphasize that you can perform integration here using any analysis technique that places cells across datasets into a shared space. This includes CCA Integration, Harmony, and scVI. We demonstrate how to use these tools in Seurat v5 here.

Now that we have integrated the subset of atoms of each dataset, placing them each in an integrated low-dimensional space, we can now place each cell from each dataset in this space as well. We load the full datasets back in individually, and use the ProjectIntegration function to integrate all cells. After this function is run, the integrated.rpca.full space now embeds all cells in the dataset.Even though all cells in the dataset have been integrated together, the non-sketched cells are not loaded into memory. Users can still switch between the sketch (sketched cells, in-memory) and RNA (full dataset, on disk) for analysis. After integration, we can also project cell type labels from the sketched cells onto the full dataset using ProjectData.

By integrating all samples together, we can now compare healthy and diabetic cells in matched cell states. To maximize statistical power, we want to use all cells - not just the sketched cells - to perform this analysis. As recommended by Soneson et all. and Crowell et al., we use an aggregation-based (pseudobulk) workflow. We aggregate all cells within the same cell type and sample using the AggregateExpression function. This returns a Seurat object where each ‘cell’ represents the pseudobulk profile of one cell type in one individual.

After we aggregate cells, we can perform celltype-specific differential expression between healthy and diabetic samples using DESeq2. We demonstrate this for CD14 monocytes.

Developed by Rahul Satija, Satija Lab and Collaborators.

Site built with pkgdown 2.0.7.

**Examples:**

Example 1 (unknown):
```unknown
vignettes/ParseBio_sketch_integration.Rmd
```

Example 2 (unknown):
```unknown
ParseBio_sketch_integration.Rmd
```

Example 3 (unknown):
```unknown
library(Seurat)
library(BPCells)
library(dplyr)
library(ggplot2)
library(ggrepel)
library(patchwork)
# set this option when analyzing large datasets
options(future.globals.maxSize = 3e+09)
```

Example 4 (r):
```r
library(Seurat)
library(BPCells)
library(dplyr)
library(ggplot2)
library(ggrepel)
library(patchwork)
# set this option when analyzing large datasets
options(future.globals.maxSize = 3e+09)
```

Example 5 (r):
```r
library(Seurat)
library(BPCells)
library(dplyr)
library(ggplot2)
library(ggrepel)
library(patchwork)
# set this option when analyzing large datasets
options(future.globals.maxSize = 3e+09)
```

Example 6 (unknown):
```unknown
CreateSeuratObject
```

Example 7 (python):
```python
parse.mat <- open_matrix_dir(dir = "/brahms/hartmana/vignette_data/bpcells/parse_1m_pbmc")
# need to move
metadata <- readRDS("/brahms/haoy/vignette_data/ParseBio_PBMC_meta.rds")
object <- CreateSeuratObject(counts = parse.mat, meta.data = metadata)

object <- NormalizeData(object)
# split assay into 24 layers
object[["RNA"]] <- split(object[["RNA"]], f = object$sample)
object <- FindVariableFeatures(object, verbose = FALSE)
```

Example 8 (r):
```r
parse.mat <- open_matrix_dir(dir = "/brahms/hartmana/vignette_data/bpcells/parse_1m_pbmc")
# need to move
metadata <- readRDS("/brahms/haoy/vignette_data/ParseBio_PBMC_meta.rds")
object <- CreateSeuratObject(counts = parse.mat, meta.data = metadata)

object <- NormalizeData(object)
# split assay into 24 layers
object[["RNA"]] <- split(object[["RNA"]], f = object$sample)
object <- FindVariableFeatures(object, verbose = FALSE)
```

Example 9 (r):
```r
parse.mat <- open_matrix_dir(dir = "/brahms/hartmana/vignette_data/bpcells/parse_1m_pbmc")
# need to move
metadata <- readRDS("/brahms/haoy/vignette_data/ParseBio_PBMC_meta.rds")
object <- CreateSeuratObject(counts = parse.mat, meta.data = metadata)

object <- NormalizeData(object)
# split assay into 24 layers
object[["RNA"]] <- split(object[["RNA"]], f = object$sample)
object <- FindVariableFeatures(object, verbose = FALSE)
```

Example 10 (unknown):
```unknown
object <- SketchData(object = object, ncells = 5000, method = "LeverageScore", sketched.assay = "sketch")
object
```

Example 11 (r):
```r
object <- SketchData(object = object, ncells = 5000, method = "LeverageScore", sketched.assay = "sketch")
object
```

Example 12 (r):
```r
object <- SketchData(object = object, ncells = 5000, method = "LeverageScore", sketched.assay = "sketch")
object
```

Example 13 (python):
```python
## An object of class Seurat 
## 121328 features across 966344 samples within 2 assays 
## Active assay: sketch (60664 features, 2000 variable features)
##  48 layers present: counts.H_3128, counts.H_3060, counts.H_409, counts.H_7108, counts.H_120, counts.D_504, counts.H_2928, counts.H_727, counts.H_4579, counts.H_6625, counts.H_630, counts.D_500, counts.D_501, counts.D_610, counts.H_4119, counts.D_609, counts.D_644, counts.D_498, counts.H_1334, counts.D_497, counts.D_505, counts.D_506, counts.D_502, counts.D_503, data.H_3128, data.H_3060, data.H_409, data.H_7108, data.H_120, data.D_504, data.H_2928, data.H_727, data.H_4579, data.H_6625, data.H_630, data.D_500, data.D_501, data.D_610, data.H_4119, data.D_609, data.D_644, data.D_498, data.H_1334, data.D_497, data.D_505, data.D_506, data.D_502, data.D_503
##  1 other assay present: RNA
```

Example 14 (python):
```python
## An object of class Seurat 
## 121328 features across 966344 samples within 2 assays 
## Active assay: sketch (60664 features, 2000 variable features)
##  48 layers present: counts.H_3128, counts.H_3060, counts.H_409, counts.H_7108, counts.H_120, counts.D_504, counts.H_2928, counts.H_727, counts.H_4579, counts.H_6625, counts.H_630, counts.D_500, counts.D_501, counts.D_610, counts.H_4119, counts.D_609, counts.D_644, counts.D_498, counts.H_1334, counts.D_497, counts.D_505, counts.D_506, counts.D_502, counts.D_503, data.H_3128, data.H_3060, data.H_409, data.H_7108, data.H_120, data.D_504, data.H_2928, data.H_727, data.H_4579, data.H_6625, data.H_630, data.D_500, data.D_501, data.D_610, data.H_4119, data.D_609, data.D_644, data.D_498, data.H_1334, data.D_497, data.D_505, data.D_506, data.D_502, data.D_503
##  1 other assay present: RNA
```

Example 15 (unknown):
```unknown
RPCAIntegration
```

Example 16 (unknown):
```unknown
integrated.rpca
```

Example 17 (unknown):
```unknown
DefaultAssay(object) <- "sketch"
object <- FindVariableFeatures(object, verbose = F)
object <- ScaleData(object, verbose = F)
object <- RunPCA(object, verbose = F)
# integrate the datasets
object <- IntegrateLayers(object, method = RPCAIntegration, orig = "pca", new.reduction = "integrated.rpca",
    dims = 1:30, k.anchor = 20, reference = which(Layers(object, search = "data") %in% c("data.H_3060")),
    verbose = F)
# cluster the integrated data
object <- FindNeighbors(object, reduction = "integrated.rpca", dims = 1:30)
object <- FindClusters(object, resolution = 2)
```

Example 18 (r):
```r
DefaultAssay(object) <- "sketch"
object <- FindVariableFeatures(object, verbose = F)
object <- ScaleData(object, verbose = F)
object <- RunPCA(object, verbose = F)
# integrate the datasets
object <- IntegrateLayers(object, method = RPCAIntegration, orig = "pca", new.reduction = "integrated.rpca",
    dims = 1:30, k.anchor = 20, reference = which(Layers(object, search = "data") %in% c("data.H_3060")),
    verbose = F)
# cluster the integrated data
object <- FindNeighbors(object, reduction = "integrated.rpca", dims = 1:30)
object <- FindClusters(object, resolution = 2)
```

Example 19 (r):
```r
DefaultAssay(object) <- "sketch"
object <- FindVariableFeatures(object, verbose = F)
object <- ScaleData(object, verbose = F)
object <- RunPCA(object, verbose = F)
# integrate the datasets
object <- IntegrateLayers(object, method = RPCAIntegration, orig = "pca", new.reduction = "integrated.rpca",
    dims = 1:30, k.anchor = 20, reference = which(Layers(object, search = "data") %in% c("data.H_3060")),
    verbose = F)
# cluster the integrated data
object <- FindNeighbors(object, reduction = "integrated.rpca", dims = 1:30)
object <- FindClusters(object, resolution = 2)
```

Example 20 (unknown):
```unknown
## Modularity Optimizer version 1.3.0 by Ludo Waltman and Nees Jan van Eck
## 
## Number of nodes: 120000
## Number of edges: 5137782
## 
## Running Louvain algorithm...
## Maximum modularity in 10 random starts: 0.8765
## Number of communities: 47
## Elapsed time: 83 seconds
```

Example 21 (unknown):
```unknown
## Modularity Optimizer version 1.3.0 by Ludo Waltman and Nees Jan van Eck
## 
## Number of nodes: 120000
## Number of edges: 5137782
## 
## Running Louvain algorithm...
## Maximum modularity in 10 random starts: 0.8765
## Number of communities: 47
## Elapsed time: 83 seconds
```

Example 22 (unknown):
```unknown
object <- RunUMAP(object, reduction = "integrated.rpca", dims = 1:30, return.model = T, verbose = F)
```

Example 23 (r):
```r
object <- RunUMAP(object, reduction = "integrated.rpca", dims = 1:30, return.model = T, verbose = F)
```

Example 24 (r):
```r
object <- RunUMAP(object, reduction = "integrated.rpca", dims = 1:30, return.model = T, verbose = F)
```

Example 25 (unknown):
```unknown
# you can now rejoin the layers in the sketched assay this is required to perform differential
# expression
object[["sketch"]] <- JoinLayers(object[["sketch"]])
c10_markers <- FindMarkers(object = object, ident.1 = 10, max.cells.per.ident = 500, only.pos = TRUE)
head(c10_markers)
```

Example 26 (r):
```r
# you can now rejoin the layers in the sketched assay this is required to perform differential
# expression
object[["sketch"]] <- JoinLayers(object[["sketch"]])
c10_markers <- FindMarkers(object = object, ident.1 = 10, max.cells.per.ident = 500, only.pos = TRUE)
head(c10_markers)
```

Example 27 (r):
```r
# you can now rejoin the layers in the sketched assay this is required to perform differential
# expression
object[["sketch"]] <- JoinLayers(object[["sketch"]])
c10_markers <- FindMarkers(object = object, ident.1 = 10, max.cells.per.ident = 500, only.pos = TRUE)
head(c10_markers)
```

Example 28 (unknown):
```unknown
##                  p_val avg_log2FC pct.1 pct.2     p_val_adj
## BANK1    8.652285e-142   3.183046 0.980 0.183 5.248822e-137
## RALGPS2  1.870876e-134   3.168787 0.949 0.215 1.134948e-129
## OSBPL10  4.406924e-133   3.556864 0.890 0.118 2.673417e-128
## ARHGAP24 1.666152e-121   2.957065 0.916 0.263 1.010754e-116
## AFF3     6.864595e-107   2.248398 0.978 0.306 4.164338e-102
## EBF1     7.805461e-107   2.994191 0.841 0.126 4.735105e-102
```

Example 29 (unknown):
```unknown
##                  p_val avg_log2FC pct.1 pct.2     p_val_adj
## BANK1    8.652285e-142   3.183046 0.980 0.183 5.248822e-137
## RALGPS2  1.870876e-134   3.168787 0.949 0.215 1.134948e-129
## OSBPL10  4.406924e-133   3.556864 0.890 0.118 2.673417e-128
## ARHGAP24 1.666152e-121   2.957065 0.916 0.263 1.010754e-116
## AFF3     6.864595e-107   2.248398 0.978 0.306 4.164338e-102
## EBF1     7.805461e-107   2.994191 0.841 0.126 4.735105e-102
```

Example 30 (python):
```python
# You can now annotate clusters using marker genes.  We performed this step, and include the
# results in the 'sketch.celltype' metadata column

plot.s1 <- DimPlot(object, group.by = "sample", reduction = "umap")
plot.s2 <- DimPlot(object, group.by = "celltype.manual", reduction = "umap")
```

Example 31 (r):
```r
# You can now annotate clusters using marker genes.  We performed this step, and include the
# results in the 'sketch.celltype' metadata column

plot.s1 <- DimPlot(object, group.by = "sample", reduction = "umap")
plot.s2 <- DimPlot(object, group.by = "celltype.manual", reduction = "umap")
```

Example 32 (r):
```r
# You can now annotate clusters using marker genes.  We performed this step, and include the
# results in the 'sketch.celltype' metadata column

plot.s1 <- DimPlot(object, group.by = "sample", reduction = "umap")
plot.s2 <- DimPlot(object, group.by = "celltype.manual", reduction = "umap")
```

Example 33 (unknown):
```unknown
plot.s1 + plot.s2 + plot_layout(ncol = 1)
```

Example 34 (r):
```r
plot.s1 + plot.s2 + plot_layout(ncol = 1)
```

Example 35 (r):
```r
plot.s1 + plot.s2 + plot_layout(ncol = 1)
```

Example 36 (unknown):
```unknown
ProjectIntegration
```

Example 37 (unknown):
```unknown
integrated.rpca.full
```

Example 38 (unknown):
```unknown
ProjectData
```

Example 39 (unknown):
```unknown
# resplit the sketched cell assay into layers this is required to project the integration onto
# all cells
object[["sketch"]] <- split(object[["sketch"]], f = object$sample)

object <- ProjectIntegration(object = object, sketched.assay = "sketch", assay = "RNA", reduction = "integrated.rpca")


object <- ProjectData(object = object, sketched.assay = "sketch", assay = "RNA", sketched.reduction = "integrated.rpca.full",
    full.reduction = "integrated.rpca.full", dims = 1:30, refdata = list(celltype.full = "celltype.manual"))
```

Example 40 (r):
```r
# resplit the sketched cell assay into layers this is required to project the integration onto
# all cells
object[["sketch"]] <- split(object[["sketch"]], f = object$sample)

object <- ProjectIntegration(object = object, sketched.assay = "sketch", assay = "RNA", reduction = "integrated.rpca")


object <- ProjectData(object = object, sketched.assay = "sketch", assay = "RNA", sketched.reduction = "integrated.rpca.full",
    full.reduction = "integrated.rpca.full", dims = 1:30, refdata = list(celltype.full = "celltype.manual"))
```

Example 41 (r):
```r
# resplit the sketched cell assay into layers this is required to project the integration onto
# all cells
object[["sketch"]] <- split(object[["sketch"]], f = object$sample)

object <- ProjectIntegration(object = object, sketched.assay = "sketch", assay = "RNA", reduction = "integrated.rpca")


object <- ProjectData(object = object, sketched.assay = "sketch", assay = "RNA", sketched.reduction = "integrated.rpca.full",
    full.reduction = "integrated.rpca.full", dims = 1:30, refdata = list(celltype.full = "celltype.manual"))
```

Example 42 (unknown):
```unknown
object <- RunUMAP(object, reduction = "integrated.rpca.full", dims = 1:30, reduction.name = "umap.full",
    reduction.key = "UMAP_full_")
```

Example 43 (r):
```r
object <- RunUMAP(object, reduction = "integrated.rpca.full", dims = 1:30, reduction.name = "umap.full",
    reduction.key = "UMAP_full_")
```

Example 44 (r):
```r
object <- RunUMAP(object, reduction = "integrated.rpca.full", dims = 1:30, reduction.name = "umap.full",
    reduction.key = "UMAP_full_")
```

Example 45 (unknown):
```unknown
p1 <- DimPlot(object, reduction = "umap.full", group.by = "sample", alpha = 0.1)
p2 <- DimPlot(object, reduction = "umap.full", group.by = "celltype.full", alpha = 0.1)
p1 + p2 + plot_layout(ncol = 1)
```

Example 46 (r):
```r
p1 <- DimPlot(object, reduction = "umap.full", group.by = "sample", alpha = 0.1)
p2 <- DimPlot(object, reduction = "umap.full", group.by = "celltype.full", alpha = 0.1)
p1 + p2 + plot_layout(ncol = 1)
```

Example 47 (r):
```r
p1 <- DimPlot(object, reduction = "umap.full", group.by = "sample", alpha = 0.1)
p2 <- DimPlot(object, reduction = "umap.full", group.by = "celltype.full", alpha = 0.1)
p1 + p2 + plot_layout(ncol = 1)
```

Example 48 (unknown):
```unknown
AggregateExpression
```

Example 49 (unknown):
```unknown
bulk <- AggregateExpression(object, return.seurat = T, slot = "counts", assays = "RNA", group.by = c("celltype.full",
    "sample", "disease"))
```

Example 50 (r):
```r
bulk <- AggregateExpression(object, return.seurat = T, slot = "counts", assays = "RNA", group.by = c("celltype.full",
    "sample", "disease"))
```

Example 51 (r):
```r
bulk <- AggregateExpression(object, return.seurat = T, slot = "counts", assays = "RNA", group.by = c("celltype.full",
    "sample", "disease"))
```

Example 52 (unknown):
```unknown
# each sample is an individual-specific celltype-specific pseudobulk profile
tail(Cells(bulk))
```

Example 53 (r):
```r
# each sample is an individual-specific celltype-specific pseudobulk profile
tail(Cells(bulk))
```

Example 54 (r):
```r
# each sample is an individual-specific celltype-specific pseudobulk profile
tail(Cells(bulk))
```

Example 55 (unknown):
```unknown
## [1] "Treg_H-4119_H" "Treg_H-4579_H" "Treg_H-630_H"  "Treg_H-6625_H"
## [5] "Treg_H-7108_H" "Treg_H-727_H"
```

Example 56 (unknown):
```unknown
## [1] "Treg_H-4119_H" "Treg_H-4579_H" "Treg_H-630_H"  "Treg_H-6625_H"
## [5] "Treg_H-7108_H" "Treg_H-727_H"
```

Example 57 (unknown):
```unknown
cd14.bulk <- subset(bulk, celltype.full == "CD14 Mono")
  Idents(cd14.bulk) <- "disease"
  de_markers <- FindMarkers(cd14.bulk, ident.1 = "D", ident.2 = "H", slot = "counts", test.use = "DESeq2",
      verbose = F)
  de_markers$gene <- rownames(de_markers)
  ggplot(de_markers, aes(avg_log2FC, -log10(p_val))) + geom_point(size = 0.5, alpha = 0.5) + theme_bw() +
      ylab("-log10(unadjusted p-value)") + geom_text_repel(aes(label = ifelse(p_val_adj < 0.01, gene,
      "")), colour = "red", size = 3)
```

Example 58 (r):
```r
cd14.bulk <- subset(bulk, celltype.full == "CD14 Mono")
  Idents(cd14.bulk) <- "disease"
  de_markers <- FindMarkers(cd14.bulk, ident.1 = "D", ident.2 = "H", slot = "counts", test.use = "DESeq2",
      verbose = F)
  de_markers$gene <- rownames(de_markers)
  ggplot(de_markers, aes(avg_log2FC, -log10(p_val))) + geom_point(size = 0.5, alpha = 0.5) + theme_bw() +
      ylab("-log10(unadjusted p-value)") + geom_text_repel(aes(label = ifelse(p_val_adj < 0.01, gene,
      "")), colour = "red", size = 3)
```

Example 59 (r):
```r
cd14.bulk <- subset(bulk, celltype.full == "CD14 Mono")
  Idents(cd14.bulk) <- "disease"
  de_markers <- FindMarkers(cd14.bulk, ident.1 = "D", ident.2 = "H", slot = "counts", test.use = "DESeq2",
      verbose = F)
  de_markers$gene <- rownames(de_markers)
  ggplot(de_markers, aes(avg_log2FC, -log10(p_val))) + geom_point(size = 0.5, alpha = 0.5) + theme_bw() +
      ylab("-log10(unadjusted p-value)") + geom_text_repel(aes(label = ifelse(p_val_adj < 0.01, gene,
      "")), colour = "red", size = 3)
```

Example 60 (unknown):
```unknown
sessionInfo()
```

Example 61 (r):
```r
sessionInfo()
```

Example 62 (r):
```r
sessionInfo()
```

Example 63 (unknown):
```unknown
## R version 4.2.2 Patched (2022-11-10 r83330)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.6 LTS
## 
## Matrix products: default
## BLAS:   /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.9.0
## LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.9.0
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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       
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
## [1] patchwork_1.1.3    ggrepel_0.9.4      ggplot2_3.4.4      dplyr_1.1.3       
## [5] BPCells_0.1.0      Seurat_5.0.1       SeuratObject_5.0.1 sp_2.1-1          
## 
## loaded via a namespace (and not attached):
##   [1] spam_2.10-0            systemfonts_1.0.4      plyr_1.8.9            
##   [4] igraph_1.5.1           lazyeval_0.2.2         splines_4.2.2         
##   [7] RcppHNSW_0.5.0         listenv_0.9.0          scattermore_1.2       
##  [10] GenomeInfoDb_1.34.9    digest_0.6.33          htmltools_0.5.6.1     
##  [13] fansi_1.0.5            magrittr_2.0.3         memoise_2.0.1         
##  [16] tensor_1.5             cluster_2.1.4          ROCR_1.0-11           
##  [19] limma_3.54.1           globals_0.16.2         matrixStats_1.0.0     
##  [22] pkgdown_2.0.7          spatstat.sparse_3.0-3  colorspace_2.1-0      
##  [25] textshaping_0.3.6      xfun_0.40              RCurl_1.98-1.12       
##  [28] jsonlite_1.8.7         progressr_0.14.0       spatstat.data_3.0-3   
##  [31] survival_3.5-7         zoo_1.8-12             glue_1.6.2            
##  [34] polyclip_1.10-6        gtable_0.3.4           zlibbioc_1.44.0       
##  [37] XVector_0.38.0         leiden_0.4.3           future.apply_1.11.0   
##  [40] BiocGenerics_0.44.0    abind_1.4-5            scales_1.2.1          
##  [43] spatstat.random_3.2-1  miniUI_0.1.1.1         Rcpp_1.0.11           
##  [46] viridisLite_0.4.2      xtable_1.8-4           reticulate_1.34.0     
##  [49] dotCall64_1.1-0        stats4_4.2.2           htmlwidgets_1.6.2     
##  [52] httr_1.4.7             RColorBrewer_1.1-3     ellipsis_0.3.2        
##  [55] ica_1.0-3              farver_2.1.1           pkgconfig_2.0.3       
##  [58] sass_0.4.7             uwot_0.1.16            deldir_1.0-9          
##  [61] utf8_1.2.4             labeling_0.4.3         tidyselect_1.2.0      
##  [64] rlang_1.1.1            reshape2_1.4.4         later_1.3.1           
##  [67] munsell_0.5.0          tools_4.2.2            cachem_1.0.8          
##  [70] cli_3.6.1              generics_0.1.3         ggridges_0.5.4        
##  [73] evaluate_0.22          stringr_1.5.0          fastmap_1.1.1         
##  [76] yaml_2.3.7             ragg_1.2.5             goftest_1.2-3         
##  [79] knitr_1.45             fs_1.6.3               fitdistrplus_1.1-11   
##  [82] purrr_1.0.2            RANN_2.6.1             pbapply_1.7-2         
##  [85] future_1.33.0          nlme_3.1-162           mime_0.12             
##  [88] formatR_1.14           compiler_4.2.2         plotly_4.10.3         
##  [91] png_0.1-8              spatstat.utils_3.0-4   tibble_3.2.1          
##  [94] bslib_0.5.1            stringi_1.7.12         highr_0.10            
##  [97] desc_1.4.2             RSpectra_0.16-1        lattice_0.21-9        
## [100] Matrix_1.6-1.1         vctrs_0.6.4            pillar_1.9.0          
## [103] lifecycle_1.0.4        spatstat.geom_3.2-7    lmtest_0.9-40         
## [106] jquerylib_0.1.4        RcppAnnoy_0.0.21       data.table_1.14.8     
## [109] cowplot_1.1.1          bitops_1.0-7           irlba_2.3.5.1         
## [112] httpuv_1.6.12          GenomicRanges_1.50.2   R6_2.5.1              
## [115] promises_1.2.1         KernSmooth_2.23-22     gridExtra_2.3         
## [118] IRanges_2.32.0         parallelly_1.36.0      codetools_0.2-19      
## [121] fastDummies_1.7.3      MASS_7.3-58.2          rprojroot_2.0.4       
## [124] withr_2.5.2            presto_1.0.0           sctransform_0.4.1     
## [127] S4Vectors_0.36.2       GenomeInfoDbData_1.2.9 parallel_4.2.2        
## [130] grid_4.2.2             tidyr_1.3.0            rmarkdown_2.25        
## [133] Rtsne_0.16             spatstat.explore_3.2-5 shiny_1.7.5.1
```

Example 64 (unknown):
```unknown
## R version 4.2.2 Patched (2022-11-10 r83330)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.6 LTS
## 
## Matrix products: default
## BLAS:   /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.9.0
## LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.9.0
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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       
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
## [1] patchwork_1.1.3    ggrepel_0.9.4      ggplot2_3.4.4      dplyr_1.1.3       
## [5] BPCells_0.1.0      Seurat_5.0.1       SeuratObject_5.0.1 sp_2.1-1          
## 
## loaded via a namespace (and not attached):
##   [1] spam_2.10-0            systemfonts_1.0.4      plyr_1.8.9            
##   [4] igraph_1.5.1           lazyeval_0.2.2         splines_4.2.2         
##   [7] RcppHNSW_0.5.0         listenv_0.9.0          scattermore_1.2       
##  [10] GenomeInfoDb_1.34.9    digest_0.6.33          htmltools_0.5.6.1     
##  [13] fansi_1.0.5            magrittr_2.0.3         memoise_2.0.1         
##  [16] tensor_1.5             cluster_2.1.4          ROCR_1.0-11           
##  [19] limma_3.54.1           globals_0.16.2         matrixStats_1.0.0     
##  [22] pkgdown_2.0.7          spatstat.sparse_3.0-3  colorspace_2.1-0      
##  [25] textshaping_0.3.6      xfun_0.40              RCurl_1.98-1.12       
##  [28] jsonlite_1.8.7         progressr_0.14.0       spatstat.data_3.0-3   
##  [31] survival_3.5-7         zoo_1.8-12             glue_1.6.2            
##  [34] polyclip_1.10-6        gtable_0.3.4           zlibbioc_1.44.0       
##  [37] XVector_0.38.0         leiden_0.4.3           future.apply_1.11.0   
##  [40] BiocGenerics_0.44.0    abind_1.4-5            scales_1.2.1          
##  [43] spatstat.random_3.2-1  miniUI_0.1.1.1         Rcpp_1.0.11           
##  [46] viridisLite_0.4.2      xtable_1.8-4           reticulate_1.34.0     
##  [49] dotCall64_1.1-0        stats4_4.2.2           htmlwidgets_1.6.2     
##  [52] httr_1.4.7             RColorBrewer_1.1-3     ellipsis_0.3.2        
##  [55] ica_1.0-3              farver_2.1.1           pkgconfig_2.0.3       
##  [58] sass_0.4.7             uwot_0.1.16            deldir_1.0-9          
##  [61] utf8_1.2.4             labeling_0.4.3         tidyselect_1.2.0      
##  [64] rlang_1.1.1            reshape2_1.4.4         later_1.3.1           
##  [67] munsell_0.5.0          tools_4.2.2            cachem_1.0.8          
##  [70] cli_3.6.1              generics_0.1.3         ggridges_0.5.4        
##  [73] evaluate_0.22          stringr_1.5.0          fastmap_1.1.1         
##  [76] yaml_2.3.7             ragg_1.2.5             goftest_1.2-3         
##  [79] knitr_1.45             fs_1.6.3               fitdistrplus_1.1-11   
##  [82] purrr_1.0.2            RANN_2.6.1             pbapply_1.7-2         
##  [85] future_1.33.0          nlme_3.1-162           mime_0.12             
##  [88] formatR_1.14           compiler_4.2.2         plotly_4.10.3         
##  [91] png_0.1-8              spatstat.utils_3.0-4   tibble_3.2.1          
##  [94] bslib_0.5.1            stringi_1.7.12         highr_0.10            
##  [97] desc_1.4.2             RSpectra_0.16-1        lattice_0.21-9        
## [100] Matrix_1.6-1.1         vctrs_0.6.4            pillar_1.9.0          
## [103] lifecycle_1.0.4        spatstat.geom_3.2-7    lmtest_0.9-40         
## [106] jquerylib_0.1.4        RcppAnnoy_0.0.21       data.table_1.14.8     
## [109] cowplot_1.1.1          bitops_1.0-7           irlba_2.3.5.1         
## [112] httpuv_1.6.12          GenomicRanges_1.50.2   R6_2.5.1              
## [115] promises_1.2.1         KernSmooth_2.23-22     gridExtra_2.3         
## [118] IRanges_2.32.0         parallelly_1.36.0      codetools_0.2-19      
## [121] fastDummies_1.7.3      MASS_7.3-58.2          rprojroot_2.0.4       
## [124] withr_2.5.2            presto_1.0.0           sctransform_0.4.1     
## [127] S4Vectors_0.36.2       GenomeInfoDbData_1.2.9 parallel_4.2.2        
## [130] grid_4.2.2             tidyr_1.3.0            rmarkdown_2.25        
## [133] Rtsne_0.16             spatstat.explore_3.2-5 shiny_1.7.5.1
```

---

## Analysis, visualization, and integration of Visium HD spatial datasets with Seurat • Seurat

**URL:** http://127.0.0.1:9173/articles_archive.html

**Contents:**
- Documentation Archive
- Version 2-4 tutorials
    - PBMC scATAC-seq Vignette
    - Cell-Cycle Scoring and Regression
    - Interoperability between single-cell object formats
    - Differential expression testing
    - Seurat - Dimensional Reduction Vignette
    - Parallelization in Seurat with future
    - Demultiplexing with hashtag oligos (HTOs)
    - Tutorial: Integrating stimulated vs. control PBMC datasets to learn cell- type specific responses
    - Integration and Label Transfer
    - Mapping and annotating query datasets
    - Tips for integrating large datasets
    - Fast integration using reciprocal PCA (RPCA)
    - Seurat - Interaction Tips
    - Guided Clustering of the Microwell-seq Mouse Cell Atlas
    - Seurat - Combining Two 10X Runs
    - Mixscape Vignette
    - Multimodal reference mapping
    - Using Seurat with multi-modal data
    - Guided tutorial — 2,700 PBMCs
    - Using sctransform in Seurat
    - SCTransform v2
    - Analysis, visualization, and integration of spatial datasets with Seurat
    - New data visualization methods in v3.0
    - Weighted Nearest Neighbor Analysis
- Version 1.3-1.4 tutorials
- Version <=1.2 tutorials
- Contents

In version 4, the Seurat documentation was transitioned to pkgdown. Here we provide access to all previous versions of the documentation.

For versions 1.3-1.4, we provide access to the old documentation pages here

For versions <=1.2, we provide access to the old documentation pages here

Developed by Rahul Satija, Satija Lab and Collaborators.

Site built with pkgdown 2.0.7.

**Examples:**

Example 1 (unknown):
```unknown
vignettes/archive.Rmd
```

Example 2 (unknown):
```unknown
archive.Rmd
```

---

## Tools for Single Cell Genomics • Seurat

**URL:** http://127.0.0.1:9173/seurat/index.html

**Contents:**
- Seurat v5
- Changes between v4 and v5
- About Seurat
- Links
- License
- Community
- Citation
- Developers

We are excited to release Seurat v5! To install, please follow the instructions in our install page. This update brings the following new features and functionality:

Integrative multimodal analysis: The cellular transcriptome is just one aspect of cellular identity, and recent technologies enable routine profiling of chromatin accessibility, histone modifications, and protein levels from single cells. In Seurat v5, we introduce ‘bridge integration’, a statistical method to integrate experiments measuring different modalities (i.e. separate scRNA-seq and scATAC-seq datasets), using a separate multiomic dataset as a molecular ‘bridge’. For example, we demonstrate how to map scATAC-seq datasets onto scRNA-seq datasets, to assist users in interpreting and annotating data from new modalities. We recognize that while the goal of matching shared cell types across datasets may be important for many problems, users may also be concerned about which method to use, or that integration could result in a loss of biological resolution. In Seurat v5, we also introduce flexible and streamlined workflows for the integration of multiple scRNA-seq datasets. This makes it easier to explore the results of different integration methods, and to compare these results to a workflow that excludes integration steps.

Flexible, interactive, and highly scalable analsyis: The size and scale of single-cell sequencing datasets is rapidly increasing, outpacing even Moore’s law. In Seurat v5, we introduce new infrastructure and methods to analyze, interpret, and explore exciting datasets spanning millions of cells, even if they cannot be fully loaded into memory. We introduce support for ‘sketch’-based analysis, where representative subsamples of a large dataset are stored in-memory to enable rapid and iterative analysis - while the full dataset remains accessible via on-disk storage. We enable high-performance via the BPCells package, developed by Ben Parks in the Greenleaf Lab. The BPCells package enables high-performance analysis via innovative bit-packing compression techniques, optimized C++ code, and use of streamlined and lazy operations.

Analysis of sequencing and imaging-based spatial datasets: Spatially resolved datasets are redefining our understanding of cellular interactions and the organization of human tissues. Both sequencing-based(i.e. Visium, SLIDE-seq, etc.), and imaging-based (MERFISH/Vizgen, Xenium, CosMX, etc.) technologies have unique advantages, and require tailored analytical methods and software infrastructure. In Seurat v5, we introduce flexible and diverse support for a wide variety of spatially resolved data types, and support for analytical techniqiues for scRNA-seq integration, deconvolution, and niche identification.

Backwards compatibility: While Seurat v5 introduces new functionality, we have ensured that the software is backwards-compatible with previous versions, so that users will continue to be able to re-run existing workflows. Previous versions of Seurat, such as Seurat v4, can also be installed following the instructions in our install page.

We have documented major changes between Seurat v4 and v5 in our News page for reference.

Seurat is an R package designed for QC, analysis, and exploration of single-cell RNA-seq data. Seurat aims to enable users to identify and interpret sources of heterogeneity from single-cell transcriptomic measurements, and to integrate diverse types of single-cell data.

If you use Seurat in your research, please considering citing:

All methods emphasize clear, attractive, and interpretable visualizations, and were designed to be easily used by both dry-lab and wet-lab researchers.

Seurat is developed and maintained by the Satija lab and is released under the MIT license.

Developed by Rahul Satija, Satija Lab and Collaborators.

Site built with pkgdown 2.0.7.

---

## Analysis, visualization, and integration of Visium HD spatial datasets with Seurat • Seurat

**URL:** http://127.0.0.1:9173/articles_seurat5_sketch_analysis.html

**Contents:**
- Sketch-based analysis in Seurat v5
    - Compiled: 2023-10-31
- Intro: Sketch-based analysis in Seurat v5
- Create a Seurat object with a v5 assay for on-disk storage
- ‘Sketch’ a subset of cells, and load these into memory
- Perform clustering on the sketched dataset
- Extend results to the full datasets
- Perform iterative sub-clustering
- Contents

As single-cell sequencing technologies continue to improve in scalability in throughput, the generation of datasets spanning a million or more cells is becoming increasingly routine. In Seurat v5, we introduce new infrastructure and methods to analyze, interpret, and explore these exciting datasets.

In this vignette, we introduce a sketch-based analysis workflow to analyze a 1.3 million cell dataset of the developing mouse brain, freely available from 10x Genomics. Analyzing datasets of this size with standard workflows can be challenging, slow, and memory-intensive. Here we introduce an alternative workflow that is highly scalable, even to datasets ranging beyond 10 million cells in size. Our ‘sketch-based’ workflow involves three new features in Seurat v5:

Storing expression matrices in memory can be challenging for extremely large scRNA-seq datasets. In Seurat v5, we introduce support for multiple on-disk storage formats.

As introduced in Hie et al, 2019, cell sketching methods aim to compactly summarize large single-cell datasets in a small number of cells, while preserving the presence of both abundant and rare cell types. In Seurat v5, we leverage this idea to select subsamples (‘sketches’) of cells from large datasets that are stored on-disk. However, after sketching, the subsampled cells can be stored in-memory, allowing for interactive and rapid visualization and exploration. We store sketched cells (in-memory) and the full dataset (on-disk) as two assays in the same Seurat object. Users can then easily switch between the two versions, providing the flexibility to perform quick analyses on a subset of cells in-memory, while retaining access to the full dataset on-disk.

We demonstrate the on-disk capabilities in Seurat v5 using the BPCells package developed by Ben Parks in the Greenleaf Lab. This package utilizes bit-packing compression and optimized, streaming-compatible C++ code to substantially improve I/O and computational performance when working with on-disk data. To run this vignette please install Seurat v5, using the installation instructions found here. Additionally, you will need to install the BPcells package, using the installation instructions found here.

We start by loading the 1.3M dataset from 10x Genomics using the open_matrix_dir function from BPCells. Note that in our Introduction to on-disk storage vignette, we demonstrate how to create this on-disk representation. This function does not load the dataset into memory, but instead, creates a connection to the data stored on-disk. We then store this on-disk representation in the Seurat object, which is loaded using readRDS as per usual.

We select a subset (‘sketch’) of 50,000 cells (out of 1.3M). Rather than sampling all cells with uniform probability, we compute and sample based off a ‘leverage score’ for each cell, which reflects the magnitude of its contribution to the gene-covariance matrix, and its importance to the overall dataset. In Hao et al, 2022, we demonstrate that the leverage score is highest for rare populations in a dataset. Therefore, our sketched set of 50,000 cells will oversample rare populations, retaining the biological complexity of the sample while drastically compressing the dataset.

The function SketchData takes a normalized single-cell dataset (stored either on-disk or in-memory), and a set of variable features. It returns a Seurat object with a new assay (sketch), consisting of 50,000 cells, but these cells are now stored in-memory. Users can now easily switch between the in-memory and on-disk representation just by changing the default assay.

Now that we have compressed the dataset, we can perform standard clustering and visualization of a 50,000 cell dataset. After clustering, we can see groups of cells that clearly correspond to precursors of distinct lineages, including endothelial cells (Igfbp7), Excitatory (Neurod6) and Inhibitory (Dlx2) neurons, Intermediate Progenitors (Eomes), Radial Glia (Vim), Cajal-Retzius cells (Reln), Oligodendroytes (Olig1), and extremely rare populations of macrophages (C1qa) that were oversampled in our sketched data.

We can now extend the cluster labels and dimensional reductions learned on the sketched cells to the full dataset. The ProjectData function projects the on-disk data, onto the sketch assay. It returns a Seurat object that includes a

Now that we have performed an initial analysis of the dataset, we can iteratively ‘zoom-in’ on a cell subtype of interest, extract all cells of this type, and perform iterative sub-clustering. For example, we can see that Dlx2+ interneuron precursors are defined by clusters 2, 15, 18, 28 and 40.

We therefore extract all cells from the full on-disk dataset that are present in these clusters. There are 200,892 of them. Since this is a manageable number, we can convert these data from on-disk storage into in-memory storage. We can then proceed with standard clustering.

Note that we can start to see distinct interneuron lineages emerging in this dataset. We can see a clear separation of interneuron precursors that originated from the medial ganglionic eminence (Lhx6) or caudal ganglionic eminence (Nr2f2). We can further see the emergence of Sst (Sst) and Pvalb (Mef2c)-committed interneurons, and a CGE-derived Meis2-expressing progenitor population. These results closely mirror our findings from Mayer, Hafemeister, Bandler* et al, Nature 2018, where we enriched for interneuron precursors using a Dlx6a-cre fate-mapping strategy. Here, we obtain similar results using only computational enrichment, enabled by the large size of the original dataset.

Developed by Rahul Satija, Satija Lab and Collaborators.

Site built with pkgdown 2.0.7.

**Examples:**

Example 1 (unknown):
```unknown
vignettes/seurat5_sketch_analysis.Rmd
```

Example 2 (unknown):
```unknown
seurat5_sketch_analysis.Rmd
```

Example 3 (unknown):
```unknown
library(Seurat)
library(BPCells)
library(ggplot2)
# needs to be set for large dataset analysis
options(future.globals.maxSize = 1e9)
```

Example 4 (r):
```r
library(Seurat)
library(BPCells)
library(ggplot2)
# needs to be set for large dataset analysis
options(future.globals.maxSize = 1e9)
```

Example 5 (r):
```r
library(Seurat)
library(BPCells)
library(ggplot2)
# needs to be set for large dataset analysis
options(future.globals.maxSize = 1e9)
```

Example 6 (unknown):
```unknown
open_matrix_dir
```

Example 7 (unknown):
```unknown
# Read the Seurat object, which contains 1.3M cells stored on-disk as part of the 'RNA' assay
obj <- readRDS("/brahms/hartmana/vignette_data/1p3_million_mouse_brain.rds")
obj
```

Example 8 (r):
```r
# Read the Seurat object, which contains 1.3M cells stored on-disk as part of the 'RNA' assay
obj <- readRDS("/brahms/hartmana/vignette_data/1p3_million_mouse_brain.rds")
obj
```

Example 9 (r):
```r
# Read the Seurat object, which contains 1.3M cells stored on-disk as part of the 'RNA' assay
obj <- readRDS("/brahms/hartmana/vignette_data/1p3_million_mouse_brain.rds")
obj
```

Example 10 (python):
```python
## An object of class Seurat 
## 27282 features across 1306127 samples within 1 assay 
## Active assay: RNA (27282 features, 0 variable features)
##  1 layer present: counts
```

Example 11 (python):
```python
## An object of class Seurat 
## 27282 features across 1306127 samples within 1 assay 
## Active assay: RNA (27282 features, 0 variable features)
##  1 layer present: counts
```

Example 12 (unknown):
```unknown
# Note that since the data is stored on-disk, the object size easily fits in-memory (<1GB)
format(object.size(obj), units = "Mb")
```

Example 13 (r):
```r
# Note that since the data is stored on-disk, the object size easily fits in-memory (<1GB)
format(object.size(obj), units = "Mb")
```

Example 14 (r):
```r
# Note that since the data is stored on-disk, the object size easily fits in-memory (<1GB)
format(object.size(obj), units = "Mb")
```

Example 15 (unknown):
```unknown
## [1] "596.2 Mb"
```

Example 16 (unknown):
```unknown
## [1] "596.2 Mb"
```

Example 17 (unknown):
```unknown
obj <- NormalizeData(obj)
obj <- FindVariableFeatures(obj)
obj <- SketchData(
  object = obj,
  ncells = 50000,
  method = "LeverageScore",
  sketched.assay = "sketch"
)
obj
```

Example 18 (r):
```r
obj <- NormalizeData(obj)
obj <- FindVariableFeatures(obj)
obj <- SketchData(
  object = obj,
  ncells = 50000,
  method = "LeverageScore",
  sketched.assay = "sketch"
)
obj
```

Example 19 (r):
```r
obj <- NormalizeData(obj)
obj <- FindVariableFeatures(obj)
obj <- SketchData(
  object = obj,
  ncells = 50000,
  method = "LeverageScore",
  sketched.assay = "sketch"
)
obj
```

Example 20 (python):
```python
## An object of class Seurat 
## 54564 features across 1306127 samples within 2 assays 
## Active assay: sketch (27282 features, 2000 variable features)
##  2 layers present: counts, data
##  1 other assay present: RNA
```

Example 21 (python):
```python
## An object of class Seurat 
## 54564 features across 1306127 samples within 2 assays 
## Active assay: sketch (27282 features, 2000 variable features)
##  2 layers present: counts, data
##  1 other assay present: RNA
```

Example 22 (unknown):
```unknown
# switch to analyzing the full dataset (on-disk)
DefaultAssay(obj) <- "RNA"
# switch to analyzing the sketched dataset (in-memory)
DefaultAssay(obj) <- "sketch"
```

Example 23 (r):
```r
# switch to analyzing the full dataset (on-disk)
DefaultAssay(obj) <- "RNA"
# switch to analyzing the sketched dataset (in-memory)
DefaultAssay(obj) <- "sketch"
```

Example 24 (r):
```r
# switch to analyzing the full dataset (on-disk)
DefaultAssay(obj) <- "RNA"
# switch to analyzing the sketched dataset (in-memory)
DefaultAssay(obj) <- "sketch"
```

Example 25 (unknown):
```unknown
DefaultAssay(obj) <- "sketch"
obj <- FindVariableFeatures(obj)
obj <- ScaleData(obj)
obj <- RunPCA(obj)
obj <- FindNeighbors(obj, dims = 1:50)
obj <- FindClusters(obj, resolution = 2)
```

Example 26 (r):
```r
DefaultAssay(obj) <- "sketch"
obj <- FindVariableFeatures(obj)
obj <- ScaleData(obj)
obj <- RunPCA(obj)
obj <- FindNeighbors(obj, dims = 1:50)
obj <- FindClusters(obj, resolution = 2)
```

Example 27 (r):
```r
DefaultAssay(obj) <- "sketch"
obj <- FindVariableFeatures(obj)
obj <- ScaleData(obj)
obj <- RunPCA(obj)
obj <- FindNeighbors(obj, dims = 1:50)
obj <- FindClusters(obj, resolution = 2)
```

Example 28 (unknown):
```unknown
## Modularity Optimizer version 1.3.0 by Ludo Waltman and Nees Jan van Eck
## 
## Number of nodes: 50000
## Number of edges: 1992657
## 
## Running Louvain algorithm...
## Maximum modularity in 10 random starts: 0.8766
## Number of communities: 51
## Elapsed time: 19 seconds
```

Example 29 (unknown):
```unknown
## Modularity Optimizer version 1.3.0 by Ludo Waltman and Nees Jan van Eck
## 
## Number of nodes: 50000
## Number of edges: 1992657
## 
## Running Louvain algorithm...
## Maximum modularity in 10 random starts: 0.8766
## Number of communities: 51
## Elapsed time: 19 seconds
```

Example 30 (unknown):
```unknown
obj <- RunUMAP(obj, dims = 1:50, return.model = T)
DimPlot(obj, label = T, label.size = 3, reduction = "umap") + NoLegend()
```

Example 31 (r):
```r
obj <- RunUMAP(obj, dims = 1:50, return.model = T)
DimPlot(obj, label = T, label.size = 3, reduction = "umap") + NoLegend()
```

Example 32 (r):
```r
obj <- RunUMAP(obj, dims = 1:50, return.model = T)
DimPlot(obj, label = T, label.size = 3, reduction = "umap") + NoLegend()
```

Example 33 (unknown):
```unknown
FeaturePlot(
  object = obj,
  features = c(
    "Igfbp7", "Neurod6", "Dlx2", "Gad2",
    "Eomes", "Vim", "Reln", "Olig1", "C1qa"
  ),
  ncol = 3
)
```

Example 34 (r):
```r
FeaturePlot(
  object = obj,
  features = c(
    "Igfbp7", "Neurod6", "Dlx2", "Gad2",
    "Eomes", "Vim", "Reln", "Olig1", "C1qa"
  ),
  ncol = 3
)
```

Example 35 (r):
```r
FeaturePlot(
  object = obj,
  features = c(
    "Igfbp7", "Neurod6", "Dlx2", "Gad2",
    "Eomes", "Vim", "Reln", "Olig1", "C1qa"
  ),
  ncol = 3
)
```

Example 36 (unknown):
```unknown
ProjectData
```

Example 37 (unknown):
```unknown
cluster_full
```

Example 38 (unknown):
```unknown
obj <- ProjectData(
  object = obj,
  assay = "RNA",
  full.reduction = "pca.full",
  sketched.assay = "sketch",
  sketched.reduction = "pca",
  umap.model = "umap",
  dims = 1:50,
  refdata = list(cluster_full = "seurat_clusters")
)
# now that we have projected the full dataset, switch back to analyzing all cells
DefaultAssay(obj) <- "RNA"
```

Example 39 (r):
```r
obj <- ProjectData(
  object = obj,
  assay = "RNA",
  full.reduction = "pca.full",
  sketched.assay = "sketch",
  sketched.reduction = "pca",
  umap.model = "umap",
  dims = 1:50,
  refdata = list(cluster_full = "seurat_clusters")
)
# now that we have projected the full dataset, switch back to analyzing all cells
DefaultAssay(obj) <- "RNA"
```

Example 40 (r):
```r
obj <- ProjectData(
  object = obj,
  assay = "RNA",
  full.reduction = "pca.full",
  sketched.assay = "sketch",
  sketched.reduction = "pca",
  umap.model = "umap",
  dims = 1:50,
  refdata = list(cluster_full = "seurat_clusters")
)
# now that we have projected the full dataset, switch back to analyzing all cells
DefaultAssay(obj) <- "RNA"
```

Example 41 (unknown):
```unknown
DimPlot(obj, label = T, label.size = 3, reduction = "full.umap", group.by = "cluster_full", alpha = 0.1) + NoLegend()
```

Example 42 (r):
```r
DimPlot(obj, label = T, label.size = 3, reduction = "full.umap", group.by = "cluster_full", alpha = 0.1) + NoLegend()
```

Example 43 (r):
```r
DimPlot(obj, label = T, label.size = 3, reduction = "full.umap", group.by = "cluster_full", alpha = 0.1) + NoLegend()
```

Example 44 (unknown):
```unknown
# visualize gene expression on the sketched cells (fast) and the full dataset (slower)
DefaultAssay(obj) <- "sketch"
x1 <- FeaturePlot(obj, "C1qa")
DefaultAssay(obj) <- "RNA"
x2 <- FeaturePlot(obj, "C1qa")
x1 | x2
```

Example 45 (r):
```r
# visualize gene expression on the sketched cells (fast) and the full dataset (slower)
DefaultAssay(obj) <- "sketch"
x1 <- FeaturePlot(obj, "C1qa")
DefaultAssay(obj) <- "RNA"
x2 <- FeaturePlot(obj, "C1qa")
x1 | x2
```

Example 46 (r):
```r
# visualize gene expression on the sketched cells (fast) and the full dataset (slower)
DefaultAssay(obj) <- "sketch"
x1 <- FeaturePlot(obj, "C1qa")
DefaultAssay(obj) <- "RNA"
x2 <- FeaturePlot(obj, "C1qa")
x1 | x2
```

Example 47 (unknown):
```unknown
DefaultAssay(obj) <- "sketch"
VlnPlot(obj, "Dlx2")
```

Example 48 (r):
```r
DefaultAssay(obj) <- "sketch"
VlnPlot(obj, "Dlx2")
```

Example 49 (r):
```r
DefaultAssay(obj) <- "sketch"
VlnPlot(obj, "Dlx2")
```

Example 50 (unknown):
```unknown
# subset cells in these clusters. Note that the data remains on-disk after subsetting
obj.sub <- subset(obj, subset = cluster_full %in% c(2, 15, 18, 28, 40))
DefaultAssay(obj.sub) <- "RNA"

# now convert the RNA assay (previously on-disk) into an in-memory representation (sparse Matrix)
# we only convert the data layer, and keep the counts on-disk
obj.sub[["RNA"]]$data <- as(obj.sub[["RNA"]]$data, Class = "dgCMatrix")

# recluster the cells
obj.sub <- FindVariableFeatures(obj.sub)
obj.sub <- ScaleData(obj.sub)
obj.sub <- RunPCA(obj.sub)
obj.sub <- RunUMAP(obj.sub, dims = 1:30)
obj.sub <- FindNeighbors(obj.sub, dims = 1:30)
obj.sub <- FindClusters(obj.sub)
```

Example 51 (r):
```r
# subset cells in these clusters. Note that the data remains on-disk after subsetting
obj.sub <- subset(obj, subset = cluster_full %in% c(2, 15, 18, 28, 40))
DefaultAssay(obj.sub) <- "RNA"

# now convert the RNA assay (previously on-disk) into an in-memory representation (sparse Matrix)
# we only convert the data layer, and keep the counts on-disk
obj.sub[["RNA"]]$data <- as(obj.sub[["RNA"]]$data, Class = "dgCMatrix")

# recluster the cells
obj.sub <- FindVariableFeatures(obj.sub)
obj.sub <- ScaleData(obj.sub)
obj.sub <- RunPCA(obj.sub)
obj.sub <- RunUMAP(obj.sub, dims = 1:30)
obj.sub <- FindNeighbors(obj.sub, dims = 1:30)
obj.sub <- FindClusters(obj.sub)
```

Example 52 (r):
```r
# subset cells in these clusters. Note that the data remains on-disk after subsetting
obj.sub <- subset(obj, subset = cluster_full %in% c(2, 15, 18, 28, 40))
DefaultAssay(obj.sub) <- "RNA"

# now convert the RNA assay (previously on-disk) into an in-memory representation (sparse Matrix)
# we only convert the data layer, and keep the counts on-disk
obj.sub[["RNA"]]$data <- as(obj.sub[["RNA"]]$data, Class = "dgCMatrix")

# recluster the cells
obj.sub <- FindVariableFeatures(obj.sub)
obj.sub <- ScaleData(obj.sub)
obj.sub <- RunPCA(obj.sub)
obj.sub <- RunUMAP(obj.sub, dims = 1:30)
obj.sub <- FindNeighbors(obj.sub, dims = 1:30)
obj.sub <- FindClusters(obj.sub)
```

Example 53 (unknown):
```unknown
## Modularity Optimizer version 1.3.0 by Ludo Waltman and Nees Jan van Eck
## 
## Number of nodes: 236276
## Number of edges: 5470656
## 
## Running Louvain algorithm...
## Maximum modularity in 10 random starts: 0.8577
## Number of communities: 28
## Elapsed time: 191 seconds
```

Example 54 (unknown):
```unknown
## Modularity Optimizer version 1.3.0 by Ludo Waltman and Nees Jan van Eck
## 
## Number of nodes: 236276
## Number of edges: 5470656
## 
## Running Louvain algorithm...
## Maximum modularity in 10 random starts: 0.8577
## Number of communities: 28
## Elapsed time: 191 seconds
```

Example 55 (unknown):
```unknown
DimPlot(obj.sub, label = T, label.size = 3) + NoLegend()
```

Example 56 (r):
```r
DimPlot(obj.sub, label = T, label.size = 3) + NoLegend()
```

Example 57 (r):
```r
DimPlot(obj.sub, label = T, label.size = 3) + NoLegend()
```

Example 58 (unknown):
```unknown
FeaturePlot(
  object = obj.sub,
  features = c(
    "Dlx2", "Gad2", "Lhx6", "Nr2f2", "Sst",
    "Mef2c", "Meis2", "Id2", "Dlx6os1"
  ),
  ncol = 3
)
```

Example 59 (r):
```r
FeaturePlot(
  object = obj.sub,
  features = c(
    "Dlx2", "Gad2", "Lhx6", "Nr2f2", "Sst",
    "Mef2c", "Meis2", "Id2", "Dlx6os1"
  ),
  ncol = 3
)
```

Example 60 (r):
```r
FeaturePlot(
  object = obj.sub,
  features = c(
    "Dlx2", "Gad2", "Lhx6", "Nr2f2", "Sst",
    "Mef2c", "Meis2", "Id2", "Dlx6os1"
  ),
  ncol = 3
)
```

Example 61 (unknown):
```unknown
sessionInfo()
```

Example 62 (r):
```r
sessionInfo()
```

Example 63 (r):
```r
sessionInfo()
```

Example 64 (unknown):
```unknown
## R version 4.2.2 Patched (2022-11-10 r83330)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.6 LTS
## 
## Matrix products: default
## BLAS:   /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.9.0
## LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.9.0
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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       
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
## [1] ggplot2_3.4.4      BPCells_0.1.0      Seurat_5.0.0       SeuratObject_5.0.0
## [5] sp_2.1-1          
## 
## loaded via a namespace (and not attached):
##   [1] spam_2.10-0            systemfonts_1.0.4      plyr_1.8.9            
##   [4] igraph_1.5.1           lazyeval_0.2.2         splines_4.2.2         
##   [7] RcppHNSW_0.5.0         listenv_0.9.0          scattermore_1.2       
##  [10] GenomeInfoDb_1.34.9    digest_0.6.33          htmltools_0.5.6.1     
##  [13] fansi_1.0.5            magrittr_2.0.3         memoise_2.0.1         
##  [16] tensor_1.5             cluster_2.1.4          ROCR_1.0-11           
##  [19] globals_0.16.2         matrixStats_1.0.0      R.utils_2.12.2        
##  [22] pkgdown_2.0.7          spatstat.sparse_3.0-3  colorspace_2.1-0      
##  [25] ggrepel_0.9.4          textshaping_0.3.6      xfun_0.40             
##  [28] dplyr_1.1.3            RCurl_1.98-1.12        jsonlite_1.8.7        
##  [31] progressr_0.14.0       spatstat.data_3.0-3    survival_3.5-7        
##  [34] zoo_1.8-12             glue_1.6.2             polyclip_1.10-6       
##  [37] gtable_0.3.4           zlibbioc_1.44.0        XVector_0.38.0        
##  [40] leiden_0.4.3           R.cache_0.16.0         future.apply_1.11.0   
##  [43] BiocGenerics_0.44.0    abind_1.4-5            scales_1.2.1          
##  [46] spatstat.random_3.2-1  miniUI_0.1.1.1         Rcpp_1.0.11           
##  [49] viridisLite_0.4.2      xtable_1.8-4           reticulate_1.34.0     
##  [52] dotCall64_1.1-0        stats4_4.2.2           htmlwidgets_1.6.2     
##  [55] httr_1.4.7             RColorBrewer_1.1-3     ellipsis_0.3.2        
##  [58] ica_1.0-3              farver_2.1.1           pkgconfig_2.0.3       
##  [61] R.methodsS3_1.8.2      sass_0.4.7             uwot_0.1.16           
##  [64] deldir_1.0-9           utf8_1.2.4             labeling_0.4.3        
##  [67] tidyselect_1.2.0       rlang_1.1.1            reshape2_1.4.4        
##  [70] later_1.3.1            munsell_0.5.0          tools_4.2.2           
##  [73] cachem_1.0.8           cli_3.6.1              generics_0.1.3        
##  [76] ggridges_0.5.4         evaluate_0.22          stringr_1.5.0         
##  [79] fastmap_1.1.1          yaml_2.3.7             ragg_1.2.5            
##  [82] goftest_1.2-3          knitr_1.45             fs_1.6.3              
##  [85] fitdistrplus_1.1-11    purrr_1.0.2            RANN_2.6.1            
##  [88] pbapply_1.7-2          future_1.33.0          nlme_3.1-162          
##  [91] mime_0.12              ggrastr_1.0.1          R.oo_1.25.0           
##  [94] compiler_4.2.2         beeswarm_0.4.0         plotly_4.10.3         
##  [97] png_0.1-8              spatstat.utils_3.0-4   tibble_3.2.1          
## [100] bslib_0.5.1            stringi_1.7.12         highr_0.10            
## [103] desc_1.4.2             RSpectra_0.16-1        lattice_0.21-9        
## [106] Matrix_1.6-1.1         styler_1.10.2          vctrs_0.6.4           
## [109] pillar_1.9.0           lifecycle_1.0.3        spatstat.geom_3.2-7   
## [112] lmtest_0.9-40          jquerylib_0.1.4        RcppAnnoy_0.0.21      
## [115] bitops_1.0-7           data.table_1.14.8      cowplot_1.1.1         
## [118] irlba_2.3.5.1          httpuv_1.6.12          patchwork_1.1.3       
## [121] GenomicRanges_1.50.2   R6_2.5.1               promises_1.2.1        
## [124] KernSmooth_2.23-22     gridExtra_2.3          vipor_0.4.5           
## [127] IRanges_2.32.0         parallelly_1.36.0      codetools_0.2-19      
## [130] fastDummies_1.7.3      MASS_7.3-58.2          rprojroot_2.0.3       
## [133] withr_2.5.2            sctransform_0.4.1      GenomeInfoDbData_1.2.9
## [136] S4Vectors_0.36.2       parallel_4.2.2         grid_4.2.2            
## [139] tidyr_1.3.0            rmarkdown_2.25         Rtsne_0.16            
## [142] spatstat.explore_3.2-5 shiny_1.7.5.1          ggbeeswarm_0.7.1
```

Example 65 (unknown):
```unknown
## R version 4.2.2 Patched (2022-11-10 r83330)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.6 LTS
## 
## Matrix products: default
## BLAS:   /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.9.0
## LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.9.0
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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       
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
## [1] ggplot2_3.4.4      BPCells_0.1.0      Seurat_5.0.0       SeuratObject_5.0.0
## [5] sp_2.1-1          
## 
## loaded via a namespace (and not attached):
##   [1] spam_2.10-0            systemfonts_1.0.4      plyr_1.8.9            
##   [4] igraph_1.5.1           lazyeval_0.2.2         splines_4.2.2         
##   [7] RcppHNSW_0.5.0         listenv_0.9.0          scattermore_1.2       
##  [10] GenomeInfoDb_1.34.9    digest_0.6.33          htmltools_0.5.6.1     
##  [13] fansi_1.0.5            magrittr_2.0.3         memoise_2.0.1         
##  [16] tensor_1.5             cluster_2.1.4          ROCR_1.0-11           
##  [19] globals_0.16.2         matrixStats_1.0.0      R.utils_2.12.2        
##  [22] pkgdown_2.0.7          spatstat.sparse_3.0-3  colorspace_2.1-0      
##  [25] ggrepel_0.9.4          textshaping_0.3.6      xfun_0.40             
##  [28] dplyr_1.1.3            RCurl_1.98-1.12        jsonlite_1.8.7        
##  [31] progressr_0.14.0       spatstat.data_3.0-3    survival_3.5-7        
##  [34] zoo_1.8-12             glue_1.6.2             polyclip_1.10-6       
##  [37] gtable_0.3.4           zlibbioc_1.44.0        XVector_0.38.0        
##  [40] leiden_0.4.3           R.cache_0.16.0         future.apply_1.11.0   
##  [43] BiocGenerics_0.44.0    abind_1.4-5            scales_1.2.1          
##  [46] spatstat.random_3.2-1  miniUI_0.1.1.1         Rcpp_1.0.11           
##  [49] viridisLite_0.4.2      xtable_1.8-4           reticulate_1.34.0     
##  [52] dotCall64_1.1-0        stats4_4.2.2           htmlwidgets_1.6.2     
##  [55] httr_1.4.7             RColorBrewer_1.1-3     ellipsis_0.3.2        
##  [58] ica_1.0-3              farver_2.1.1           pkgconfig_2.0.3       
##  [61] R.methodsS3_1.8.2      sass_0.4.7             uwot_0.1.16           
##  [64] deldir_1.0-9           utf8_1.2.4             labeling_0.4.3        
##  [67] tidyselect_1.2.0       rlang_1.1.1            reshape2_1.4.4        
##  [70] later_1.3.1            munsell_0.5.0          tools_4.2.2           
##  [73] cachem_1.0.8           cli_3.6.1              generics_0.1.3        
##  [76] ggridges_0.5.4         evaluate_0.22          stringr_1.5.0         
##  [79] fastmap_1.1.1          yaml_2.3.7             ragg_1.2.5            
##  [82] goftest_1.2-3          knitr_1.45             fs_1.6.3              
##  [85] fitdistrplus_1.1-11    purrr_1.0.2            RANN_2.6.1            
##  [88] pbapply_1.7-2          future_1.33.0          nlme_3.1-162          
##  [91] mime_0.12              ggrastr_1.0.1          R.oo_1.25.0           
##  [94] compiler_4.2.2         beeswarm_0.4.0         plotly_4.10.3         
##  [97] png_0.1-8              spatstat.utils_3.0-4   tibble_3.2.1          
## [100] bslib_0.5.1            stringi_1.7.12         highr_0.10            
## [103] desc_1.4.2             RSpectra_0.16-1        lattice_0.21-9        
## [106] Matrix_1.6-1.1         styler_1.10.2          vctrs_0.6.4           
## [109] pillar_1.9.0           lifecycle_1.0.3        spatstat.geom_3.2-7   
## [112] lmtest_0.9-40          jquerylib_0.1.4        RcppAnnoy_0.0.21      
## [115] bitops_1.0-7           data.table_1.14.8      cowplot_1.1.1         
## [118] irlba_2.3.5.1          httpuv_1.6.12          patchwork_1.1.3       
## [121] GenomicRanges_1.50.2   R6_2.5.1               promises_1.2.1        
## [124] KernSmooth_2.23-22     gridExtra_2.3          vipor_0.4.5           
## [127] IRanges_2.32.0         parallelly_1.36.0      codetools_0.2-19      
## [130] fastDummies_1.7.3      MASS_7.3-58.2          rprojroot_2.0.3       
## [133] withr_2.5.2            sctransform_0.4.1      GenomeInfoDbData_1.2.9
## [136] S4Vectors_0.36.2       parallel_4.2.2         grid_4.2.2            
## [139] tidyr_1.3.0            rmarkdown_2.25         Rtsne_0.16            
## [142] spatstat.explore_3.2-5 shiny_1.7.5.1          ggbeeswarm_0.7.1
```

---

## Data visualization methods in Seurat • Seurat

**URL:** http://127.0.0.1:9173/seurat/archive/v4.3/visualization_vignette/index.html

**Contents:**
- Data visualization methods in Seurat
    - Compiled: 2023-03-27
- Five visualizations of marker feature expression
- New additions to FeaturePlot
- Updated and expanded visualization functions
- Applying themes to plots
- Interactive plotting features
- Plotting Accessories
- Contents

We’ll demonstrate visualization techniques in Seurat using our previously computed Seurat object from the 2,700 PBMC tutorial. You can download this dataset from SeuratData SeuratData::InstallData("pbmc3k") library(Seurat) library(SeuratData) library(ggplot2) library(patchwork) data("pbmc3k.final") pbmc3k.final$groups <- sample(c("group1", "group2"), size = ncol(pbmc3k.final), replace = TRUE) features <- c("LYZ", "CCL5", "IL32", "PTPRCAP", "FCGR3A", "PF4") pbmc3k.final## An object of class Seurat ## 13714 features across 2638 samples within 1 assay ## Active assay: RNA (13714 features, 2000 variable features) ## 2 dimensional reductions calculated: pca, umapFive visualizations of marker feature expression # Ridge plots - from ggridges. Visualize single cell expression distributions in each cluster RidgePlot(pbmc3k.final, features = features, ncol = 2) # Violin plot - Visualize single cell expression distributions in each cluster VlnPlot(pbmc3k.final, features = features) # Feature plot - visualize feature expression in low-dimensional space FeaturePlot(pbmc3k.final, features = features) # Dot plots - the size of the dot corresponds to the percentage of cells expressing the # feature in each cluster. The color represents the average expression level DotPlot(pbmc3k.final, features = features) + RotatedAxis() # Single cell heatmap of feature expression DoHeatmap(subset(pbmc3k.final, downsample = 100), features = features, size = 3)New additions to FeaturePlot # Plot a legend to map colors to expression levels FeaturePlot(pbmc3k.final, features = "MS4A1") # Adjust the contrast in the plot FeaturePlot(pbmc3k.final, features = "MS4A1", min.cutoff = 1, max.cutoff = 3) # Calculate feature-specific contrast levels based on quantiles of non-zero expression. # Particularly useful when plotting multiple markers FeaturePlot(pbmc3k.final, features = c("MS4A1", "PTPRCAP"), min.cutoff = "q10", max.cutoff = "q90") # Visualize co-expression of two features simultaneously FeaturePlot(pbmc3k.final, features = c("MS4A1", "CD79A"), blend = TRUE) # Split visualization to view expression by groups (replaces FeatureHeatmap) FeaturePlot(pbmc3k.final, features = c("MS4A1", "CD79A"), split.by = "groups")Updated and expanded visualization functionsIn addition to changes to FeaturePlot(), several other plotting functions have been updated and expanded with new features and taking over the role of now-deprecated functions # Violin plots can also be split on some variable. Simply add the splitting variable to object # metadata and pass it to the split.by argument VlnPlot(pbmc3k.final, features = "percent.mt", split.by = "groups") # SplitDotPlotGG has been replaced with the `split.by` parameter for DotPlot DotPlot(pbmc3k.final, features = features, split.by = "groups") + RotatedAxis() # DimPlot replaces TSNEPlot, PCAPlot, etc. In addition, it will plot either 'umap', 'tsne', or # 'pca' by default, in that order DimPlot(pbmc3k.final) pbmc3k.final.no.umap <- pbmc3k.final pbmc3k.final.no.umap[["umap"]] <- NULL DimPlot(pbmc3k.final.no.umap) + RotatedAxis() # DoHeatmap now shows a grouping bar, splitting the heatmap into groups or clusters. This can # be changed with the `group.by` parameter DoHeatmap(pbmc3k.final, features = VariableFeatures(pbmc3k.final)[1:100], cells = 1:500, size = 4, angle = 90) + NoLegend()Applying themes to plotsWith Seurat, all plotting functions return ggplot2-based plots by default, allowing one to easily capture and manipulate plots just like any other ggplot2-based plot. baseplot <- DimPlot(pbmc3k.final, reduction = "umap") # Add custom labels and titles baseplot + labs(title = "Clustering of 2,700 PBMCs") # Use community-created themes, overwriting the default Seurat-applied theme Install ggmin # with remotes::install_github('sjessa/ggmin') baseplot + ggmin::theme_powerpoint() # Seurat also provides several built-in themes, such as DarkTheme; for more details see # ?SeuratTheme baseplot + DarkTheme() # Chain themes together baseplot + FontSize(x.title = 20, y.title = 20) + NoLegend()Interactive plotting featuresSeurat utilizes R’s plotly graphing library to create interactive plots. This interactive plotting feature works with any ggplot2-based scatter plots (requires a geom_point layer). To use, simply make a ggplot2-based scatter plot (such as DimPlot() or FeaturePlot()) and pass the resulting plot to HoverLocator() # Include additional data to display alongside cell names by passing in a data frame of # information Works well when using FetchData plot <- FeaturePlot(pbmc3k.final, features = "MS4A1") HoverLocator(plot = plot, information = FetchData(pbmc3k.final, vars = c("ident", "PC_1", "nFeature_RNA")))Another interactive feature provided by Seurat is being able to manually select cells for further investigation. We have found this particularly useful for small clusters that do not always separate using unbiased clustering, but which look tantalizingly distinct. You can now select these cells by creating a ggplot2-based scatter plot (such as with DimPlot() or FeaturePlot(), and passing the returned plot to CellSelector(). CellSelector() will return a vector with the names of the points selected, so that you can then set them to a new identity class and perform differential expression.For example, lets pretend that DCs had merged with monocytes in the clustering, but we wanted to see what was unique about them based on their position in the tSNE plot. pbmc3k.final <- RenameIdents(pbmc3k.final, DC = "CD14+ Mono") plot <- DimPlot(pbmc3k.final, reduction = "umap") select.cells <- CellSelector(plot = plot)We can then change the identity of these cells to turn them into their own mini-cluster. head(select.cells)## [1] "AAGATTACCGCCTT" "AAGCCATGAACTGC" "AATTACGAATTCCT" "ACCCGTTGCTTCTA" ## [5] "ACGAGGGACAGGAG" "ACGTGATGCCATGA" Idents(pbmc3k.final, cells = select.cells) <- "NewCells" # Now, we find markers that are specific to the new cells, and find clear DC markers newcells.markers <- FindMarkers(pbmc3k.final, ident.1 = "NewCells", ident.2 = "CD14+ Mono", min.diff.pct = 0.3, only.pos = TRUE) head(newcells.markers)## p_val avg_log2FC pct.1 pct.2 p_val_adj ## FCER1A 3.239004e-69 3.7008561 0.800 0.017 4.441970e-65 ## SERPINF1 7.761413e-36 1.5737896 0.457 0.013 1.064400e-31 ## HLA-DQB2 1.721094e-34 0.9685974 0.429 0.010 2.360309e-30 ## CD1C 2.304106e-33 1.7785158 0.514 0.025 3.159851e-29 ## ENHO 5.099765e-32 1.3734708 0.400 0.010 6.993818e-28 ## ITM2C 4.299994e-29 1.5590007 0.371 0.010 5.897012e-25Using CellSelector to Automatically Assign Cell IdentitiesIn addition to returning a vector of cell names, CellSelector() can also take the selected cells and assign a new identity to them, returning a Seurat object with the identity classes already set. This is done by passing the Seurat object used to make the plot into CellSelector(), as well as an identity class. As an example, we’re going to select the same set of cells as before, and set their identity class to “selected” pbmc3k.final <- CellSelector(plot = plot, object = pbmc3k.final, ident = "selected") levels(pbmc3k.final)## [1] "selected" "Naive CD4 T" "Memory CD4 T" "CD14+ Mono" "B" ## [6] "CD8 T" "FCGR3A+ Mono" "NK" "Platelet"Plotting AccessoriesAlong with new functions add interactive functionality to plots, Seurat provides new accessory functions for manipulating and combining plots. # LabelClusters and LabelPoints will label clusters (a coloring variable) or individual points # on a ggplot2-based scatter plot plot <- DimPlot(pbmc3k.final, reduction = "pca") + NoLegend() LabelClusters(plot = plot, id = "ident") # Both functions support `repel`, which will intelligently stagger labels and draw connecting # lines from the labels to the points or clusters LabelPoints(plot = plot, points = TopCells(object = pbmc3k.final[["pca"]]), repel = TRUE)Plotting multiple plots was previously achieved with the CombinePlot() function. We are deprecating this functionality in favor of the patchwork system. Below is a brief demonstration but please see the patchwork package website here for more details and examples. plot1 <- DimPlot(pbmc3k.final) plot2 <- FeatureScatter(pbmc3k.final, feature1 = "LYZ", feature2 = "CCL5") # Combine two plots plot1 + plot2 # Remove the legend from all plots (plot1 + plot2) & NoLegend()Session Info sessionInfo()## R version 4.2.0 (2022-04-22) ## Platform: x86_64-pc-linux-gnu (64-bit) ## Running under: Ubuntu 20.04.5 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/liblapack.so.3 ## ## locale: ## [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C ## [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8 ## [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 ## ## attached base packages: ## [1] stats graphics grDevices utils datasets methods base ## ## other attached packages: ## [1] patchwork_1.1.2 ggplot2_3.4.1 ## [3] thp1.eccite.SeuratData_3.1.5 stxBrain.SeuratData_0.1.1 ## [5] ssHippo.SeuratData_3.1.4 pbmcsca.SeuratData_3.0.0 ## [7] pbmcMultiome.SeuratData_0.1.2 pbmc3k.SeuratData_3.1.4 ## [9] panc8.SeuratData_3.0.2 ifnb.SeuratData_3.1.0 ## [11] hcabm40k.SeuratData_3.0.0 bmcite.SeuratData_0.3.0 ## [13] SeuratData_0.2.2 SeuratObject_4.1.3 ## [15] Seurat_4.2.1.9001 ## ## loaded via a namespace (and not attached): ## [1] systemfonts_1.0.4 plyr_1.8.8 igraph_1.4.1 ## [4] lazyeval_0.2.2 sp_1.6-0 splines_4.2.0 ## [7] crosstalk_1.2.0 listenv_0.9.0 scattermore_0.8 ## [10] digest_0.6.31 htmltools_0.5.5 fansi_1.0.4 ## [13] magrittr_2.0.3 memoise_2.0.1 tensor_1.5 ## [16] cluster_2.1.3 ROCR_1.0-11 limma_3.54.1 ## [19] globals_0.16.2 matrixStats_0.63.0 pkgdown_2.0.7 ## [22] spatstat.sparse_3.0-1 colorspace_2.1-0 rappdirs_0.3.3 ## [25] ggrepel_0.9.3 textshaping_0.3.6 xfun_0.38 ## [28] dplyr_1.1.1 crayon_1.5.2 jsonlite_1.8.4 ## [31] progressr_0.13.0 spatstat.data_3.0-1 survival_3.3-1 ## [34] zoo_1.8-11 glue_1.6.2 polyclip_1.10-4 ## [37] gtable_0.3.3 leiden_0.4.3 future.apply_1.10.0 ## [40] abind_1.4-5 scales_1.2.1 spatstat.random_3.1-4 ## [43] miniUI_0.1.1.1 Rcpp_1.0.10 viridisLite_0.4.1 ## [46] xtable_1.8-4 reticulate_1.28 ggmin_0.0.0.9000 ## [49] htmlwidgets_1.6.2 httr_1.4.5 RColorBrewer_1.1-3 ## [52] ellipsis_0.3.2 ica_1.0-3 farver_2.1.1 ## [55] pkgconfig_2.0.3 sass_0.4.5 uwot_0.1.14 ## [58] deldir_1.0-6 utf8_1.2.3 tidyselect_1.2.0 ## [61] labeling_0.4.2 rlang_1.1.0 reshape2_1.4.4 ## [64] later_1.3.0 munsell_0.5.0 tools_4.2.0 ## [67] cachem_1.0.7 cli_3.6.1 generics_0.1.3 ## [70] ggridges_0.5.4 evaluate_0.20 stringr_1.5.0 ## [73] fastmap_1.1.1 yaml_2.3.7 ragg_1.2.5 ## [76] goftest_1.2-3 knitr_1.42 fs_1.6.1 ## [79] fitdistrplus_1.1-8 purrr_1.0.1 RANN_2.6.1 ## [82] pbapply_1.7-0 future_1.32.0 nlme_3.1-157 ## [85] mime_0.12 formatR_1.14 compiler_4.2.0 ## [88] plotly_4.10.1 png_0.1-8 spatstat.utils_3.0-2 ## [91] tibble_3.2.1 bslib_0.4.2 stringi_1.7.12 ## [94] highr_0.10 desc_1.4.2 lattice_0.20-45 ## [97] Matrix_1.5-3 vctrs_0.6.1 pillar_1.9.0 ## [100] lifecycle_1.0.3 spatstat.geom_3.1-0 lmtest_0.9-40 ## [103] jquerylib_0.1.4 RcppAnnoy_0.0.20 data.table_1.14.8 ## [106] cowplot_1.1.1 irlba_2.3.5.1 httpuv_1.6.9 ## [109] R6_2.5.1 promises_1.2.0.1 KernSmooth_2.23-20 ## [112] gridExtra_2.3 parallelly_1.35.0 codetools_0.2-18 ## [115] MASS_7.3-56 rprojroot_2.0.3 withr_2.5.0 ## [118] sctransform_0.3.5 parallel_4.2.0 grid_4.2.0 ## [121] tidyr_1.3.0 rmarkdown_2.21 Rtsne_0.16 ## [124] spatstat.explore_3.1-0 shiny_1.7.4

# Violin plot - Visualize single cell expression distributions in each cluster VlnPlot(pbmc3k.final, features = features) # Feature plot - visualize feature expression in low-dimensional space FeaturePlot(pbmc3k.final, features = features) # Dot plots - the size of the dot corresponds to the percentage of cells expressing the # feature in each cluster. The color represents the average expression level DotPlot(pbmc3k.final, features = features) + RotatedAxis() # Single cell heatmap of feature expression DoHeatmap(subset(pbmc3k.final, downsample = 100), features = features, size = 3)

# Feature plot - visualize feature expression in low-dimensional space FeaturePlot(pbmc3k.final, features = features) # Dot plots - the size of the dot corresponds to the percentage of cells expressing the # feature in each cluster. The color represents the average expression level DotPlot(pbmc3k.final, features = features) + RotatedAxis() # Single cell heatmap of feature expression DoHeatmap(subset(pbmc3k.final, downsample = 100), features = features, size = 3)

# Dot plots - the size of the dot corresponds to the percentage of cells expressing the # feature in each cluster. The color represents the average expression level DotPlot(pbmc3k.final, features = features) + RotatedAxis() # Single cell heatmap of feature expression DoHeatmap(subset(pbmc3k.final, downsample = 100), features = features, size = 3)

# Single cell heatmap of feature expression DoHeatmap(subset(pbmc3k.final, downsample = 100), features = features, size = 3)

# Adjust the contrast in the plot FeaturePlot(pbmc3k.final, features = "MS4A1", min.cutoff = 1, max.cutoff = 3) # Calculate feature-specific contrast levels based on quantiles of non-zero expression. # Particularly useful when plotting multiple markers FeaturePlot(pbmc3k.final, features = c("MS4A1", "PTPRCAP"), min.cutoff = "q10", max.cutoff = "q90") # Visualize co-expression of two features simultaneously FeaturePlot(pbmc3k.final, features = c("MS4A1", "CD79A"), blend = TRUE) # Split visualization to view expression by groups (replaces FeatureHeatmap) FeaturePlot(pbmc3k.final, features = c("MS4A1", "CD79A"), split.by = "groups")

# Calculate feature-specific contrast levels based on quantiles of non-zero expression. # Particularly useful when plotting multiple markers FeaturePlot(pbmc3k.final, features = c("MS4A1", "PTPRCAP"), min.cutoff = "q10", max.cutoff = "q90") # Visualize co-expression of two features simultaneously FeaturePlot(pbmc3k.final, features = c("MS4A1", "CD79A"), blend = TRUE) # Split visualization to view expression by groups (replaces FeatureHeatmap) FeaturePlot(pbmc3k.final, features = c("MS4A1", "CD79A"), split.by = "groups")

# Visualize co-expression of two features simultaneously FeaturePlot(pbmc3k.final, features = c("MS4A1", "CD79A"), blend = TRUE) # Split visualization to view expression by groups (replaces FeatureHeatmap) FeaturePlot(pbmc3k.final, features = c("MS4A1", "CD79A"), split.by = "groups")

# Split visualization to view expression by groups (replaces FeatureHeatmap) FeaturePlot(pbmc3k.final, features = c("MS4A1", "CD79A"), split.by = "groups")

In addition to changes to FeaturePlot(), several other plotting functions have been updated and expanded with new features and taking over the role of now-deprecated functions # Violin plots can also be split on some variable. Simply add the splitting variable to object # metadata and pass it to the split.by argument VlnPlot(pbmc3k.final, features = "percent.mt", split.by = "groups") # SplitDotPlotGG has been replaced with the `split.by` parameter for DotPlot DotPlot(pbmc3k.final, features = features, split.by = "groups") + RotatedAxis() # DimPlot replaces TSNEPlot, PCAPlot, etc. In addition, it will plot either 'umap', 'tsne', or # 'pca' by default, in that order DimPlot(pbmc3k.final) pbmc3k.final.no.umap <- pbmc3k.final pbmc3k.final.no.umap[["umap"]] <- NULL DimPlot(pbmc3k.final.no.umap) + RotatedAxis() # DoHeatmap now shows a grouping bar, splitting the heatmap into groups or clusters. This can # be changed with the `group.by` parameter DoHeatmap(pbmc3k.final, features = VariableFeatures(pbmc3k.final)[1:100], cells = 1:500, size = 4, angle = 90) + NoLegend()

# SplitDotPlotGG has been replaced with the `split.by` parameter for DotPlot DotPlot(pbmc3k.final, features = features, split.by = "groups") + RotatedAxis() # DimPlot replaces TSNEPlot, PCAPlot, etc. In addition, it will plot either 'umap', 'tsne', or # 'pca' by default, in that order DimPlot(pbmc3k.final) pbmc3k.final.no.umap <- pbmc3k.final pbmc3k.final.no.umap[["umap"]] <- NULL DimPlot(pbmc3k.final.no.umap) + RotatedAxis() # DoHeatmap now shows a grouping bar, splitting the heatmap into groups or clusters. This can # be changed with the `group.by` parameter DoHeatmap(pbmc3k.final, features = VariableFeatures(pbmc3k.final)[1:100], cells = 1:500, size = 4, angle = 90) + NoLegend()

# DimPlot replaces TSNEPlot, PCAPlot, etc. In addition, it will plot either 'umap', 'tsne', or # 'pca' by default, in that order DimPlot(pbmc3k.final) pbmc3k.final.no.umap <- pbmc3k.final pbmc3k.final.no.umap[["umap"]] <- NULL DimPlot(pbmc3k.final.no.umap) + RotatedAxis() # DoHeatmap now shows a grouping bar, splitting the heatmap into groups or clusters. This can # be changed with the `group.by` parameter DoHeatmap(pbmc3k.final, features = VariableFeatures(pbmc3k.final)[1:100], cells = 1:500, size = 4, angle = 90) + NoLegend()

pbmc3k.final.no.umap <- pbmc3k.final pbmc3k.final.no.umap[["umap"]] <- NULL DimPlot(pbmc3k.final.no.umap) + RotatedAxis() # DoHeatmap now shows a grouping bar, splitting the heatmap into groups or clusters. This can # be changed with the `group.by` parameter DoHeatmap(pbmc3k.final, features = VariableFeatures(pbmc3k.final)[1:100], cells = 1:500, size = 4, angle = 90) + NoLegend()

# DoHeatmap now shows a grouping bar, splitting the heatmap into groups or clusters. This can # be changed with the `group.by` parameter DoHeatmap(pbmc3k.final, features = VariableFeatures(pbmc3k.final)[1:100], cells = 1:500, size = 4, angle = 90) + NoLegend()

With Seurat, all plotting functions return ggplot2-based plots by default, allowing one to easily capture and manipulate plots just like any other ggplot2-based plot. baseplot <- DimPlot(pbmc3k.final, reduction = "umap") # Add custom labels and titles baseplot + labs(title = "Clustering of 2,700 PBMCs") # Use community-created themes, overwriting the default Seurat-applied theme Install ggmin # with remotes::install_github('sjessa/ggmin') baseplot + ggmin::theme_powerpoint() # Seurat also provides several built-in themes, such as DarkTheme; for more details see # ?SeuratTheme baseplot + DarkTheme() # Chain themes together baseplot + FontSize(x.title = 20, y.title = 20) + NoLegend()

# Use community-created themes, overwriting the default Seurat-applied theme Install ggmin # with remotes::install_github('sjessa/ggmin') baseplot + ggmin::theme_powerpoint() # Seurat also provides several built-in themes, such as DarkTheme; for more details see # ?SeuratTheme baseplot + DarkTheme() # Chain themes together baseplot + FontSize(x.title = 20, y.title = 20) + NoLegend()

# Seurat also provides several built-in themes, such as DarkTheme; for more details see # ?SeuratTheme baseplot + DarkTheme() # Chain themes together baseplot + FontSize(x.title = 20, y.title = 20) + NoLegend()

# Chain themes together baseplot + FontSize(x.title = 20, y.title = 20) + NoLegend()

Seurat utilizes R’s plotly graphing library to create interactive plots. This interactive plotting feature works with any ggplot2-based scatter plots (requires a geom_point layer). To use, simply make a ggplot2-based scatter plot (such as DimPlot() or FeaturePlot()) and pass the resulting plot to HoverLocator() # Include additional data to display alongside cell names by passing in a data frame of # information Works well when using FetchData plot <- FeaturePlot(pbmc3k.final, features = "MS4A1") HoverLocator(plot = plot, information = FetchData(pbmc3k.final, vars = c("ident", "PC_1", "nFeature_RNA")))Another interactive feature provided by Seurat is being able to manually select cells for further investigation. We have found this particularly useful for small clusters that do not always separate using unbiased clustering, but which look tantalizingly distinct. You can now select these cells by creating a ggplot2-based scatter plot (such as with DimPlot() or FeaturePlot(), and passing the returned plot to CellSelector(). CellSelector() will return a vector with the names of the points selected, so that you can then set them to a new identity class and perform differential expression.For example, lets pretend that DCs had merged with monocytes in the clustering, but we wanted to see what was unique about them based on their position in the tSNE plot. pbmc3k.final <- RenameIdents(pbmc3k.final, DC = "CD14+ Mono") plot <- DimPlot(pbmc3k.final, reduction = "umap") select.cells <- CellSelector(plot = plot)We can then change the identity of these cells to turn them into their own mini-cluster. head(select.cells)## [1] "AAGATTACCGCCTT" "AAGCCATGAACTGC" "AATTACGAATTCCT" "ACCCGTTGCTTCTA" ## [5] "ACGAGGGACAGGAG" "ACGTGATGCCATGA" Idents(pbmc3k.final, cells = select.cells) <- "NewCells" # Now, we find markers that are specific to the new cells, and find clear DC markers newcells.markers <- FindMarkers(pbmc3k.final, ident.1 = "NewCells", ident.2 = "CD14+ Mono", min.diff.pct = 0.3, only.pos = TRUE) head(newcells.markers)## p_val avg_log2FC pct.1 pct.2 p_val_adj ## FCER1A 3.239004e-69 3.7008561 0.800 0.017 4.441970e-65 ## SERPINF1 7.761413e-36 1.5737896 0.457 0.013 1.064400e-31 ## HLA-DQB2 1.721094e-34 0.9685974 0.429 0.010 2.360309e-30 ## CD1C 2.304106e-33 1.7785158 0.514 0.025 3.159851e-29 ## ENHO 5.099765e-32 1.3734708 0.400 0.010 6.993818e-28 ## ITM2C 4.299994e-29 1.5590007 0.371 0.010 5.897012e-25Using CellSelector to Automatically Assign Cell IdentitiesIn addition to returning a vector of cell names, CellSelector() can also take the selected cells and assign a new identity to them, returning a Seurat object with the identity classes already set. This is done by passing the Seurat object used to make the plot into CellSelector(), as well as an identity class. As an example, we’re going to select the same set of cells as before, and set their identity class to “selected” pbmc3k.final <- CellSelector(plot = plot, object = pbmc3k.final, ident = "selected") levels(pbmc3k.final)## [1] "selected" "Naive CD4 T" "Memory CD4 T" "CD14+ Mono" "B" ## [6] "CD8 T" "FCGR3A+ Mono" "NK" "Platelet"

Another interactive feature provided by Seurat is being able to manually select cells for further investigation. We have found this particularly useful for small clusters that do not always separate using unbiased clustering, but which look tantalizingly distinct. You can now select these cells by creating a ggplot2-based scatter plot (such as with DimPlot() or FeaturePlot(), and passing the returned plot to CellSelector(). CellSelector() will return a vector with the names of the points selected, so that you can then set them to a new identity class and perform differential expression.For example, lets pretend that DCs had merged with monocytes in the clustering, but we wanted to see what was unique about them based on their position in the tSNE plot. pbmc3k.final <- RenameIdents(pbmc3k.final, DC = "CD14+ Mono") plot <- DimPlot(pbmc3k.final, reduction = "umap") select.cells <- CellSelector(plot = plot)We can then change the identity of these cells to turn them into their own mini-cluster. head(select.cells)## [1] "AAGATTACCGCCTT" "AAGCCATGAACTGC" "AATTACGAATTCCT" "ACCCGTTGCTTCTA" ## [5] "ACGAGGGACAGGAG" "ACGTGATGCCATGA" Idents(pbmc3k.final, cells = select.cells) <- "NewCells" # Now, we find markers that are specific to the new cells, and find clear DC markers newcells.markers <- FindMarkers(pbmc3k.final, ident.1 = "NewCells", ident.2 = "CD14+ Mono", min.diff.pct = 0.3, only.pos = TRUE) head(newcells.markers)## p_val avg_log2FC pct.1 pct.2 p_val_adj ## FCER1A 3.239004e-69 3.7008561 0.800 0.017 4.441970e-65 ## SERPINF1 7.761413e-36 1.5737896 0.457 0.013 1.064400e-31 ## HLA-DQB2 1.721094e-34 0.9685974 0.429 0.010 2.360309e-30 ## CD1C 2.304106e-33 1.7785158 0.514 0.025 3.159851e-29 ## ENHO 5.099765e-32 1.3734708 0.400 0.010 6.993818e-28 ## ITM2C 4.299994e-29 1.5590007 0.371 0.010 5.897012e-25Using CellSelector to Automatically Assign Cell IdentitiesIn addition to returning a vector of cell names, CellSelector() can also take the selected cells and assign a new identity to them, returning a Seurat object with the identity classes already set. This is done by passing the Seurat object used to make the plot into CellSelector(), as well as an identity class. As an example, we’re going to select the same set of cells as before, and set their identity class to “selected” pbmc3k.final <- CellSelector(plot = plot, object = pbmc3k.final, ident = "selected") levels(pbmc3k.final)## [1] "selected" "Naive CD4 T" "Memory CD4 T" "CD14+ Mono" "B" ## [6] "CD8 T" "FCGR3A+ Mono" "NK" "Platelet"

For example, lets pretend that DCs had merged with monocytes in the clustering, but we wanted to see what was unique about them based on their position in the tSNE plot. pbmc3k.final <- RenameIdents(pbmc3k.final, DC = "CD14+ Mono") plot <- DimPlot(pbmc3k.final, reduction = "umap") select.cells <- CellSelector(plot = plot)We can then change the identity of these cells to turn them into their own mini-cluster. head(select.cells)## [1] "AAGATTACCGCCTT" "AAGCCATGAACTGC" "AATTACGAATTCCT" "ACCCGTTGCTTCTA" ## [5] "ACGAGGGACAGGAG" "ACGTGATGCCATGA" Idents(pbmc3k.final, cells = select.cells) <- "NewCells" # Now, we find markers that are specific to the new cells, and find clear DC markers newcells.markers <- FindMarkers(pbmc3k.final, ident.1 = "NewCells", ident.2 = "CD14+ Mono", min.diff.pct = 0.3, only.pos = TRUE) head(newcells.markers)## p_val avg_log2FC pct.1 pct.2 p_val_adj ## FCER1A 3.239004e-69 3.7008561 0.800 0.017 4.441970e-65 ## SERPINF1 7.761413e-36 1.5737896 0.457 0.013 1.064400e-31 ## HLA-DQB2 1.721094e-34 0.9685974 0.429 0.010 2.360309e-30 ## CD1C 2.304106e-33 1.7785158 0.514 0.025 3.159851e-29 ## ENHO 5.099765e-32 1.3734708 0.400 0.010 6.993818e-28 ## ITM2C 4.299994e-29 1.5590007 0.371 0.010 5.897012e-25Using CellSelector to Automatically Assign Cell IdentitiesIn addition to returning a vector of cell names, CellSelector() can also take the selected cells and assign a new identity to them, returning a Seurat object with the identity classes already set. This is done by passing the Seurat object used to make the plot into CellSelector(), as well as an identity class. As an example, we’re going to select the same set of cells as before, and set their identity class to “selected” pbmc3k.final <- CellSelector(plot = plot, object = pbmc3k.final, ident = "selected") levels(pbmc3k.final)## [1] "selected" "Naive CD4 T" "Memory CD4 T" "CD14+ Mono" "B" ## [6] "CD8 T" "FCGR3A+ Mono" "NK" "Platelet"

We can then change the identity of these cells to turn them into their own mini-cluster. head(select.cells)## [1] "AAGATTACCGCCTT" "AAGCCATGAACTGC" "AATTACGAATTCCT" "ACCCGTTGCTTCTA" ## [5] "ACGAGGGACAGGAG" "ACGTGATGCCATGA" Idents(pbmc3k.final, cells = select.cells) <- "NewCells" # Now, we find markers that are specific to the new cells, and find clear DC markers newcells.markers <- FindMarkers(pbmc3k.final, ident.1 = "NewCells", ident.2 = "CD14+ Mono", min.diff.pct = 0.3, only.pos = TRUE) head(newcells.markers)## p_val avg_log2FC pct.1 pct.2 p_val_adj ## FCER1A 3.239004e-69 3.7008561 0.800 0.017 4.441970e-65 ## SERPINF1 7.761413e-36 1.5737896 0.457 0.013 1.064400e-31 ## HLA-DQB2 1.721094e-34 0.9685974 0.429 0.010 2.360309e-30 ## CD1C 2.304106e-33 1.7785158 0.514 0.025 3.159851e-29 ## ENHO 5.099765e-32 1.3734708 0.400 0.010 6.993818e-28 ## ITM2C 4.299994e-29 1.5590007 0.371 0.010 5.897012e-25Using CellSelector to Automatically Assign Cell IdentitiesIn addition to returning a vector of cell names, CellSelector() can also take the selected cells and assign a new identity to them, returning a Seurat object with the identity classes already set. This is done by passing the Seurat object used to make the plot into CellSelector(), as well as an identity class. As an example, we’re going to select the same set of cells as before, and set their identity class to “selected” pbmc3k.final <- CellSelector(plot = plot, object = pbmc3k.final, ident = "selected") levels(pbmc3k.final)## [1] "selected" "Naive CD4 T" "Memory CD4 T" "CD14+ Mono" "B" ## [6] "CD8 T" "FCGR3A+ Mono" "NK" "Platelet"

We can then change the identity of these cells to turn them into their own mini-cluster. head(select.cells)## [1] "AAGATTACCGCCTT" "AAGCCATGAACTGC" "AATTACGAATTCCT" "ACCCGTTGCTTCTA" ## [5] "ACGAGGGACAGGAG" "ACGTGATGCCATGA" Idents(pbmc3k.final, cells = select.cells) <- "NewCells" # Now, we find markers that are specific to the new cells, and find clear DC markers newcells.markers <- FindMarkers(pbmc3k.final, ident.1 = "NewCells", ident.2 = "CD14+ Mono", min.diff.pct = 0.3, only.pos = TRUE) head(newcells.markers)## p_val avg_log2FC pct.1 pct.2 p_val_adj ## FCER1A 3.239004e-69 3.7008561 0.800 0.017 4.441970e-65 ## SERPINF1 7.761413e-36 1.5737896 0.457 0.013 1.064400e-31 ## HLA-DQB2 1.721094e-34 0.9685974 0.429 0.010 2.360309e-30 ## CD1C 2.304106e-33 1.7785158 0.514 0.025 3.159851e-29 ## ENHO 5.099765e-32 1.3734708 0.400 0.010 6.993818e-28 ## ITM2C 4.299994e-29 1.5590007 0.371 0.010 5.897012e-25Using CellSelector to Automatically Assign Cell IdentitiesIn addition to returning a vector of cell names, CellSelector() can also take the selected cells and assign a new identity to them, returning a Seurat object with the identity classes already set. This is done by passing the Seurat object used to make the plot into CellSelector(), as well as an identity class. As an example, we’re going to select the same set of cells as before, and set their identity class to “selected” pbmc3k.final <- CellSelector(plot = plot, object = pbmc3k.final, ident = "selected") levels(pbmc3k.final)## [1] "selected" "Naive CD4 T" "Memory CD4 T" "CD14+ Mono" "B" ## [6] "CD8 T" "FCGR3A+ Mono" "NK" "Platelet"

In addition to returning a vector of cell names, CellSelector() can also take the selected cells and assign a new identity to them, returning a Seurat object with the identity classes already set. This is done by passing the Seurat object used to make the plot into CellSelector(), as well as an identity class. As an example, we’re going to select the same set of cells as before, and set their identity class to “selected” pbmc3k.final <- CellSelector(plot = plot, object = pbmc3k.final, ident = "selected") levels(pbmc3k.final)## [1] "selected" "Naive CD4 T" "Memory CD4 T" "CD14+ Mono" "B" ## [6] "CD8 T" "FCGR3A+ Mono" "NK" "Platelet"

In addition to returning a vector of cell names, CellSelector() can also take the selected cells and assign a new identity to them, returning a Seurat object with the identity classes already set. This is done by passing the Seurat object used to make the plot into CellSelector(), as well as an identity class. As an example, we’re going to select the same set of cells as before, and set their identity class to “selected” pbmc3k.final <- CellSelector(plot = plot, object = pbmc3k.final, ident = "selected") levels(pbmc3k.final)## [1] "selected" "Naive CD4 T" "Memory CD4 T" "CD14+ Mono" "B" ## [6] "CD8 T" "FCGR3A+ Mono" "NK" "Platelet"

levels(pbmc3k.final)## [1] "selected" "Naive CD4 T" "Memory CD4 T" "CD14+ Mono" "B" ## [6] "CD8 T" "FCGR3A+ Mono" "NK" "Platelet"

Along with new functions add interactive functionality to plots, Seurat provides new accessory functions for manipulating and combining plots. # LabelClusters and LabelPoints will label clusters (a coloring variable) or individual points # on a ggplot2-based scatter plot plot <- DimPlot(pbmc3k.final, reduction = "pca") + NoLegend() LabelClusters(plot = plot, id = "ident") # Both functions support `repel`, which will intelligently stagger labels and draw connecting # lines from the labels to the points or clusters LabelPoints(plot = plot, points = TopCells(object = pbmc3k.final[["pca"]]), repel = TRUE)Plotting multiple plots was previously achieved with the CombinePlot() function. We are deprecating this functionality in favor of the patchwork system. Below is a brief demonstration but please see the patchwork package website here for more details and examples. plot1 <- DimPlot(pbmc3k.final) plot2 <- FeatureScatter(pbmc3k.final, feature1 = "LYZ", feature2 = "CCL5") # Combine two plots plot1 + plot2 # Remove the legend from all plots (plot1 + plot2) & NoLegend()Session Info sessionInfo()## R version 4.2.0 (2022-04-22) ## Platform: x86_64-pc-linux-gnu (64-bit) ## Running under: Ubuntu 20.04.5 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/liblapack.so.3 ## ## locale: ## [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C ## [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8 ## [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 ## ## attached base packages: ## [1] stats graphics grDevices utils datasets methods base ## ## other attached packages: ## [1] patchwork_1.1.2 ggplot2_3.4.1 ## [3] thp1.eccite.SeuratData_3.1.5 stxBrain.SeuratData_0.1.1 ## [5] ssHippo.SeuratData_3.1.4 pbmcsca.SeuratData_3.0.0 ## [7] pbmcMultiome.SeuratData_0.1.2 pbmc3k.SeuratData_3.1.4 ## [9] panc8.SeuratData_3.0.2 ifnb.SeuratData_3.1.0 ## [11] hcabm40k.SeuratData_3.0.0 bmcite.SeuratData_0.3.0 ## [13] SeuratData_0.2.2 SeuratObject_4.1.3 ## [15] Seurat_4.2.1.9001 ## ## loaded via a namespace (and not attached): ## [1] systemfonts_1.0.4 plyr_1.8.8 igraph_1.4.1 ## [4] lazyeval_0.2.2 sp_1.6-0 splines_4.2.0 ## [7] crosstalk_1.2.0 listenv_0.9.0 scattermore_0.8 ## [10] digest_0.6.31 htmltools_0.5.5 fansi_1.0.4 ## [13] magrittr_2.0.3 memoise_2.0.1 tensor_1.5 ## [16] cluster_2.1.3 ROCR_1.0-11 limma_3.54.1 ## [19] globals_0.16.2 matrixStats_0.63.0 pkgdown_2.0.7 ## [22] spatstat.sparse_3.0-1 colorspace_2.1-0 rappdirs_0.3.3 ## [25] ggrepel_0.9.3 textshaping_0.3.6 xfun_0.38 ## [28] dplyr_1.1.1 crayon_1.5.2 jsonlite_1.8.4 ## [31] progressr_0.13.0 spatstat.data_3.0-1 survival_3.3-1 ## [34] zoo_1.8-11 glue_1.6.2 polyclip_1.10-4 ## [37] gtable_0.3.3 leiden_0.4.3 future.apply_1.10.0 ## [40] abind_1.4-5 scales_1.2.1 spatstat.random_3.1-4 ## [43] miniUI_0.1.1.1 Rcpp_1.0.10 viridisLite_0.4.1 ## [46] xtable_1.8-4 reticulate_1.28 ggmin_0.0.0.9000 ## [49] htmlwidgets_1.6.2 httr_1.4.5 RColorBrewer_1.1-3 ## [52] ellipsis_0.3.2 ica_1.0-3 farver_2.1.1 ## [55] pkgconfig_2.0.3 sass_0.4.5 uwot_0.1.14 ## [58] deldir_1.0-6 utf8_1.2.3 tidyselect_1.2.0 ## [61] labeling_0.4.2 rlang_1.1.0 reshape2_1.4.4 ## [64] later_1.3.0 munsell_0.5.0 tools_4.2.0 ## [67] cachem_1.0.7 cli_3.6.1 generics_0.1.3 ## [70] ggridges_0.5.4 evaluate_0.20 stringr_1.5.0 ## [73] fastmap_1.1.1 yaml_2.3.7 ragg_1.2.5 ## [76] goftest_1.2-3 knitr_1.42 fs_1.6.1 ## [79] fitdistrplus_1.1-8 purrr_1.0.1 RANN_2.6.1 ## [82] pbapply_1.7-0 future_1.32.0 nlme_3.1-157 ## [85] mime_0.12 formatR_1.14 compiler_4.2.0 ## [88] plotly_4.10.1 png_0.1-8 spatstat.utils_3.0-2 ## [91] tibble_3.2.1 bslib_0.4.2 stringi_1.7.12 ## [94] highr_0.10 desc_1.4.2 lattice_0.20-45 ## [97] Matrix_1.5-3 vctrs_0.6.1 pillar_1.9.0 ## [100] lifecycle_1.0.3 spatstat.geom_3.1-0 lmtest_0.9-40 ## [103] jquerylib_0.1.4 RcppAnnoy_0.0.20 data.table_1.14.8 ## [106] cowplot_1.1.1 irlba_2.3.5.1 httpuv_1.6.9 ## [109] R6_2.5.1 promises_1.2.0.1 KernSmooth_2.23-20 ## [112] gridExtra_2.3 parallelly_1.35.0 codetools_0.2-18 ## [115] MASS_7.3-56 rprojroot_2.0.3 withr_2.5.0 ## [118] sctransform_0.3.5 parallel_4.2.0 grid_4.2.0 ## [121] tidyr_1.3.0 rmarkdown_2.21 Rtsne_0.16 ## [124] spatstat.explore_3.1-0 shiny_1.7.4

# Both functions support `repel`, which will intelligently stagger labels and draw connecting # lines from the labels to the points or clusters LabelPoints(plot = plot, points = TopCells(object = pbmc3k.final[["pca"]]), repel = TRUE)Plotting multiple plots was previously achieved with the CombinePlot() function. We are deprecating this functionality in favor of the patchwork system. Below is a brief demonstration but please see the patchwork package website here for more details and examples. plot1 <- DimPlot(pbmc3k.final) plot2 <- FeatureScatter(pbmc3k.final, feature1 = "LYZ", feature2 = "CCL5") # Combine two plots plot1 + plot2 # Remove the legend from all plots (plot1 + plot2) & NoLegend()Session Info sessionInfo()## R version 4.2.0 (2022-04-22) ## Platform: x86_64-pc-linux-gnu (64-bit) ## Running under: Ubuntu 20.04.5 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/liblapack.so.3 ## ## locale: ## [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C ## [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8 ## [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 ## ## attached base packages: ## [1] stats graphics grDevices utils datasets methods base ## ## other attached packages: ## [1] patchwork_1.1.2 ggplot2_3.4.1 ## [3] thp1.eccite.SeuratData_3.1.5 stxBrain.SeuratData_0.1.1 ## [5] ssHippo.SeuratData_3.1.4 pbmcsca.SeuratData_3.0.0 ## [7] pbmcMultiome.SeuratData_0.1.2 pbmc3k.SeuratData_3.1.4 ## [9] panc8.SeuratData_3.0.2 ifnb.SeuratData_3.1.0 ## [11] hcabm40k.SeuratData_3.0.0 bmcite.SeuratData_0.3.0 ## [13] SeuratData_0.2.2 SeuratObject_4.1.3 ## [15] Seurat_4.2.1.9001 ## ## loaded via a namespace (and not attached): ## [1] systemfonts_1.0.4 plyr_1.8.8 igraph_1.4.1 ## [4] lazyeval_0.2.2 sp_1.6-0 splines_4.2.0 ## [7] crosstalk_1.2.0 listenv_0.9.0 scattermore_0.8 ## [10] digest_0.6.31 htmltools_0.5.5 fansi_1.0.4 ## [13] magrittr_2.0.3 memoise_2.0.1 tensor_1.5 ## [16] cluster_2.1.3 ROCR_1.0-11 limma_3.54.1 ## [19] globals_0.16.2 matrixStats_0.63.0 pkgdown_2.0.7 ## [22] spatstat.sparse_3.0-1 colorspace_2.1-0 rappdirs_0.3.3 ## [25] ggrepel_0.9.3 textshaping_0.3.6 xfun_0.38 ## [28] dplyr_1.1.1 crayon_1.5.2 jsonlite_1.8.4 ## [31] progressr_0.13.0 spatstat.data_3.0-1 survival_3.3-1 ## [34] zoo_1.8-11 glue_1.6.2 polyclip_1.10-4 ## [37] gtable_0.3.3 leiden_0.4.3 future.apply_1.10.0 ## [40] abind_1.4-5 scales_1.2.1 spatstat.random_3.1-4 ## [43] miniUI_0.1.1.1 Rcpp_1.0.10 viridisLite_0.4.1 ## [46] xtable_1.8-4 reticulate_1.28 ggmin_0.0.0.9000 ## [49] htmlwidgets_1.6.2 httr_1.4.5 RColorBrewer_1.1-3 ## [52] ellipsis_0.3.2 ica_1.0-3 farver_2.1.1 ## [55] pkgconfig_2.0.3 sass_0.4.5 uwot_0.1.14 ## [58] deldir_1.0-6 utf8_1.2.3 tidyselect_1.2.0 ## [61] labeling_0.4.2 rlang_1.1.0 reshape2_1.4.4 ## [64] later_1.3.0 munsell_0.5.0 tools_4.2.0 ## [67] cachem_1.0.7 cli_3.6.1 generics_0.1.3 ## [70] ggridges_0.5.4 evaluate_0.20 stringr_1.5.0 ## [73] fastmap_1.1.1 yaml_2.3.7 ragg_1.2.5 ## [76] goftest_1.2-3 knitr_1.42 fs_1.6.1 ## [79] fitdistrplus_1.1-8 purrr_1.0.1 RANN_2.6.1 ## [82] pbapply_1.7-0 future_1.32.0 nlme_3.1-157 ## [85] mime_0.12 formatR_1.14 compiler_4.2.0 ## [88] plotly_4.10.1 png_0.1-8 spatstat.utils_3.0-2 ## [91] tibble_3.2.1 bslib_0.4.2 stringi_1.7.12 ## [94] highr_0.10 desc_1.4.2 lattice_0.20-45 ## [97] Matrix_1.5-3 vctrs_0.6.1 pillar_1.9.0 ## [100] lifecycle_1.0.3 spatstat.geom_3.1-0 lmtest_0.9-40 ## [103] jquerylib_0.1.4 RcppAnnoy_0.0.20 data.table_1.14.8 ## [106] cowplot_1.1.1 irlba_2.3.5.1 httpuv_1.6.9 ## [109] R6_2.5.1 promises_1.2.0.1 KernSmooth_2.23-20 ## [112] gridExtra_2.3 parallelly_1.35.0 codetools_0.2-18 ## [115] MASS_7.3-56 rprojroot_2.0.3 withr_2.5.0 ## [118] sctransform_0.3.5 parallel_4.2.0 grid_4.2.0 ## [121] tidyr_1.3.0 rmarkdown_2.21 Rtsne_0.16 ## [124] spatstat.explore_3.1-0 shiny_1.7.4

Plotting multiple plots was previously achieved with the CombinePlot() function. We are deprecating this functionality in favor of the patchwork system. Below is a brief demonstration but please see the patchwork package website here for more details and examples. plot1 <- DimPlot(pbmc3k.final) plot2 <- FeatureScatter(pbmc3k.final, feature1 = "LYZ", feature2 = "CCL5") # Combine two plots plot1 + plot2 # Remove the legend from all plots (plot1 + plot2) & NoLegend()Session Info sessionInfo()## R version 4.2.0 (2022-04-22) ## Platform: x86_64-pc-linux-gnu (64-bit) ## Running under: Ubuntu 20.04.5 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/liblapack.so.3 ## ## locale: ## [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C ## [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8 ## [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 ## ## attached base packages: ## [1] stats graphics grDevices utils datasets methods base ## ## other attached packages: ## [1] patchwork_1.1.2 ggplot2_3.4.1 ## [3] thp1.eccite.SeuratData_3.1.5 stxBrain.SeuratData_0.1.1 ## [5] ssHippo.SeuratData_3.1.4 pbmcsca.SeuratData_3.0.0 ## [7] pbmcMultiome.SeuratData_0.1.2 pbmc3k.SeuratData_3.1.4 ## [9] panc8.SeuratData_3.0.2 ifnb.SeuratData_3.1.0 ## [11] hcabm40k.SeuratData_3.0.0 bmcite.SeuratData_0.3.0 ## [13] SeuratData_0.2.2 SeuratObject_4.1.3 ## [15] Seurat_4.2.1.9001 ## ## loaded via a namespace (and not attached): ## [1] systemfonts_1.0.4 plyr_1.8.8 igraph_1.4.1 ## [4] lazyeval_0.2.2 sp_1.6-0 splines_4.2.0 ## [7] crosstalk_1.2.0 listenv_0.9.0 scattermore_0.8 ## [10] digest_0.6.31 htmltools_0.5.5 fansi_1.0.4 ## [13] magrittr_2.0.3 memoise_2.0.1 tensor_1.5 ## [16] cluster_2.1.3 ROCR_1.0-11 limma_3.54.1 ## [19] globals_0.16.2 matrixStats_0.63.0 pkgdown_2.0.7 ## [22] spatstat.sparse_3.0-1 colorspace_2.1-0 rappdirs_0.3.3 ## [25] ggrepel_0.9.3 textshaping_0.3.6 xfun_0.38 ## [28] dplyr_1.1.1 crayon_1.5.2 jsonlite_1.8.4 ## [31] progressr_0.13.0 spatstat.data_3.0-1 survival_3.3-1 ## [34] zoo_1.8-11 glue_1.6.2 polyclip_1.10-4 ## [37] gtable_0.3.3 leiden_0.4.3 future.apply_1.10.0 ## [40] abind_1.4-5 scales_1.2.1 spatstat.random_3.1-4 ## [43] miniUI_0.1.1.1 Rcpp_1.0.10 viridisLite_0.4.1 ## [46] xtable_1.8-4 reticulate_1.28 ggmin_0.0.0.9000 ## [49] htmlwidgets_1.6.2 httr_1.4.5 RColorBrewer_1.1-3 ## [52] ellipsis_0.3.2 ica_1.0-3 farver_2.1.1 ## [55] pkgconfig_2.0.3 sass_0.4.5 uwot_0.1.14 ## [58] deldir_1.0-6 utf8_1.2.3 tidyselect_1.2.0 ## [61] labeling_0.4.2 rlang_1.1.0 reshape2_1.4.4 ## [64] later_1.3.0 munsell_0.5.0 tools_4.2.0 ## [67] cachem_1.0.7 cli_3.6.1 generics_0.1.3 ## [70] ggridges_0.5.4 evaluate_0.20 stringr_1.5.0 ## [73] fastmap_1.1.1 yaml_2.3.7 ragg_1.2.5 ## [76] goftest_1.2-3 knitr_1.42 fs_1.6.1 ## [79] fitdistrplus_1.1-8 purrr_1.0.1 RANN_2.6.1 ## [82] pbapply_1.7-0 future_1.32.0 nlme_3.1-157 ## [85] mime_0.12 formatR_1.14 compiler_4.2.0 ## [88] plotly_4.10.1 png_0.1-8 spatstat.utils_3.0-2 ## [91] tibble_3.2.1 bslib_0.4.2 stringi_1.7.12 ## [94] highr_0.10 desc_1.4.2 lattice_0.20-45 ## [97] Matrix_1.5-3 vctrs_0.6.1 pillar_1.9.0 ## [100] lifecycle_1.0.3 spatstat.geom_3.1-0 lmtest_0.9-40 ## [103] jquerylib_0.1.4 RcppAnnoy_0.0.20 data.table_1.14.8 ## [106] cowplot_1.1.1 irlba_2.3.5.1 httpuv_1.6.9 ## [109] R6_2.5.1 promises_1.2.0.1 KernSmooth_2.23-20 ## [112] gridExtra_2.3 parallelly_1.35.0 codetools_0.2-18 ## [115] MASS_7.3-56 rprojroot_2.0.3 withr_2.5.0 ## [118] sctransform_0.3.5 parallel_4.2.0 grid_4.2.0 ## [121] tidyr_1.3.0 rmarkdown_2.21 Rtsne_0.16 ## [124] spatstat.explore_3.1-0 shiny_1.7.4

Plotting multiple plots was previously achieved with the CombinePlot() function. We are deprecating this functionality in favor of the patchwork system. Below is a brief demonstration but please see the patchwork package website here for more details and examples. plot1 <- DimPlot(pbmc3k.final) plot2 <- FeatureScatter(pbmc3k.final, feature1 = "LYZ", feature2 = "CCL5") # Combine two plots plot1 + plot2 # Remove the legend from all plots (plot1 + plot2) & NoLegend()Session Info sessionInfo()## R version 4.2.0 (2022-04-22) ## Platform: x86_64-pc-linux-gnu (64-bit) ## Running under: Ubuntu 20.04.5 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/liblapack.so.3 ## ## locale: ## [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C ## [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8 ## [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 ## ## attached base packages: ## [1] stats graphics grDevices utils datasets methods base ## ## other attached packages: ## [1] patchwork_1.1.2 ggplot2_3.4.1 ## [3] thp1.eccite.SeuratData_3.1.5 stxBrain.SeuratData_0.1.1 ## [5] ssHippo.SeuratData_3.1.4 pbmcsca.SeuratData_3.0.0 ## [7] pbmcMultiome.SeuratData_0.1.2 pbmc3k.SeuratData_3.1.4 ## [9] panc8.SeuratData_3.0.2 ifnb.SeuratData_3.1.0 ## [11] hcabm40k.SeuratData_3.0.0 bmcite.SeuratData_0.3.0 ## [13] SeuratData_0.2.2 SeuratObject_4.1.3 ## [15] Seurat_4.2.1.9001 ## ## loaded via a namespace (and not attached): ## [1] systemfonts_1.0.4 plyr_1.8.8 igraph_1.4.1 ## [4] lazyeval_0.2.2 sp_1.6-0 splines_4.2.0 ## [7] crosstalk_1.2.0 listenv_0.9.0 scattermore_0.8 ## [10] digest_0.6.31 htmltools_0.5.5 fansi_1.0.4 ## [13] magrittr_2.0.3 memoise_2.0.1 tensor_1.5 ## [16] cluster_2.1.3 ROCR_1.0-11 limma_3.54.1 ## [19] globals_0.16.2 matrixStats_0.63.0 pkgdown_2.0.7 ## [22] spatstat.sparse_3.0-1 colorspace_2.1-0 rappdirs_0.3.3 ## [25] ggrepel_0.9.3 textshaping_0.3.6 xfun_0.38 ## [28] dplyr_1.1.1 crayon_1.5.2 jsonlite_1.8.4 ## [31] progressr_0.13.0 spatstat.data_3.0-1 survival_3.3-1 ## [34] zoo_1.8-11 glue_1.6.2 polyclip_1.10-4 ## [37] gtable_0.3.3 leiden_0.4.3 future.apply_1.10.0 ## [40] abind_1.4-5 scales_1.2.1 spatstat.random_3.1-4 ## [43] miniUI_0.1.1.1 Rcpp_1.0.10 viridisLite_0.4.1 ## [46] xtable_1.8-4 reticulate_1.28 ggmin_0.0.0.9000 ## [49] htmlwidgets_1.6.2 httr_1.4.5 RColorBrewer_1.1-3 ## [52] ellipsis_0.3.2 ica_1.0-3 farver_2.1.1 ## [55] pkgconfig_2.0.3 sass_0.4.5 uwot_0.1.14 ## [58] deldir_1.0-6 utf8_1.2.3 tidyselect_1.2.0 ## [61] labeling_0.4.2 rlang_1.1.0 reshape2_1.4.4 ## [64] later_1.3.0 munsell_0.5.0 tools_4.2.0 ## [67] cachem_1.0.7 cli_3.6.1 generics_0.1.3 ## [70] ggridges_0.5.4 evaluate_0.20 stringr_1.5.0 ## [73] fastmap_1.1.1 yaml_2.3.7 ragg_1.2.5 ## [76] goftest_1.2-3 knitr_1.42 fs_1.6.1 ## [79] fitdistrplus_1.1-8 purrr_1.0.1 RANN_2.6.1 ## [82] pbapply_1.7-0 future_1.32.0 nlme_3.1-157 ## [85] mime_0.12 formatR_1.14 compiler_4.2.0 ## [88] plotly_4.10.1 png_0.1-8 spatstat.utils_3.0-2 ## [91] tibble_3.2.1 bslib_0.4.2 stringi_1.7.12 ## [94] highr_0.10 desc_1.4.2 lattice_0.20-45 ## [97] Matrix_1.5-3 vctrs_0.6.1 pillar_1.9.0 ## [100] lifecycle_1.0.3 spatstat.geom_3.1-0 lmtest_0.9-40 ## [103] jquerylib_0.1.4 RcppAnnoy_0.0.20 data.table_1.14.8 ## [106] cowplot_1.1.1 irlba_2.3.5.1 httpuv_1.6.9 ## [109] R6_2.5.1 promises_1.2.0.1 KernSmooth_2.23-20 ## [112] gridExtra_2.3 parallelly_1.35.0 codetools_0.2-18 ## [115] MASS_7.3-56 rprojroot_2.0.3 withr_2.5.0 ## [118] sctransform_0.3.5 parallel_4.2.0 grid_4.2.0 ## [121] tidyr_1.3.0 rmarkdown_2.21 Rtsne_0.16 ## [124] spatstat.explore_3.1-0 shiny_1.7.4

# Remove the legend from all plots (plot1 + plot2) & NoLegend()Session Info sessionInfo()## R version 4.2.0 (2022-04-22) ## Platform: x86_64-pc-linux-gnu (64-bit) ## Running under: Ubuntu 20.04.5 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/liblapack.so.3 ## ## locale: ## [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C ## [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8 ## [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 ## ## attached base packages: ## [1] stats graphics grDevices utils datasets methods base ## ## other attached packages: ## [1] patchwork_1.1.2 ggplot2_3.4.1 ## [3] thp1.eccite.SeuratData_3.1.5 stxBrain.SeuratData_0.1.1 ## [5] ssHippo.SeuratData_3.1.4 pbmcsca.SeuratData_3.0.0 ## [7] pbmcMultiome.SeuratData_0.1.2 pbmc3k.SeuratData_3.1.4 ## [9] panc8.SeuratData_3.0.2 ifnb.SeuratData_3.1.0 ## [11] hcabm40k.SeuratData_3.0.0 bmcite.SeuratData_0.3.0 ## [13] SeuratData_0.2.2 SeuratObject_4.1.3 ## [15] Seurat_4.2.1.9001 ## ## loaded via a namespace (and not attached): ## [1] systemfonts_1.0.4 plyr_1.8.8 igraph_1.4.1 ## [4] lazyeval_0.2.2 sp_1.6-0 splines_4.2.0 ## [7] crosstalk_1.2.0 listenv_0.9.0 scattermore_0.8 ## [10] digest_0.6.31 htmltools_0.5.5 fansi_1.0.4 ## [13] magrittr_2.0.3 memoise_2.0.1 tensor_1.5 ## [16] cluster_2.1.3 ROCR_1.0-11 limma_3.54.1 ## [19] globals_0.16.2 matrixStats_0.63.0 pkgdown_2.0.7 ## [22] spatstat.sparse_3.0-1 colorspace_2.1-0 rappdirs_0.3.3 ## [25] ggrepel_0.9.3 textshaping_0.3.6 xfun_0.38 ## [28] dplyr_1.1.1 crayon_1.5.2 jsonlite_1.8.4 ## [31] progressr_0.13.0 spatstat.data_3.0-1 survival_3.3-1 ## [34] zoo_1.8-11 glue_1.6.2 polyclip_1.10-4 ## [37] gtable_0.3.3 leiden_0.4.3 future.apply_1.10.0 ## [40] abind_1.4-5 scales_1.2.1 spatstat.random_3.1-4 ## [43] miniUI_0.1.1.1 Rcpp_1.0.10 viridisLite_0.4.1 ## [46] xtable_1.8-4 reticulate_1.28 ggmin_0.0.0.9000 ## [49] htmlwidgets_1.6.2 httr_1.4.5 RColorBrewer_1.1-3 ## [52] ellipsis_0.3.2 ica_1.0-3 farver_2.1.1 ## [55] pkgconfig_2.0.3 sass_0.4.5 uwot_0.1.14 ## [58] deldir_1.0-6 utf8_1.2.3 tidyselect_1.2.0 ## [61] labeling_0.4.2 rlang_1.1.0 reshape2_1.4.4 ## [64] later_1.3.0 munsell_0.5.0 tools_4.2.0 ## [67] cachem_1.0.7 cli_3.6.1 generics_0.1.3 ## [70] ggridges_0.5.4 evaluate_0.20 stringr_1.5.0 ## [73] fastmap_1.1.1 yaml_2.3.7 ragg_1.2.5 ## [76] goftest_1.2-3 knitr_1.42 fs_1.6.1 ## [79] fitdistrplus_1.1-8 purrr_1.0.1 RANN_2.6.1 ## [82] pbapply_1.7-0 future_1.32.0 nlme_3.1-157 ## [85] mime_0.12 formatR_1.14 compiler_4.2.0 ## [88] plotly_4.10.1 png_0.1-8 spatstat.utils_3.0-2 ## [91] tibble_3.2.1 bslib_0.4.2 stringi_1.7.12 ## [94] highr_0.10 desc_1.4.2 lattice_0.20-45 ## [97] Matrix_1.5-3 vctrs_0.6.1 pillar_1.9.0 ## [100] lifecycle_1.0.3 spatstat.geom_3.1-0 lmtest_0.9-40 ## [103] jquerylib_0.1.4 RcppAnnoy_0.0.20 data.table_1.14.8 ## [106] cowplot_1.1.1 irlba_2.3.5.1 httpuv_1.6.9 ## [109] R6_2.5.1 promises_1.2.0.1 KernSmooth_2.23-20 ## [112] gridExtra_2.3 parallelly_1.35.0 codetools_0.2-18 ## [115] MASS_7.3-56 rprojroot_2.0.3 withr_2.5.0 ## [118] sctransform_0.3.5 parallel_4.2.0 grid_4.2.0 ## [121] tidyr_1.3.0 rmarkdown_2.21 Rtsne_0.16 ## [124] spatstat.explore_3.1-0 shiny_1.7.4

Session Info sessionInfo()## R version 4.2.0 (2022-04-22) ## Platform: x86_64-pc-linux-gnu (64-bit) ## Running under: Ubuntu 20.04.5 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/liblapack.so.3 ## ## locale: ## [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C ## [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8 ## [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 ## ## attached base packages: ## [1] stats graphics grDevices utils datasets methods base ## ## other attached packages: ## [1] patchwork_1.1.2 ggplot2_3.4.1 ## [3] thp1.eccite.SeuratData_3.1.5 stxBrain.SeuratData_0.1.1 ## [5] ssHippo.SeuratData_3.1.4 pbmcsca.SeuratData_3.0.0 ## [7] pbmcMultiome.SeuratData_0.1.2 pbmc3k.SeuratData_3.1.4 ## [9] panc8.SeuratData_3.0.2 ifnb.SeuratData_3.1.0 ## [11] hcabm40k.SeuratData_3.0.0 bmcite.SeuratData_0.3.0 ## [13] SeuratData_0.2.2 SeuratObject_4.1.3 ## [15] Seurat_4.2.1.9001 ## ## loaded via a namespace (and not attached): ## [1] systemfonts_1.0.4 plyr_1.8.8 igraph_1.4.1 ## [4] lazyeval_0.2.2 sp_1.6-0 splines_4.2.0 ## [7] crosstalk_1.2.0 listenv_0.9.0 scattermore_0.8 ## [10] digest_0.6.31 htmltools_0.5.5 fansi_1.0.4 ## [13] magrittr_2.0.3 memoise_2.0.1 tensor_1.5 ## [16] cluster_2.1.3 ROCR_1.0-11 limma_3.54.1 ## [19] globals_0.16.2 matrixStats_0.63.0 pkgdown_2.0.7 ## [22] spatstat.sparse_3.0-1 colorspace_2.1-0 rappdirs_0.3.3 ## [25] ggrepel_0.9.3 textshaping_0.3.6 xfun_0.38 ## [28] dplyr_1.1.1 crayon_1.5.2 jsonlite_1.8.4 ## [31] progressr_0.13.0 spatstat.data_3.0-1 survival_3.3-1 ## [34] zoo_1.8-11 glue_1.6.2 polyclip_1.10-4 ## [37] gtable_0.3.3 leiden_0.4.3 future.apply_1.10.0 ## [40] abind_1.4-5 scales_1.2.1 spatstat.random_3.1-4 ## [43] miniUI_0.1.1.1 Rcpp_1.0.10 viridisLite_0.4.1 ## [46] xtable_1.8-4 reticulate_1.28 ggmin_0.0.0.9000 ## [49] htmlwidgets_1.6.2 httr_1.4.5 RColorBrewer_1.1-3 ## [52] ellipsis_0.3.2 ica_1.0-3 farver_2.1.1 ## [55] pkgconfig_2.0.3 sass_0.4.5 uwot_0.1.14 ## [58] deldir_1.0-6 utf8_1.2.3 tidyselect_1.2.0 ## [61] labeling_0.4.2 rlang_1.1.0 reshape2_1.4.4 ## [64] later_1.3.0 munsell_0.5.0 tools_4.2.0 ## [67] cachem_1.0.7 cli_3.6.1 generics_0.1.3 ## [70] ggridges_0.5.4 evaluate_0.20 stringr_1.5.0 ## [73] fastmap_1.1.1 yaml_2.3.7 ragg_1.2.5 ## [76] goftest_1.2-3 knitr_1.42 fs_1.6.1 ## [79] fitdistrplus_1.1-8 purrr_1.0.1 RANN_2.6.1 ## [82] pbapply_1.7-0 future_1.32.0 nlme_3.1-157 ## [85] mime_0.12 formatR_1.14 compiler_4.2.0 ## [88] plotly_4.10.1 png_0.1-8 spatstat.utils_3.0-2 ## [91] tibble_3.2.1 bslib_0.4.2 stringi_1.7.12 ## [94] highr_0.10 desc_1.4.2 lattice_0.20-45 ## [97] Matrix_1.5-3 vctrs_0.6.1 pillar_1.9.0 ## [100] lifecycle_1.0.3 spatstat.geom_3.1-0 lmtest_0.9-40 ## [103] jquerylib_0.1.4 RcppAnnoy_0.0.20 data.table_1.14.8 ## [106] cowplot_1.1.1 irlba_2.3.5.1 httpuv_1.6.9 ## [109] R6_2.5.1 promises_1.2.0.1 KernSmooth_2.23-20 ## [112] gridExtra_2.3 parallelly_1.35.0 codetools_0.2-18 ## [115] MASS_7.3-56 rprojroot_2.0.3 withr_2.5.0 ## [118] sctransform_0.3.5 parallel_4.2.0 grid_4.2.0 ## [121] tidyr_1.3.0 rmarkdown_2.21 Rtsne_0.16 ## [124] spatstat.explore_3.1-0 shiny_1.7.4

sessionInfo()## R version 4.2.0 (2022-04-22) ## Platform: x86_64-pc-linux-gnu (64-bit) ## Running under: Ubuntu 20.04.5 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/liblapack.so.3 ## ## locale: ## [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C ## [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8 ## [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 ## ## attached base packages: ## [1] stats graphics grDevices utils datasets methods base ## ## other attached packages: ## [1] patchwork_1.1.2 ggplot2_3.4.1 ## [3] thp1.eccite.SeuratData_3.1.5 stxBrain.SeuratData_0.1.1 ## [5] ssHippo.SeuratData_3.1.4 pbmcsca.SeuratData_3.0.0 ## [7] pbmcMultiome.SeuratData_0.1.2 pbmc3k.SeuratData_3.1.4 ## [9] panc8.SeuratData_3.0.2 ifnb.SeuratData_3.1.0 ## [11] hcabm40k.SeuratData_3.0.0 bmcite.SeuratData_0.3.0 ## [13] SeuratData_0.2.2 SeuratObject_4.1.3 ## [15] Seurat_4.2.1.9001 ## ## loaded via a namespace (and not attached): ## [1] systemfonts_1.0.4 plyr_1.8.8 igraph_1.4.1 ## [4] lazyeval_0.2.2 sp_1.6-0 splines_4.2.0 ## [7] crosstalk_1.2.0 listenv_0.9.0 scattermore_0.8 ## [10] digest_0.6.31 htmltools_0.5.5 fansi_1.0.4 ## [13] magrittr_2.0.3 memoise_2.0.1 tensor_1.5 ## [16] cluster_2.1.3 ROCR_1.0-11 limma_3.54.1 ## [19] globals_0.16.2 matrixStats_0.63.0 pkgdown_2.0.7 ## [22] spatstat.sparse_3.0-1 colorspace_2.1-0 rappdirs_0.3.3 ## [25] ggrepel_0.9.3 textshaping_0.3.6 xfun_0.38 ## [28] dplyr_1.1.1 crayon_1.5.2 jsonlite_1.8.4 ## [31] progressr_0.13.0 spatstat.data_3.0-1 survival_3.3-1 ## [34] zoo_1.8-11 glue_1.6.2 polyclip_1.10-4 ## [37] gtable_0.3.3 leiden_0.4.3 future.apply_1.10.0 ## [40] abind_1.4-5 scales_1.2.1 spatstat.random_3.1-4 ## [43] miniUI_0.1.1.1 Rcpp_1.0.10 viridisLite_0.4.1 ## [46] xtable_1.8-4 reticulate_1.28 ggmin_0.0.0.9000 ## [49] htmlwidgets_1.6.2 httr_1.4.5 RColorBrewer_1.1-3 ## [52] ellipsis_0.3.2 ica_1.0-3 farver_2.1.1 ## [55] pkgconfig_2.0.3 sass_0.4.5 uwot_0.1.14 ## [58] deldir_1.0-6 utf8_1.2.3 tidyselect_1.2.0 ## [61] labeling_0.4.2 rlang_1.1.0 reshape2_1.4.4 ## [64] later_1.3.0 munsell_0.5.0 tools_4.2.0 ## [67] cachem_1.0.7 cli_3.6.1 generics_0.1.3 ## [70] ggridges_0.5.4 evaluate_0.20 stringr_1.5.0 ## [73] fastmap_1.1.1 yaml_2.3.7 ragg_1.2.5 ## [76] goftest_1.2-3 knitr_1.42 fs_1.6.1 ## [79] fitdistrplus_1.1-8 purrr_1.0.1 RANN_2.6.1 ## [82] pbapply_1.7-0 future_1.32.0 nlme_3.1-157 ## [85] mime_0.12 formatR_1.14 compiler_4.2.0 ## [88] plotly_4.10.1 png_0.1-8 spatstat.utils_3.0-2 ## [91] tibble_3.2.1 bslib_0.4.2 stringi_1.7.12 ## [94] highr_0.10 desc_1.4.2 lattice_0.20-45 ## [97] Matrix_1.5-3 vctrs_0.6.1 pillar_1.9.0 ## [100] lifecycle_1.0.3 spatstat.geom_3.1-0 lmtest_0.9-40 ## [103] jquerylib_0.1.4 RcppAnnoy_0.0.20 data.table_1.14.8 ## [106] cowplot_1.1.1 irlba_2.3.5.1 httpuv_1.6.9 ## [109] R6_2.5.1 promises_1.2.0.1 KernSmooth_2.23-20 ## [112] gridExtra_2.3 parallelly_1.35.0 codetools_0.2-18 ## [115] MASS_7.3-56 rprojroot_2.0.3 withr_2.5.0 ## [118] sctransform_0.3.5 parallel_4.2.0 grid_4.2.0 ## [121] tidyr_1.3.0 rmarkdown_2.21 Rtsne_0.16 ## [124] spatstat.explore_3.1-0 shiny_1.7.4

Developed by Paul Hoffman, Satija Lab and Collaborators.

Developed by Paul Hoffman, Satija Lab and Collaborators.

Site built with pkgdown 2.0.7.

Site built with pkgdown 2.0.7.

**Examples:**

Example 1 (unknown):
```unknown
vignettes/visualization_vignette.Rmd
```

Example 2 (unknown):
```unknown
visualization_vignette.Rmd
```

Example 3 (unknown):
```unknown
SeuratData::InstallData("pbmc3k")
```

Example 4 (r):
```r
SeuratData::InstallData("pbmc3k")
```

Example 5 (r):
```r
SeuratData::InstallData("pbmc3k")
```

Example 6 (unknown):
```unknown
library(Seurat)
library(SeuratData)
library(ggplot2)
library(patchwork)
data("pbmc3k.final")
pbmc3k.final$groups <- sample(c("group1", "group2"), size = ncol(pbmc3k.final), replace = TRUE)
features <- c("LYZ", "CCL5", "IL32", "PTPRCAP", "FCGR3A", "PF4")
pbmc3k.final
```

Example 7 (r):
```r
library(Seurat)
library(SeuratData)
library(ggplot2)
library(patchwork)
data("pbmc3k.final")
pbmc3k.final$groups <- sample(c("group1", "group2"), size = ncol(pbmc3k.final), replace = TRUE)
features <- c("LYZ", "CCL5", "IL32", "PTPRCAP", "FCGR3A", "PF4")
pbmc3k.final
```

Example 8 (r):
```r
library(Seurat)
library(SeuratData)
library(ggplot2)
library(patchwork)
data("pbmc3k.final")
pbmc3k.final$groups <- sample(c("group1", "group2"), size = ncol(pbmc3k.final), replace = TRUE)
features <- c("LYZ", "CCL5", "IL32", "PTPRCAP", "FCGR3A", "PF4")
pbmc3k.final
```

Example 9 (python):
```python
## An object of class Seurat 
## 13714 features across 2638 samples within 1 assay 
## Active assay: RNA (13714 features, 2000 variable features)
##  2 dimensional reductions calculated: pca, umap
```

Example 10 (python):
```python
## An object of class Seurat 
## 13714 features across 2638 samples within 1 assay 
## Active assay: RNA (13714 features, 2000 variable features)
##  2 dimensional reductions calculated: pca, umap
```

Example 11 (python):
```python
# Ridge plots - from ggridges. Visualize single cell expression distributions in each cluster
RidgePlot(pbmc3k.final, features = features, ncol = 2)
```

Example 12 (r):
```r
# Ridge plots - from ggridges. Visualize single cell expression distributions in each cluster
RidgePlot(pbmc3k.final, features = features, ncol = 2)
```

Example 13 (r):
```r
# Ridge plots - from ggridges. Visualize single cell expression distributions in each cluster
RidgePlot(pbmc3k.final, features = features, ncol = 2)
```

Example 14 (unknown):
```unknown
# Violin plot - Visualize single cell expression distributions in each cluster
VlnPlot(pbmc3k.final, features = features)
```

Example 15 (r):
```r
# Violin plot - Visualize single cell expression distributions in each cluster
VlnPlot(pbmc3k.final, features = features)
```

Example 16 (r):
```r
# Violin plot - Visualize single cell expression distributions in each cluster
VlnPlot(pbmc3k.final, features = features)
```

Example 17 (unknown):
```unknown
# Feature plot - visualize feature expression in low-dimensional space
FeaturePlot(pbmc3k.final, features = features)
```

Example 18 (r):
```r
# Feature plot - visualize feature expression in low-dimensional space
FeaturePlot(pbmc3k.final, features = features)
```

Example 19 (r):
```r
# Feature plot - visualize feature expression in low-dimensional space
FeaturePlot(pbmc3k.final, features = features)
```

Example 20 (unknown):
```unknown
# Dot plots - the size of the dot corresponds to the percentage of cells expressing the
# feature in each cluster. The color represents the average expression level
DotPlot(pbmc3k.final, features = features) + RotatedAxis()
```

Example 21 (r):
```r
# Dot plots - the size of the dot corresponds to the percentage of cells expressing the
# feature in each cluster. The color represents the average expression level
DotPlot(pbmc3k.final, features = features) + RotatedAxis()
```

Example 22 (r):
```r
# Dot plots - the size of the dot corresponds to the percentage of cells expressing the
# feature in each cluster. The color represents the average expression level
DotPlot(pbmc3k.final, features = features) + RotatedAxis()
```

Example 23 (unknown):
```unknown
# Single cell heatmap of feature expression
DoHeatmap(subset(pbmc3k.final, downsample = 100), features = features, size = 3)
```

Example 24 (r):
```r
# Single cell heatmap of feature expression
DoHeatmap(subset(pbmc3k.final, downsample = 100), features = features, size = 3)
```

Example 25 (r):
```r
# Single cell heatmap of feature expression
DoHeatmap(subset(pbmc3k.final, downsample = 100), features = features, size = 3)
```

Example 26 (unknown):
```unknown
FeaturePlot
```

Example 27 (unknown):
```unknown
# Plot a legend to map colors to expression levels
FeaturePlot(pbmc3k.final, features = "MS4A1")
```

Example 28 (r):
```r
# Plot a legend to map colors to expression levels
FeaturePlot(pbmc3k.final, features = "MS4A1")
```

Example 29 (r):
```r
# Plot a legend to map colors to expression levels
FeaturePlot(pbmc3k.final, features = "MS4A1")
```

Example 30 (unknown):
```unknown
# Adjust the contrast in the plot
FeaturePlot(pbmc3k.final, features = "MS4A1", min.cutoff = 1, max.cutoff = 3)
```

Example 31 (r):
```r
# Adjust the contrast in the plot
FeaturePlot(pbmc3k.final, features = "MS4A1", min.cutoff = 1, max.cutoff = 3)
```

Example 32 (r):
```r
# Adjust the contrast in the plot
FeaturePlot(pbmc3k.final, features = "MS4A1", min.cutoff = 1, max.cutoff = 3)
```

Example 33 (unknown):
```unknown
# Calculate feature-specific contrast levels based on quantiles of non-zero expression.
# Particularly useful when plotting multiple markers
FeaturePlot(pbmc3k.final, features = c("MS4A1", "PTPRCAP"), min.cutoff = "q10", max.cutoff = "q90")
```

Example 34 (r):
```r
# Calculate feature-specific contrast levels based on quantiles of non-zero expression.
# Particularly useful when plotting multiple markers
FeaturePlot(pbmc3k.final, features = c("MS4A1", "PTPRCAP"), min.cutoff = "q10", max.cutoff = "q90")
```

Example 35 (r):
```r
# Calculate feature-specific contrast levels based on quantiles of non-zero expression.
# Particularly useful when plotting multiple markers
FeaturePlot(pbmc3k.final, features = c("MS4A1", "PTPRCAP"), min.cutoff = "q10", max.cutoff = "q90")
```

Example 36 (unknown):
```unknown
# Visualize co-expression of two features simultaneously
FeaturePlot(pbmc3k.final, features = c("MS4A1", "CD79A"), blend = TRUE)
```

Example 37 (r):
```r
# Visualize co-expression of two features simultaneously
FeaturePlot(pbmc3k.final, features = c("MS4A1", "CD79A"), blend = TRUE)
```

Example 38 (r):
```r
# Visualize co-expression of two features simultaneously
FeaturePlot(pbmc3k.final, features = c("MS4A1", "CD79A"), blend = TRUE)
```

Example 39 (unknown):
```unknown
# Split visualization to view expression by groups (replaces FeatureHeatmap)
FeaturePlot(pbmc3k.final, features = c("MS4A1", "CD79A"), split.by = "groups")
```

Example 40 (r):
```r
# Split visualization to view expression by groups (replaces FeatureHeatmap)
FeaturePlot(pbmc3k.final, features = c("MS4A1", "CD79A"), split.by = "groups")
```

Example 41 (r):
```r
# Split visualization to view expression by groups (replaces FeatureHeatmap)
FeaturePlot(pbmc3k.final, features = c("MS4A1", "CD79A"), split.by = "groups")
```

Example 42 (unknown):
```unknown
FeaturePlot()
```

Example 43 (python):
```python
# Violin plots can also be split on some variable. Simply add the splitting variable to object
# metadata and pass it to the split.by argument
VlnPlot(pbmc3k.final, features = "percent.mt", split.by = "groups")
```

Example 44 (r):
```r
# Violin plots can also be split on some variable. Simply add the splitting variable to object
# metadata and pass it to the split.by argument
VlnPlot(pbmc3k.final, features = "percent.mt", split.by = "groups")
```

Example 45 (r):
```r
# Violin plots can also be split on some variable. Simply add the splitting variable to object
# metadata and pass it to the split.by argument
VlnPlot(pbmc3k.final, features = "percent.mt", split.by = "groups")
```

Example 46 (unknown):
```unknown
# SplitDotPlotGG has been replaced with the `split.by` parameter for DotPlot
DotPlot(pbmc3k.final, features = features, split.by = "groups") + RotatedAxis()
```

Example 47 (r):
```r
# SplitDotPlotGG has been replaced with the `split.by` parameter for DotPlot
DotPlot(pbmc3k.final, features = features, split.by = "groups") + RotatedAxis()
```

Example 48 (r):
```r
# SplitDotPlotGG has been replaced with the `split.by` parameter for DotPlot
DotPlot(pbmc3k.final, features = features, split.by = "groups") + RotatedAxis()
```

Example 49 (unknown):
```unknown
# DimPlot replaces TSNEPlot, PCAPlot, etc. In addition, it will plot either 'umap', 'tsne', or
# 'pca' by default, in that order
DimPlot(pbmc3k.final)
```

Example 50 (r):
```r
# DimPlot replaces TSNEPlot, PCAPlot, etc. In addition, it will plot either 'umap', 'tsne', or
# 'pca' by default, in that order
DimPlot(pbmc3k.final)
```

Example 51 (r):
```r
# DimPlot replaces TSNEPlot, PCAPlot, etc. In addition, it will plot either 'umap', 'tsne', or
# 'pca' by default, in that order
DimPlot(pbmc3k.final)
```

Example 52 (unknown):
```unknown
pbmc3k.final.no.umap <- pbmc3k.final
pbmc3k.final.no.umap[["umap"]] <- NULL
DimPlot(pbmc3k.final.no.umap) + RotatedAxis()
```

Example 53 (r):
```r
pbmc3k.final.no.umap <- pbmc3k.final
pbmc3k.final.no.umap[["umap"]] <- NULL
DimPlot(pbmc3k.final.no.umap) + RotatedAxis()
```

Example 54 (r):
```r
pbmc3k.final.no.umap <- pbmc3k.final
pbmc3k.final.no.umap[["umap"]] <- NULL
DimPlot(pbmc3k.final.no.umap) + RotatedAxis()
```

Example 55 (unknown):
```unknown
# DoHeatmap now shows a grouping bar, splitting the heatmap into groups or clusters. This can
# be changed with the `group.by` parameter
DoHeatmap(pbmc3k.final, features = VariableFeatures(pbmc3k.final)[1:100], cells = 1:500, size = 4,
    angle = 90) + NoLegend()
```

Example 56 (r):
```r
# DoHeatmap now shows a grouping bar, splitting the heatmap into groups or clusters. This can
# be changed with the `group.by` parameter
DoHeatmap(pbmc3k.final, features = VariableFeatures(pbmc3k.final)[1:100], cells = 1:500, size = 4,
    angle = 90) + NoLegend()
```

Example 57 (r):
```r
# DoHeatmap now shows a grouping bar, splitting the heatmap into groups or clusters. This can
# be changed with the `group.by` parameter
DoHeatmap(pbmc3k.final, features = VariableFeatures(pbmc3k.final)[1:100], cells = 1:500, size = 4,
    angle = 90) + NoLegend()
```

Example 58 (unknown):
```unknown
baseplot <- DimPlot(pbmc3k.final, reduction = "umap")
# Add custom labels and titles
baseplot + labs(title = "Clustering of 2,700 PBMCs")
```

Example 59 (r):
```r
baseplot <- DimPlot(pbmc3k.final, reduction = "umap")
# Add custom labels and titles
baseplot + labs(title = "Clustering of 2,700 PBMCs")
```

Example 60 (r):
```r
baseplot <- DimPlot(pbmc3k.final, reduction = "umap")
# Add custom labels and titles
baseplot + labs(title = "Clustering of 2,700 PBMCs")
```

Example 61 (unknown):
```unknown
# Use community-created themes, overwriting the default Seurat-applied theme Install ggmin
# with remotes::install_github('sjessa/ggmin')
baseplot + ggmin::theme_powerpoint()
```

Example 62 (r):
```r
# Use community-created themes, overwriting the default Seurat-applied theme Install ggmin
# with remotes::install_github('sjessa/ggmin')
baseplot + ggmin::theme_powerpoint()
```

Example 63 (r):
```r
# Use community-created themes, overwriting the default Seurat-applied theme Install ggmin
# with remotes::install_github('sjessa/ggmin')
baseplot + ggmin::theme_powerpoint()
```

Example 64 (unknown):
```unknown
# Seurat also provides several built-in themes, such as DarkTheme; for more details see
# ?SeuratTheme
baseplot + DarkTheme()
```

Example 65 (r):
```r
# Seurat also provides several built-in themes, such as DarkTheme; for more details see
# ?SeuratTheme
baseplot + DarkTheme()
```

Example 66 (r):
```r
# Seurat also provides several built-in themes, such as DarkTheme; for more details see
# ?SeuratTheme
baseplot + DarkTheme()
```

Example 67 (unknown):
```unknown
# Chain themes together
baseplot + FontSize(x.title = 20, y.title = 20) + NoLegend()
```

Example 68 (r):
```r
# Chain themes together
baseplot + FontSize(x.title = 20, y.title = 20) + NoLegend()
```

Example 69 (r):
```r
# Chain themes together
baseplot + FontSize(x.title = 20, y.title = 20) + NoLegend()
```

Example 70 (unknown):
```unknown
FeaturePlot()
```

Example 71 (unknown):
```unknown
HoverLocator()
```

Example 72 (unknown):
```unknown
# Include additional data to display alongside cell names by passing in a data frame of
# information Works well when using FetchData
plot <- FeaturePlot(pbmc3k.final, features = "MS4A1")
HoverLocator(plot = plot, information = FetchData(pbmc3k.final, vars = c("ident", "PC_1", "nFeature_RNA")))
```

Example 73 (r):
```r
# Include additional data to display alongside cell names by passing in a data frame of
# information Works well when using FetchData
plot <- FeaturePlot(pbmc3k.final, features = "MS4A1")
HoverLocator(plot = plot, information = FetchData(pbmc3k.final, vars = c("ident", "PC_1", "nFeature_RNA")))
```

Example 74 (r):
```r
# Include additional data to display alongside cell names by passing in a data frame of
# information Works well when using FetchData
plot <- FeaturePlot(pbmc3k.final, features = "MS4A1")
HoverLocator(plot = plot, information = FetchData(pbmc3k.final, vars = c("ident", "PC_1", "nFeature_RNA")))
```

Example 75 (unknown):
```unknown
FeaturePlot()
```

Example 76 (unknown):
```unknown
CellSelector()
```

Example 77 (unknown):
```unknown
CellSelector()
```

Example 78 (unknown):
```unknown
pbmc3k.final <- RenameIdents(pbmc3k.final, DC = "CD14+ Mono")
plot <- DimPlot(pbmc3k.final, reduction = "umap")
select.cells <- CellSelector(plot = plot)
```

Example 79 (r):
```r
pbmc3k.final <- RenameIdents(pbmc3k.final, DC = "CD14+ Mono")
plot <- DimPlot(pbmc3k.final, reduction = "umap")
select.cells <- CellSelector(plot = plot)
```

Example 80 (r):
```r
pbmc3k.final <- RenameIdents(pbmc3k.final, DC = "CD14+ Mono")
plot <- DimPlot(pbmc3k.final, reduction = "umap")
select.cells <- CellSelector(plot = plot)
```

Example 81 (unknown):
```unknown
head(select.cells)
```

Example 82 (r):
```r
head(select.cells)
```

Example 83 (r):
```r
head(select.cells)
```

Example 84 (unknown):
```unknown
## [1] "AAGATTACCGCCTT" "AAGCCATGAACTGC" "AATTACGAATTCCT" "ACCCGTTGCTTCTA"
## [5] "ACGAGGGACAGGAG" "ACGTGATGCCATGA"
```

Example 85 (unknown):
```unknown
## [1] "AAGATTACCGCCTT" "AAGCCATGAACTGC" "AATTACGAATTCCT" "ACCCGTTGCTTCTA"
## [5] "ACGAGGGACAGGAG" "ACGTGATGCCATGA"
```

Example 86 (unknown):
```unknown
Idents(pbmc3k.final, cells = select.cells) <- "NewCells"

# Now, we find markers that are specific to the new cells, and find clear DC markers
newcells.markers <- FindMarkers(pbmc3k.final, ident.1 = "NewCells", ident.2 = "CD14+ Mono", min.diff.pct = 0.3,
    only.pos = TRUE)
head(newcells.markers)
```

Example 87 (r):
```r
Idents(pbmc3k.final, cells = select.cells) <- "NewCells"

# Now, we find markers that are specific to the new cells, and find clear DC markers
newcells.markers <- FindMarkers(pbmc3k.final, ident.1 = "NewCells", ident.2 = "CD14+ Mono", min.diff.pct = 0.3,
    only.pos = TRUE)
head(newcells.markers)
```

Example 88 (r):
```r
Idents(pbmc3k.final, cells = select.cells) <- "NewCells"

# Now, we find markers that are specific to the new cells, and find clear DC markers
newcells.markers <- FindMarkers(pbmc3k.final, ident.1 = "NewCells", ident.2 = "CD14+ Mono", min.diff.pct = 0.3,
    only.pos = TRUE)
head(newcells.markers)
```

Example 89 (unknown):
```unknown
##                 p_val avg_log2FC pct.1 pct.2    p_val_adj
## FCER1A   3.239004e-69  3.7008561 0.800 0.017 4.441970e-65
## SERPINF1 7.761413e-36  1.5737896 0.457 0.013 1.064400e-31
## HLA-DQB2 1.721094e-34  0.9685974 0.429 0.010 2.360309e-30
## CD1C     2.304106e-33  1.7785158 0.514 0.025 3.159851e-29
## ENHO     5.099765e-32  1.3734708 0.400 0.010 6.993818e-28
## ITM2C    4.299994e-29  1.5590007 0.371 0.010 5.897012e-25
```

Example 90 (unknown):
```unknown
##                 p_val avg_log2FC pct.1 pct.2    p_val_adj
## FCER1A   3.239004e-69  3.7008561 0.800 0.017 4.441970e-65
## SERPINF1 7.761413e-36  1.5737896 0.457 0.013 1.064400e-31
## HLA-DQB2 1.721094e-34  0.9685974 0.429 0.010 2.360309e-30
## CD1C     2.304106e-33  1.7785158 0.514 0.025 3.159851e-29
## ENHO     5.099765e-32  1.3734708 0.400 0.010 6.993818e-28
## ITM2C    4.299994e-29  1.5590007 0.371 0.010 5.897012e-25
```

Example 91 (unknown):
```unknown
CellSelector
```

Example 92 (unknown):
```unknown
CellSelector()
```

Example 93 (unknown):
```unknown
CellSelector()
```

Example 94 (unknown):
```unknown
pbmc3k.final <- CellSelector(plot = plot, object = pbmc3k.final, ident = "selected")
```

Example 95 (r):
```r
pbmc3k.final <- CellSelector(plot = plot, object = pbmc3k.final, ident = "selected")
```

Example 96 (r):
```r
pbmc3k.final <- CellSelector(plot = plot, object = pbmc3k.final, ident = "selected")
```

Example 97 (unknown):
```unknown
levels(pbmc3k.final)
```

Example 98 (r):
```r
levels(pbmc3k.final)
```

Example 99 (r):
```r
levels(pbmc3k.final)
```

Example 100 (unknown):
```unknown
## [1] "selected"     "Naive CD4 T"  "Memory CD4 T" "CD14+ Mono"   "B"           
## [6] "CD8 T"        "FCGR3A+ Mono" "NK"           "Platelet"
```

Example 101 (unknown):
```unknown
## [1] "selected"     "Naive CD4 T"  "Memory CD4 T" "CD14+ Mono"   "B"           
## [6] "CD8 T"        "FCGR3A+ Mono" "NK"           "Platelet"
```

Example 102 (unknown):
```unknown
# LabelClusters and LabelPoints will label clusters (a coloring variable) or individual points
# on a ggplot2-based scatter plot
plot <- DimPlot(pbmc3k.final, reduction = "pca") + NoLegend()
LabelClusters(plot = plot, id = "ident")
```

Example 103 (r):
```r
# LabelClusters and LabelPoints will label clusters (a coloring variable) or individual points
# on a ggplot2-based scatter plot
plot <- DimPlot(pbmc3k.final, reduction = "pca") + NoLegend()
LabelClusters(plot = plot, id = "ident")
```

Example 104 (r):
```r
# LabelClusters and LabelPoints will label clusters (a coloring variable) or individual points
# on a ggplot2-based scatter plot
plot <- DimPlot(pbmc3k.final, reduction = "pca") + NoLegend()
LabelClusters(plot = plot, id = "ident")
```

Example 105 (python):
```python
# Both functions support `repel`, which will intelligently stagger labels and draw connecting
# lines from the labels to the points or clusters
LabelPoints(plot = plot, points = TopCells(object = pbmc3k.final[["pca"]]), repel = TRUE)
```

Example 106 (r):
```r
# Both functions support `repel`, which will intelligently stagger labels and draw connecting
# lines from the labels to the points or clusters
LabelPoints(plot = plot, points = TopCells(object = pbmc3k.final[["pca"]]), repel = TRUE)
```

Example 107 (r):
```r
# Both functions support `repel`, which will intelligently stagger labels and draw connecting
# lines from the labels to the points or clusters
LabelPoints(plot = plot, points = TopCells(object = pbmc3k.final[["pca"]]), repel = TRUE)
```

Example 108 (unknown):
```unknown
CombinePlot()
```

Example 109 (unknown):
```unknown
plot1 <- DimPlot(pbmc3k.final)
plot2 <- FeatureScatter(pbmc3k.final, feature1 = "LYZ", feature2 = "CCL5")
# Combine two plots
plot1 + plot2
```

Example 110 (r):
```r
plot1 <- DimPlot(pbmc3k.final)
plot2 <- FeatureScatter(pbmc3k.final, feature1 = "LYZ", feature2 = "CCL5")
# Combine two plots
plot1 + plot2
```

Example 111 (r):
```r
plot1 <- DimPlot(pbmc3k.final)
plot2 <- FeatureScatter(pbmc3k.final, feature1 = "LYZ", feature2 = "CCL5")
# Combine two plots
plot1 + plot2
```

Example 112 (python):
```python
# Remove the legend from all plots
(plot1 + plot2) & NoLegend()
```

Example 113 (r):
```r
# Remove the legend from all plots
(plot1 + plot2) & NoLegend()
```

Example 114 (r):
```r
# Remove the legend from all plots
(plot1 + plot2) & NoLegend()
```

Example 115 (unknown):
```unknown
sessionInfo()
```

Example 116 (r):
```r
sessionInfo()
```

Example 117 (r):
```r
sessionInfo()
```

Example 118 (unknown):
```unknown
## R version 4.2.0 (2022-04-22)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.5 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/liblapack.so.3
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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       
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
##  [1] patchwork_1.1.2               ggplot2_3.4.1                
##  [3] thp1.eccite.SeuratData_3.1.5  stxBrain.SeuratData_0.1.1    
##  [5] ssHippo.SeuratData_3.1.4      pbmcsca.SeuratData_3.0.0     
##  [7] pbmcMultiome.SeuratData_0.1.2 pbmc3k.SeuratData_3.1.4      
##  [9] panc8.SeuratData_3.0.2        ifnb.SeuratData_3.1.0        
## [11] hcabm40k.SeuratData_3.0.0     bmcite.SeuratData_0.3.0      
## [13] SeuratData_0.2.2              SeuratObject_4.1.3           
## [15] Seurat_4.2.1.9001            
## 
## loaded via a namespace (and not attached):
##   [1] systemfonts_1.0.4      plyr_1.8.8             igraph_1.4.1          
##   [4] lazyeval_0.2.2         sp_1.6-0               splines_4.2.0         
##   [7] crosstalk_1.2.0        listenv_0.9.0          scattermore_0.8       
##  [10] digest_0.6.31          htmltools_0.5.5        fansi_1.0.4           
##  [13] magrittr_2.0.3         memoise_2.0.1          tensor_1.5            
##  [16] cluster_2.1.3          ROCR_1.0-11            limma_3.54.1          
##  [19] globals_0.16.2         matrixStats_0.63.0     pkgdown_2.0.7         
##  [22] spatstat.sparse_3.0-1  colorspace_2.1-0       rappdirs_0.3.3        
##  [25] ggrepel_0.9.3          textshaping_0.3.6      xfun_0.38             
##  [28] dplyr_1.1.1            crayon_1.5.2           jsonlite_1.8.4        
##  [31] progressr_0.13.0       spatstat.data_3.0-1    survival_3.3-1        
##  [34] zoo_1.8-11             glue_1.6.2             polyclip_1.10-4       
##  [37] gtable_0.3.3           leiden_0.4.3           future.apply_1.10.0   
##  [40] abind_1.4-5            scales_1.2.1           spatstat.random_3.1-4 
##  [43] miniUI_0.1.1.1         Rcpp_1.0.10            viridisLite_0.4.1     
##  [46] xtable_1.8-4           reticulate_1.28        ggmin_0.0.0.9000      
##  [49] htmlwidgets_1.6.2      httr_1.4.5             RColorBrewer_1.1-3    
##  [52] ellipsis_0.3.2         ica_1.0-3              farver_2.1.1          
##  [55] pkgconfig_2.0.3        sass_0.4.5             uwot_0.1.14           
##  [58] deldir_1.0-6           utf8_1.2.3             tidyselect_1.2.0      
##  [61] labeling_0.4.2         rlang_1.1.0            reshape2_1.4.4        
##  [64] later_1.3.0            munsell_0.5.0          tools_4.2.0           
##  [67] cachem_1.0.7           cli_3.6.1              generics_0.1.3        
##  [70] ggridges_0.5.4         evaluate_0.20          stringr_1.5.0         
##  [73] fastmap_1.1.1          yaml_2.3.7             ragg_1.2.5            
##  [76] goftest_1.2-3          knitr_1.42             fs_1.6.1              
##  [79] fitdistrplus_1.1-8     purrr_1.0.1            RANN_2.6.1            
##  [82] pbapply_1.7-0          future_1.32.0          nlme_3.1-157          
##  [85] mime_0.12              formatR_1.14           compiler_4.2.0        
##  [88] plotly_4.10.1          png_0.1-8              spatstat.utils_3.0-2  
##  [91] tibble_3.2.1           bslib_0.4.2            stringi_1.7.12        
##  [94] highr_0.10             desc_1.4.2             lattice_0.20-45       
##  [97] Matrix_1.5-3           vctrs_0.6.1            pillar_1.9.0          
## [100] lifecycle_1.0.3        spatstat.geom_3.1-0    lmtest_0.9-40         
## [103] jquerylib_0.1.4        RcppAnnoy_0.0.20       data.table_1.14.8     
## [106] cowplot_1.1.1          irlba_2.3.5.1          httpuv_1.6.9          
## [109] R6_2.5.1               promises_1.2.0.1       KernSmooth_2.23-20    
## [112] gridExtra_2.3          parallelly_1.35.0      codetools_0.2-18      
## [115] MASS_7.3-56            rprojroot_2.0.3        withr_2.5.0           
## [118] sctransform_0.3.5      parallel_4.2.0         grid_4.2.0            
## [121] tidyr_1.3.0            rmarkdown_2.21         Rtsne_0.16            
## [124] spatstat.explore_3.1-0 shiny_1.7.4
```

Example 119 (unknown):
```unknown
## R version 4.2.0 (2022-04-22)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.5 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/liblapack.so.3
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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       
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
##  [1] patchwork_1.1.2               ggplot2_3.4.1                
##  [3] thp1.eccite.SeuratData_3.1.5  stxBrain.SeuratData_0.1.1    
##  [5] ssHippo.SeuratData_3.1.4      pbmcsca.SeuratData_3.0.0     
##  [7] pbmcMultiome.SeuratData_0.1.2 pbmc3k.SeuratData_3.1.4      
##  [9] panc8.SeuratData_3.0.2        ifnb.SeuratData_3.1.0        
## [11] hcabm40k.SeuratData_3.0.0     bmcite.SeuratData_0.3.0      
## [13] SeuratData_0.2.2              SeuratObject_4.1.3           
## [15] Seurat_4.2.1.9001            
## 
## loaded via a namespace (and not attached):
##   [1] systemfonts_1.0.4      plyr_1.8.8             igraph_1.4.1          
##   [4] lazyeval_0.2.2         sp_1.6-0               splines_4.2.0         
##   [7] crosstalk_1.2.0        listenv_0.9.0          scattermore_0.8       
##  [10] digest_0.6.31          htmltools_0.5.5        fansi_1.0.4           
##  [13] magrittr_2.0.3         memoise_2.0.1          tensor_1.5            
##  [16] cluster_2.1.3          ROCR_1.0-11            limma_3.54.1          
##  [19] globals_0.16.2         matrixStats_0.63.0     pkgdown_2.0.7         
##  [22] spatstat.sparse_3.0-1  colorspace_2.1-0       rappdirs_0.3.3        
##  [25] ggrepel_0.9.3          textshaping_0.3.6      xfun_0.38             
##  [28] dplyr_1.1.1            crayon_1.5.2           jsonlite_1.8.4        
##  [31] progressr_0.13.0       spatstat.data_3.0-1    survival_3.3-1        
##  [34] zoo_1.8-11             glue_1.6.2             polyclip_1.10-4       
##  [37] gtable_0.3.3           leiden_0.4.3           future.apply_1.10.0   
##  [40] abind_1.4-5            scales_1.2.1           spatstat.random_3.1-4 
##  [43] miniUI_0.1.1.1         Rcpp_1.0.10            viridisLite_0.4.1     
##  [46] xtable_1.8-4           reticulate_1.28        ggmin_0.0.0.9000      
##  [49] htmlwidgets_1.6.2      httr_1.4.5             RColorBrewer_1.1-3    
##  [52] ellipsis_0.3.2         ica_1.0-3              farver_2.1.1          
##  [55] pkgconfig_2.0.3        sass_0.4.5             uwot_0.1.14           
##  [58] deldir_1.0-6           utf8_1.2.3             tidyselect_1.2.0      
##  [61] labeling_0.4.2         rlang_1.1.0            reshape2_1.4.4        
##  [64] later_1.3.0            munsell_0.5.0          tools_4.2.0           
##  [67] cachem_1.0.7           cli_3.6.1              generics_0.1.3        
##  [70] ggridges_0.5.4         evaluate_0.20          stringr_1.5.0         
##  [73] fastmap_1.1.1          yaml_2.3.7             ragg_1.2.5            
##  [76] goftest_1.2-3          knitr_1.42             fs_1.6.1              
##  [79] fitdistrplus_1.1-8     purrr_1.0.1            RANN_2.6.1            
##  [82] pbapply_1.7-0          future_1.32.0          nlme_3.1-157          
##  [85] mime_0.12              formatR_1.14           compiler_4.2.0        
##  [88] plotly_4.10.1          png_0.1-8              spatstat.utils_3.0-2  
##  [91] tibble_3.2.1           bslib_0.4.2            stringi_1.7.12        
##  [94] highr_0.10             desc_1.4.2             lattice_0.20-45       
##  [97] Matrix_1.5-3           vctrs_0.6.1            pillar_1.9.0          
## [100] lifecycle_1.0.3        spatstat.geom_3.1-0    lmtest_0.9-40         
## [103] jquerylib_0.1.4        RcppAnnoy_0.0.20       data.table_1.14.8     
## [106] cowplot_1.1.1          irlba_2.3.5.1          httpuv_1.6.9          
## [109] R6_2.5.1               promises_1.2.0.1       KernSmooth_2.23-20    
## [112] gridExtra_2.3          parallelly_1.35.0      codetools_0.2-18      
## [115] MASS_7.3-56            rprojroot_2.0.3        withr_2.5.0           
## [118] sctransform_0.3.5      parallel_4.2.0         grid_4.2.0            
## [121] tidyr_1.3.0            rmarkdown_2.21         Rtsne_0.16            
## [124] spatstat.explore_3.1-0 shiny_1.7.4
```

---

## Using sctransform in Seurat

**URL:** http://127.0.0.1:9173/seurat/v3.0/sctransform_vignette.html

**Contents:**
- Using sctransform in Seurat
    - Christoph Hafemeister & Rahul Satija
    - Compiled: 2019-06-24

This vignette shows how to use the sctransform wrapper in Seurat.

Install sctransform and Seurat v3.

Load data and create Seurat object

Apply sctransform normalization

Perform dimensionality reduction by PCA and UMAP embedding

Why can we choose more PCs when using sctransform?

In the standard Seurat workflow we focus on 10 PCs for this dataset, though we highlight that the results are similar with higher settings for this parameter. Interestingtly, we’ve found that when using sctransform, we often benefit by pushing this parameter even higher. We believe this is because the sctransform workflow performs more effective normalization, strongly removing technical effects from the data.

Even after standard log-normalization, variation in sequencing depth is still a confounding factor (see Figure 1), and this effect can subtly influence higher PCs. In sctransform, this effect is substantially mitigated (see Figure 3). This means that higher PCs are more likely to represent subtle, but biologically relevant, sources of heterogeneity – so including them may improve downstream analysis.

In addition, sctransform returns 3,000 variable features by default, instead of 2,000. The rationale is similar, the additional variable features are less likely to be driven by technical differences across cells, and instead may represent more subtle biological fluctuations. In general, we find that results produced with sctransform are less dependent on these parameters (indeed, we achieve nearly identical results when using all genes in the transcriptome, though this does reduce computational efficiency). This can help users generate more robust results, and in addition, enables the application of standard anlaysis pipelines with identical parameter settings that can quickly be applied to new datasets:

For example, the following code replicates the full end-to-end workflow, in a single command:

Where are normalized values stored for sctransform?

As described in our preprint, sctransform calculates a model of technical noise in scRNA-seq data using ‘regularized negative binomial regression’. The residuals for this model are normalized values, and can be positive or negative. Positive residuals for a given gene in a given cell indicate that we observed more UMIs than expected given the gene’s average expression in the population and cellular sequencing depth, while negative residuals indicate the converse.

The results of sctransfrom are stored in the “SCT” assay. You can learn more about multi-assay data and commands in Seurat in our vignette, command cheat sheet, or developer guide.

Users can individually annotate clusters based on canonical markers. However, the sctransform normalization reveals sharper biological distinctions compared to the standard Seurat workflow, in a few ways:

**Examples:**

Example 1 (r):
```r
install.packages("Seurat")
```

Example 2 (r):
```r
install.packages("Seurat")
```

Example 3 (r):
```r
library(Seurat)
library(ggplot2)
library(sctransform)
```

Example 4 (r):
```r
library(Seurat)
library(ggplot2)
library(sctransform)
```

Example 5 (r):
```r
pbmc_data <- Read10X(data.dir = "../data/pbmc3k/filtered_gene_bc_matrices/hg19/")
pbmc <- CreateSeuratObject(counts = pbmc_data)
```

Example 6 (r):
```r
pbmc_data <- Read10X(data.dir = "../data/pbmc3k/filtered_gene_bc_matrices/hg19/")
pbmc <- CreateSeuratObject(counts = pbmc_data)
```

Example 7 (unknown):
```unknown
NormalizeData
```

Example 8 (unknown):
```unknown
FindVariableFeatures
```

Example 9 (r):
```r
# store mitochondrial percentage in object meta data
pbmc <- PercentageFeatureSet(pbmc, pattern = "^MT-", col.name = "percent.mt")

# run sctransform
pbmc <- SCTransform(pbmc, vars.to.regress = "percent.mt", verbose = FALSE)
```

Example 10 (r):
```r
# store mitochondrial percentage in object meta data
pbmc <- PercentageFeatureSet(pbmc, pattern = "^MT-", col.name = "percent.mt")

# run sctransform
pbmc <- SCTransform(pbmc, vars.to.regress = "percent.mt", verbose = FALSE)
```

Example 11 (r):
```r
# These are now standard steps in the Seurat workflow for visualization and clustering
pbmc <- RunPCA(pbmc, verbose = FALSE)
pbmc <- RunUMAP(pbmc, dims = 1:30, verbose = FALSE)

pbmc <- FindNeighbors(pbmc, dims = 1:30, verbose = FALSE)
pbmc <- FindClusters(pbmc, verbose = FALSE)
DimPlot(pbmc, label = TRUE) + NoLegend()
```

Example 12 (r):
```r
# These are now standard steps in the Seurat workflow for visualization and clustering
pbmc <- RunPCA(pbmc, verbose = FALSE)
pbmc <- RunUMAP(pbmc, dims = 1:30, verbose = FALSE)

pbmc <- FindNeighbors(pbmc, dims = 1:30, verbose = FALSE)
pbmc <- FindClusters(pbmc, verbose = FALSE)
DimPlot(pbmc, label = TRUE) + NoLegend()
```

Example 13 (r):
```r
pbmc <- CreateSeuratObject(pbmc_data) %>% PercentageFeatureSet(pattern = "^MT-", col.name = "percent.mt") %>% 
    SCTransform(vars.to.regress = "percent.mt") %>% RunPCA() %>% FindNeighbors(dims = 1:30) %>% 
    RunUMAP(dims = 1:30) %>% FindClusters()
```

Example 14 (r):
```r
pbmc <- CreateSeuratObject(pbmc_data) %>% PercentageFeatureSet(pattern = "^MT-", col.name = "percent.mt") %>% 
    SCTransform(vars.to.regress = "percent.mt") %>% RunPCA() %>% FindNeighbors(dims = 1:30) %>% 
    RunUMAP(dims = 1:30) %>% FindClusters()
```

Example 15 (unknown):
```unknown
pbmc[["SCT"]]@scale.data
```

Example 16 (unknown):
```unknown
SCTransform
```

Example 17 (unknown):
```unknown
pbmc[["SCT"]]@counts
```

Example 18 (unknown):
```unknown
pbmc[["SCT"]]@data
```

Example 19 (r):
```r
# These are now standard steps in the Seurat workflow for visualization and clustering Visualize
# canonical marker genes as violin plots.
VlnPlot(pbmc, features = c("CD8A", "GZMK", "CCL5", "S100A4", "ANXA1", "CCR7", "ISG15", "CD3D"), 
    pt.size = 0.2, ncol = 4)
```

Example 20 (r):
```r
# These are now standard steps in the Seurat workflow for visualization and clustering Visualize
# canonical marker genes as violin plots.
VlnPlot(pbmc, features = c("CD8A", "GZMK", "CCL5", "S100A4", "ANXA1", "CCR7", "ISG15", "CD3D"), 
    pt.size = 0.2, ncol = 4)
```

Example 21 (r):
```r
# Visualize canonical marker genes on the sctransform embedding.
FeaturePlot(pbmc, features = c("CD8A", "GZMK", "CCL5", "S100A4", "ANXA1", "CCR7"), pt.size = 0.2, 
    ncol = 3)
```

Example 22 (r):
```r
# Visualize canonical marker genes on the sctransform embedding.
FeaturePlot(pbmc, features = c("CD8A", "GZMK", "CCL5", "S100A4", "ANXA1", "CCR7"), pt.size = 0.2, 
    ncol = 3)
```

Example 23 (r):
```r
FeaturePlot(pbmc, features = c("CD3D", "ISG15", "TCL1A", "FCER2", "XCL1", "FCGR3A"), pt.size = 0.2, 
    ncol = 3)
```

Example 24 (r):
```r
FeaturePlot(pbmc, features = c("CD3D", "ISG15", "TCL1A", "FCER2", "XCL1", "FCGR3A"), pt.size = 0.2, 
    ncol = 3)
```

---

## Interoperability between single-cell object formats

**URL:** http://127.0.0.1:9173/seurat/archive/v3.0/conversion_vignette/index.html

**Contents:**
- Interoperability between single-cell object formats
    - Compiled: 2019-06-24
  - Converting to/from SingleCellExperiment
  - Converting to/from loom
  - Converting to/from AnnData
- Acknowledgments

In this vignette, we demonstrate the ability to convert between Seurat objects, SingleCellExperiment objects, and anndata objects.

SingleCellExperiment is a class for storing single-cell experiment data, created by Davide Risso, Aaron Lun, and Keegan Korthauer, and is used by many Bioconductor analysis packages. Here we demonstrate converting the Seurat object produced in our 3k PBMC tutorial to SingleCellExperiment for use with Davis McCarthy’s scater package.

Seurat also allows conversion from SingleCellExperiment objects to Seurat objects; we demonstrate this on some publicly available data downloaded from a repository maintained by Martin Hemberg’s group.

The loom format is a file structure imposed on HDF5 files designed by Sten Linnarson’s group. It is designed to efficiently hold large single-cell genomics datasets. For more details about the loom format, please see the loom file format specification.

Seurat can also read in loom files connected via loomR into a Seurat object; we demonstrate this on a subset of the Mouse Brain Atlas created by the Linnarson lab.

For more details about interacting with loom files in R and Seurat, please see loomR on GitHub.

AnnData provides a Python class, created by Alex Wolf and Philipp Angerer, that can be used to store single-cell data. This data format is also use for storage in their Scanpy package for which we now support interoperability. Seurat has a new function ReadH5AD to read the data from the H5AD files that AnnData uses.

We currently do not support writing to an H5AD file at this time; however, transferring data from Seurat to Scanpy can be done via loom files

Many thanks to Davis McCarthy and Alex Wolf for their help in drafting the conversion functions.

**Examples:**

Example 1 (r):
```r
# install scater https://bioconductor.org/packages/release/bioc/html/scater.html
library(scater)
# install loomR from GitHub using the remotes package remotes::install_github(repo =
# 'mojaveazure/loomR', ref = 'develop')
library(loomR)
library(Seurat)
```

Example 2 (r):
```r
# install scater https://bioconductor.org/packages/release/bioc/html/scater.html
library(scater)
# install loomR from GitHub using the remotes package remotes::install_github(repo =
# 'mojaveazure/loomR', ref = 'develop')
library(loomR)
library(Seurat)
```

Example 3 (unknown):
```unknown
SingleCellExperiment
```

Example 4 (unknown):
```unknown
SingleCellExperiment
```

Example 5 (r):
```r
# download from satija lab https://www.dropbox.com/s/kwd3kcxkmpzqg6w/pbmc3k_final.rds?dl=0
pbmc <- readRDS(file = "../data/pbmc3k_final.rds")
pbmc.sce <- as.SingleCellExperiment(pbmc)
p1 <- plotExpression(pbmc.sce, features = "MS4A1", x = "ident") + theme(axis.text.x = element_text(angle = 45, 
    hjust = 1))
p2 <- plotPCA(pbmc.sce, colour_by = "ident")
CombinePlots(plots = list(p1, p2))
```

Example 6 (r):
```r
# download from satija lab https://www.dropbox.com/s/kwd3kcxkmpzqg6w/pbmc3k_final.rds?dl=0
pbmc <- readRDS(file = "../data/pbmc3k_final.rds")
pbmc.sce <- as.SingleCellExperiment(pbmc)
p1 <- plotExpression(pbmc.sce, features = "MS4A1", x = "ident") + theme(axis.text.x = element_text(angle = 45, 
    hjust = 1))
p2 <- plotPCA(pbmc.sce, colour_by = "ident")
CombinePlots(plots = list(p1, p2))
```

Example 7 (unknown):
```unknown
SingleCellExperiment
```

Example 8 (r):
```r
# download from hemberg lab
# https://scrnaseq-public-datasets.s3.amazonaws.com/scater-objects/manno_human.rds
manno <- readRDS(file = "../data/manno_human.rds")
manno <- runPCA(manno)
manno.seurat <- as.Seurat(manno, counts = "counts", data = "logcounts")
# gives the same results; but omits defaults provided in the last line
manno.seurat <- as.Seurat(manno)
Idents(manno.seurat) <- "cell_type1"
p1 <- DimPlot(manno.seurat, reduction = "PCA", group.by = "Source") + NoLegend()
p2 <- RidgePlot(manno.seurat, features = "ACTB", group.by = "Source")
CombinePlots(plots = list(p1, p2))
```

Example 9 (r):
```r
# download from hemberg lab
# https://scrnaseq-public-datasets.s3.amazonaws.com/scater-objects/manno_human.rds
manno <- readRDS(file = "../data/manno_human.rds")
manno <- runPCA(manno)
manno.seurat <- as.Seurat(manno, counts = "counts", data = "logcounts")
# gives the same results; but omits defaults provided in the last line
manno.seurat <- as.Seurat(manno)
Idents(manno.seurat) <- "cell_type1"
p1 <- DimPlot(manno.seurat, reduction = "PCA", group.by = "Source") + NoLegend()
p2 <- RidgePlot(manno.seurat, features = "ACTB", group.by = "Source")
CombinePlots(plots = list(p1, p2))
```

Example 10 (r):
```r
pbmc.loom <- as.loom(pbmc, filename = "../output/pbmc3k.loom", verbose = FALSE)
pbmc.loom
```

Example 11 (r):
```r
pbmc.loom <- as.loom(pbmc, filename = "../output/pbmc3k.loom", verbose = FALSE)
pbmc.loom
```

Example 12 (unknown):
```unknown
## Class: loom
## Filename: /home/butlera/online_workflows/output/pbmc3k.loom
## Access type: H5F_ACC_RDWR
## Attributes: version, chunks, LOOM_SPEC_VERSION, assay, last_modified
## Listing:
##        name    obj_type dataset.dims dataset.type_class
##   col_attrs   H5I_GROUP         <NA>               <NA>
##  col_graphs   H5I_GROUP         <NA>               <NA>
##      layers   H5I_GROUP         <NA>               <NA>
##      matrix H5I_DATASET 2638 x 13714          H5T_FLOAT
##   row_attrs   H5I_GROUP         <NA>               <NA>
##  row_graphs   H5I_GROUP         <NA>               <NA>
```

Example 13 (unknown):
```unknown
## Class: loom
## Filename: /home/butlera/online_workflows/output/pbmc3k.loom
## Access type: H5F_ACC_RDWR
## Attributes: version, chunks, LOOM_SPEC_VERSION, assay, last_modified
## Listing:
##        name    obj_type dataset.dims dataset.type_class
##   col_attrs   H5I_GROUP         <NA>               <NA>
##  col_graphs   H5I_GROUP         <NA>               <NA>
##      layers   H5I_GROUP         <NA>               <NA>
##      matrix H5I_DATASET 2638 x 13714          H5T_FLOAT
##   row_attrs   H5I_GROUP         <NA>               <NA>
##  row_graphs   H5I_GROUP         <NA>               <NA>
```

Example 14 (r):
```r
# Always remember to close loom files when done
pbmc.loom$close_all()
```

Example 15 (r):
```r
# Always remember to close loom files when done
pbmc.loom$close_all()
```

Example 16 (r):
```r
# download from linnarson lab
# https://storage.googleapis.com/linnarsson-lab-loom/l6_r1_immune_cells.loom
l6.immune <- connect(filename = "../data/l6_r1_immune_cells.loom", mode = "r")
l6.immune
```

Example 17 (r):
```r
# download from linnarson lab
# https://storage.googleapis.com/linnarsson-lab-loom/l6_r1_immune_cells.loom
l6.immune <- connect(filename = "../data/l6_r1_immune_cells.loom", mode = "r")
l6.immune
```

Example 18 (unknown):
```unknown
## Class: loom
## Filename: /home/butlera/online_workflows/data/l6_r1_immune_cells.loom
## Access type: H5F_ACC_RDONLY
## Attributes: CreationDate, last_modified
## Listing:
##        name    obj_type  dataset.dims dataset.type_class
##   col_attrs   H5I_GROUP          <NA>               <NA>
##  col_graphs   H5I_GROUP          <NA>               <NA>
##      layers   H5I_GROUP          <NA>               <NA>
##      matrix H5I_DATASET 14908 x 27998          H5T_FLOAT
##   row_attrs   H5I_GROUP          <NA>               <NA>
##  row_graphs   H5I_GROUP          <NA>               <NA>
```

Example 19 (unknown):
```unknown
## Class: loom
## Filename: /home/butlera/online_workflows/data/l6_r1_immune_cells.loom
## Access type: H5F_ACC_RDONLY
## Attributes: CreationDate, last_modified
## Listing:
##        name    obj_type  dataset.dims dataset.type_class
##   col_attrs   H5I_GROUP          <NA>               <NA>
##  col_graphs   H5I_GROUP          <NA>               <NA>
##      layers   H5I_GROUP          <NA>               <NA>
##      matrix H5I_DATASET 14908 x 27998          H5T_FLOAT
##   row_attrs   H5I_GROUP          <NA>               <NA>
##  row_graphs   H5I_GROUP          <NA>               <NA>
```

Example 20 (r):
```r
l6.seurat <- as.Seurat(l6.immune)
VlnPlot(l6.seurat, features = c("Sparc", "Ftl1", "Junb", "Ccl4"), ncol = 2, pt.size = 0.1)
```

Example 21 (r):
```r
l6.seurat <- as.Seurat(l6.immune)
VlnPlot(l6.seurat, features = c("Sparc", "Ftl1", "Junb", "Ccl4"), ncol = 2, pt.size = 0.1)
```

Example 22 (r):
```r
# Always remember to close loom files when done
l6.immune$close_all()
```

Example 23 (r):
```r
# Always remember to close loom files when done
l6.immune$close_all()
```

Example 24 (r):
```r
# download from satija lab https://www.dropbox.com/s/ngs3p8n2i8y33hj/pbmc3k.h5ad?dl=0
pbmc3k <- ReadH5AD(file = "../data/pbmc3k.h5ad")
Idents(pbmc3k) <- "louvain"
p1 <- DimPlot(pbmc3k, label = TRUE) + NoLegend()
p2 <- VlnPlot(pbmc3k, features = c("CST3", "NKG7", "PPBP"), combine = FALSE)
CombinePlots(plots = c(list(p1), p2), ncol = 2, legend = "none")
```

Example 25 (r):
```r
# download from satija lab https://www.dropbox.com/s/ngs3p8n2i8y33hj/pbmc3k.h5ad?dl=0
pbmc3k <- ReadH5AD(file = "../data/pbmc3k.h5ad")
Idents(pbmc3k) <- "louvain"
p1 <- DimPlot(pbmc3k, label = TRUE) + NoLegend()
p2 <- VlnPlot(pbmc3k, features = c("CST3", "NKG7", "PPBP"), combine = FALSE)
CombinePlots(plots = c(list(p1), p2), ncol = 2, legend = "none")
```

---

## Analysis, visualization, and integration of Visium HD spatial datasets with Seurat • Seurat

**URL:** http://127.0.0.1:9173/seurat/articles/multimodal_vignette/index.html

**Contents:**
- Using Seurat with multimodal data
    - Compiled: 2023-11-16
- Load in the data
- Setup a Seurat object, add the RNA and protein data
- Cluster cells on the basis of their scRNA-seq profiles
- Visualize multiple modalities side-by-side
- Identify cell surface markers for scRNA-seq clusters
- Additional visualizations of multimodal data
- Loading data from 10X multi-modal experiments
- Additional functionality for multimodal data in Seurat
- Contents

The ability to make simultaneous measurements of multiple data types from the same cell, known as multimodal analysis, represents a new and exciting frontier for single-cell genomics. For example, CITE-seq enables the simultaneous measurements of transcriptomes and cell-surface proteins from the same cell. Other exciting multimodal technologies, such as the 10x multiome kit allow for the paired measurements of cellular transcriptome and chromatin accessibility (i.e scRNA-seq+scATAC-seq). Other modalities that can be measured alongside cellular transcriptomes include genetic perturbations, cellular methylomes, and hashtag oligos from Cell Hashing. We have designed Seurat to enable for the seamless storage, analysis, and exploration of diverse multimodal single-cell datasets.

In this vignette, we present an introductory workflow for creating a multimodal Seurat object and performing an initial analysis. For example, we demonstrate how to cluster a CITE-seq dataset on the basis of the measured cellular transcriptomes, and subsequently discover cell surface proteins that are enriched in each cluster. We note that Seurat also enables more advanced techniques for the analysis of multimodal data, in particular the application of our Weighted Nearest Neighbors (WNN) approach that enables simultaneous clustering of cells based on a weighted combination of both modalities, and you can explore this functionality here.

Here, we analyze a dataset of 8,617 cord blood mononuclear cells (CBMCs), where transcriptomic measurements are paired with abundance estimates for 11 surface proteins, whose levels are quantified with DNA-barcoded antibodies. First, we load in two count matrices : one for the RNA measurements, and one for the antibody-derived tags (ADT). You can download the ADT file here and the RNA file here

Now we create a Seurat object, and add the ADT data as a second assay

The steps below represent a quick clustering of the PBMCs based on the scRNA-seq data. For more detail on individual steps or more advanced options, see our PBMC clustering guided tutorial here

Now that we have obtained clusters from scRNA-seq profiles, we can visualize the expression of either protein or RNA molecules in our dataset. Importantly, Seurat provides a couple ways to switch between modalities, and specify which modality you are interested in analyzing or visualizing. This is particularly important as, in some cases, the same feature can be present in multiple modalities - for example this dataset contains independent measurements of the B cell marker CD19 (both protein and RNA levels).

We can leverage our paired CITE-seq measurements to help annotate clusters derived from scRNA-seq, and to identify both protein and RNA markers.

Seurat is also able to analyze data from multimodal 10X experiments processed using CellRanger v3; as an example, we recreate the plots above using a dataset of 7,900 peripheral blood mononuclear cells (PBMC), freely available from 10X Genomics here.

Seurat v4 also includes additional functionality for the analysis, visualization, and integration of multimodal datasets. For more information, please explore the resources below:

Developed by Rahul Satija, Satija Lab and Collaborators.

Site built with pkgdown 2.0.7.

**Examples:**

Example 1 (unknown):
```unknown
vignettes/multimodal_vignette.Rmd
```

Example 2 (unknown):
```unknown
multimodal_vignette.Rmd
```

Example 3 (unknown):
```unknown
library(Seurat)
library(ggplot2)
library(patchwork)
```

Example 4 (r):
```r
library(Seurat)
library(ggplot2)
library(patchwork)
```

Example 5 (r):
```r
library(Seurat)
library(ggplot2)
library(patchwork)
```

Example 6 (python):
```python
# Load in the RNA UMI matrix

# Note that this dataset also contains ~5% of mouse cells, which we can use as negative
# controls for the protein measurements. For this reason, the gene expression matrix has
# HUMAN_ or MOUSE_ appended to the beginning of each gene.
cbmc.rna <- as.sparse(read.csv(file = "/brahms/shared/vignette-data/GSE100866_CBMC_8K_13AB_10X-RNA_umi.csv.gz",
    sep = ",", header = TRUE, row.names = 1))

# To make life a bit easier going forward, we're going to discard all but the top 100 most
# highly expressed mouse genes, and remove the 'HUMAN_' from the CITE-seq prefix
cbmc.rna <- CollapseSpeciesExpressionMatrix(cbmc.rna)

# Load in the ADT UMI matrix
cbmc.adt <- as.sparse(read.csv(file = "/brahms/shared/vignette-data/GSE100866_CBMC_8K_13AB_10X-ADT_umi.csv.gz",
    sep = ",", header = TRUE, row.names = 1))

# Note that since measurements were made in the same cells, the two matrices have identical
# column names
all.equal(colnames(cbmc.rna), colnames(cbmc.adt))
```

Example 7 (r):
```r
# Load in the RNA UMI matrix

# Note that this dataset also contains ~5% of mouse cells, which we can use as negative
# controls for the protein measurements. For this reason, the gene expression matrix has
# HUMAN_ or MOUSE_ appended to the beginning of each gene.
cbmc.rna <- as.sparse(read.csv(file = "/brahms/shared/vignette-data/GSE100866_CBMC_8K_13AB_10X-RNA_umi.csv.gz",
    sep = ",", header = TRUE, row.names = 1))

# To make life a bit easier going forward, we're going to discard all but the top 100 most
# highly expressed mouse genes, and remove the 'HUMAN_' from the CITE-seq prefix
cbmc.rna <- CollapseSpeciesExpressionMatrix(cbmc.rna)

# Load in the ADT UMI matrix
cbmc.adt <- as.sparse(read.csv(file = "/brahms/shared/vignette-data/GSE100866_CBMC_8K_13AB_10X-ADT_umi.csv.gz",
    sep = ",", header = TRUE, row.names = 1))

# Note that since measurements were made in the same cells, the two matrices have identical
# column names
all.equal(colnames(cbmc.rna), colnames(cbmc.adt))
```

Example 8 (r):
```r
# Load in the RNA UMI matrix

# Note that this dataset also contains ~5% of mouse cells, which we can use as negative
# controls for the protein measurements. For this reason, the gene expression matrix has
# HUMAN_ or MOUSE_ appended to the beginning of each gene.
cbmc.rna <- as.sparse(read.csv(file = "/brahms/shared/vignette-data/GSE100866_CBMC_8K_13AB_10X-RNA_umi.csv.gz",
    sep = ",", header = TRUE, row.names = 1))

# To make life a bit easier going forward, we're going to discard all but the top 100 most
# highly expressed mouse genes, and remove the 'HUMAN_' from the CITE-seq prefix
cbmc.rna <- CollapseSpeciesExpressionMatrix(cbmc.rna)

# Load in the ADT UMI matrix
cbmc.adt <- as.sparse(read.csv(file = "/brahms/shared/vignette-data/GSE100866_CBMC_8K_13AB_10X-ADT_umi.csv.gz",
    sep = ",", header = TRUE, row.names = 1))

# Note that since measurements were made in the same cells, the two matrices have identical
# column names
all.equal(colnames(cbmc.rna), colnames(cbmc.adt))
```

Example 9 (unknown):
```unknown
## [1] TRUE
```

Example 10 (unknown):
```unknown
## [1] TRUE
```

Example 11 (unknown):
```unknown
# creates a Seurat object based on the scRNA-seq data
cbmc <- CreateSeuratObject(counts = cbmc.rna)

# We can see that by default, the cbmc object contains an assay storing RNA measurement
Assays(cbmc)
```

Example 12 (r):
```r
# creates a Seurat object based on the scRNA-seq data
cbmc <- CreateSeuratObject(counts = cbmc.rna)

# We can see that by default, the cbmc object contains an assay storing RNA measurement
Assays(cbmc)
```

Example 13 (r):
```r
# creates a Seurat object based on the scRNA-seq data
cbmc <- CreateSeuratObject(counts = cbmc.rna)

# We can see that by default, the cbmc object contains an assay storing RNA measurement
Assays(cbmc)
```

Example 14 (unknown):
```unknown
## [1] "RNA"
```

Example 15 (unknown):
```unknown
## [1] "RNA"
```

Example 16 (unknown):
```unknown
# create a new assay to store ADT information
adt_assay <- CreateAssay5Object(counts = cbmc.adt)

# add this assay to the previously created Seurat object
cbmc[["ADT"]] <- adt_assay

# Validate that the object now contains multiple assays
Assays(cbmc)
```

Example 17 (r):
```r
# create a new assay to store ADT information
adt_assay <- CreateAssay5Object(counts = cbmc.adt)

# add this assay to the previously created Seurat object
cbmc[["ADT"]] <- adt_assay

# Validate that the object now contains multiple assays
Assays(cbmc)
```

Example 18 (r):
```r
# create a new assay to store ADT information
adt_assay <- CreateAssay5Object(counts = cbmc.adt)

# add this assay to the previously created Seurat object
cbmc[["ADT"]] <- adt_assay

# Validate that the object now contains multiple assays
Assays(cbmc)
```

Example 19 (unknown):
```unknown
## [1] "RNA" "ADT"
```

Example 20 (unknown):
```unknown
## [1] "RNA" "ADT"
```

Example 21 (unknown):
```unknown
# Extract a list of features measured in the ADT assay
rownames(cbmc[["ADT"]])
```

Example 22 (r):
```r
# Extract a list of features measured in the ADT assay
rownames(cbmc[["ADT"]])
```

Example 23 (r):
```r
# Extract a list of features measured in the ADT assay
rownames(cbmc[["ADT"]])
```

Example 24 (unknown):
```unknown
##  [1] "CD3"    "CD4"    "CD8"    "CD45RA" "CD56"   "CD16"   "CD10"   "CD11c" 
##  [9] "CD14"   "CD19"   "CD34"   "CCR5"   "CCR7"
```

Example 25 (unknown):
```unknown
##  [1] "CD3"    "CD4"    "CD8"    "CD45RA" "CD56"   "CD16"   "CD10"   "CD11c" 
##  [9] "CD14"   "CD19"   "CD34"   "CCR5"   "CCR7"
```

Example 26 (unknown):
```unknown
# Note that we can easily switch back and forth between the two assays to specify the default
# for visualization and analysis

# List the current default assay
DefaultAssay(cbmc)
```

Example 27 (r):
```r
# Note that we can easily switch back and forth between the two assays to specify the default
# for visualization and analysis

# List the current default assay
DefaultAssay(cbmc)
```

Example 28 (r):
```r
# Note that we can easily switch back and forth between the two assays to specify the default
# for visualization and analysis

# List the current default assay
DefaultAssay(cbmc)
```

Example 29 (unknown):
```unknown
## [1] "RNA"
```

Example 30 (unknown):
```unknown
## [1] "RNA"
```

Example 31 (unknown):
```unknown
# Switch the default to ADT
DefaultAssay(cbmc) <- "ADT"
DefaultAssay(cbmc)
```

Example 32 (r):
```r
# Switch the default to ADT
DefaultAssay(cbmc) <- "ADT"
DefaultAssay(cbmc)
```

Example 33 (r):
```r
# Switch the default to ADT
DefaultAssay(cbmc) <- "ADT"
DefaultAssay(cbmc)
```

Example 34 (unknown):
```unknown
## [1] "ADT"
```

Example 35 (unknown):
```unknown
## [1] "ADT"
```

Example 36 (unknown):
```unknown
# Note that all operations below are performed on the RNA assay Set and verify that the
# default assay is RNA
DefaultAssay(cbmc) <- "RNA"
DefaultAssay(cbmc)
```

Example 37 (r):
```r
# Note that all operations below are performed on the RNA assay Set and verify that the
# default assay is RNA
DefaultAssay(cbmc) <- "RNA"
DefaultAssay(cbmc)
```

Example 38 (r):
```r
# Note that all operations below are performed on the RNA assay Set and verify that the
# default assay is RNA
DefaultAssay(cbmc) <- "RNA"
DefaultAssay(cbmc)
```

Example 39 (unknown):
```unknown
## [1] "RNA"
```

Example 40 (unknown):
```unknown
## [1] "RNA"
```

Example 41 (unknown):
```unknown
# perform visualization and clustering steps
cbmc <- NormalizeData(cbmc)
cbmc <- FindVariableFeatures(cbmc)
cbmc <- ScaleData(cbmc)
cbmc <- RunPCA(cbmc, verbose = FALSE)
cbmc <- FindNeighbors(cbmc, dims = 1:30)
cbmc <- FindClusters(cbmc, resolution = 0.8, verbose = FALSE)
cbmc <- RunUMAP(cbmc, dims = 1:30)
DimPlot(cbmc, label = TRUE)
```

Example 42 (r):
```r
# perform visualization and clustering steps
cbmc <- NormalizeData(cbmc)
cbmc <- FindVariableFeatures(cbmc)
cbmc <- ScaleData(cbmc)
cbmc <- RunPCA(cbmc, verbose = FALSE)
cbmc <- FindNeighbors(cbmc, dims = 1:30)
cbmc <- FindClusters(cbmc, resolution = 0.8, verbose = FALSE)
cbmc <- RunUMAP(cbmc, dims = 1:30)
DimPlot(cbmc, label = TRUE)
```

Example 43 (r):
```r
# perform visualization and clustering steps
cbmc <- NormalizeData(cbmc)
cbmc <- FindVariableFeatures(cbmc)
cbmc <- ScaleData(cbmc)
cbmc <- RunPCA(cbmc, verbose = FALSE)
cbmc <- FindNeighbors(cbmc, dims = 1:30)
cbmc <- FindClusters(cbmc, resolution = 0.8, verbose = FALSE)
cbmc <- RunUMAP(cbmc, dims = 1:30)
DimPlot(cbmc, label = TRUE)
```

Example 44 (unknown):
```unknown
# Normalize ADT data,
DefaultAssay(cbmc) <- "ADT"
cbmc <- NormalizeData(cbmc, normalization.method = "CLR", margin = 2)
DefaultAssay(cbmc) <- "RNA"

# Note that the following command is an alternative but returns the same result
cbmc <- NormalizeData(cbmc, normalization.method = "CLR", margin = 2, assay = "ADT")

# Now, we will visualize CD14 levels for RNA and protein By setting the default assay, we can
# visualize one or the other
DefaultAssay(cbmc) <- "ADT"
p1 <- FeaturePlot(cbmc, "CD19", cols = c("lightgrey", "darkgreen")) + ggtitle("CD19 protein")
DefaultAssay(cbmc) <- "RNA"
p2 <- FeaturePlot(cbmc, "CD19") + ggtitle("CD19 RNA")

# place plots side-by-side
p1 | p2
```

Example 45 (r):
```r
# Normalize ADT data,
DefaultAssay(cbmc) <- "ADT"
cbmc <- NormalizeData(cbmc, normalization.method = "CLR", margin = 2)
DefaultAssay(cbmc) <- "RNA"

# Note that the following command is an alternative but returns the same result
cbmc <- NormalizeData(cbmc, normalization.method = "CLR", margin = 2, assay = "ADT")

# Now, we will visualize CD14 levels for RNA and protein By setting the default assay, we can
# visualize one or the other
DefaultAssay(cbmc) <- "ADT"
p1 <- FeaturePlot(cbmc, "CD19", cols = c("lightgrey", "darkgreen")) + ggtitle("CD19 protein")
DefaultAssay(cbmc) <- "RNA"
p2 <- FeaturePlot(cbmc, "CD19") + ggtitle("CD19 RNA")

# place plots side-by-side
p1 | p2
```

Example 46 (r):
```r
# Normalize ADT data,
DefaultAssay(cbmc) <- "ADT"
cbmc <- NormalizeData(cbmc, normalization.method = "CLR", margin = 2)
DefaultAssay(cbmc) <- "RNA"

# Note that the following command is an alternative but returns the same result
cbmc <- NormalizeData(cbmc, normalization.method = "CLR", margin = 2, assay = "ADT")

# Now, we will visualize CD14 levels for RNA and protein By setting the default assay, we can
# visualize one or the other
DefaultAssay(cbmc) <- "ADT"
p1 <- FeaturePlot(cbmc, "CD19", cols = c("lightgrey", "darkgreen")) + ggtitle("CD19 protein")
DefaultAssay(cbmc) <- "RNA"
p2 <- FeaturePlot(cbmc, "CD19") + ggtitle("CD19 RNA")

# place plots side-by-side
p1 | p2
```

Example 47 (unknown):
```unknown
# Alternately, we can use specific assay keys to specify a specific modality Identify the key
# for the RNA and protein assays
Key(cbmc[["RNA"]])
```

Example 48 (r):
```r
# Alternately, we can use specific assay keys to specify a specific modality Identify the key
# for the RNA and protein assays
Key(cbmc[["RNA"]])
```

Example 49 (r):
```r
# Alternately, we can use specific assay keys to specify a specific modality Identify the key
# for the RNA and protein assays
Key(cbmc[["RNA"]])
```

Example 50 (unknown):
```unknown
## [1] "rna_"
```

Example 51 (unknown):
```unknown
## [1] "rna_"
```

Example 52 (unknown):
```unknown
Key(cbmc[["ADT"]])
```

Example 53 (r):
```r
Key(cbmc[["ADT"]])
```

Example 54 (r):
```r
Key(cbmc[["ADT"]])
```

Example 55 (unknown):
```unknown
## [1] "adt_"
```

Example 56 (unknown):
```unknown
## [1] "adt_"
```

Example 57 (unknown):
```unknown
# Now, we can include the key in the feature name, which overrides the default assay
p1 <- FeaturePlot(cbmc, "adt_CD19", cols = c("lightgrey", "darkgreen")) + ggtitle("CD19 protein")
p2 <- FeaturePlot(cbmc, "rna_CD19") + ggtitle("CD19 RNA")
p1 | p2
```

Example 58 (r):
```r
# Now, we can include the key in the feature name, which overrides the default assay
p1 <- FeaturePlot(cbmc, "adt_CD19", cols = c("lightgrey", "darkgreen")) + ggtitle("CD19 protein")
p2 <- FeaturePlot(cbmc, "rna_CD19") + ggtitle("CD19 RNA")
p1 | p2
```

Example 59 (r):
```r
# Now, we can include the key in the feature name, which overrides the default assay
p1 <- FeaturePlot(cbmc, "adt_CD19", cols = c("lightgrey", "darkgreen")) + ggtitle("CD19 protein")
p2 <- FeaturePlot(cbmc, "rna_CD19") + ggtitle("CD19 RNA")
p1 | p2
```

Example 60 (unknown):
```unknown
# as we know that CD19 is a B cell marker, we can identify cluster 6 as expressing CD19 on the
# surface
VlnPlot(cbmc, "adt_CD19")
```

Example 61 (r):
```r
# as we know that CD19 is a B cell marker, we can identify cluster 6 as expressing CD19 on the
# surface
VlnPlot(cbmc, "adt_CD19")
```

Example 62 (r):
```r
# as we know that CD19 is a B cell marker, we can identify cluster 6 as expressing CD19 on the
# surface
VlnPlot(cbmc, "adt_CD19")
```

Example 63 (unknown):
```unknown
# we can also identify alternative protein and RNA markers for this cluster through
# differential expression
adt_markers <- FindMarkers(cbmc, ident.1 = 6, assay = "ADT")
rna_markers <- FindMarkers(cbmc, ident.1 = 6, assay = "RNA")

head(adt_markers)
```

Example 64 (r):
```r
# we can also identify alternative protein and RNA markers for this cluster through
# differential expression
adt_markers <- FindMarkers(cbmc, ident.1 = 6, assay = "ADT")
rna_markers <- FindMarkers(cbmc, ident.1 = 6, assay = "RNA")

head(adt_markers)
```

Example 65 (r):
```r
# we can also identify alternative protein and RNA markers for this cluster through
# differential expression
adt_markers <- FindMarkers(cbmc, ident.1 = 6, assay = "ADT")
rna_markers <- FindMarkers(cbmc, ident.1 = 6, assay = "RNA")

head(adt_markers)
```

Example 66 (unknown):
```unknown
##                p_val avg_log2FC pct.1 pct.2     p_val_adj
## CD19   2.067533e-215  2.5741873     1     1 2.687793e-214
## CD45RA 8.108073e-109  0.5300346     1     1 1.054049e-107
## CD4    1.123162e-107 -1.6707420     1     1 1.460110e-106
## CD14   7.212876e-106 -1.0332070     1     1 9.376739e-105
## CD3     1.639633e-87 -1.5823056     1     1  2.131523e-86
## CCR5    2.552859e-63  0.3753989     1     1  3.318716e-62
```

Example 67 (unknown):
```unknown
##                p_val avg_log2FC pct.1 pct.2     p_val_adj
## CD19   2.067533e-215  2.5741873     1     1 2.687793e-214
## CD45RA 8.108073e-109  0.5300346     1     1 1.054049e-107
## CD4    1.123162e-107 -1.6707420     1     1 1.460110e-106
## CD14   7.212876e-106 -1.0332070     1     1 9.376739e-105
## CD3     1.639633e-87 -1.5823056     1     1  2.131523e-86
## CCR5    2.552859e-63  0.3753989     1     1  3.318716e-62
```

Example 68 (unknown):
```unknown
head(rna_markers)
```

Example 69 (r):
```r
head(rna_markers)
```

Example 70 (r):
```r
head(rna_markers)
```

Example 71 (unknown):
```unknown
##       p_val avg_log2FC pct.1 pct.2 p_val_adj
## IGHM      0   6.660187 0.977 0.044         0
## CD79A     0   6.748356 0.965 0.045         0
## TCL1A     0   7.428099 0.904 0.028         0
## CD79B     0   5.525568 0.944 0.089         0
## IGHD      0   7.811884 0.857 0.015         0
## MS4A1     0   7.523215 0.851 0.016         0
```

Example 72 (unknown):
```unknown
##       p_val avg_log2FC pct.1 pct.2 p_val_adj
## IGHM      0   6.660187 0.977 0.044         0
## CD79A     0   6.748356 0.965 0.045         0
## TCL1A     0   7.428099 0.904 0.028         0
## CD79B     0   5.525568 0.944 0.089         0
## IGHD      0   7.811884 0.857 0.015         0
## MS4A1     0   7.523215 0.851 0.016         0
```

Example 73 (unknown):
```unknown
# Draw ADT scatter plots (like biaxial plots for FACS). Note that you can even 'gate' cells if
# desired by using HoverLocator and FeatureLocator
FeatureScatter(cbmc, feature1 = "adt_CD19", feature2 = "adt_CD3")
```

Example 74 (r):
```r
# Draw ADT scatter plots (like biaxial plots for FACS). Note that you can even 'gate' cells if
# desired by using HoverLocator and FeatureLocator
FeatureScatter(cbmc, feature1 = "adt_CD19", feature2 = "adt_CD3")
```

Example 75 (r):
```r
# Draw ADT scatter plots (like biaxial plots for FACS). Note that you can even 'gate' cells if
# desired by using HoverLocator and FeatureLocator
FeatureScatter(cbmc, feature1 = "adt_CD19", feature2 = "adt_CD3")
```

Example 76 (unknown):
```unknown
# view relationship between protein and RNA
FeatureScatter(cbmc, feature1 = "adt_CD3", feature2 = "rna_CD3E")
```

Example 77 (r):
```r
# view relationship between protein and RNA
FeatureScatter(cbmc, feature1 = "adt_CD3", feature2 = "rna_CD3E")
```

Example 78 (r):
```r
# view relationship between protein and RNA
FeatureScatter(cbmc, feature1 = "adt_CD3", feature2 = "rna_CD3E")
```

Example 79 (unknown):
```unknown
FeatureScatter(cbmc, feature1 = "adt_CD4", feature2 = "adt_CD8")
```

Example 80 (r):
```r
FeatureScatter(cbmc, feature1 = "adt_CD4", feature2 = "adt_CD8")
```

Example 81 (r):
```r
FeatureScatter(cbmc, feature1 = "adt_CD4", feature2 = "adt_CD8")
```

Example 82 (unknown):
```unknown
# Let's look at the raw (non-normalized) ADT counts. You can see the values are quite high,
# particularly in comparison to RNA values. This is due to the significantly higher protein
# copy number in cells, which significantly reduces 'drop-out' in ADT data
FeatureScatter(cbmc, feature1 = "adt_CD4", feature2 = "adt_CD8", slot = "counts")
```

Example 83 (r):
```r
# Let's look at the raw (non-normalized) ADT counts. You can see the values are quite high,
# particularly in comparison to RNA values. This is due to the significantly higher protein
# copy number in cells, which significantly reduces 'drop-out' in ADT data
FeatureScatter(cbmc, feature1 = "adt_CD4", feature2 = "adt_CD8", slot = "counts")
```

Example 84 (r):
```r
# Let's look at the raw (non-normalized) ADT counts. You can see the values are quite high,
# particularly in comparison to RNA values. This is due to the significantly higher protein
# copy number in cells, which significantly reduces 'drop-out' in ADT data
FeatureScatter(cbmc, feature1 = "adt_CD4", feature2 = "adt_CD8", slot = "counts")
```

Example 85 (unknown):
```unknown
pbmc10k.data <- Read10X(data.dir = "/brahms/shared/vignette-data/pbmc10k/filtered_feature_bc_matrix/")
rownames(x = pbmc10k.data[["Antibody Capture"]]) <- gsub(pattern = "_[control_]*TotalSeqB", replacement = "",
    x = rownames(x = pbmc10k.data[["Antibody Capture"]]))

pbmc10k <- CreateSeuratObject(counts = pbmc10k.data[["Gene Expression"]], min.cells = 3, min.features = 200)
pbmc10k <- NormalizeData(pbmc10k)
pbmc10k[["ADT"]] <- CreateAssayObject(pbmc10k.data[["Antibody Capture"]][, colnames(x = pbmc10k)])
pbmc10k <- NormalizeData(pbmc10k, assay = "ADT", normalization.method = "CLR")

plot1 <- FeatureScatter(pbmc10k, feature1 = "adt_CD19", feature2 = "adt_CD3", pt.size = 1)
plot2 <- FeatureScatter(pbmc10k, feature1 = "adt_CD4", feature2 = "adt_CD8a", pt.size = 1)
plot3 <- FeatureScatter(pbmc10k, feature1 = "adt_CD3", feature2 = "CD3E", pt.size = 1)
(plot1 + plot2 + plot3) & NoLegend()
```

Example 86 (r):
```r
pbmc10k.data <- Read10X(data.dir = "/brahms/shared/vignette-data/pbmc10k/filtered_feature_bc_matrix/")
rownames(x = pbmc10k.data[["Antibody Capture"]]) <- gsub(pattern = "_[control_]*TotalSeqB", replacement = "",
    x = rownames(x = pbmc10k.data[["Antibody Capture"]]))

pbmc10k <- CreateSeuratObject(counts = pbmc10k.data[["Gene Expression"]], min.cells = 3, min.features = 200)
pbmc10k <- NormalizeData(pbmc10k)
pbmc10k[["ADT"]] <- CreateAssayObject(pbmc10k.data[["Antibody Capture"]][, colnames(x = pbmc10k)])
pbmc10k <- NormalizeData(pbmc10k, assay = "ADT", normalization.method = "CLR")

plot1 <- FeatureScatter(pbmc10k, feature1 = "adt_CD19", feature2 = "adt_CD3", pt.size = 1)
plot2 <- FeatureScatter(pbmc10k, feature1 = "adt_CD4", feature2 = "adt_CD8a", pt.size = 1)
plot3 <- FeatureScatter(pbmc10k, feature1 = "adt_CD3", feature2 = "CD3E", pt.size = 1)
(plot1 + plot2 + plot3) & NoLegend()
```

Example 87 (r):
```r
pbmc10k.data <- Read10X(data.dir = "/brahms/shared/vignette-data/pbmc10k/filtered_feature_bc_matrix/")
rownames(x = pbmc10k.data[["Antibody Capture"]]) <- gsub(pattern = "_[control_]*TotalSeqB", replacement = "",
    x = rownames(x = pbmc10k.data[["Antibody Capture"]]))

pbmc10k <- CreateSeuratObject(counts = pbmc10k.data[["Gene Expression"]], min.cells = 3, min.features = 200)
pbmc10k <- NormalizeData(pbmc10k)
pbmc10k[["ADT"]] <- CreateAssayObject(pbmc10k.data[["Antibody Capture"]][, colnames(x = pbmc10k)])
pbmc10k <- NormalizeData(pbmc10k, assay = "ADT", normalization.method = "CLR")

plot1 <- FeatureScatter(pbmc10k, feature1 = "adt_CD19", feature2 = "adt_CD3", pt.size = 1)
plot2 <- FeatureScatter(pbmc10k, feature1 = "adt_CD4", feature2 = "adt_CD8a", pt.size = 1)
plot3 <- FeatureScatter(pbmc10k, feature1 = "adt_CD3", feature2 = "CD3E", pt.size = 1)
(plot1 + plot2 + plot3) & NoLegend()
```

Example 88 (unknown):
```unknown
plot <- FeatureScatter(cbmc, feature1 = "adt_CD19", feature2 = "adt_CD3") + NoLegend() + theme(axis.title = element_text(size = 18),
    legend.text = element_text(size = 18))
ggsave(filename = "../output/images/citeseq_plot.jpg", height = 7, width = 12, plot = plot, quality = 50)
```

Example 89 (r):
```r
plot <- FeatureScatter(cbmc, feature1 = "adt_CD19", feature2 = "adt_CD3") + NoLegend() + theme(axis.title = element_text(size = 18),
    legend.text = element_text(size = 18))
ggsave(filename = "../output/images/citeseq_plot.jpg", height = 7, width = 12, plot = plot, quality = 50)
```

Example 90 (r):
```r
plot <- FeatureScatter(cbmc, feature1 = "adt_CD19", feature2 = "adt_CD3") + NoLegend() + theme(axis.title = element_text(size = 18),
    legend.text = element_text(size = 18))
ggsave(filename = "../output/images/citeseq_plot.jpg", height = 7, width = 12, plot = plot, quality = 50)
```

Example 91 (unknown):
```unknown
sessionInfo()
```

Example 92 (r):
```r
sessionInfo()
```

Example 93 (r):
```r
sessionInfo()
```

Example 94 (unknown):
```unknown
## R version 4.2.2 Patched (2022-11-10 r83330)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.6 LTS
## 
## Matrix products: default
## BLAS:   /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.9.0
## LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.9.0
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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       
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
## [1] patchwork_1.1.3    ggplot2_3.4.4      Seurat_5.0.1  testthat_3.2.0    
## [5] SeuratObject_5.0.1 sp_2.1-1          
## 
## loaded via a namespace (and not attached):
##   [1] spam_2.10-0            systemfonts_1.0.4      plyr_1.8.9            
##   [4] igraph_1.5.1           lazyeval_0.2.2         splines_4.2.2         
##   [7] RcppHNSW_0.5.0         listenv_0.9.0          scattermore_1.2       
##  [10] usethis_2.1.6          digest_0.6.33          htmltools_0.5.6.1     
##  [13] fansi_1.0.5            magrittr_2.0.3         memoise_2.0.1         
##  [16] tensor_1.5             cluster_2.1.4          ROCR_1.0-11           
##  [19] limma_3.54.1           remotes_2.4.2.1        globals_0.16.2        
##  [22] matrixStats_1.0.0      R.utils_2.12.2         pkgdown_2.0.7         
##  [25] spatstat.sparse_3.0-3  prettyunits_1.2.0      colorspace_2.1-0      
##  [28] ggrepel_0.9.4          textshaping_0.3.6      xfun_0.40             
##  [31] dplyr_1.1.3            callr_3.7.3            crayon_1.5.2          
##  [34] jsonlite_1.8.7         progressr_0.14.0       spatstat.data_3.0-3   
##  [37] survival_3.5-7         zoo_1.8-12             glue_1.6.2            
##  [40] polyclip_1.10-6        gtable_0.3.4           leiden_0.4.3          
##  [43] pkgbuild_1.4.2         future.apply_1.11.0    abind_1.4-5           
##  [46] scales_1.2.1           spatstat.random_3.2-1  miniUI_0.1.1.1        
##  [49] Rcpp_1.0.11            viridisLite_0.4.2      xtable_1.8-4          
##  [52] reticulate_1.34.0      dotCall64_1.1-0        profvis_0.3.7         
##  [55] htmlwidgets_1.6.2      httr_1.4.7             RColorBrewer_1.1-3    
##  [58] ellipsis_0.3.2         ica_1.0-3              R.methodsS3_1.8.2     
##  [61] farver_2.1.1           urlchecker_1.0.1       pkgconfig_2.0.3       
##  [64] uwot_0.1.16            sass_0.4.7             deldir_1.0-9          
##  [67] utf8_1.2.4             labeling_0.4.3         tidyselect_1.2.0      
##  [70] rlang_1.1.1            reshape2_1.4.4         later_1.3.1           
##  [73] munsell_0.5.0          tools_4.2.2            cachem_1.0.8          
##  [76] cli_3.6.1              generics_0.1.3         devtools_2.4.5        
##  [79] ggridges_0.5.4         evaluate_0.22          stringr_1.5.0         
##  [82] fastmap_1.1.1          goftest_1.2-3          yaml_2.3.7            
##  [85] ragg_1.2.5             processx_3.8.2         knitr_1.45            
##  [88] fs_1.6.3               fitdistrplus_1.1-11    purrr_1.0.2           
##  [91] RANN_2.6.1             nlme_3.1-162           pbapply_1.7-2         
##  [94] future_1.33.0          mime_0.12              formatR_1.14          
##  [97] R.oo_1.25.0            ggrastr_1.0.1          brio_1.1.3            
## [100] compiler_4.2.2         rstudioapi_0.14        beeswarm_0.4.0        
## [103] plotly_4.10.3          png_0.1-8              spatstat.utils_3.0-4  
## [106] tibble_3.2.1           bslib_0.5.1            stringi_1.7.12        
## [109] highr_0.10             ps_1.7.5               desc_1.4.2            
## [112] RSpectra_0.16-1        lattice_0.21-9         Matrix_1.6-1.1        
## [115] vctrs_0.6.4            pillar_1.9.0           lifecycle_1.0.4       
## [118] spatstat.geom_3.2-7    lmtest_0.9-40          jquerylib_0.1.4       
## [121] RcppAnnoy_0.0.21       data.table_1.14.8      cowplot_1.1.1         
## [124] irlba_2.3.5.1          httpuv_1.6.12          R6_2.5.1              
## [127] promises_1.2.1         KernSmooth_2.23-22     gridExtra_2.3         
## [130] vipor_0.4.5            parallelly_1.36.0      sessioninfo_1.2.2     
## [133] codetools_0.2-19       fastDummies_1.7.3      MASS_7.3-58.2         
## [136] pkgload_1.3.3          rprojroot_2.0.4        withr_2.5.2           
## [139] presto_1.0.0           sctransform_0.4.1      parallel_4.2.2        
## [142] grid_4.2.2             tidyr_1.3.0            rmarkdown_2.25        
## [145] Rtsne_0.16             spatstat.explore_3.2-5 shiny_1.7.5.1         
## [148] ggbeeswarm_0.7.1
```

Example 95 (unknown):
```unknown
## R version 4.2.2 Patched (2022-11-10 r83330)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.6 LTS
## 
## Matrix products: default
## BLAS:   /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.9.0
## LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.9.0
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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       
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
## [1] patchwork_1.1.3    ggplot2_3.4.4      Seurat_5.0.1  testthat_3.2.0    
## [5] SeuratObject_5.0.1 sp_2.1-1          
## 
## loaded via a namespace (and not attached):
##   [1] spam_2.10-0            systemfonts_1.0.4      plyr_1.8.9            
##   [4] igraph_1.5.1           lazyeval_0.2.2         splines_4.2.2         
##   [7] RcppHNSW_0.5.0         listenv_0.9.0          scattermore_1.2       
##  [10] usethis_2.1.6          digest_0.6.33          htmltools_0.5.6.1     
##  [13] fansi_1.0.5            magrittr_2.0.3         memoise_2.0.1         
##  [16] tensor_1.5             cluster_2.1.4          ROCR_1.0-11           
##  [19] limma_3.54.1           remotes_2.4.2.1        globals_0.16.2        
##  [22] matrixStats_1.0.0      R.utils_2.12.2         pkgdown_2.0.7         
##  [25] spatstat.sparse_3.0-3  prettyunits_1.2.0      colorspace_2.1-0      
##  [28] ggrepel_0.9.4          textshaping_0.3.6      xfun_0.40             
##  [31] dplyr_1.1.3            callr_3.7.3            crayon_1.5.2          
##  [34] jsonlite_1.8.7         progressr_0.14.0       spatstat.data_3.0-3   
##  [37] survival_3.5-7         zoo_1.8-12             glue_1.6.2            
##  [40] polyclip_1.10-6        gtable_0.3.4           leiden_0.4.3          
##  [43] pkgbuild_1.4.2         future.apply_1.11.0    abind_1.4-5           
##  [46] scales_1.2.1           spatstat.random_3.2-1  miniUI_0.1.1.1        
##  [49] Rcpp_1.0.11            viridisLite_0.4.2      xtable_1.8-4          
##  [52] reticulate_1.34.0      dotCall64_1.1-0        profvis_0.3.7         
##  [55] htmlwidgets_1.6.2      httr_1.4.7             RColorBrewer_1.1-3    
##  [58] ellipsis_0.3.2         ica_1.0-3              R.methodsS3_1.8.2     
##  [61] farver_2.1.1           urlchecker_1.0.1       pkgconfig_2.0.3       
##  [64] uwot_0.1.16            sass_0.4.7             deldir_1.0-9          
##  [67] utf8_1.2.4             labeling_0.4.3         tidyselect_1.2.0      
##  [70] rlang_1.1.1            reshape2_1.4.4         later_1.3.1           
##  [73] munsell_0.5.0          tools_4.2.2            cachem_1.0.8          
##  [76] cli_3.6.1              generics_0.1.3         devtools_2.4.5        
##  [79] ggridges_0.5.4         evaluate_0.22          stringr_1.5.0         
##  [82] fastmap_1.1.1          goftest_1.2-3          yaml_2.3.7            
##  [85] ragg_1.2.5             processx_3.8.2         knitr_1.45            
##  [88] fs_1.6.3               fitdistrplus_1.1-11    purrr_1.0.2           
##  [91] RANN_2.6.1             nlme_3.1-162           pbapply_1.7-2         
##  [94] future_1.33.0          mime_0.12              formatR_1.14          
##  [97] R.oo_1.25.0            ggrastr_1.0.1          brio_1.1.3            
## [100] compiler_4.2.2         rstudioapi_0.14        beeswarm_0.4.0        
## [103] plotly_4.10.3          png_0.1-8              spatstat.utils_3.0-4  
## [106] tibble_3.2.1           bslib_0.5.1            stringi_1.7.12        
## [109] highr_0.10             ps_1.7.5               desc_1.4.2            
## [112] RSpectra_0.16-1        lattice_0.21-9         Matrix_1.6-1.1        
## [115] vctrs_0.6.4            pillar_1.9.0           lifecycle_1.0.4       
## [118] spatstat.geom_3.2-7    lmtest_0.9-40          jquerylib_0.1.4       
## [121] RcppAnnoy_0.0.21       data.table_1.14.8      cowplot_1.1.1         
## [124] irlba_2.3.5.1          httpuv_1.6.12          R6_2.5.1              
## [127] promises_1.2.1         KernSmooth_2.23-22     gridExtra_2.3         
## [130] vipor_0.4.5            parallelly_1.36.0      sessioninfo_1.2.2     
## [133] codetools_0.2-19       fastDummies_1.7.3      MASS_7.3-58.2         
## [136] pkgload_1.3.3          rprojroot_2.0.4        withr_2.5.2           
## [139] presto_1.0.0           sctransform_0.4.1      parallel_4.2.2        
## [142] grid_4.2.2             tidyr_1.3.0            rmarkdown_2.25        
## [145] Rtsne_0.16             spatstat.explore_3.2-5 shiny_1.7.5.1         
## [148] ggbeeswarm_0.7.1
```

---

## Demultiplexing with hashtag oligos (HTOs) • Seurat

**URL:** http://127.0.0.1:9173/seurat/archive/v4.3/hashing_vignette/index.html

**Contents:**
- Demultiplexing with hashtag oligos (HTOs)
    - Compiled: 2023-03-27
- 8-HTO dataset from human PBMCs
  - Basic setup
  - Adding HTO data as an independent assay
  - Demultiplex cells based on HTO enrichment
  - Visualize demultiplexing results
- 12-HTO dataset from four human cell lines
  - Create Seurat object, add HTO data and perform normalization
  - Demultiplex data
  - Visualize demultiplexing results
  - Visualize RNA clustering
- Contents

Developed in collaboration with the Technology Innovation Group at NYGC, Cell Hashing uses oligo-tagged antibodies against ubiquitously expressed surface proteins to place a “sample barcode” on each single cell, enabling different samples to be multiplexed together and run in a single experiment. For more information, please refer to this paper.This vignette will give a brief demonstration on how to work with data produced with Cell Hashing in Seurat. Applied to two datasets, we can successfully demultiplex cells to their the original sample-of-origin, and identify cross-sample doublets.The demultiplexing function HTODemux() implements the following procedure:We perform a k-medoid clustering on the normalized HTO values, which initially separates cells into K(# of samples)+1 clusters.We calculate a ‘negative’ distribution for HTO. For each HTO, we use the cluster with the lowest average value as the negative group.For each HTO, we fit a negative binomial distribution to the negative cluster. We use the 0.99 quantile of this distribution as a threshold.Based on these thresholds, each cell is classified as positive or negative for each HTO.Cells that are positive for more than one HTOs are annotated as doublets.8-HTO dataset from human PBMCsDataset description:Data represent peripheral blood mononuclear cells (PBMCs) from eight different donors.Cells from each donor are uniquely labeled, using CD45 as a hashing antibody.Samples were subsequently pooled, and run on a single lane of the the 10X Chromium v2 system.You can download the count matrices for RNA and HTO here, or the FASTQ files from GEOBasic setupLoad packages library(Seurat)Read in data # Load in the UMI matrix pbmc.umis <- readRDS("../data/pbmc_umi_mtx.rds") # For generating a hashtag count matrix from FASTQ files, please refer to # https://github.com/Hoohm/CITE-seq-Count. Load in the HTO count matrix pbmc.htos <- readRDS("../data/pbmc_hto_mtx.rds") # Select cell barcodes detected by both RNA and HTO In the example datasets we have already # filtered the cells for you, but perform this step for clarity. joint.bcs <- intersect(colnames(pbmc.umis), colnames(pbmc.htos)) # Subset RNA and HTO counts by joint cell barcodes pbmc.umis <- pbmc.umis[, joint.bcs] pbmc.htos <- as.matrix(pbmc.htos[, joint.bcs]) # Confirm that the HTO have the correct names rownames(pbmc.htos)## [1] "HTO_A" "HTO_B" "HTO_C" "HTO_D" "HTO_E" "HTO_F" "HTO_G" "HTO_H"Setup Seurat object and add in the HTO data # Setup Seurat object pbmc.hashtag <- CreateSeuratObject(counts = pbmc.umis) # Normalize RNA data with log normalization pbmc.hashtag <- NormalizeData(pbmc.hashtag) # Find and scale variable features pbmc.hashtag <- FindVariableFeatures(pbmc.hashtag, selection.method = "mean.var.plot") pbmc.hashtag <- ScaleData(pbmc.hashtag, features = VariableFeatures(pbmc.hashtag))Adding HTO data as an independent assayYou can read more about working with multi-modal data here # Add HTO data as a new assay independent from RNA pbmc.hashtag[["HTO"]] <- CreateAssayObject(counts = pbmc.htos) # Normalize HTO data, here we use centered log-ratio (CLR) transformation pbmc.hashtag <- NormalizeData(pbmc.hashtag, assay = "HTO", normalization.method = "CLR")Demultiplex cells based on HTO enrichmentHere we use the Seurat function HTODemux() to assign single cells back to their sample origins. # If you have a very large dataset we suggest using k_function = 'clara'. This is a k-medoid # clustering function for large applications You can also play with additional parameters (see # documentation for HTODemux()) to adjust the threshold for classification Here we are using # the default settings pbmc.hashtag <- HTODemux(pbmc.hashtag, assay = "HTO", positive.quantile = 0.99)Visualize demultiplexing resultsOutput from running HTODemux() is saved in the object metadata. We can visualize how many cells are classified as singlets, doublets and negative/ambiguous cells. # Global classification results table(pbmc.hashtag$HTO_classification.global)## ## Doublet Negative Singlet ## 2598 346 13972Visualize enrichment for selected HTOs with ridge plots # Group cells based on the max HTO signal Idents(pbmc.hashtag) <- "HTO_maxID" RidgePlot(pbmc.hashtag, assay = "HTO", features = rownames(pbmc.hashtag[["HTO"]])[1:2], ncol = 2)Visualize pairs of HTO signals to confirm mutual exclusivity in singlets FeatureScatter(pbmc.hashtag, feature1 = "hto_HTO-A", feature2 = "hto_HTO-B")Compare number of UMIs for singlets, doublets and negative cells Idents(pbmc.hashtag) <- "HTO_classification.global" VlnPlot(pbmc.hashtag, features = "nCount_RNA", pt.size = 0.1, log = TRUE)Generate a two dimensional tSNE embedding for HTOs.Here we are grouping cells by singlets and doublets for simplicity. # First, we will remove negative cells from the object pbmc.hashtag.subset <- subset(pbmc.hashtag, idents = "Negative", invert = TRUE) # Calculate a tSNE embedding of the HTO data DefaultAssay(pbmc.hashtag.subset) <- "HTO" pbmc.hashtag.subset <- ScaleData(pbmc.hashtag.subset, features = rownames(pbmc.hashtag.subset), verbose = FALSE) pbmc.hashtag.subset <- RunPCA(pbmc.hashtag.subset, features = rownames(pbmc.hashtag.subset), approx = FALSE) pbmc.hashtag.subset <- RunTSNE(pbmc.hashtag.subset, dims = 1:8, perplexity = 100) DimPlot(pbmc.hashtag.subset) # You can also visualize the more detailed classification result by running Idents(object) <- # 'HTO_classification' before plotting. Here, you can see that each of the small clouds on the # tSNE plot corresponds to one of the 28 possible doublet combinations.Create an HTO heatmap, based on Figure 1C in the Cell Hashing paper. # To increase the efficiency of plotting, you can subsample cells using the num.cells argument HTOHeatmap(pbmc.hashtag, assay = "HTO", ncells = 5000)Cluster and visualize cells using the usual scRNA-seq workflow, and examine for the potential presence of batch effects. # Extract the singlets pbmc.singlet <- subset(pbmc.hashtag, idents = "Singlet") # Select the top 1000 most variable features pbmc.singlet <- FindVariableFeatures(pbmc.singlet, selection.method = "mean.var.plot") # Scaling RNA data, we only scale the variable features here for efficiency pbmc.singlet <- ScaleData(pbmc.singlet, features = VariableFeatures(pbmc.singlet)) # Run PCA pbmc.singlet <- RunPCA(pbmc.singlet, features = VariableFeatures(pbmc.singlet)) # We select the top 10 PCs for clustering and tSNE based on PCElbowPlot pbmc.singlet <- FindNeighbors(pbmc.singlet, reduction = "pca", dims = 1:10) pbmc.singlet <- FindClusters(pbmc.singlet, resolution = 0.6, verbose = FALSE) pbmc.singlet <- RunTSNE(pbmc.singlet, reduction = "pca", dims = 1:10) # Projecting singlet identities on TSNE visualization DimPlot(pbmc.singlet, group.by = "HTO_classification")12-HTO dataset from four human cell linesDataset description:Data represent single cells collected from four cell lines: HEK, K562, KG1 and THP1Each cell line was further split into three samples (12 samples in total).Each sample was labeled with a hashing antibody mixture (CD29 and CD45), pooled, and run on a single lane of 10X.Based on this design, we should be able to detect doublets both across and within cell typesYou can download the count matrices for RNA and HTO here, and are available on GEO hereCreate Seurat object, add HTO data and perform normalization # Read in UMI count matrix for RNA hto12.umis <- readRDS("../data/hto12_umi_mtx.rds") # Read in HTO count matrix hto12.htos <- readRDS("../data/hto12_hto_mtx.rds") # Select cell barcodes detected in both RNA and HTO cells.use <- intersect(rownames(hto12.htos), colnames(hto12.umis)) # Create Seurat object and add HTO data hto12 <- CreateSeuratObject(counts = hto12.umis[, cells.use], min.features = 300) hto12[["HTO"]] <- CreateAssayObject(counts = t(x = hto12.htos[colnames(hto12), 1:12])) # Normalize data hto12 <- NormalizeData(hto12) hto12 <- NormalizeData(hto12, assay = "HTO", normalization.method = "CLR")Demultiplex data hto12 <- HTODemux(hto12, assay = "HTO", positive.quantile = 0.99)Visualize demultiplexing resultsDistribution of selected HTOs grouped by classification, displayed by ridge plots RidgePlot(hto12, assay = "HTO", features = c("HEK-A", "K562-B", "KG1-A", "THP1-C"), ncol = 2)Visualize HTO signals in a heatmap HTOHeatmap(hto12, assay = "HTO")Visualize RNA clusteringBelow, we cluster the cells using our standard scRNA-seq workflow. As expected we see four major clusters, corresponding to the cell linesIn addition, we see small clusters in between, representing mixed transcriptomes that are correctly annotated as doublets.We also see within-cell type doublets, that are (perhaps unsurprisingly) intermixed with singlets of the same cell type # Remove the negative cells hto12 <- subset(hto12, idents = "Negative", invert = TRUE) # Run PCA on most variable features hto12 <- FindVariableFeatures(hto12, selection.method = "mean.var.plot") hto12 <- ScaleData(hto12, features = VariableFeatures(hto12)) hto12 <- RunPCA(hto12) hto12 <- RunTSNE(hto12, dims = 1:5, perplexity = 100) DimPlot(hto12) + NoLegend()Session Info sessionInfo()## R version 4.2.0 (2022-04-22) ## Platform: x86_64-pc-linux-gnu (64-bit) ## Running under: Ubuntu 20.04.5 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/liblapack.so.3 ## ## locale: ## [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C ## [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8 ## [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 ## ## attached base packages: ## [1] stats graphics grDevices utils datasets methods base ## ## other attached packages: ## [1] SeuratObject_4.1.3 Seurat_4.3.0 ## ## loaded via a namespace (and not attached): ## [1] Rtsne_0.16 colorspace_2.1-0 deldir_1.0-6 ## [4] ellipsis_0.3.2 ggridges_0.5.4 rprojroot_2.0.3 ## [7] fs_1.6.1 spatstat.data_3.0-0 farver_2.1.1 ## [10] leiden_0.4.3 listenv_0.9.0 ggrepel_0.9.3 ## [13] fansi_1.0.4 codetools_0.2-18 splines_4.2.0 ## [16] cachem_1.0.7 knitr_1.42 polyclip_1.10-4 ## [19] jsonlite_1.8.4 ica_1.0-3 cluster_2.1.3 ## [22] png_0.1-8 uwot_0.1.14 spatstat.sparse_3.0-0 ## [25] shiny_1.7.4 sctransform_0.3.5 compiler_4.2.0 ## [28] httr_1.4.5 Matrix_1.5-3 fastmap_1.1.1 ## [31] lazyeval_0.2.2 cli_3.6.0 later_1.3.0 ## [34] formatR_1.14 htmltools_0.5.4 tools_4.2.0 ## [37] igraph_1.4.1 gtable_0.3.1 glue_1.6.2 ## [40] RANN_2.6.1 reshape2_1.4.4 dplyr_1.1.0 ## [43] Rcpp_1.0.10 scattermore_0.8 jquerylib_0.1.4 ## [46] pkgdown_2.0.7 vctrs_0.5.2 nlme_3.1-157 ## [49] spatstat.explore_3.0-6 progressr_0.13.0 lmtest_0.9-40 ## [52] spatstat.random_3.1-3 xfun_0.37 stringr_1.5.0 ## [55] globals_0.16.2 mime_0.12 miniUI_0.1.1.1 ## [58] lifecycle_1.0.3 irlba_2.3.5.1 goftest_1.2-3 ## [61] future_1.31.0 MASS_7.3-56 zoo_1.8-11 ## [64] scales_1.2.1 ragg_1.2.5 promises_1.2.0.1 ## [67] spatstat.utils_3.0-1 parallel_4.2.0 RColorBrewer_1.1-3 ## [70] yaml_2.3.7 memoise_2.0.1 reticulate_1.28 ## [73] pbapply_1.7-0 gridExtra_2.3 ggplot2_3.4.1 ## [76] sass_0.4.5 stringi_1.7.12 highr_0.10 ## [79] desc_1.4.2 rlang_1.0.6 pkgconfig_2.0.3 ## [82] systemfonts_1.0.4 matrixStats_0.63.0 evaluate_0.20 ## [85] lattice_0.20-45 tensor_1.5 ROCR_1.0-11 ## [88] purrr_1.0.1 labeling_0.4.2 patchwork_1.1.2 ## [91] htmlwidgets_1.6.1 cowplot_1.1.1 tidyselect_1.2.0 ## [94] parallelly_1.34.0 RcppAnnoy_0.0.20 plyr_1.8.8 ## [97] magrittr_2.0.3 R6_2.5.1 generics_0.1.3 ## [100] withr_2.5.0 pillar_1.8.1 fitdistrplus_1.1-8 ## [103] abind_1.4-5 survival_3.3-1 sp_1.6-0 ## [106] tibble_3.1.8 future.apply_1.10.0 KernSmooth_2.23-20 ## [109] utf8_1.2.3 spatstat.geom_3.0-6 plotly_4.10.1 ## [112] rmarkdown_2.20 grid_4.2.0 data.table_1.14.8 ## [115] digest_0.6.31 xtable_1.8-4 tidyr_1.3.0 ## [118] httpuv_1.6.9 textshaping_0.3.6 munsell_0.5.0 ## [121] viridisLite_0.4.1 bslib_0.4.2

This vignette will give a brief demonstration on how to work with data produced with Cell Hashing in Seurat. Applied to two datasets, we can successfully demultiplex cells to their the original sample-of-origin, and identify cross-sample doublets.The demultiplexing function HTODemux() implements the following procedure:We perform a k-medoid clustering on the normalized HTO values, which initially separates cells into K(# of samples)+1 clusters.We calculate a ‘negative’ distribution for HTO. For each HTO, we use the cluster with the lowest average value as the negative group.For each HTO, we fit a negative binomial distribution to the negative cluster. We use the 0.99 quantile of this distribution as a threshold.Based on these thresholds, each cell is classified as positive or negative for each HTO.Cells that are positive for more than one HTOs are annotated as doublets.8-HTO dataset from human PBMCsDataset description:Data represent peripheral blood mononuclear cells (PBMCs) from eight different donors.Cells from each donor are uniquely labeled, using CD45 as a hashing antibody.Samples were subsequently pooled, and run on a single lane of the the 10X Chromium v2 system.You can download the count matrices for RNA and HTO here, or the FASTQ files from GEOBasic setupLoad packages library(Seurat)Read in data # Load in the UMI matrix pbmc.umis <- readRDS("../data/pbmc_umi_mtx.rds") # For generating a hashtag count matrix from FASTQ files, please refer to # https://github.com/Hoohm/CITE-seq-Count. Load in the HTO count matrix pbmc.htos <- readRDS("../data/pbmc_hto_mtx.rds") # Select cell barcodes detected by both RNA and HTO In the example datasets we have already # filtered the cells for you, but perform this step for clarity. joint.bcs <- intersect(colnames(pbmc.umis), colnames(pbmc.htos)) # Subset RNA and HTO counts by joint cell barcodes pbmc.umis <- pbmc.umis[, joint.bcs] pbmc.htos <- as.matrix(pbmc.htos[, joint.bcs]) # Confirm that the HTO have the correct names rownames(pbmc.htos)## [1] "HTO_A" "HTO_B" "HTO_C" "HTO_D" "HTO_E" "HTO_F" "HTO_G" "HTO_H"Setup Seurat object and add in the HTO data # Setup Seurat object pbmc.hashtag <- CreateSeuratObject(counts = pbmc.umis) # Normalize RNA data with log normalization pbmc.hashtag <- NormalizeData(pbmc.hashtag) # Find and scale variable features pbmc.hashtag <- FindVariableFeatures(pbmc.hashtag, selection.method = "mean.var.plot") pbmc.hashtag <- ScaleData(pbmc.hashtag, features = VariableFeatures(pbmc.hashtag))Adding HTO data as an independent assayYou can read more about working with multi-modal data here # Add HTO data as a new assay independent from RNA pbmc.hashtag[["HTO"]] <- CreateAssayObject(counts = pbmc.htos) # Normalize HTO data, here we use centered log-ratio (CLR) transformation pbmc.hashtag <- NormalizeData(pbmc.hashtag, assay = "HTO", normalization.method = "CLR")Demultiplex cells based on HTO enrichmentHere we use the Seurat function HTODemux() to assign single cells back to their sample origins. # If you have a very large dataset we suggest using k_function = 'clara'. This is a k-medoid # clustering function for large applications You can also play with additional parameters (see # documentation for HTODemux()) to adjust the threshold for classification Here we are using # the default settings pbmc.hashtag <- HTODemux(pbmc.hashtag, assay = "HTO", positive.quantile = 0.99)Visualize demultiplexing resultsOutput from running HTODemux() is saved in the object metadata. We can visualize how many cells are classified as singlets, doublets and negative/ambiguous cells. # Global classification results table(pbmc.hashtag$HTO_classification.global)## ## Doublet Negative Singlet ## 2598 346 13972Visualize enrichment for selected HTOs with ridge plots # Group cells based on the max HTO signal Idents(pbmc.hashtag) <- "HTO_maxID" RidgePlot(pbmc.hashtag, assay = "HTO", features = rownames(pbmc.hashtag[["HTO"]])[1:2], ncol = 2)Visualize pairs of HTO signals to confirm mutual exclusivity in singlets FeatureScatter(pbmc.hashtag, feature1 = "hto_HTO-A", feature2 = "hto_HTO-B")Compare number of UMIs for singlets, doublets and negative cells Idents(pbmc.hashtag) <- "HTO_classification.global" VlnPlot(pbmc.hashtag, features = "nCount_RNA", pt.size = 0.1, log = TRUE)Generate a two dimensional tSNE embedding for HTOs.Here we are grouping cells by singlets and doublets for simplicity. # First, we will remove negative cells from the object pbmc.hashtag.subset <- subset(pbmc.hashtag, idents = "Negative", invert = TRUE) # Calculate a tSNE embedding of the HTO data DefaultAssay(pbmc.hashtag.subset) <- "HTO" pbmc.hashtag.subset <- ScaleData(pbmc.hashtag.subset, features = rownames(pbmc.hashtag.subset), verbose = FALSE) pbmc.hashtag.subset <- RunPCA(pbmc.hashtag.subset, features = rownames(pbmc.hashtag.subset), approx = FALSE) pbmc.hashtag.subset <- RunTSNE(pbmc.hashtag.subset, dims = 1:8, perplexity = 100) DimPlot(pbmc.hashtag.subset) # You can also visualize the more detailed classification result by running Idents(object) <- # 'HTO_classification' before plotting. Here, you can see that each of the small clouds on the # tSNE plot corresponds to one of the 28 possible doublet combinations.Create an HTO heatmap, based on Figure 1C in the Cell Hashing paper. # To increase the efficiency of plotting, you can subsample cells using the num.cells argument HTOHeatmap(pbmc.hashtag, assay = "HTO", ncells = 5000)Cluster and visualize cells using the usual scRNA-seq workflow, and examine for the potential presence of batch effects. # Extract the singlets pbmc.singlet <- subset(pbmc.hashtag, idents = "Singlet") # Select the top 1000 most variable features pbmc.singlet <- FindVariableFeatures(pbmc.singlet, selection.method = "mean.var.plot") # Scaling RNA data, we only scale the variable features here for efficiency pbmc.singlet <- ScaleData(pbmc.singlet, features = VariableFeatures(pbmc.singlet)) # Run PCA pbmc.singlet <- RunPCA(pbmc.singlet, features = VariableFeatures(pbmc.singlet)) # We select the top 10 PCs for clustering and tSNE based on PCElbowPlot pbmc.singlet <- FindNeighbors(pbmc.singlet, reduction = "pca", dims = 1:10) pbmc.singlet <- FindClusters(pbmc.singlet, resolution = 0.6, verbose = FALSE) pbmc.singlet <- RunTSNE(pbmc.singlet, reduction = "pca", dims = 1:10) # Projecting singlet identities on TSNE visualization DimPlot(pbmc.singlet, group.by = "HTO_classification")12-HTO dataset from four human cell linesDataset description:Data represent single cells collected from four cell lines: HEK, K562, KG1 and THP1Each cell line was further split into three samples (12 samples in total).Each sample was labeled with a hashing antibody mixture (CD29 and CD45), pooled, and run on a single lane of 10X.Based on this design, we should be able to detect doublets both across and within cell typesYou can download the count matrices for RNA and HTO here, and are available on GEO hereCreate Seurat object, add HTO data and perform normalization # Read in UMI count matrix for RNA hto12.umis <- readRDS("../data/hto12_umi_mtx.rds") # Read in HTO count matrix hto12.htos <- readRDS("../data/hto12_hto_mtx.rds") # Select cell barcodes detected in both RNA and HTO cells.use <- intersect(rownames(hto12.htos), colnames(hto12.umis)) # Create Seurat object and add HTO data hto12 <- CreateSeuratObject(counts = hto12.umis[, cells.use], min.features = 300) hto12[["HTO"]] <- CreateAssayObject(counts = t(x = hto12.htos[colnames(hto12), 1:12])) # Normalize data hto12 <- NormalizeData(hto12) hto12 <- NormalizeData(hto12, assay = "HTO", normalization.method = "CLR")Demultiplex data hto12 <- HTODemux(hto12, assay = "HTO", positive.quantile = 0.99)Visualize demultiplexing resultsDistribution of selected HTOs grouped by classification, displayed by ridge plots RidgePlot(hto12, assay = "HTO", features = c("HEK-A", "K562-B", "KG1-A", "THP1-C"), ncol = 2)Visualize HTO signals in a heatmap HTOHeatmap(hto12, assay = "HTO")Visualize RNA clusteringBelow, we cluster the cells using our standard scRNA-seq workflow. As expected we see four major clusters, corresponding to the cell linesIn addition, we see small clusters in between, representing mixed transcriptomes that are correctly annotated as doublets.We also see within-cell type doublets, that are (perhaps unsurprisingly) intermixed with singlets of the same cell type # Remove the negative cells hto12 <- subset(hto12, idents = "Negative", invert = TRUE) # Run PCA on most variable features hto12 <- FindVariableFeatures(hto12, selection.method = "mean.var.plot") hto12 <- ScaleData(hto12, features = VariableFeatures(hto12)) hto12 <- RunPCA(hto12) hto12 <- RunTSNE(hto12, dims = 1:5, perplexity = 100) DimPlot(hto12) + NoLegend()Session Info sessionInfo()## R version 4.2.0 (2022-04-22) ## Platform: x86_64-pc-linux-gnu (64-bit) ## Running under: Ubuntu 20.04.5 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/liblapack.so.3 ## ## locale: ## [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C ## [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8 ## [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 ## ## attached base packages: ## [1] stats graphics grDevices utils datasets methods base ## ## other attached packages: ## [1] SeuratObject_4.1.3 Seurat_4.3.0 ## ## loaded via a namespace (and not attached): ## [1] Rtsne_0.16 colorspace_2.1-0 deldir_1.0-6 ## [4] ellipsis_0.3.2 ggridges_0.5.4 rprojroot_2.0.3 ## [7] fs_1.6.1 spatstat.data_3.0-0 farver_2.1.1 ## [10] leiden_0.4.3 listenv_0.9.0 ggrepel_0.9.3 ## [13] fansi_1.0.4 codetools_0.2-18 splines_4.2.0 ## [16] cachem_1.0.7 knitr_1.42 polyclip_1.10-4 ## [19] jsonlite_1.8.4 ica_1.0-3 cluster_2.1.3 ## [22] png_0.1-8 uwot_0.1.14 spatstat.sparse_3.0-0 ## [25] shiny_1.7.4 sctransform_0.3.5 compiler_4.2.0 ## [28] httr_1.4.5 Matrix_1.5-3 fastmap_1.1.1 ## [31] lazyeval_0.2.2 cli_3.6.0 later_1.3.0 ## [34] formatR_1.14 htmltools_0.5.4 tools_4.2.0 ## [37] igraph_1.4.1 gtable_0.3.1 glue_1.6.2 ## [40] RANN_2.6.1 reshape2_1.4.4 dplyr_1.1.0 ## [43] Rcpp_1.0.10 scattermore_0.8 jquerylib_0.1.4 ## [46] pkgdown_2.0.7 vctrs_0.5.2 nlme_3.1-157 ## [49] spatstat.explore_3.0-6 progressr_0.13.0 lmtest_0.9-40 ## [52] spatstat.random_3.1-3 xfun_0.37 stringr_1.5.0 ## [55] globals_0.16.2 mime_0.12 miniUI_0.1.1.1 ## [58] lifecycle_1.0.3 irlba_2.3.5.1 goftest_1.2-3 ## [61] future_1.31.0 MASS_7.3-56 zoo_1.8-11 ## [64] scales_1.2.1 ragg_1.2.5 promises_1.2.0.1 ## [67] spatstat.utils_3.0-1 parallel_4.2.0 RColorBrewer_1.1-3 ## [70] yaml_2.3.7 memoise_2.0.1 reticulate_1.28 ## [73] pbapply_1.7-0 gridExtra_2.3 ggplot2_3.4.1 ## [76] sass_0.4.5 stringi_1.7.12 highr_0.10 ## [79] desc_1.4.2 rlang_1.0.6 pkgconfig_2.0.3 ## [82] systemfonts_1.0.4 matrixStats_0.63.0 evaluate_0.20 ## [85] lattice_0.20-45 tensor_1.5 ROCR_1.0-11 ## [88] purrr_1.0.1 labeling_0.4.2 patchwork_1.1.2 ## [91] htmlwidgets_1.6.1 cowplot_1.1.1 tidyselect_1.2.0 ## [94] parallelly_1.34.0 RcppAnnoy_0.0.20 plyr_1.8.8 ## [97] magrittr_2.0.3 R6_2.5.1 generics_0.1.3 ## [100] withr_2.5.0 pillar_1.8.1 fitdistrplus_1.1-8 ## [103] abind_1.4-5 survival_3.3-1 sp_1.6-0 ## [106] tibble_3.1.8 future.apply_1.10.0 KernSmooth_2.23-20 ## [109] utf8_1.2.3 spatstat.geom_3.0-6 plotly_4.10.1 ## [112] rmarkdown_2.20 grid_4.2.0 data.table_1.14.8 ## [115] digest_0.6.31 xtable_1.8-4 tidyr_1.3.0 ## [118] httpuv_1.6.9 textshaping_0.3.6 munsell_0.5.0 ## [121] viridisLite_0.4.1 bslib_0.4.2

Load packages library(Seurat)Read in data # Load in the UMI matrix pbmc.umis <- readRDS("../data/pbmc_umi_mtx.rds") # For generating a hashtag count matrix from FASTQ files, please refer to # https://github.com/Hoohm/CITE-seq-Count. Load in the HTO count matrix pbmc.htos <- readRDS("../data/pbmc_hto_mtx.rds") # Select cell barcodes detected by both RNA and HTO In the example datasets we have already # filtered the cells for you, but perform this step for clarity. joint.bcs <- intersect(colnames(pbmc.umis), colnames(pbmc.htos)) # Subset RNA and HTO counts by joint cell barcodes pbmc.umis <- pbmc.umis[, joint.bcs] pbmc.htos <- as.matrix(pbmc.htos[, joint.bcs]) # Confirm that the HTO have the correct names rownames(pbmc.htos)## [1] "HTO_A" "HTO_B" "HTO_C" "HTO_D" "HTO_E" "HTO_F" "HTO_G" "HTO_H"Setup Seurat object and add in the HTO data # Setup Seurat object pbmc.hashtag <- CreateSeuratObject(counts = pbmc.umis) # Normalize RNA data with log normalization pbmc.hashtag <- NormalizeData(pbmc.hashtag) # Find and scale variable features pbmc.hashtag <- FindVariableFeatures(pbmc.hashtag, selection.method = "mean.var.plot") pbmc.hashtag <- ScaleData(pbmc.hashtag, features = VariableFeatures(pbmc.hashtag))

Read in data # Load in the UMI matrix pbmc.umis <- readRDS("../data/pbmc_umi_mtx.rds") # For generating a hashtag count matrix from FASTQ files, please refer to # https://github.com/Hoohm/CITE-seq-Count. Load in the HTO count matrix pbmc.htos <- readRDS("../data/pbmc_hto_mtx.rds") # Select cell barcodes detected by both RNA and HTO In the example datasets we have already # filtered the cells for you, but perform this step for clarity. joint.bcs <- intersect(colnames(pbmc.umis), colnames(pbmc.htos)) # Subset RNA and HTO counts by joint cell barcodes pbmc.umis <- pbmc.umis[, joint.bcs] pbmc.htos <- as.matrix(pbmc.htos[, joint.bcs]) # Confirm that the HTO have the correct names rownames(pbmc.htos)## [1] "HTO_A" "HTO_B" "HTO_C" "HTO_D" "HTO_E" "HTO_F" "HTO_G" "HTO_H"Setup Seurat object and add in the HTO data # Setup Seurat object pbmc.hashtag <- CreateSeuratObject(counts = pbmc.umis) # Normalize RNA data with log normalization pbmc.hashtag <- NormalizeData(pbmc.hashtag) # Find and scale variable features pbmc.hashtag <- FindVariableFeatures(pbmc.hashtag, selection.method = "mean.var.plot") pbmc.hashtag <- ScaleData(pbmc.hashtag, features = VariableFeatures(pbmc.hashtag))

Setup Seurat object and add in the HTO data # Setup Seurat object pbmc.hashtag <- CreateSeuratObject(counts = pbmc.umis) # Normalize RNA data with log normalization pbmc.hashtag <- NormalizeData(pbmc.hashtag) # Find and scale variable features pbmc.hashtag <- FindVariableFeatures(pbmc.hashtag, selection.method = "mean.var.plot") pbmc.hashtag <- ScaleData(pbmc.hashtag, features = VariableFeatures(pbmc.hashtag))

You can read more about working with multi-modal data here # Add HTO data as a new assay independent from RNA pbmc.hashtag[["HTO"]] <- CreateAssayObject(counts = pbmc.htos) # Normalize HTO data, here we use centered log-ratio (CLR) transformation pbmc.hashtag <- NormalizeData(pbmc.hashtag, assay = "HTO", normalization.method = "CLR")

Here we use the Seurat function HTODemux() to assign single cells back to their sample origins. # If you have a very large dataset we suggest using k_function = 'clara'. This is a k-medoid # clustering function for large applications You can also play with additional parameters (see # documentation for HTODemux()) to adjust the threshold for classification Here we are using # the default settings pbmc.hashtag <- HTODemux(pbmc.hashtag, assay = "HTO", positive.quantile = 0.99)

Output from running HTODemux() is saved in the object metadata. We can visualize how many cells are classified as singlets, doublets and negative/ambiguous cells. # Global classification results table(pbmc.hashtag$HTO_classification.global)## ## Doublet Negative Singlet ## 2598 346 13972Visualize enrichment for selected HTOs with ridge plots # Group cells based on the max HTO signal Idents(pbmc.hashtag) <- "HTO_maxID" RidgePlot(pbmc.hashtag, assay = "HTO", features = rownames(pbmc.hashtag[["HTO"]])[1:2], ncol = 2)Visualize pairs of HTO signals to confirm mutual exclusivity in singlets FeatureScatter(pbmc.hashtag, feature1 = "hto_HTO-A", feature2 = "hto_HTO-B")Compare number of UMIs for singlets, doublets and negative cells Idents(pbmc.hashtag) <- "HTO_classification.global" VlnPlot(pbmc.hashtag, features = "nCount_RNA", pt.size = 0.1, log = TRUE)Generate a two dimensional tSNE embedding for HTOs.Here we are grouping cells by singlets and doublets for simplicity. # First, we will remove negative cells from the object pbmc.hashtag.subset <- subset(pbmc.hashtag, idents = "Negative", invert = TRUE) # Calculate a tSNE embedding of the HTO data DefaultAssay(pbmc.hashtag.subset) <- "HTO" pbmc.hashtag.subset <- ScaleData(pbmc.hashtag.subset, features = rownames(pbmc.hashtag.subset), verbose = FALSE) pbmc.hashtag.subset <- RunPCA(pbmc.hashtag.subset, features = rownames(pbmc.hashtag.subset), approx = FALSE) pbmc.hashtag.subset <- RunTSNE(pbmc.hashtag.subset, dims = 1:8, perplexity = 100) DimPlot(pbmc.hashtag.subset) # You can also visualize the more detailed classification result by running Idents(object) <- # 'HTO_classification' before plotting. Here, you can see that each of the small clouds on the # tSNE plot corresponds to one of the 28 possible doublet combinations.Create an HTO heatmap, based on Figure 1C in the Cell Hashing paper. # To increase the efficiency of plotting, you can subsample cells using the num.cells argument HTOHeatmap(pbmc.hashtag, assay = "HTO", ncells = 5000)Cluster and visualize cells using the usual scRNA-seq workflow, and examine for the potential presence of batch effects. # Extract the singlets pbmc.singlet <- subset(pbmc.hashtag, idents = "Singlet") # Select the top 1000 most variable features pbmc.singlet <- FindVariableFeatures(pbmc.singlet, selection.method = "mean.var.plot") # Scaling RNA data, we only scale the variable features here for efficiency pbmc.singlet <- ScaleData(pbmc.singlet, features = VariableFeatures(pbmc.singlet)) # Run PCA pbmc.singlet <- RunPCA(pbmc.singlet, features = VariableFeatures(pbmc.singlet)) # We select the top 10 PCs for clustering and tSNE based on PCElbowPlot pbmc.singlet <- FindNeighbors(pbmc.singlet, reduction = "pca", dims = 1:10) pbmc.singlet <- FindClusters(pbmc.singlet, resolution = 0.6, verbose = FALSE) pbmc.singlet <- RunTSNE(pbmc.singlet, reduction = "pca", dims = 1:10) # Projecting singlet identities on TSNE visualization DimPlot(pbmc.singlet, group.by = "HTO_classification")

Visualize enrichment for selected HTOs with ridge plots # Group cells based on the max HTO signal Idents(pbmc.hashtag) <- "HTO_maxID" RidgePlot(pbmc.hashtag, assay = "HTO", features = rownames(pbmc.hashtag[["HTO"]])[1:2], ncol = 2)Visualize pairs of HTO signals to confirm mutual exclusivity in singlets FeatureScatter(pbmc.hashtag, feature1 = "hto_HTO-A", feature2 = "hto_HTO-B")Compare number of UMIs for singlets, doublets and negative cells Idents(pbmc.hashtag) <- "HTO_classification.global" VlnPlot(pbmc.hashtag, features = "nCount_RNA", pt.size = 0.1, log = TRUE)Generate a two dimensional tSNE embedding for HTOs.Here we are grouping cells by singlets and doublets for simplicity. # First, we will remove negative cells from the object pbmc.hashtag.subset <- subset(pbmc.hashtag, idents = "Negative", invert = TRUE) # Calculate a tSNE embedding of the HTO data DefaultAssay(pbmc.hashtag.subset) <- "HTO" pbmc.hashtag.subset <- ScaleData(pbmc.hashtag.subset, features = rownames(pbmc.hashtag.subset), verbose = FALSE) pbmc.hashtag.subset <- RunPCA(pbmc.hashtag.subset, features = rownames(pbmc.hashtag.subset), approx = FALSE) pbmc.hashtag.subset <- RunTSNE(pbmc.hashtag.subset, dims = 1:8, perplexity = 100) DimPlot(pbmc.hashtag.subset) # You can also visualize the more detailed classification result by running Idents(object) <- # 'HTO_classification' before plotting. Here, you can see that each of the small clouds on the # tSNE plot corresponds to one of the 28 possible doublet combinations.Create an HTO heatmap, based on Figure 1C in the Cell Hashing paper. # To increase the efficiency of plotting, you can subsample cells using the num.cells argument HTOHeatmap(pbmc.hashtag, assay = "HTO", ncells = 5000)Cluster and visualize cells using the usual scRNA-seq workflow, and examine for the potential presence of batch effects. # Extract the singlets pbmc.singlet <- subset(pbmc.hashtag, idents = "Singlet") # Select the top 1000 most variable features pbmc.singlet <- FindVariableFeatures(pbmc.singlet, selection.method = "mean.var.plot") # Scaling RNA data, we only scale the variable features here for efficiency pbmc.singlet <- ScaleData(pbmc.singlet, features = VariableFeatures(pbmc.singlet)) # Run PCA pbmc.singlet <- RunPCA(pbmc.singlet, features = VariableFeatures(pbmc.singlet)) # We select the top 10 PCs for clustering and tSNE based on PCElbowPlot pbmc.singlet <- FindNeighbors(pbmc.singlet, reduction = "pca", dims = 1:10) pbmc.singlet <- FindClusters(pbmc.singlet, resolution = 0.6, verbose = FALSE) pbmc.singlet <- RunTSNE(pbmc.singlet, reduction = "pca", dims = 1:10) # Projecting singlet identities on TSNE visualization DimPlot(pbmc.singlet, group.by = "HTO_classification")

Visualize pairs of HTO signals to confirm mutual exclusivity in singlets FeatureScatter(pbmc.hashtag, feature1 = "hto_HTO-A", feature2 = "hto_HTO-B")Compare number of UMIs for singlets, doublets and negative cells Idents(pbmc.hashtag) <- "HTO_classification.global" VlnPlot(pbmc.hashtag, features = "nCount_RNA", pt.size = 0.1, log = TRUE)Generate a two dimensional tSNE embedding for HTOs.Here we are grouping cells by singlets and doublets for simplicity. # First, we will remove negative cells from the object pbmc.hashtag.subset <- subset(pbmc.hashtag, idents = "Negative", invert = TRUE) # Calculate a tSNE embedding of the HTO data DefaultAssay(pbmc.hashtag.subset) <- "HTO" pbmc.hashtag.subset <- ScaleData(pbmc.hashtag.subset, features = rownames(pbmc.hashtag.subset), verbose = FALSE) pbmc.hashtag.subset <- RunPCA(pbmc.hashtag.subset, features = rownames(pbmc.hashtag.subset), approx = FALSE) pbmc.hashtag.subset <- RunTSNE(pbmc.hashtag.subset, dims = 1:8, perplexity = 100) DimPlot(pbmc.hashtag.subset) # You can also visualize the more detailed classification result by running Idents(object) <- # 'HTO_classification' before plotting. Here, you can see that each of the small clouds on the # tSNE plot corresponds to one of the 28 possible doublet combinations.Create an HTO heatmap, based on Figure 1C in the Cell Hashing paper. # To increase the efficiency of plotting, you can subsample cells using the num.cells argument HTOHeatmap(pbmc.hashtag, assay = "HTO", ncells = 5000)Cluster and visualize cells using the usual scRNA-seq workflow, and examine for the potential presence of batch effects. # Extract the singlets pbmc.singlet <- subset(pbmc.hashtag, idents = "Singlet") # Select the top 1000 most variable features pbmc.singlet <- FindVariableFeatures(pbmc.singlet, selection.method = "mean.var.plot") # Scaling RNA data, we only scale the variable features here for efficiency pbmc.singlet <- ScaleData(pbmc.singlet, features = VariableFeatures(pbmc.singlet)) # Run PCA pbmc.singlet <- RunPCA(pbmc.singlet, features = VariableFeatures(pbmc.singlet)) # We select the top 10 PCs for clustering and tSNE based on PCElbowPlot pbmc.singlet <- FindNeighbors(pbmc.singlet, reduction = "pca", dims = 1:10) pbmc.singlet <- FindClusters(pbmc.singlet, resolution = 0.6, verbose = FALSE) pbmc.singlet <- RunTSNE(pbmc.singlet, reduction = "pca", dims = 1:10) # Projecting singlet identities on TSNE visualization DimPlot(pbmc.singlet, group.by = "HTO_classification")

Visualize pairs of HTO signals to confirm mutual exclusivity in singlets FeatureScatter(pbmc.hashtag, feature1 = "hto_HTO-A", feature2 = "hto_HTO-B")Compare number of UMIs for singlets, doublets and negative cells Idents(pbmc.hashtag) <- "HTO_classification.global" VlnPlot(pbmc.hashtag, features = "nCount_RNA", pt.size = 0.1, log = TRUE)Generate a two dimensional tSNE embedding for HTOs.Here we are grouping cells by singlets and doublets for simplicity. # First, we will remove negative cells from the object pbmc.hashtag.subset <- subset(pbmc.hashtag, idents = "Negative", invert = TRUE) # Calculate a tSNE embedding of the HTO data DefaultAssay(pbmc.hashtag.subset) <- "HTO" pbmc.hashtag.subset <- ScaleData(pbmc.hashtag.subset, features = rownames(pbmc.hashtag.subset), verbose = FALSE) pbmc.hashtag.subset <- RunPCA(pbmc.hashtag.subset, features = rownames(pbmc.hashtag.subset), approx = FALSE) pbmc.hashtag.subset <- RunTSNE(pbmc.hashtag.subset, dims = 1:8, perplexity = 100) DimPlot(pbmc.hashtag.subset) # You can also visualize the more detailed classification result by running Idents(object) <- # 'HTO_classification' before plotting. Here, you can see that each of the small clouds on the # tSNE plot corresponds to one of the 28 possible doublet combinations.Create an HTO heatmap, based on Figure 1C in the Cell Hashing paper. # To increase the efficiency of plotting, you can subsample cells using the num.cells argument HTOHeatmap(pbmc.hashtag, assay = "HTO", ncells = 5000)Cluster and visualize cells using the usual scRNA-seq workflow, and examine for the potential presence of batch effects. # Extract the singlets pbmc.singlet <- subset(pbmc.hashtag, idents = "Singlet") # Select the top 1000 most variable features pbmc.singlet <- FindVariableFeatures(pbmc.singlet, selection.method = "mean.var.plot") # Scaling RNA data, we only scale the variable features here for efficiency pbmc.singlet <- ScaleData(pbmc.singlet, features = VariableFeatures(pbmc.singlet)) # Run PCA pbmc.singlet <- RunPCA(pbmc.singlet, features = VariableFeatures(pbmc.singlet)) # We select the top 10 PCs for clustering and tSNE based on PCElbowPlot pbmc.singlet <- FindNeighbors(pbmc.singlet, reduction = "pca", dims = 1:10) pbmc.singlet <- FindClusters(pbmc.singlet, resolution = 0.6, verbose = FALSE) pbmc.singlet <- RunTSNE(pbmc.singlet, reduction = "pca", dims = 1:10) # Projecting singlet identities on TSNE visualization DimPlot(pbmc.singlet, group.by = "HTO_classification")

Compare number of UMIs for singlets, doublets and negative cells Idents(pbmc.hashtag) <- "HTO_classification.global" VlnPlot(pbmc.hashtag, features = "nCount_RNA", pt.size = 0.1, log = TRUE)Generate a two dimensional tSNE embedding for HTOs.Here we are grouping cells by singlets and doublets for simplicity. # First, we will remove negative cells from the object pbmc.hashtag.subset <- subset(pbmc.hashtag, idents = "Negative", invert = TRUE) # Calculate a tSNE embedding of the HTO data DefaultAssay(pbmc.hashtag.subset) <- "HTO" pbmc.hashtag.subset <- ScaleData(pbmc.hashtag.subset, features = rownames(pbmc.hashtag.subset), verbose = FALSE) pbmc.hashtag.subset <- RunPCA(pbmc.hashtag.subset, features = rownames(pbmc.hashtag.subset), approx = FALSE) pbmc.hashtag.subset <- RunTSNE(pbmc.hashtag.subset, dims = 1:8, perplexity = 100) DimPlot(pbmc.hashtag.subset) # You can also visualize the more detailed classification result by running Idents(object) <- # 'HTO_classification' before plotting. Here, you can see that each of the small clouds on the # tSNE plot corresponds to one of the 28 possible doublet combinations.Create an HTO heatmap, based on Figure 1C in the Cell Hashing paper. # To increase the efficiency of plotting, you can subsample cells using the num.cells argument HTOHeatmap(pbmc.hashtag, assay = "HTO", ncells = 5000)Cluster and visualize cells using the usual scRNA-seq workflow, and examine for the potential presence of batch effects. # Extract the singlets pbmc.singlet <- subset(pbmc.hashtag, idents = "Singlet") # Select the top 1000 most variable features pbmc.singlet <- FindVariableFeatures(pbmc.singlet, selection.method = "mean.var.plot") # Scaling RNA data, we only scale the variable features here for efficiency pbmc.singlet <- ScaleData(pbmc.singlet, features = VariableFeatures(pbmc.singlet)) # Run PCA pbmc.singlet <- RunPCA(pbmc.singlet, features = VariableFeatures(pbmc.singlet)) # We select the top 10 PCs for clustering and tSNE based on PCElbowPlot pbmc.singlet <- FindNeighbors(pbmc.singlet, reduction = "pca", dims = 1:10) pbmc.singlet <- FindClusters(pbmc.singlet, resolution = 0.6, verbose = FALSE) pbmc.singlet <- RunTSNE(pbmc.singlet, reduction = "pca", dims = 1:10) # Projecting singlet identities on TSNE visualization DimPlot(pbmc.singlet, group.by = "HTO_classification")

Compare number of UMIs for singlets, doublets and negative cells Idents(pbmc.hashtag) <- "HTO_classification.global" VlnPlot(pbmc.hashtag, features = "nCount_RNA", pt.size = 0.1, log = TRUE)Generate a two dimensional tSNE embedding for HTOs.Here we are grouping cells by singlets and doublets for simplicity. # First, we will remove negative cells from the object pbmc.hashtag.subset <- subset(pbmc.hashtag, idents = "Negative", invert = TRUE) # Calculate a tSNE embedding of the HTO data DefaultAssay(pbmc.hashtag.subset) <- "HTO" pbmc.hashtag.subset <- ScaleData(pbmc.hashtag.subset, features = rownames(pbmc.hashtag.subset), verbose = FALSE) pbmc.hashtag.subset <- RunPCA(pbmc.hashtag.subset, features = rownames(pbmc.hashtag.subset), approx = FALSE) pbmc.hashtag.subset <- RunTSNE(pbmc.hashtag.subset, dims = 1:8, perplexity = 100) DimPlot(pbmc.hashtag.subset) # You can also visualize the more detailed classification result by running Idents(object) <- # 'HTO_classification' before plotting. Here, you can see that each of the small clouds on the # tSNE plot corresponds to one of the 28 possible doublet combinations.Create an HTO heatmap, based on Figure 1C in the Cell Hashing paper. # To increase the efficiency of plotting, you can subsample cells using the num.cells argument HTOHeatmap(pbmc.hashtag, assay = "HTO", ncells = 5000)Cluster and visualize cells using the usual scRNA-seq workflow, and examine for the potential presence of batch effects. # Extract the singlets pbmc.singlet <- subset(pbmc.hashtag, idents = "Singlet") # Select the top 1000 most variable features pbmc.singlet <- FindVariableFeatures(pbmc.singlet, selection.method = "mean.var.plot") # Scaling RNA data, we only scale the variable features here for efficiency pbmc.singlet <- ScaleData(pbmc.singlet, features = VariableFeatures(pbmc.singlet)) # Run PCA pbmc.singlet <- RunPCA(pbmc.singlet, features = VariableFeatures(pbmc.singlet)) # We select the top 10 PCs for clustering and tSNE based on PCElbowPlot pbmc.singlet <- FindNeighbors(pbmc.singlet, reduction = "pca", dims = 1:10) pbmc.singlet <- FindClusters(pbmc.singlet, resolution = 0.6, verbose = FALSE) pbmc.singlet <- RunTSNE(pbmc.singlet, reduction = "pca", dims = 1:10) # Projecting singlet identities on TSNE visualization DimPlot(pbmc.singlet, group.by = "HTO_classification")

Generate a two dimensional tSNE embedding for HTOs.Here we are grouping cells by singlets and doublets for simplicity. # First, we will remove negative cells from the object pbmc.hashtag.subset <- subset(pbmc.hashtag, idents = "Negative", invert = TRUE) # Calculate a tSNE embedding of the HTO data DefaultAssay(pbmc.hashtag.subset) <- "HTO" pbmc.hashtag.subset <- ScaleData(pbmc.hashtag.subset, features = rownames(pbmc.hashtag.subset), verbose = FALSE) pbmc.hashtag.subset <- RunPCA(pbmc.hashtag.subset, features = rownames(pbmc.hashtag.subset), approx = FALSE) pbmc.hashtag.subset <- RunTSNE(pbmc.hashtag.subset, dims = 1:8, perplexity = 100) DimPlot(pbmc.hashtag.subset) # You can also visualize the more detailed classification result by running Idents(object) <- # 'HTO_classification' before plotting. Here, you can see that each of the small clouds on the # tSNE plot corresponds to one of the 28 possible doublet combinations.Create an HTO heatmap, based on Figure 1C in the Cell Hashing paper. # To increase the efficiency of plotting, you can subsample cells using the num.cells argument HTOHeatmap(pbmc.hashtag, assay = "HTO", ncells = 5000)Cluster and visualize cells using the usual scRNA-seq workflow, and examine for the potential presence of batch effects. # Extract the singlets pbmc.singlet <- subset(pbmc.hashtag, idents = "Singlet") # Select the top 1000 most variable features pbmc.singlet <- FindVariableFeatures(pbmc.singlet, selection.method = "mean.var.plot") # Scaling RNA data, we only scale the variable features here for efficiency pbmc.singlet <- ScaleData(pbmc.singlet, features = VariableFeatures(pbmc.singlet)) # Run PCA pbmc.singlet <- RunPCA(pbmc.singlet, features = VariableFeatures(pbmc.singlet)) # We select the top 10 PCs for clustering and tSNE based on PCElbowPlot pbmc.singlet <- FindNeighbors(pbmc.singlet, reduction = "pca", dims = 1:10) pbmc.singlet <- FindClusters(pbmc.singlet, resolution = 0.6, verbose = FALSE) pbmc.singlet <- RunTSNE(pbmc.singlet, reduction = "pca", dims = 1:10) # Projecting singlet identities on TSNE visualization DimPlot(pbmc.singlet, group.by = "HTO_classification")

Generate a two dimensional tSNE embedding for HTOs.Here we are grouping cells by singlets and doublets for simplicity. # First, we will remove negative cells from the object pbmc.hashtag.subset <- subset(pbmc.hashtag, idents = "Negative", invert = TRUE) # Calculate a tSNE embedding of the HTO data DefaultAssay(pbmc.hashtag.subset) <- "HTO" pbmc.hashtag.subset <- ScaleData(pbmc.hashtag.subset, features = rownames(pbmc.hashtag.subset), verbose = FALSE) pbmc.hashtag.subset <- RunPCA(pbmc.hashtag.subset, features = rownames(pbmc.hashtag.subset), approx = FALSE) pbmc.hashtag.subset <- RunTSNE(pbmc.hashtag.subset, dims = 1:8, perplexity = 100) DimPlot(pbmc.hashtag.subset) # You can also visualize the more detailed classification result by running Idents(object) <- # 'HTO_classification' before plotting. Here, you can see that each of the small clouds on the # tSNE plot corresponds to one of the 28 possible doublet combinations.Create an HTO heatmap, based on Figure 1C in the Cell Hashing paper. # To increase the efficiency of plotting, you can subsample cells using the num.cells argument HTOHeatmap(pbmc.hashtag, assay = "HTO", ncells = 5000)Cluster and visualize cells using the usual scRNA-seq workflow, and examine for the potential presence of batch effects. # Extract the singlets pbmc.singlet <- subset(pbmc.hashtag, idents = "Singlet") # Select the top 1000 most variable features pbmc.singlet <- FindVariableFeatures(pbmc.singlet, selection.method = "mean.var.plot") # Scaling RNA data, we only scale the variable features here for efficiency pbmc.singlet <- ScaleData(pbmc.singlet, features = VariableFeatures(pbmc.singlet)) # Run PCA pbmc.singlet <- RunPCA(pbmc.singlet, features = VariableFeatures(pbmc.singlet)) # We select the top 10 PCs for clustering and tSNE based on PCElbowPlot pbmc.singlet <- FindNeighbors(pbmc.singlet, reduction = "pca", dims = 1:10) pbmc.singlet <- FindClusters(pbmc.singlet, resolution = 0.6, verbose = FALSE) pbmc.singlet <- RunTSNE(pbmc.singlet, reduction = "pca", dims = 1:10) # Projecting singlet identities on TSNE visualization DimPlot(pbmc.singlet, group.by = "HTO_classification")

# You can also visualize the more detailed classification result by running Idents(object) <- # 'HTO_classification' before plotting. Here, you can see that each of the small clouds on the # tSNE plot corresponds to one of the 28 possible doublet combinations.Create an HTO heatmap, based on Figure 1C in the Cell Hashing paper. # To increase the efficiency of plotting, you can subsample cells using the num.cells argument HTOHeatmap(pbmc.hashtag, assay = "HTO", ncells = 5000)Cluster and visualize cells using the usual scRNA-seq workflow, and examine for the potential presence of batch effects. # Extract the singlets pbmc.singlet <- subset(pbmc.hashtag, idents = "Singlet") # Select the top 1000 most variable features pbmc.singlet <- FindVariableFeatures(pbmc.singlet, selection.method = "mean.var.plot") # Scaling RNA data, we only scale the variable features here for efficiency pbmc.singlet <- ScaleData(pbmc.singlet, features = VariableFeatures(pbmc.singlet)) # Run PCA pbmc.singlet <- RunPCA(pbmc.singlet, features = VariableFeatures(pbmc.singlet)) # We select the top 10 PCs for clustering and tSNE based on PCElbowPlot pbmc.singlet <- FindNeighbors(pbmc.singlet, reduction = "pca", dims = 1:10) pbmc.singlet <- FindClusters(pbmc.singlet, resolution = 0.6, verbose = FALSE) pbmc.singlet <- RunTSNE(pbmc.singlet, reduction = "pca", dims = 1:10) # Projecting singlet identities on TSNE visualization DimPlot(pbmc.singlet, group.by = "HTO_classification")

Create an HTO heatmap, based on Figure 1C in the Cell Hashing paper. # To increase the efficiency of plotting, you can subsample cells using the num.cells argument HTOHeatmap(pbmc.hashtag, assay = "HTO", ncells = 5000)Cluster and visualize cells using the usual scRNA-seq workflow, and examine for the potential presence of batch effects. # Extract the singlets pbmc.singlet <- subset(pbmc.hashtag, idents = "Singlet") # Select the top 1000 most variable features pbmc.singlet <- FindVariableFeatures(pbmc.singlet, selection.method = "mean.var.plot") # Scaling RNA data, we only scale the variable features here for efficiency pbmc.singlet <- ScaleData(pbmc.singlet, features = VariableFeatures(pbmc.singlet)) # Run PCA pbmc.singlet <- RunPCA(pbmc.singlet, features = VariableFeatures(pbmc.singlet)) # We select the top 10 PCs for clustering and tSNE based on PCElbowPlot pbmc.singlet <- FindNeighbors(pbmc.singlet, reduction = "pca", dims = 1:10) pbmc.singlet <- FindClusters(pbmc.singlet, resolution = 0.6, verbose = FALSE) pbmc.singlet <- RunTSNE(pbmc.singlet, reduction = "pca", dims = 1:10) # Projecting singlet identities on TSNE visualization DimPlot(pbmc.singlet, group.by = "HTO_classification")

Cluster and visualize cells using the usual scRNA-seq workflow, and examine for the potential presence of batch effects. # Extract the singlets pbmc.singlet <- subset(pbmc.hashtag, idents = "Singlet") # Select the top 1000 most variable features pbmc.singlet <- FindVariableFeatures(pbmc.singlet, selection.method = "mean.var.plot") # Scaling RNA data, we only scale the variable features here for efficiency pbmc.singlet <- ScaleData(pbmc.singlet, features = VariableFeatures(pbmc.singlet)) # Run PCA pbmc.singlet <- RunPCA(pbmc.singlet, features = VariableFeatures(pbmc.singlet)) # We select the top 10 PCs for clustering and tSNE based on PCElbowPlot pbmc.singlet <- FindNeighbors(pbmc.singlet, reduction = "pca", dims = 1:10) pbmc.singlet <- FindClusters(pbmc.singlet, resolution = 0.6, verbose = FALSE) pbmc.singlet <- RunTSNE(pbmc.singlet, reduction = "pca", dims = 1:10) # Projecting singlet identities on TSNE visualization DimPlot(pbmc.singlet, group.by = "HTO_classification")

Cluster and visualize cells using the usual scRNA-seq workflow, and examine for the potential presence of batch effects. # Extract the singlets pbmc.singlet <- subset(pbmc.hashtag, idents = "Singlet") # Select the top 1000 most variable features pbmc.singlet <- FindVariableFeatures(pbmc.singlet, selection.method = "mean.var.plot") # Scaling RNA data, we only scale the variable features here for efficiency pbmc.singlet <- ScaleData(pbmc.singlet, features = VariableFeatures(pbmc.singlet)) # Run PCA pbmc.singlet <- RunPCA(pbmc.singlet, features = VariableFeatures(pbmc.singlet)) # We select the top 10 PCs for clustering and tSNE based on PCElbowPlot pbmc.singlet <- FindNeighbors(pbmc.singlet, reduction = "pca", dims = 1:10) pbmc.singlet <- FindClusters(pbmc.singlet, resolution = 0.6, verbose = FALSE) pbmc.singlet <- RunTSNE(pbmc.singlet, reduction = "pca", dims = 1:10) # Projecting singlet identities on TSNE visualization DimPlot(pbmc.singlet, group.by = "HTO_classification")

Distribution of selected HTOs grouped by classification, displayed by ridge plots RidgePlot(hto12, assay = "HTO", features = c("HEK-A", "K562-B", "KG1-A", "THP1-C"), ncol = 2)Visualize HTO signals in a heatmap HTOHeatmap(hto12, assay = "HTO")

Visualize HTO signals in a heatmap HTOHeatmap(hto12, assay = "HTO")

Visualize HTO signals in a heatmap HTOHeatmap(hto12, assay = "HTO")

Session Info sessionInfo()## R version 4.2.0 (2022-04-22) ## Platform: x86_64-pc-linux-gnu (64-bit) ## Running under: Ubuntu 20.04.5 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/liblapack.so.3 ## ## locale: ## [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C ## [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8 ## [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 ## ## attached base packages: ## [1] stats graphics grDevices utils datasets methods base ## ## other attached packages: ## [1] SeuratObject_4.1.3 Seurat_4.3.0 ## ## loaded via a namespace (and not attached): ## [1] Rtsne_0.16 colorspace_2.1-0 deldir_1.0-6 ## [4] ellipsis_0.3.2 ggridges_0.5.4 rprojroot_2.0.3 ## [7] fs_1.6.1 spatstat.data_3.0-0 farver_2.1.1 ## [10] leiden_0.4.3 listenv_0.9.0 ggrepel_0.9.3 ## [13] fansi_1.0.4 codetools_0.2-18 splines_4.2.0 ## [16] cachem_1.0.7 knitr_1.42 polyclip_1.10-4 ## [19] jsonlite_1.8.4 ica_1.0-3 cluster_2.1.3 ## [22] png_0.1-8 uwot_0.1.14 spatstat.sparse_3.0-0 ## [25] shiny_1.7.4 sctransform_0.3.5 compiler_4.2.0 ## [28] httr_1.4.5 Matrix_1.5-3 fastmap_1.1.1 ## [31] lazyeval_0.2.2 cli_3.6.0 later_1.3.0 ## [34] formatR_1.14 htmltools_0.5.4 tools_4.2.0 ## [37] igraph_1.4.1 gtable_0.3.1 glue_1.6.2 ## [40] RANN_2.6.1 reshape2_1.4.4 dplyr_1.1.0 ## [43] Rcpp_1.0.10 scattermore_0.8 jquerylib_0.1.4 ## [46] pkgdown_2.0.7 vctrs_0.5.2 nlme_3.1-157 ## [49] spatstat.explore_3.0-6 progressr_0.13.0 lmtest_0.9-40 ## [52] spatstat.random_3.1-3 xfun_0.37 stringr_1.5.0 ## [55] globals_0.16.2 mime_0.12 miniUI_0.1.1.1 ## [58] lifecycle_1.0.3 irlba_2.3.5.1 goftest_1.2-3 ## [61] future_1.31.0 MASS_7.3-56 zoo_1.8-11 ## [64] scales_1.2.1 ragg_1.2.5 promises_1.2.0.1 ## [67] spatstat.utils_3.0-1 parallel_4.2.0 RColorBrewer_1.1-3 ## [70] yaml_2.3.7 memoise_2.0.1 reticulate_1.28 ## [73] pbapply_1.7-0 gridExtra_2.3 ggplot2_3.4.1 ## [76] sass_0.4.5 stringi_1.7.12 highr_0.10 ## [79] desc_1.4.2 rlang_1.0.6 pkgconfig_2.0.3 ## [82] systemfonts_1.0.4 matrixStats_0.63.0 evaluate_0.20 ## [85] lattice_0.20-45 tensor_1.5 ROCR_1.0-11 ## [88] purrr_1.0.1 labeling_0.4.2 patchwork_1.1.2 ## [91] htmlwidgets_1.6.1 cowplot_1.1.1 tidyselect_1.2.0 ## [94] parallelly_1.34.0 RcppAnnoy_0.0.20 plyr_1.8.8 ## [97] magrittr_2.0.3 R6_2.5.1 generics_0.1.3 ## [100] withr_2.5.0 pillar_1.8.1 fitdistrplus_1.1-8 ## [103] abind_1.4-5 survival_3.3-1 sp_1.6-0 ## [106] tibble_3.1.8 future.apply_1.10.0 KernSmooth_2.23-20 ## [109] utf8_1.2.3 spatstat.geom_3.0-6 plotly_4.10.1 ## [112] rmarkdown_2.20 grid_4.2.0 data.table_1.14.8 ## [115] digest_0.6.31 xtable_1.8-4 tidyr_1.3.0 ## [118] httpuv_1.6.9 textshaping_0.3.6 munsell_0.5.0 ## [121] viridisLite_0.4.1 bslib_0.4.2

sessionInfo()## R version 4.2.0 (2022-04-22) ## Platform: x86_64-pc-linux-gnu (64-bit) ## Running under: Ubuntu 20.04.5 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/liblapack.so.3 ## ## locale: ## [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C ## [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8 ## [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 ## ## attached base packages: ## [1] stats graphics grDevices utils datasets methods base ## ## other attached packages: ## [1] SeuratObject_4.1.3 Seurat_4.3.0 ## ## loaded via a namespace (and not attached): ## [1] Rtsne_0.16 colorspace_2.1-0 deldir_1.0-6 ## [4] ellipsis_0.3.2 ggridges_0.5.4 rprojroot_2.0.3 ## [7] fs_1.6.1 spatstat.data_3.0-0 farver_2.1.1 ## [10] leiden_0.4.3 listenv_0.9.0 ggrepel_0.9.3 ## [13] fansi_1.0.4 codetools_0.2-18 splines_4.2.0 ## [16] cachem_1.0.7 knitr_1.42 polyclip_1.10-4 ## [19] jsonlite_1.8.4 ica_1.0-3 cluster_2.1.3 ## [22] png_0.1-8 uwot_0.1.14 spatstat.sparse_3.0-0 ## [25] shiny_1.7.4 sctransform_0.3.5 compiler_4.2.0 ## [28] httr_1.4.5 Matrix_1.5-3 fastmap_1.1.1 ## [31] lazyeval_0.2.2 cli_3.6.0 later_1.3.0 ## [34] formatR_1.14 htmltools_0.5.4 tools_4.2.0 ## [37] igraph_1.4.1 gtable_0.3.1 glue_1.6.2 ## [40] RANN_2.6.1 reshape2_1.4.4 dplyr_1.1.0 ## [43] Rcpp_1.0.10 scattermore_0.8 jquerylib_0.1.4 ## [46] pkgdown_2.0.7 vctrs_0.5.2 nlme_3.1-157 ## [49] spatstat.explore_3.0-6 progressr_0.13.0 lmtest_0.9-40 ## [52] spatstat.random_3.1-3 xfun_0.37 stringr_1.5.0 ## [55] globals_0.16.2 mime_0.12 miniUI_0.1.1.1 ## [58] lifecycle_1.0.3 irlba_2.3.5.1 goftest_1.2-3 ## [61] future_1.31.0 MASS_7.3-56 zoo_1.8-11 ## [64] scales_1.2.1 ragg_1.2.5 promises_1.2.0.1 ## [67] spatstat.utils_3.0-1 parallel_4.2.0 RColorBrewer_1.1-3 ## [70] yaml_2.3.7 memoise_2.0.1 reticulate_1.28 ## [73] pbapply_1.7-0 gridExtra_2.3 ggplot2_3.4.1 ## [76] sass_0.4.5 stringi_1.7.12 highr_0.10 ## [79] desc_1.4.2 rlang_1.0.6 pkgconfig_2.0.3 ## [82] systemfonts_1.0.4 matrixStats_0.63.0 evaluate_0.20 ## [85] lattice_0.20-45 tensor_1.5 ROCR_1.0-11 ## [88] purrr_1.0.1 labeling_0.4.2 patchwork_1.1.2 ## [91] htmlwidgets_1.6.1 cowplot_1.1.1 tidyselect_1.2.0 ## [94] parallelly_1.34.0 RcppAnnoy_0.0.20 plyr_1.8.8 ## [97] magrittr_2.0.3 R6_2.5.1 generics_0.1.3 ## [100] withr_2.5.0 pillar_1.8.1 fitdistrplus_1.1-8 ## [103] abind_1.4-5 survival_3.3-1 sp_1.6-0 ## [106] tibble_3.1.8 future.apply_1.10.0 KernSmooth_2.23-20 ## [109] utf8_1.2.3 spatstat.geom_3.0-6 plotly_4.10.1 ## [112] rmarkdown_2.20 grid_4.2.0 data.table_1.14.8 ## [115] digest_0.6.31 xtable_1.8-4 tidyr_1.3.0 ## [118] httpuv_1.6.9 textshaping_0.3.6 munsell_0.5.0 ## [121] viridisLite_0.4.1 bslib_0.4.2

Developed by Paul Hoffman, Satija Lab and Collaborators.

Developed by Paul Hoffman, Satija Lab and Collaborators.

Site built with pkgdown 2.0.7.

Site built with pkgdown 2.0.7.

**Examples:**

Example 1 (unknown):
```unknown
vignettes/hashing_vignette.Rmd
```

Example 2 (unknown):
```unknown
hashing_vignette.Rmd
```

Example 3 (unknown):
```unknown
library(Seurat)
```

Example 4 (r):
```r
library(Seurat)
```

Example 5 (r):
```r
library(Seurat)
```

Example 6 (python):
```python
# Load in the UMI matrix
pbmc.umis <- readRDS("../data/pbmc_umi_mtx.rds")

# For generating a hashtag count matrix from FASTQ files, please refer to
# https://github.com/Hoohm/CITE-seq-Count.  Load in the HTO count matrix
pbmc.htos <- readRDS("../data/pbmc_hto_mtx.rds")

# Select cell barcodes detected by both RNA and HTO In the example datasets we have already
# filtered the cells for you, but perform this step for clarity.
joint.bcs <- intersect(colnames(pbmc.umis), colnames(pbmc.htos))

# Subset RNA and HTO counts by joint cell barcodes
pbmc.umis <- pbmc.umis[, joint.bcs]
pbmc.htos <- as.matrix(pbmc.htos[, joint.bcs])

# Confirm that the HTO have the correct names
rownames(pbmc.htos)
```

Example 7 (r):
```r
# Load in the UMI matrix
pbmc.umis <- readRDS("../data/pbmc_umi_mtx.rds")

# For generating a hashtag count matrix from FASTQ files, please refer to
# https://github.com/Hoohm/CITE-seq-Count.  Load in the HTO count matrix
pbmc.htos <- readRDS("../data/pbmc_hto_mtx.rds")

# Select cell barcodes detected by both RNA and HTO In the example datasets we have already
# filtered the cells for you, but perform this step for clarity.
joint.bcs <- intersect(colnames(pbmc.umis), colnames(pbmc.htos))

# Subset RNA and HTO counts by joint cell barcodes
pbmc.umis <- pbmc.umis[, joint.bcs]
pbmc.htos <- as.matrix(pbmc.htos[, joint.bcs])

# Confirm that the HTO have the correct names
rownames(pbmc.htos)
```

Example 8 (r):
```r
# Load in the UMI matrix
pbmc.umis <- readRDS("../data/pbmc_umi_mtx.rds")

# For generating a hashtag count matrix from FASTQ files, please refer to
# https://github.com/Hoohm/CITE-seq-Count.  Load in the HTO count matrix
pbmc.htos <- readRDS("../data/pbmc_hto_mtx.rds")

# Select cell barcodes detected by both RNA and HTO In the example datasets we have already
# filtered the cells for you, but perform this step for clarity.
joint.bcs <- intersect(colnames(pbmc.umis), colnames(pbmc.htos))

# Subset RNA and HTO counts by joint cell barcodes
pbmc.umis <- pbmc.umis[, joint.bcs]
pbmc.htos <- as.matrix(pbmc.htos[, joint.bcs])

# Confirm that the HTO have the correct names
rownames(pbmc.htos)
```

Example 9 (unknown):
```unknown
## [1] "HTO_A" "HTO_B" "HTO_C" "HTO_D" "HTO_E" "HTO_F" "HTO_G" "HTO_H"
```

Example 10 (unknown):
```unknown
## [1] "HTO_A" "HTO_B" "HTO_C" "HTO_D" "HTO_E" "HTO_F" "HTO_G" "HTO_H"
```

Example 11 (unknown):
```unknown
# Setup Seurat object
pbmc.hashtag <- CreateSeuratObject(counts = pbmc.umis)

# Normalize RNA data with log normalization
pbmc.hashtag <- NormalizeData(pbmc.hashtag)
# Find and scale variable features
pbmc.hashtag <- FindVariableFeatures(pbmc.hashtag, selection.method = "mean.var.plot")
pbmc.hashtag <- ScaleData(pbmc.hashtag, features = VariableFeatures(pbmc.hashtag))
```

Example 12 (r):
```r
# Setup Seurat object
pbmc.hashtag <- CreateSeuratObject(counts = pbmc.umis)

# Normalize RNA data with log normalization
pbmc.hashtag <- NormalizeData(pbmc.hashtag)
# Find and scale variable features
pbmc.hashtag <- FindVariableFeatures(pbmc.hashtag, selection.method = "mean.var.plot")
pbmc.hashtag <- ScaleData(pbmc.hashtag, features = VariableFeatures(pbmc.hashtag))
```

Example 13 (r):
```r
# Setup Seurat object
pbmc.hashtag <- CreateSeuratObject(counts = pbmc.umis)

# Normalize RNA data with log normalization
pbmc.hashtag <- NormalizeData(pbmc.hashtag)
# Find and scale variable features
pbmc.hashtag <- FindVariableFeatures(pbmc.hashtag, selection.method = "mean.var.plot")
pbmc.hashtag <- ScaleData(pbmc.hashtag, features = VariableFeatures(pbmc.hashtag))
```

Example 14 (python):
```python
# Add HTO data as a new assay independent from RNA
pbmc.hashtag[["HTO"]] <- CreateAssayObject(counts = pbmc.htos)
# Normalize HTO data, here we use centered log-ratio (CLR) transformation
pbmc.hashtag <- NormalizeData(pbmc.hashtag, assay = "HTO", normalization.method = "CLR")
```

Example 15 (r):
```r
# Add HTO data as a new assay independent from RNA
pbmc.hashtag[["HTO"]] <- CreateAssayObject(counts = pbmc.htos)
# Normalize HTO data, here we use centered log-ratio (CLR) transformation
pbmc.hashtag <- NormalizeData(pbmc.hashtag, assay = "HTO", normalization.method = "CLR")
```

Example 16 (r):
```r
# Add HTO data as a new assay independent from RNA
pbmc.hashtag[["HTO"]] <- CreateAssayObject(counts = pbmc.htos)
# Normalize HTO data, here we use centered log-ratio (CLR) transformation
pbmc.hashtag <- NormalizeData(pbmc.hashtag, assay = "HTO", normalization.method = "CLR")
```

Example 17 (unknown):
```unknown
# If you have a very large dataset we suggest using k_function = 'clara'. This is a k-medoid
# clustering function for large applications You can also play with additional parameters (see
# documentation for HTODemux()) to adjust the threshold for classification Here we are using
# the default settings
pbmc.hashtag <- HTODemux(pbmc.hashtag, assay = "HTO", positive.quantile = 0.99)
```

Example 18 (r):
```r
# If you have a very large dataset we suggest using k_function = 'clara'. This is a k-medoid
# clustering function for large applications You can also play with additional parameters (see
# documentation for HTODemux()) to adjust the threshold for classification Here we are using
# the default settings
pbmc.hashtag <- HTODemux(pbmc.hashtag, assay = "HTO", positive.quantile = 0.99)
```

Example 19 (r):
```r
# If you have a very large dataset we suggest using k_function = 'clara'. This is a k-medoid
# clustering function for large applications You can also play with additional parameters (see
# documentation for HTODemux()) to adjust the threshold for classification Here we are using
# the default settings
pbmc.hashtag <- HTODemux(pbmc.hashtag, assay = "HTO", positive.quantile = 0.99)
```

Example 20 (unknown):
```unknown
# Global classification results
table(pbmc.hashtag$HTO_classification.global)
```

Example 21 (r):
```r
# Global classification results
table(pbmc.hashtag$HTO_classification.global)
```

Example 22 (r):
```r
# Global classification results
table(pbmc.hashtag$HTO_classification.global)
```

Example 23 (javascript):
```javascript
## 
##  Doublet Negative  Singlet 
##     2598      346    13972
```

Example 24 (javascript):
```javascript
## 
##  Doublet Negative  Singlet 
##     2598      346    13972
```

Example 25 (unknown):
```unknown
# Group cells based on the max HTO signal
Idents(pbmc.hashtag) <- "HTO_maxID"
RidgePlot(pbmc.hashtag, assay = "HTO", features = rownames(pbmc.hashtag[["HTO"]])[1:2], ncol = 2)
```

Example 26 (r):
```r
# Group cells based on the max HTO signal
Idents(pbmc.hashtag) <- "HTO_maxID"
RidgePlot(pbmc.hashtag, assay = "HTO", features = rownames(pbmc.hashtag[["HTO"]])[1:2], ncol = 2)
```

Example 27 (r):
```r
# Group cells based on the max HTO signal
Idents(pbmc.hashtag) <- "HTO_maxID"
RidgePlot(pbmc.hashtag, assay = "HTO", features = rownames(pbmc.hashtag[["HTO"]])[1:2], ncol = 2)
```

Example 28 (unknown):
```unknown
FeatureScatter(pbmc.hashtag, feature1 = "hto_HTO-A", feature2 = "hto_HTO-B")
```

Example 29 (r):
```r
FeatureScatter(pbmc.hashtag, feature1 = "hto_HTO-A", feature2 = "hto_HTO-B")
```

Example 30 (r):
```r
FeatureScatter(pbmc.hashtag, feature1 = "hto_HTO-A", feature2 = "hto_HTO-B")
```

Example 31 (unknown):
```unknown
Idents(pbmc.hashtag) <- "HTO_classification.global"
VlnPlot(pbmc.hashtag, features = "nCount_RNA", pt.size = 0.1, log = TRUE)
```

Example 32 (r):
```r
Idents(pbmc.hashtag) <- "HTO_classification.global"
VlnPlot(pbmc.hashtag, features = "nCount_RNA", pt.size = 0.1, log = TRUE)
```

Example 33 (r):
```r
Idents(pbmc.hashtag) <- "HTO_classification.global"
VlnPlot(pbmc.hashtag, features = "nCount_RNA", pt.size = 0.1, log = TRUE)
```

Example 34 (python):
```python
# First, we will remove negative cells from the object
pbmc.hashtag.subset <- subset(pbmc.hashtag, idents = "Negative", invert = TRUE)

# Calculate a tSNE embedding of the HTO data
DefaultAssay(pbmc.hashtag.subset) <- "HTO"
pbmc.hashtag.subset <- ScaleData(pbmc.hashtag.subset, features = rownames(pbmc.hashtag.subset),
    verbose = FALSE)
pbmc.hashtag.subset <- RunPCA(pbmc.hashtag.subset, features = rownames(pbmc.hashtag.subset), approx = FALSE)
pbmc.hashtag.subset <- RunTSNE(pbmc.hashtag.subset, dims = 1:8, perplexity = 100)
DimPlot(pbmc.hashtag.subset)
```

Example 35 (r):
```r
# First, we will remove negative cells from the object
pbmc.hashtag.subset <- subset(pbmc.hashtag, idents = "Negative", invert = TRUE)

# Calculate a tSNE embedding of the HTO data
DefaultAssay(pbmc.hashtag.subset) <- "HTO"
pbmc.hashtag.subset <- ScaleData(pbmc.hashtag.subset, features = rownames(pbmc.hashtag.subset),
    verbose = FALSE)
pbmc.hashtag.subset <- RunPCA(pbmc.hashtag.subset, features = rownames(pbmc.hashtag.subset), approx = FALSE)
pbmc.hashtag.subset <- RunTSNE(pbmc.hashtag.subset, dims = 1:8, perplexity = 100)
DimPlot(pbmc.hashtag.subset)
```

Example 36 (r):
```r
# First, we will remove negative cells from the object
pbmc.hashtag.subset <- subset(pbmc.hashtag, idents = "Negative", invert = TRUE)

# Calculate a tSNE embedding of the HTO data
DefaultAssay(pbmc.hashtag.subset) <- "HTO"
pbmc.hashtag.subset <- ScaleData(pbmc.hashtag.subset, features = rownames(pbmc.hashtag.subset),
    verbose = FALSE)
pbmc.hashtag.subset <- RunPCA(pbmc.hashtag.subset, features = rownames(pbmc.hashtag.subset), approx = FALSE)
pbmc.hashtag.subset <- RunTSNE(pbmc.hashtag.subset, dims = 1:8, perplexity = 100)
DimPlot(pbmc.hashtag.subset)
```

Example 37 (javascript):
```javascript
# You can also visualize the more detailed classification result by running Idents(object) <-
# 'HTO_classification' before plotting. Here, you can see that each of the small clouds on the
# tSNE plot corresponds to one of the 28 possible doublet combinations.
```

Example 38 (r):
```r
# You can also visualize the more detailed classification result by running Idents(object) <-
# 'HTO_classification' before plotting. Here, you can see that each of the small clouds on the
# tSNE plot corresponds to one of the 28 possible doublet combinations.
```

Example 39 (r):
```r
# You can also visualize the more detailed classification result by running Idents(object) <-
# 'HTO_classification' before plotting. Here, you can see that each of the small clouds on the
# tSNE plot corresponds to one of the 28 possible doublet combinations.
```

Example 40 (unknown):
```unknown
# To increase the efficiency of plotting, you can subsample cells using the num.cells argument
HTOHeatmap(pbmc.hashtag, assay = "HTO", ncells = 5000)
```

Example 41 (r):
```r
# To increase the efficiency of plotting, you can subsample cells using the num.cells argument
HTOHeatmap(pbmc.hashtag, assay = "HTO", ncells = 5000)
```

Example 42 (r):
```r
# To increase the efficiency of plotting, you can subsample cells using the num.cells argument
HTOHeatmap(pbmc.hashtag, assay = "HTO", ncells = 5000)
```

Example 43 (javascript):
```javascript
# Extract the singlets
pbmc.singlet <- subset(pbmc.hashtag, idents = "Singlet")

# Select the top 1000 most variable features
pbmc.singlet <- FindVariableFeatures(pbmc.singlet, selection.method = "mean.var.plot")

# Scaling RNA data, we only scale the variable features here for efficiency
pbmc.singlet <- ScaleData(pbmc.singlet, features = VariableFeatures(pbmc.singlet))

# Run PCA
pbmc.singlet <- RunPCA(pbmc.singlet, features = VariableFeatures(pbmc.singlet))
```

Example 44 (r):
```r
# Extract the singlets
pbmc.singlet <- subset(pbmc.hashtag, idents = "Singlet")

# Select the top 1000 most variable features
pbmc.singlet <- FindVariableFeatures(pbmc.singlet, selection.method = "mean.var.plot")

# Scaling RNA data, we only scale the variable features here for efficiency
pbmc.singlet <- ScaleData(pbmc.singlet, features = VariableFeatures(pbmc.singlet))

# Run PCA
pbmc.singlet <- RunPCA(pbmc.singlet, features = VariableFeatures(pbmc.singlet))
```

Example 45 (r):
```r
# Extract the singlets
pbmc.singlet <- subset(pbmc.hashtag, idents = "Singlet")

# Select the top 1000 most variable features
pbmc.singlet <- FindVariableFeatures(pbmc.singlet, selection.method = "mean.var.plot")

# Scaling RNA data, we only scale the variable features here for efficiency
pbmc.singlet <- ScaleData(pbmc.singlet, features = VariableFeatures(pbmc.singlet))

# Run PCA
pbmc.singlet <- RunPCA(pbmc.singlet, features = VariableFeatures(pbmc.singlet))
```

Example 46 (javascript):
```javascript
# We select the top 10 PCs for clustering and tSNE based on PCElbowPlot
pbmc.singlet <- FindNeighbors(pbmc.singlet, reduction = "pca", dims = 1:10)
pbmc.singlet <- FindClusters(pbmc.singlet, resolution = 0.6, verbose = FALSE)
pbmc.singlet <- RunTSNE(pbmc.singlet, reduction = "pca", dims = 1:10)

# Projecting singlet identities on TSNE visualization
DimPlot(pbmc.singlet, group.by = "HTO_classification")
```

Example 47 (r):
```r
# We select the top 10 PCs for clustering and tSNE based on PCElbowPlot
pbmc.singlet <- FindNeighbors(pbmc.singlet, reduction = "pca", dims = 1:10)
pbmc.singlet <- FindClusters(pbmc.singlet, resolution = 0.6, verbose = FALSE)
pbmc.singlet <- RunTSNE(pbmc.singlet, reduction = "pca", dims = 1:10)

# Projecting singlet identities on TSNE visualization
DimPlot(pbmc.singlet, group.by = "HTO_classification")
```

Example 48 (r):
```r
# We select the top 10 PCs for clustering and tSNE based on PCElbowPlot
pbmc.singlet <- FindNeighbors(pbmc.singlet, reduction = "pca", dims = 1:10)
pbmc.singlet <- FindClusters(pbmc.singlet, resolution = 0.6, verbose = FALSE)
pbmc.singlet <- RunTSNE(pbmc.singlet, reduction = "pca", dims = 1:10)

# Projecting singlet identities on TSNE visualization
DimPlot(pbmc.singlet, group.by = "HTO_classification")
```

Example 49 (unknown):
```unknown
# Read in UMI count matrix for RNA
hto12.umis <- readRDS("../data/hto12_umi_mtx.rds")

# Read in HTO count matrix
hto12.htos <- readRDS("../data/hto12_hto_mtx.rds")

# Select cell barcodes detected in both RNA and HTO
cells.use <- intersect(rownames(hto12.htos), colnames(hto12.umis))

# Create Seurat object and add HTO data
hto12 <- CreateSeuratObject(counts = hto12.umis[, cells.use], min.features = 300)
hto12[["HTO"]] <- CreateAssayObject(counts = t(x = hto12.htos[colnames(hto12), 1:12]))

# Normalize data
hto12 <- NormalizeData(hto12)
hto12 <- NormalizeData(hto12, assay = "HTO", normalization.method = "CLR")
```

Example 50 (r):
```r
# Read in UMI count matrix for RNA
hto12.umis <- readRDS("../data/hto12_umi_mtx.rds")

# Read in HTO count matrix
hto12.htos <- readRDS("../data/hto12_hto_mtx.rds")

# Select cell barcodes detected in both RNA and HTO
cells.use <- intersect(rownames(hto12.htos), colnames(hto12.umis))

# Create Seurat object and add HTO data
hto12 <- CreateSeuratObject(counts = hto12.umis[, cells.use], min.features = 300)
hto12[["HTO"]] <- CreateAssayObject(counts = t(x = hto12.htos[colnames(hto12), 1:12]))

# Normalize data
hto12 <- NormalizeData(hto12)
hto12 <- NormalizeData(hto12, assay = "HTO", normalization.method = "CLR")
```

Example 51 (r):
```r
# Read in UMI count matrix for RNA
hto12.umis <- readRDS("../data/hto12_umi_mtx.rds")

# Read in HTO count matrix
hto12.htos <- readRDS("../data/hto12_hto_mtx.rds")

# Select cell barcodes detected in both RNA and HTO
cells.use <- intersect(rownames(hto12.htos), colnames(hto12.umis))

# Create Seurat object and add HTO data
hto12 <- CreateSeuratObject(counts = hto12.umis[, cells.use], min.features = 300)
hto12[["HTO"]] <- CreateAssayObject(counts = t(x = hto12.htos[colnames(hto12), 1:12]))

# Normalize data
hto12 <- NormalizeData(hto12)
hto12 <- NormalizeData(hto12, assay = "HTO", normalization.method = "CLR")
```

Example 52 (unknown):
```unknown
hto12 <- HTODemux(hto12, assay = "HTO", positive.quantile = 0.99)
```

Example 53 (r):
```r
hto12 <- HTODemux(hto12, assay = "HTO", positive.quantile = 0.99)
```

Example 54 (r):
```r
hto12 <- HTODemux(hto12, assay = "HTO", positive.quantile = 0.99)
```

Example 55 (unknown):
```unknown
RidgePlot(hto12, assay = "HTO", features = c("HEK-A", "K562-B", "KG1-A", "THP1-C"), ncol = 2)
```

Example 56 (r):
```r
RidgePlot(hto12, assay = "HTO", features = c("HEK-A", "K562-B", "KG1-A", "THP1-C"), ncol = 2)
```

Example 57 (r):
```r
RidgePlot(hto12, assay = "HTO", features = c("HEK-A", "K562-B", "KG1-A", "THP1-C"), ncol = 2)
```

Example 58 (unknown):
```unknown
HTOHeatmap(hto12, assay = "HTO")
```

Example 59 (r):
```r
HTOHeatmap(hto12, assay = "HTO")
```

Example 60 (r):
```r
HTOHeatmap(hto12, assay = "HTO")
```

Example 61 (unknown):
```unknown
# Remove the negative cells
hto12 <- subset(hto12, idents = "Negative", invert = TRUE)

# Run PCA on most variable features
hto12 <- FindVariableFeatures(hto12, selection.method = "mean.var.plot")
hto12 <- ScaleData(hto12, features = VariableFeatures(hto12))
hto12 <- RunPCA(hto12)
hto12 <- RunTSNE(hto12, dims = 1:5, perplexity = 100)
DimPlot(hto12) + NoLegend()
```

Example 62 (r):
```r
# Remove the negative cells
hto12 <- subset(hto12, idents = "Negative", invert = TRUE)

# Run PCA on most variable features
hto12 <- FindVariableFeatures(hto12, selection.method = "mean.var.plot")
hto12 <- ScaleData(hto12, features = VariableFeatures(hto12))
hto12 <- RunPCA(hto12)
hto12 <- RunTSNE(hto12, dims = 1:5, perplexity = 100)
DimPlot(hto12) + NoLegend()
```

Example 63 (r):
```r
# Remove the negative cells
hto12 <- subset(hto12, idents = "Negative", invert = TRUE)

# Run PCA on most variable features
hto12 <- FindVariableFeatures(hto12, selection.method = "mean.var.plot")
hto12 <- ScaleData(hto12, features = VariableFeatures(hto12))
hto12 <- RunPCA(hto12)
hto12 <- RunTSNE(hto12, dims = 1:5, perplexity = 100)
DimPlot(hto12) + NoLegend()
```

Example 64 (unknown):
```unknown
sessionInfo()
```

Example 65 (r):
```r
sessionInfo()
```

Example 66 (r):
```r
sessionInfo()
```

Example 67 (unknown):
```unknown
## R version 4.2.0 (2022-04-22)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.5 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/liblapack.so.3
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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       
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
## [1] SeuratObject_4.1.3 Seurat_4.3.0      
## 
## loaded via a namespace (and not attached):
##   [1] Rtsne_0.16             colorspace_2.1-0       deldir_1.0-6          
##   [4] ellipsis_0.3.2         ggridges_0.5.4         rprojroot_2.0.3       
##   [7] fs_1.6.1               spatstat.data_3.0-0    farver_2.1.1          
##  [10] leiden_0.4.3           listenv_0.9.0          ggrepel_0.9.3         
##  [13] fansi_1.0.4            codetools_0.2-18       splines_4.2.0         
##  [16] cachem_1.0.7           knitr_1.42             polyclip_1.10-4       
##  [19] jsonlite_1.8.4         ica_1.0-3              cluster_2.1.3         
##  [22] png_0.1-8              uwot_0.1.14            spatstat.sparse_3.0-0 
##  [25] shiny_1.7.4            sctransform_0.3.5      compiler_4.2.0        
##  [28] httr_1.4.5             Matrix_1.5-3           fastmap_1.1.1         
##  [31] lazyeval_0.2.2         cli_3.6.0              later_1.3.0           
##  [34] formatR_1.14           htmltools_0.5.4        tools_4.2.0           
##  [37] igraph_1.4.1           gtable_0.3.1           glue_1.6.2            
##  [40] RANN_2.6.1             reshape2_1.4.4         dplyr_1.1.0           
##  [43] Rcpp_1.0.10            scattermore_0.8        jquerylib_0.1.4       
##  [46] pkgdown_2.0.7          vctrs_0.5.2            nlme_3.1-157          
##  [49] spatstat.explore_3.0-6 progressr_0.13.0       lmtest_0.9-40         
##  [52] spatstat.random_3.1-3  xfun_0.37              stringr_1.5.0         
##  [55] globals_0.16.2         mime_0.12              miniUI_0.1.1.1        
##  [58] lifecycle_1.0.3        irlba_2.3.5.1          goftest_1.2-3         
##  [61] future_1.31.0          MASS_7.3-56            zoo_1.8-11            
##  [64] scales_1.2.1           ragg_1.2.5             promises_1.2.0.1      
##  [67] spatstat.utils_3.0-1   parallel_4.2.0         RColorBrewer_1.1-3    
##  [70] yaml_2.3.7             memoise_2.0.1          reticulate_1.28       
##  [73] pbapply_1.7-0          gridExtra_2.3          ggplot2_3.4.1         
##  [76] sass_0.4.5             stringi_1.7.12         highr_0.10            
##  [79] desc_1.4.2             rlang_1.0.6            pkgconfig_2.0.3       
##  [82] systemfonts_1.0.4      matrixStats_0.63.0     evaluate_0.20         
##  [85] lattice_0.20-45        tensor_1.5             ROCR_1.0-11           
##  [88] purrr_1.0.1            labeling_0.4.2         patchwork_1.1.2       
##  [91] htmlwidgets_1.6.1      cowplot_1.1.1          tidyselect_1.2.0      
##  [94] parallelly_1.34.0      RcppAnnoy_0.0.20       plyr_1.8.8            
##  [97] magrittr_2.0.3         R6_2.5.1               generics_0.1.3        
## [100] withr_2.5.0            pillar_1.8.1           fitdistrplus_1.1-8    
## [103] abind_1.4-5            survival_3.3-1         sp_1.6-0              
## [106] tibble_3.1.8           future.apply_1.10.0    KernSmooth_2.23-20    
## [109] utf8_1.2.3             spatstat.geom_3.0-6    plotly_4.10.1         
## [112] rmarkdown_2.20         grid_4.2.0             data.table_1.14.8     
## [115] digest_0.6.31          xtable_1.8-4           tidyr_1.3.0           
## [118] httpuv_1.6.9           textshaping_0.3.6      munsell_0.5.0         
## [121] viridisLite_0.4.1      bslib_0.4.2
```

Example 68 (unknown):
```unknown
## R version 4.2.0 (2022-04-22)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.5 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/liblapack.so.3
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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       
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
## [1] SeuratObject_4.1.3 Seurat_4.3.0      
## 
## loaded via a namespace (and not attached):
##   [1] Rtsne_0.16             colorspace_2.1-0       deldir_1.0-6          
##   [4] ellipsis_0.3.2         ggridges_0.5.4         rprojroot_2.0.3       
##   [7] fs_1.6.1               spatstat.data_3.0-0    farver_2.1.1          
##  [10] leiden_0.4.3           listenv_0.9.0          ggrepel_0.9.3         
##  [13] fansi_1.0.4            codetools_0.2-18       splines_4.2.0         
##  [16] cachem_1.0.7           knitr_1.42             polyclip_1.10-4       
##  [19] jsonlite_1.8.4         ica_1.0-3              cluster_2.1.3         
##  [22] png_0.1-8              uwot_0.1.14            spatstat.sparse_3.0-0 
##  [25] shiny_1.7.4            sctransform_0.3.5      compiler_4.2.0        
##  [28] httr_1.4.5             Matrix_1.5-3           fastmap_1.1.1         
##  [31] lazyeval_0.2.2         cli_3.6.0              later_1.3.0           
##  [34] formatR_1.14           htmltools_0.5.4        tools_4.2.0           
##  [37] igraph_1.4.1           gtable_0.3.1           glue_1.6.2            
##  [40] RANN_2.6.1             reshape2_1.4.4         dplyr_1.1.0           
##  [43] Rcpp_1.0.10            scattermore_0.8        jquerylib_0.1.4       
##  [46] pkgdown_2.0.7          vctrs_0.5.2            nlme_3.1-157          
##  [49] spatstat.explore_3.0-6 progressr_0.13.0       lmtest_0.9-40         
##  [52] spatstat.random_3.1-3  xfun_0.37              stringr_1.5.0         
##  [55] globals_0.16.2         mime_0.12              miniUI_0.1.1.1        
##  [58] lifecycle_1.0.3        irlba_2.3.5.1          goftest_1.2-3         
##  [61] future_1.31.0          MASS_7.3-56            zoo_1.8-11            
##  [64] scales_1.2.1           ragg_1.2.5             promises_1.2.0.1      
##  [67] spatstat.utils_3.0-1   parallel_4.2.0         RColorBrewer_1.1-3    
##  [70] yaml_2.3.7             memoise_2.0.1          reticulate_1.28       
##  [73] pbapply_1.7-0          gridExtra_2.3          ggplot2_3.4.1         
##  [76] sass_0.4.5             stringi_1.7.12         highr_0.10            
##  [79] desc_1.4.2             rlang_1.0.6            pkgconfig_2.0.3       
##  [82] systemfonts_1.0.4      matrixStats_0.63.0     evaluate_0.20         
##  [85] lattice_0.20-45        tensor_1.5             ROCR_1.0-11           
##  [88] purrr_1.0.1            labeling_0.4.2         patchwork_1.1.2       
##  [91] htmlwidgets_1.6.1      cowplot_1.1.1          tidyselect_1.2.0      
##  [94] parallelly_1.34.0      RcppAnnoy_0.0.20       plyr_1.8.8            
##  [97] magrittr_2.0.3         R6_2.5.1               generics_0.1.3        
## [100] withr_2.5.0            pillar_1.8.1           fitdistrplus_1.1-8    
## [103] abind_1.4-5            survival_3.3-1         sp_1.6-0              
## [106] tibble_3.1.8           future.apply_1.10.0    KernSmooth_2.23-20    
## [109] utf8_1.2.3             spatstat.geom_3.0-6    plotly_4.10.1         
## [112] rmarkdown_2.20         grid_4.2.0             data.table_1.14.8     
## [115] digest_0.6.31          xtable_1.8-4           tidyr_1.3.0           
## [118] httpuv_1.6.9           textshaping_0.3.6      munsell_0.5.0         
## [121] viridisLite_0.4.1      bslib_0.4.2
```

---

## Cell-Cycle Scoring and Regression

**URL:** http://127.0.0.1:9173/seurat/archive/v3.1/cell_cycle_vignette/index.html

**Contents:**
- Cell-Cycle Scoring and Regression
    - Compiled: 2020-04-17
  - Assign Cell-Cycle Scores
  - Regress out cell cycle scores during data scaling
  - Alternate Workflow

We demonstrate how to mitigate the effects of cell cycle heterogeneity in scRNA-seq data by calculating cell cycle phase scores based on canonical markers, and regressing these out of the data during pre-processing. We demonstrate this on a dataset of murine hematopoietic progenitors (Nestorowa et al., Blood 2016.You can download the files needed to run this vignette here.

If we run a PCA on our object, using the variable genes we found in FindVariableFeatures above, we see that while most of the variance can be explained by lineage, PC8 and PC10 are split on cell-cycle genes including TOP2A and MKI67. We will attempt to regress this signal from the data, so that cell-cycle heterogneity does not contribute to PCA or downstream analysis.

First, we assign each cell a score, based on its expression of G2/M and S phase markers. These marker sets should be anticorrelated in their expression levels, and cells expressing neither are likely not cycling and in G1 phase.

We assign scores in the CellCycleScoring function, which stores S and G2/M scores in object meta data, along with the predicted classification of each cell in either G2M, S or G1 phase. CellCycleScoring can also set the identity of the Seurat object to the cell-cycle phase by passing set.ident = TRUE (the original identities are stored as old.ident). Please note that Seurat does not use the discrete classifications (G2M/G1/S) in downstream cell cycle regression. Instead, it uses the quantitative scores for G2M and S phase. However, we provide our predicted classifications in case they are of interest.

We score single cells based on the scoring strategy described in Tirosh et al. 2016. See ?AddModuleScore in Seurat for more information, this function can be used to calculate supervised module scores for any gene list.

We now attempt to subtract (‘regress out’) this source of heterogeneity from the data. For users of Seurat v1.4, this was implemented in RegressOut. However, as the results of this procedure are stored in the scaled data slot (therefore overwriting the output of ScaleData), we now merge this functionality into the ScaleData function itself.

For each gene, Seurat models the relationship between gene expression and the S and G2M cell cycle scores. The scaled residuals of this model represent a ‘corrected’ expression matrix, that can be used downstream for dimensional reduction.

As the best cell cycle markers are extremely well conserved across tissues and species, we have found this procedure to work robustly and reliably on diverse datasets.

The procedure above removes all signal associated with cell cycle. In some cases, we’ve found that this can negatively impact downstream analysis, particularly in differentiating processes (like murine hematopoiesis), where stem cells are quiescent and differentiated cells are proliferating (or vice versa). In this case, regressing out all cell cycle effects can blur the distinction between stem and progenitor cells as well.

As an alternative, we suggest regressing out the difference between the G2M and S phase scores. This means that signals separating non-cycling cells and cycling cells will be maintained, but differences in cell cycle phase amongst proliferating cells (which are often uninteresting), will be regressed out of the data

**Examples:**

Example 1 (r):
```r
library(Seurat)

# Read in the expression matrix The first row is a header row, the first column is rownames
exp.mat <- read.table(file = "../data/nestorawa_forcellcycle_expressionMatrix.txt", header = TRUE, 
    as.is = TRUE, row.names = 1)

# A list of cell cycle markers, from Tirosh et al, 2015, is loaded with Seurat.  We can
# segregate this list into markers of G2/M phase and markers of S phase
s.genes <- cc.genes$s.genes
g2m.genes <- cc.genes$g2m.genes

# Create our Seurat object and complete the initalization steps
marrow <- CreateSeuratObject(counts = exp.mat)
marrow <- NormalizeData(marrow)
marrow <- FindVariableFeatures(marrow, selection.method = "vst")
marrow <- ScaleData(marrow, features = rownames(marrow))
```

Example 2 (r):
```r
library(Seurat)

# Read in the expression matrix The first row is a header row, the first column is rownames
exp.mat <- read.table(file = "../data/nestorawa_forcellcycle_expressionMatrix.txt", header = TRUE, 
    as.is = TRUE, row.names = 1)

# A list of cell cycle markers, from Tirosh et al, 2015, is loaded with Seurat.  We can
# segregate this list into markers of G2/M phase and markers of S phase
s.genes <- cc.genes$s.genes
g2m.genes <- cc.genes$g2m.genes

# Create our Seurat object and complete the initalization steps
marrow <- CreateSeuratObject(counts = exp.mat)
marrow <- NormalizeData(marrow)
marrow <- FindVariableFeatures(marrow, selection.method = "vst")
marrow <- ScaleData(marrow, features = rownames(marrow))
```

Example 3 (unknown):
```unknown
FindVariableFeatures
```

Example 4 (r):
```r
marrow <- RunPCA(marrow, features = VariableFeatures(marrow), ndims.print = 6:10, nfeatures.print = 10)
```

Example 5 (r):
```r
marrow <- RunPCA(marrow, features = VariableFeatures(marrow), ndims.print = 6:10, nfeatures.print = 10)
```

Example 6 (unknown):
```unknown
## PC_ 6 
## Positive:  SELL, ARL6IP1, CCL9, CD34, ADGRL4, BPIFC, NUSAP1, FAM64A, CD244, C030034L19RIK 
## Negative:  LY6C2, AA467197, CYBB, MGST2, ITGB2, PF4, CD74, ATP1B1, GP1BB, TREM3 
## PC_ 7 
## Positive:  HDC, CPA3, PGLYRP1, MS4A3, NKG7, UBE2C, CCNB1, NUSAP1, PLK1, FUT8 
## Negative:  F13A1, LY86, CFP, IRF8, CSF1R, TIFAB, IFI209, CCR2, TNS4, MS4A6C 
## PC_ 8 
## Positive:  NUSAP1, UBE2C, KIF23, PLK1, CENPF, FAM64A, CCNB1, H2AFX, ID2, CDC20 
## Negative:  WFDC17, SLC35D3, ADGRL4, VLDLR, CD33, H2AFY, P2RY14, IFI206, CCL9, CD34 
## PC_ 9 
## Positive:  IGKC, JCHAIN, LY6D, MZB1, CD74, IGLC2, FCRLA, IGKV4-50, IGHM, IGHV9-1 
## Negative:  SLC2A6, HBA-A1, HBA-A2, IGHV8-7, FCER1G, F13A1, HBB-BS, PLD4, HBB-BT, IGFBP4 
## PC_ 10 
## Positive:  CTSW, XKRX, PRR5L, RORA, MBOAT4, A630014C17RIK, ZFP105, COL9A3, CLEC2I, TRAT1 
## Negative:  H2AFX, FAM64A, ZFP383, NUSAP1, CDC25B, CENPF, GBP10, TOP2A, GBP6, GFRA1
```

Example 7 (unknown):
```unknown
## PC_ 6 
## Positive:  SELL, ARL6IP1, CCL9, CD34, ADGRL4, BPIFC, NUSAP1, FAM64A, CD244, C030034L19RIK 
## Negative:  LY6C2, AA467197, CYBB, MGST2, ITGB2, PF4, CD74, ATP1B1, GP1BB, TREM3 
## PC_ 7 
## Positive:  HDC, CPA3, PGLYRP1, MS4A3, NKG7, UBE2C, CCNB1, NUSAP1, PLK1, FUT8 
## Negative:  F13A1, LY86, CFP, IRF8, CSF1R, TIFAB, IFI209, CCR2, TNS4, MS4A6C 
## PC_ 8 
## Positive:  NUSAP1, UBE2C, KIF23, PLK1, CENPF, FAM64A, CCNB1, H2AFX, ID2, CDC20 
## Negative:  WFDC17, SLC35D3, ADGRL4, VLDLR, CD33, H2AFY, P2RY14, IFI206, CCL9, CD34 
## PC_ 9 
## Positive:  IGKC, JCHAIN, LY6D, MZB1, CD74, IGLC2, FCRLA, IGKV4-50, IGHM, IGHV9-1 
## Negative:  SLC2A6, HBA-A1, HBA-A2, IGHV8-7, FCER1G, F13A1, HBB-BS, PLD4, HBB-BT, IGFBP4 
## PC_ 10 
## Positive:  CTSW, XKRX, PRR5L, RORA, MBOAT4, A630014C17RIK, ZFP105, COL9A3, CLEC2I, TRAT1 
## Negative:  H2AFX, FAM64A, ZFP383, NUSAP1, CDC25B, CENPF, GBP10, TOP2A, GBP6, GFRA1
```

Example 8 (r):
```r
DimHeatmap(marrow, dims = c(8, 10))
```

Example 9 (r):
```r
DimHeatmap(marrow, dims = c(8, 10))
```

Example 10 (unknown):
```unknown
CellCycleScoring
```

Example 11 (unknown):
```unknown
CellCycleScoring
```

Example 12 (unknown):
```unknown
set.ident = TRUE
```

Example 13 (r):
```r
marrow <- CellCycleScoring(marrow, s.features = s.genes, g2m.features = g2m.genes, set.ident = TRUE)

# view cell cycle scores and phase assignments
head(marrow[[]])
```

Example 14 (r):
```r
marrow <- CellCycleScoring(marrow, s.features = s.genes, g2m.features = g2m.genes, set.ident = TRUE)

# view cell cycle scores and phase assignments
head(marrow[[]])
```

Example 15 (r):
```r
# Visualize the distribution of cell cycle markers across
RidgePlot(marrow, features = c("PCNA", "TOP2A", "MCM6", "MKI67"), ncol = 2)
```

Example 16 (r):
```r
# Visualize the distribution of cell cycle markers across
RidgePlot(marrow, features = c("PCNA", "TOP2A", "MCM6", "MKI67"), ncol = 2)
```

Example 17 (r):
```r
# Running a PCA on cell cycle genes reveals, unsurprisingly, that cells separate entirely by
# phase
marrow <- RunPCA(marrow, features = c(s.genes, g2m.genes))
DimPlot(marrow)
```

Example 18 (r):
```r
# Running a PCA on cell cycle genes reveals, unsurprisingly, that cells separate entirely by
# phase
marrow <- RunPCA(marrow, features = c(s.genes, g2m.genes))
DimPlot(marrow)
```

Example 19 (unknown):
```unknown
?AddModuleScore
```

Example 20 (r):
```r
marrow <- ScaleData(marrow, vars.to.regress = c("S.Score", "G2M.Score"), features = rownames(marrow))
```

Example 21 (r):
```r
marrow <- ScaleData(marrow, vars.to.regress = c("S.Score", "G2M.Score"), features = rownames(marrow))
```

Example 22 (r):
```r
# Now, a PCA on the variable genes no longer returns components associated with cell cycle
marrow <- RunPCA(marrow, features = VariableFeatures(marrow), nfeatures.print = 10)
```

Example 23 (r):
```r
# Now, a PCA on the variable genes no longer returns components associated with cell cycle
marrow <- RunPCA(marrow, features = VariableFeatures(marrow), nfeatures.print = 10)
```

Example 24 (unknown):
```unknown
## PC_ 1 
## Positive:  BLVRB, CAR2, KLF1, AQP1, CES2G, ERMAP, CAR1, FAM132A, RHD, SPHK1 
## Negative:  TMSB4X, H2AFY, CORO1A, PLAC8, EMB, MPO, PRTN3, CD34, LCP1, BC035044 
## PC_ 2 
## Positive:  ANGPT1, ADGRG1, MEIS1, ITGA2B, MPL, DAPP1, APOE, RAB37, GATA2, F2R 
## Negative:  LY6C2, ELANE, HP, IGSF6, ANXA3, CTSG, CLEC12A, TIFAB, SLPI, ALAS1 
## PC_ 3 
## Positive:  APOE, GATA2, NKG7, MUC13, MS4A3, RAB44, HDC, CPA3, FCGR3, TUBA8 
## Negative:  FLT3, DNTT, LSP1, WFDC17, MYL10, GIMAP6, LAX1, GPR171, TBXA2R, SATB1 
## PC_ 4 
## Positive:  CSRP3, ST8SIA6, DNTT, MPEG1, SCIN, LGALS1, CMAH, RGL1, APOE, MFSD2B 
## Negative:  PROCR, MPL, HLF, MMRN1, SERPINA3G, ESAM, GSTM1, D630039A03RIK, MYL10, LY6A 
## PC_ 5 
## Positive:  PF4, GP1BB, SDPR, F2RL2, RAB27B, SLC14A1, TREML1, PBX1, F2R, TUBA8 
## Negative:  CPA3, LMO4, IKZF2, IFITM1, FUT8, MS4A2, SIGLECF, CSRP3, HDC, RAB44
```

Example 25 (unknown):
```unknown
## PC_ 1 
## Positive:  BLVRB, CAR2, KLF1, AQP1, CES2G, ERMAP, CAR1, FAM132A, RHD, SPHK1 
## Negative:  TMSB4X, H2AFY, CORO1A, PLAC8, EMB, MPO, PRTN3, CD34, LCP1, BC035044 
## PC_ 2 
## Positive:  ANGPT1, ADGRG1, MEIS1, ITGA2B, MPL, DAPP1, APOE, RAB37, GATA2, F2R 
## Negative:  LY6C2, ELANE, HP, IGSF6, ANXA3, CTSG, CLEC12A, TIFAB, SLPI, ALAS1 
## PC_ 3 
## Positive:  APOE, GATA2, NKG7, MUC13, MS4A3, RAB44, HDC, CPA3, FCGR3, TUBA8 
## Negative:  FLT3, DNTT, LSP1, WFDC17, MYL10, GIMAP6, LAX1, GPR171, TBXA2R, SATB1 
## PC_ 4 
## Positive:  CSRP3, ST8SIA6, DNTT, MPEG1, SCIN, LGALS1, CMAH, RGL1, APOE, MFSD2B 
## Negative:  PROCR, MPL, HLF, MMRN1, SERPINA3G, ESAM, GSTM1, D630039A03RIK, MYL10, LY6A 
## PC_ 5 
## Positive:  PF4, GP1BB, SDPR, F2RL2, RAB27B, SLC14A1, TREML1, PBX1, F2R, TUBA8 
## Negative:  CPA3, LMO4, IKZF2, IFITM1, FUT8, MS4A2, SIGLECF, CSRP3, HDC, RAB44
```

Example 26 (r):
```r
# When running a PCA on only cell cycle genes, cells no longer separate by cell-cycle phase
marrow <- RunPCA(marrow, features = c(s.genes, g2m.genes))
DimPlot(marrow)
```

Example 27 (r):
```r
# When running a PCA on only cell cycle genes, cells no longer separate by cell-cycle phase
marrow <- RunPCA(marrow, features = c(s.genes, g2m.genes))
DimPlot(marrow)
```

Example 28 (r):
```r
marrow$CC.Difference <- marrow$S.Score - marrow$G2M.Score
marrow <- ScaleData(marrow, vars.to.regress = "CC.Difference", features = rownames(marrow))
```

Example 29 (r):
```r
marrow$CC.Difference <- marrow$S.Score - marrow$G2M.Score
marrow <- ScaleData(marrow, vars.to.regress = "CC.Difference", features = rownames(marrow))
```

Example 30 (r):
```r
# cell cycle effects strongly mitigated in PCA
marrow <- RunPCA(marrow, features = VariableFeatures(marrow), nfeatures.print = 10)
```

Example 31 (r):
```r
# cell cycle effects strongly mitigated in PCA
marrow <- RunPCA(marrow, features = VariableFeatures(marrow), nfeatures.print = 10)
```

Example 32 (unknown):
```unknown
## PC_ 1 
## Positive:  BLVRB, KLF1, ERMAP, FAM132A, CAR2, RHD, CES2G, SPHK1, AQP1, SLC38A5 
## Negative:  TMSB4X, CORO1A, PLAC8, H2AFY, LAPTM5, CD34, LCP1, TMEM176B, IGFBP4, EMB 
## PC_ 2 
## Positive:  APOE, GATA2, RAB37, ANGPT1, ADGRG1, MEIS1, MPL, F2R, PDZK1IP1, DAPP1 
## Negative:  CTSG, ELANE, LY6C2, HP, CLEC12A, ANXA3, IGSF6, TIFAB, SLPI, MPO 
## PC_ 3 
## Positive:  APOE, GATA2, NKG7, MUC13, ITGA2B, TUBA8, CPA3, RAB44, SLC18A2, CD9 
## Negative:  DNTT, FLT3, WFDC17, LSP1, MYL10, LAX1, GIMAP6, IGHM, CD24A, MN1 
## PC_ 4 
## Positive:  CSRP3, ST8SIA6, SCIN, LGALS1, APOE, ITGB7, MFSD2B, RGL1, DNTT, IGHV1-23 
## Negative:  MPL, MMRN1, PROCR, HLF, SERPINA3G, ESAM, PTGS1, D630039A03RIK, NDN, PPIC 
## PC_ 5 
## Positive:  GP1BB, PF4, SDPR, F2RL2, TREML1, RAB27B, SLC14A1, PBX1, PLEK, TUBA8 
## Negative:  HDC, LMO4, CSRP3, IFITM1, FCGR3, HLF, CPA3, PROCR, PGLYRP1, IKZF2
```

Example 33 (unknown):
```unknown
## PC_ 1 
## Positive:  BLVRB, KLF1, ERMAP, FAM132A, CAR2, RHD, CES2G, SPHK1, AQP1, SLC38A5 
## Negative:  TMSB4X, CORO1A, PLAC8, H2AFY, LAPTM5, CD34, LCP1, TMEM176B, IGFBP4, EMB 
## PC_ 2 
## Positive:  APOE, GATA2, RAB37, ANGPT1, ADGRG1, MEIS1, MPL, F2R, PDZK1IP1, DAPP1 
## Negative:  CTSG, ELANE, LY6C2, HP, CLEC12A, ANXA3, IGSF6, TIFAB, SLPI, MPO 
## PC_ 3 
## Positive:  APOE, GATA2, NKG7, MUC13, ITGA2B, TUBA8, CPA3, RAB44, SLC18A2, CD9 
## Negative:  DNTT, FLT3, WFDC17, LSP1, MYL10, LAX1, GIMAP6, IGHM, CD24A, MN1 
## PC_ 4 
## Positive:  CSRP3, ST8SIA6, SCIN, LGALS1, APOE, ITGB7, MFSD2B, RGL1, DNTT, IGHV1-23 
## Negative:  MPL, MMRN1, PROCR, HLF, SERPINA3G, ESAM, PTGS1, D630039A03RIK, NDN, PPIC 
## PC_ 5 
## Positive:  GP1BB, PF4, SDPR, F2RL2, TREML1, RAB27B, SLC14A1, PBX1, PLEK, TUBA8 
## Negative:  HDC, LMO4, CSRP3, IFITM1, FCGR3, HLF, CPA3, PROCR, PGLYRP1, IKZF2
```

Example 34 (r):
```r
# when running a PCA on cell cycle genes, actively proliferating cells remain distinct from G1
# cells however, within actively proliferating cells, G2M and S phase cells group together
marrow <- RunPCA(marrow, features = c(s.genes, g2m.genes))
DimPlot(marrow)
```

Example 35 (r):
```r
# when running a PCA on cell cycle genes, actively proliferating cells remain distinct from G1
# cells however, within actively proliferating cells, G2M and S phase cells group together
marrow <- RunPCA(marrow, features = c(s.genes, g2m.genes))
DimPlot(marrow)
```

---

## Analysis, visualization, and integration of Visium HD spatial datasets with Seurat • Seurat

**URL:** http://127.0.0.1:9173/articles_get_started.html

**Contents:**
- Getting Started with Seurat v4
- Introductory Vignettes
- Data Integration
- Additional New Methods
- Other
- SeuratWrappers
- Contents

We provide a series of vignettes, tutorials, and analysis walkthroughs to help users get started with Seurat. You can also check out our Reference page which contains a full list of functions available to users.

For new users of Seurat, we suggest starting with a guided walk through of a dataset of 2,700 Peripheral Blood Mononuclear Cells (PBMCs) made publicly available by 10X Genomics. This tutorial implements the major components of a standard unsupervised clustering workflow including QC and data filtration, calculation of high-variance genes, dimensional reduction, graph-based clustering, and the identification of cluster markers.

We provide additional introductory vignettes for users who are interested in analyzing multimodal single-cell datasets (e.g. from CITE-seq, or the 10x multiome kit), or spatial datasets (e.g. 10x Visium or Vizgen MERFISH).

Recently, we have developed computational methods for integrated analysis of single-cell datasets generated across different conditions, technologies, or species. As an example, we provide a guided walk through for integrating and comparing PBMC datasets generated under different stimulation conditions. We provide additional vignettes demonstrating how to leverage an annotated scRNA-seq reference to map and label cells from a query, and to efficiently integrate large datasets.

Seurat also offers additional novel statistical methods for analyzing single-cell data. These include:

Here we provide a series of short vignettes to demonstrate a number of features that are commonly used in Seurat. We’ve focused the vignettes around questions that we frequently receive from users. Click on a vignette to get started.

In order to facilitate the use of community tools with Seurat, we provide the Seurat Wrappers package, which contains code to run other analysis tools on Seurat objects. For the initial release, we provide wrappers for a few packages in the table below but would encourage other package developers interested in interfacing with Seurat to check out our contributor guide here.

Developed by Rahul Satija, Satija Lab and Collaborators.

Site built with pkgdown 2.0.7.

**Examples:**

Example 1 (unknown):
```unknown
vignettes/get_started.Rmd
```

Example 2 (unknown):
```unknown
get_started.Rmd
```

---

## Seurat - Interaction Tips

**URL:** http://127.0.0.1:9173/seurat/archive/v3.0/interaction_vignette/index.html

**Contents:**
- Seurat - Interaction Tips
    - Compiled: June 24, 2019
  - Load in the data
  - Switch identity class between cluster ID and replicate
  - Tabulate cells by cluster ID, replicate, or both
  - Selecting particular cells and subsetting the Seurat object
  - Calculating the average gene expression within a cluster

This vignette demonstrates some useful features for interacting with the Seurat object. For demonstration purposes, we will be using the 2,700 PBMC object that is created in the first guided tutorial. You can download the pre-computed object here. To simulate the scenario where we have two replicates, we will randomly assign half the cells in each cluster to be from “rep1” and other half from “rep2”.

**Examples:**

Example 1 (r):
```r
library(Seurat)
pbmc <- readRDS(file = "../data/pbmc3k_final.rds")

# pretend that cells were originally assigned to one of two replicates (we assign randomly here)
# if your cells do belong to multiple replicates, and you want to add this info to the Seurat
# object create a data frame with this information (similar to replicate.info below)
set.seed(42)
pbmc$replicate <- sample(c("rep1", "rep2"), size = ncol(pbmc), replace = TRUE)
```

Example 2 (r):
```r
library(Seurat)
pbmc <- readRDS(file = "../data/pbmc3k_final.rds")

# pretend that cells were originally assigned to one of two replicates (we assign randomly here)
# if your cells do belong to multiple replicates, and you want to add this info to the Seurat
# object create a data frame with this information (similar to replicate.info below)
set.seed(42)
pbmc$replicate <- sample(c("rep1", "rep2"), size = ncol(pbmc), replace = TRUE)
```

Example 3 (r):
```r
# Plot UMAP, coloring cells by cell type (currently stored in object@ident)
DimPlot(pbmc, reduction = "umap")
```

Example 4 (r):
```r
# Plot UMAP, coloring cells by cell type (currently stored in object@ident)
DimPlot(pbmc, reduction = "umap")
```

Example 5 (r):
```r
# How do I create a UMAP plot where cells are colored by replicate?  First, store the current
# identities in a new column of meta.data called CellType
pbmc$CellType <- Idents(pbmc)
# Next, switch the identity class of all cells to reflect replicate ID
Idents(pbmc) <- "replicate"
DimPlot(pbmc, reduction = "umap")
```

Example 6 (r):
```r
# How do I create a UMAP plot where cells are colored by replicate?  First, store the current
# identities in a new column of meta.data called CellType
pbmc$CellType <- Idents(pbmc)
# Next, switch the identity class of all cells to reflect replicate ID
Idents(pbmc) <- "replicate"
DimPlot(pbmc, reduction = "umap")
```

Example 7 (r):
```r
# alternately : DimPlot(pbmc, reduction = 'umap', group.by = 'replicate') you can pass the
# shape.by to label points by both replicate and cell type

# Switch back to cell type labels
Idents(pbmc) <- "CellType"
```

Example 8 (r):
```r
# alternately : DimPlot(pbmc, reduction = 'umap', group.by = 'replicate') you can pass the
# shape.by to label points by both replicate and cell type

# Switch back to cell type labels
Idents(pbmc) <- "CellType"
```

Example 9 (r):
```r
# How many cells are in each cluster
table(Idents(pbmc))
```

Example 10 (r):
```r
# How many cells are in each cluster
table(Idents(pbmc))
```

Example 11 (javascript):
```javascript
## 
##  Naive CD4 T Memory CD4 T   CD14+ Mono            B        CD8 T 
##          697          483          480          344          271 
## FCGR3A+ Mono           NK           DC     Platelet 
##          162          155           32           14
```

Example 12 (javascript):
```javascript
## 
##  Naive CD4 T Memory CD4 T   CD14+ Mono            B        CD8 T 
##          697          483          480          344          271 
## FCGR3A+ Mono           NK           DC     Platelet 
##          162          155           32           14
```

Example 13 (r):
```r
# How many cells are in each replicate?
table(pbmc$replicate)
```

Example 14 (r):
```r
# How many cells are in each replicate?
table(pbmc$replicate)
```

Example 15 (unknown):
```unknown
## 
## rep1 rep2 
## 1327 1311
```

Example 16 (unknown):
```unknown
## 
## rep1 rep2 
## 1327 1311
```

Example 17 (r):
```r
# What proportion of cells are in each cluster?
prop.table(table(Idents(pbmc)))
```

Example 18 (r):
```r
# What proportion of cells are in each cluster?
prop.table(table(Idents(pbmc)))
```

Example 19 (javascript):
```javascript
## 
##  Naive CD4 T Memory CD4 T   CD14+ Mono            B        CD8 T 
##  0.264215315  0.183093252  0.181956027  0.130401820  0.102729340 
## FCGR3A+ Mono           NK           DC     Platelet 
##  0.061410159  0.058756634  0.012130402  0.005307051
```

Example 20 (javascript):
```javascript
## 
##  Naive CD4 T Memory CD4 T   CD14+ Mono            B        CD8 T 
##  0.264215315  0.183093252  0.181956027  0.130401820  0.102729340 
## FCGR3A+ Mono           NK           DC     Platelet 
##  0.061410159  0.058756634  0.012130402  0.005307051
```

Example 21 (r):
```r
# How does cluster membership vary by replicate?
table(Idents(pbmc), pbmc$replicate)
```

Example 22 (r):
```r
# How does cluster membership vary by replicate?
table(Idents(pbmc), pbmc$replicate)
```

Example 23 (javascript):
```javascript
##               
##                rep1 rep2
##   Naive CD4 T   337  360
##   Memory CD4 T  243  240
##   CD14+ Mono    240  240
##   B             166  178
##   CD8 T         152  119
##   FCGR3A+ Mono   84   78
##   NK             83   72
##   DC             18   14
##   Platelet        4   10
```

Example 24 (javascript):
```javascript
##               
##                rep1 rep2
##   Naive CD4 T   337  360
##   Memory CD4 T  243  240
##   CD14+ Mono    240  240
##   B             166  178
##   CD8 T         152  119
##   FCGR3A+ Mono   84   78
##   NK             83   72
##   DC             18   14
##   Platelet        4   10
```

Example 25 (r):
```r
prop.table(table(Idents(pbmc), pbmc$replicate), margin = 2)
```

Example 26 (r):
```r
prop.table(table(Idents(pbmc), pbmc$replicate), margin = 2)
```

Example 27 (javascript):
```javascript
##               
##                       rep1        rep2
##   Naive CD4 T  0.253956292 0.274599542
##   Memory CD4 T 0.183119819 0.183066362
##   CD14+ Mono   0.180859081 0.183066362
##   B            0.125094197 0.135774218
##   CD8 T        0.114544084 0.090770404
##   FCGR3A+ Mono 0.063300678 0.059496568
##   NK           0.062547099 0.054919908
##   DC           0.013564431 0.010678871
##   Platelet     0.003014318 0.007627765
```

Example 28 (javascript):
```javascript
##               
##                       rep1        rep2
##   Naive CD4 T  0.253956292 0.274599542
##   Memory CD4 T 0.183119819 0.183066362
##   CD14+ Mono   0.180859081 0.183066362
##   B            0.125094197 0.135774218
##   CD8 T        0.114544084 0.090770404
##   FCGR3A+ Mono 0.063300678 0.059496568
##   NK           0.062547099 0.054919908
##   DC           0.013564431 0.010678871
##   Platelet     0.003014318 0.007627765
```

Example 29 (r):
```r
# What are the cell names of all NK cells?
WhichCells(pbmc, idents = "NK")
```

Example 30 (r):
```r
# What are the cell names of all NK cells?
WhichCells(pbmc, idents = "NK")
```

Example 31 (unknown):
```unknown
##   [1] "AAACCGTGTATGCG" "AAATTCGATTCTCA" "AACCTTACGCGAGA" "AACGCCCTCGTACA"
##   [5] "AACGTCGAGTATCG" "AAGATTACCTCAAG" "AAGCAAGAGCTTAG" "AAGCAAGAGGTGTT"
##   [9] "AAGTAGGATACAGC" "AATACTGAATTGGC" "AATCCTTGGTGAGG" "AATCTCTGCTTTAC"
##  [13] "ACAAATTGTTGCGA" "ACAACCGAGGGATG" "ACAATTGATGACTG" "ACACCCTGGTGTTG"
##  [17] "ACAGGTACTGGTGT" "ACCTGGCTAAGTAG" "ACGAACACCTTGTT" "ACGATCGAGGACTT"
##  [21] "ACGCAATGGTTCAG" "ACGCTGCTGTTCTT" "ACGGAACTCAGATC" "ACGTGATGTGACAC"
##  [25] "ACGTTGGAGCCAAT" "ACTGCCACTCCGTC" "ACTGGCCTTCAGTG" "ACTTCAACGTAGGG"
##  [29] "AGAACAGAAATGCC" "AGATATACCCGTAA" "AGATTCCTGTTCAG" "AGCCTCTGCCAATG"
##  [33] "AGCGATTGAGATCC" "AGGATGCTTTAGGC" "AGGGACGAGTCAAC" "AGTAATACATCACG"
##  [37] "AGTCACGATGAGCT" "AGTTTGCTACTGGT" "ATACCACTGCCAAT" "ATACTCTGGTATGC"
##  [41] "ATCCCGTGCAGTCA" "ATCTTTCTTGTCCC" "ATGAAGGACTTGCC" "ATGATAACTTCACT"
##  [45] "ATGATATGGTGCTA" "ATGGACACGCATCA" "ATGGGTACATCGGT" "ATTAACGATGAGAA"
##  [49] "ATTCCAACTTAGGC" "CAAGGTTGTCTGGA" "CAATCTACTGACTG" "CACCACTGGCGAAG"
##  [53] "CACGGGTGGAGGAC" "CAGATGACATTCTC" "CAGCAATGGAGGGT" "CAGCGGACCTTTAC"
##  [57] "CAGCTCTGTGTGGT" "CAGTTTACACACGT" "CATCAGGACTTCCG" "CATCAGGATAGCCA"
##  [61] "CATGAGACGTTGAC" "CATTACACCAACTG" "CATTTCGAGATACC" "CCTCGAACACTTTC"
##  [65] "CGACCACTAAAGTG" "CGACCACTGCCAAT" "CGAGGCTGACGCTA" "CGCCGAGAGCTTAG"
##  [69] "CGGCGAACGACAAA" "CGGCGAACTACTTC" "CGGGCATGTCTCTA" "CGTACCTGGCATCA"
##  [73] "CGTGTAGACGATAC" "CGTGTAGAGTTACG" "CGTGTAGATTCGGA" "CTAAACCTCTGACA"
##  [77] "CTAACGGAACCGAT" "CTACGCACTGGTCA" "CTACTCCTATGTCG" "CTAGTTACGAAACA"
##  [81] "CTATACTGCTACGA" "CTATACTGTCTCAT" "CTCGACTGGTTGAC" "CTGAGAACGTAAAG"
##  [85] "CTTTAGTGACGGGA" "GAACCAACTTCCGC" "GAAGTGCTAAACGA" "GAATGCACCTTCGC"
##  [89] "GAATTAACGTCGTA" "GACGGCACACGGGA" "GAGCGCTGAAGATG" "GAGGTACTGACACT"
##  [93] "GAGGTGGATCCTCG" "GATAGAGAAGGGTG" "GATCCCTGACCTTT" "GCACACCTGTGCTA"
##  [97] "GCACCACTTCCTTA" "GCACTAGAGTCGTA" "GCAGGGCTATCGAC" "GCCGGAACGTTCTT"
## [101] "GCCTACACAGTTCG" "GCGCATCTTGCTCC" "GCGCGATGGTGCAT" "GGAAGGTGGCGAGA"
## [105] "GGACGCTGTCCTCG" "GGAGGCCTCGTTGA" "GGCAAGGAAAAAGC" "GGCATATGCTTATC"
## [109] "GGCCGAACTCTAGG" "GGCTAAACACCTGA" "GGGTTAACGTGCAT" "GGTGGAGAAACGGG"
## [113] "GTAGTGTGAGCGGA" "GTCGACCTGAATGA" "GTGATTCTGGTTCA" "GTGTATCTAGTAGA"
## [117] "GTTAAAACCGAGAG" "GTTCAACTGGGACA" "GTTGACGATATCGG" "TAACTCACTCTACT"
## [121] "TAAGAGGACTTGTT" "TAATGCCTCGTCTC" "TACGGCCTGGGACA" "TACTACTGATGTCG"
## [125] "TACTCTGAATCGAC" "TACTGTTGAGGCGA" "TAGCATCTCAGCTA" "TAGCCCACAGCTAC"
## [129] "TAGGGACTGAACTC" "TAGTGGTGAAGTGA" "TAGTTAGAACCACA" "TATGAATGGAGGAC"
## [133] "TATGGGTGCATCAG" "TATTTCCTGGAGGT" "TCAACACTGTTTGG" "TCAGACGACGTTAG"
## [137] "TCCCGAACACAGTC" "TCCTAAACCGCATA" "TCGATTTGCAGCTA" "TCTAACACCAGTTG"
## [141] "TGATAAACTCCGTC" "TGCACAGACGACAT" "TGCCACTGCGATAC" "TGCTGAGAGAGCAG"
## [145] "TGGAACACAAACAG" "TGGTAGACCCTCAC" "TGTAATGACACAAC" "TGTAATGAGGTAAA"
## [149] "TTACTCGATCTACT" "TTAGTCTGCCAACA" "TTCCAAACTCCCAC" "TTCCCACTTGAGGG"
## [153] "TTCTAGTGGAGAGC" "TTCTGATGGAGACG" "TTGTCATGGACGGA"
```

Example 32 (unknown):
```unknown
##   [1] "AAACCGTGTATGCG" "AAATTCGATTCTCA" "AACCTTACGCGAGA" "AACGCCCTCGTACA"
##   [5] "AACGTCGAGTATCG" "AAGATTACCTCAAG" "AAGCAAGAGCTTAG" "AAGCAAGAGGTGTT"
##   [9] "AAGTAGGATACAGC" "AATACTGAATTGGC" "AATCCTTGGTGAGG" "AATCTCTGCTTTAC"
##  [13] "ACAAATTGTTGCGA" "ACAACCGAGGGATG" "ACAATTGATGACTG" "ACACCCTGGTGTTG"
##  [17] "ACAGGTACTGGTGT" "ACCTGGCTAAGTAG" "ACGAACACCTTGTT" "ACGATCGAGGACTT"
##  [21] "ACGCAATGGTTCAG" "ACGCTGCTGTTCTT" "ACGGAACTCAGATC" "ACGTGATGTGACAC"
##  [25] "ACGTTGGAGCCAAT" "ACTGCCACTCCGTC" "ACTGGCCTTCAGTG" "ACTTCAACGTAGGG"
##  [29] "AGAACAGAAATGCC" "AGATATACCCGTAA" "AGATTCCTGTTCAG" "AGCCTCTGCCAATG"
##  [33] "AGCGATTGAGATCC" "AGGATGCTTTAGGC" "AGGGACGAGTCAAC" "AGTAATACATCACG"
##  [37] "AGTCACGATGAGCT" "AGTTTGCTACTGGT" "ATACCACTGCCAAT" "ATACTCTGGTATGC"
##  [41] "ATCCCGTGCAGTCA" "ATCTTTCTTGTCCC" "ATGAAGGACTTGCC" "ATGATAACTTCACT"
##  [45] "ATGATATGGTGCTA" "ATGGACACGCATCA" "ATGGGTACATCGGT" "ATTAACGATGAGAA"
##  [49] "ATTCCAACTTAGGC" "CAAGGTTGTCTGGA" "CAATCTACTGACTG" "CACCACTGGCGAAG"
##  [53] "CACGGGTGGAGGAC" "CAGATGACATTCTC" "CAGCAATGGAGGGT" "CAGCGGACCTTTAC"
##  [57] "CAGCTCTGTGTGGT" "CAGTTTACACACGT" "CATCAGGACTTCCG" "CATCAGGATAGCCA"
##  [61] "CATGAGACGTTGAC" "CATTACACCAACTG" "CATTTCGAGATACC" "CCTCGAACACTTTC"
##  [65] "CGACCACTAAAGTG" "CGACCACTGCCAAT" "CGAGGCTGACGCTA" "CGCCGAGAGCTTAG"
##  [69] "CGGCGAACGACAAA" "CGGCGAACTACTTC" "CGGGCATGTCTCTA" "CGTACCTGGCATCA"
##  [73] "CGTGTAGACGATAC" "CGTGTAGAGTTACG" "CGTGTAGATTCGGA" "CTAAACCTCTGACA"
##  [77] "CTAACGGAACCGAT" "CTACGCACTGGTCA" "CTACTCCTATGTCG" "CTAGTTACGAAACA"
##  [81] "CTATACTGCTACGA" "CTATACTGTCTCAT" "CTCGACTGGTTGAC" "CTGAGAACGTAAAG"
##  [85] "CTTTAGTGACGGGA" "GAACCAACTTCCGC" "GAAGTGCTAAACGA" "GAATGCACCTTCGC"
##  [89] "GAATTAACGTCGTA" "GACGGCACACGGGA" "GAGCGCTGAAGATG" "GAGGTACTGACACT"
##  [93] "GAGGTGGATCCTCG" "GATAGAGAAGGGTG" "GATCCCTGACCTTT" "GCACACCTGTGCTA"
##  [97] "GCACCACTTCCTTA" "GCACTAGAGTCGTA" "GCAGGGCTATCGAC" "GCCGGAACGTTCTT"
## [101] "GCCTACACAGTTCG" "GCGCATCTTGCTCC" "GCGCGATGGTGCAT" "GGAAGGTGGCGAGA"
## [105] "GGACGCTGTCCTCG" "GGAGGCCTCGTTGA" "GGCAAGGAAAAAGC" "GGCATATGCTTATC"
## [109] "GGCCGAACTCTAGG" "GGCTAAACACCTGA" "GGGTTAACGTGCAT" "GGTGGAGAAACGGG"
## [113] "GTAGTGTGAGCGGA" "GTCGACCTGAATGA" "GTGATTCTGGTTCA" "GTGTATCTAGTAGA"
## [117] "GTTAAAACCGAGAG" "GTTCAACTGGGACA" "GTTGACGATATCGG" "TAACTCACTCTACT"
## [121] "TAAGAGGACTTGTT" "TAATGCCTCGTCTC" "TACGGCCTGGGACA" "TACTACTGATGTCG"
## [125] "TACTCTGAATCGAC" "TACTGTTGAGGCGA" "TAGCATCTCAGCTA" "TAGCCCACAGCTAC"
## [129] "TAGGGACTGAACTC" "TAGTGGTGAAGTGA" "TAGTTAGAACCACA" "TATGAATGGAGGAC"
## [133] "TATGGGTGCATCAG" "TATTTCCTGGAGGT" "TCAACACTGTTTGG" "TCAGACGACGTTAG"
## [137] "TCCCGAACACAGTC" "TCCTAAACCGCATA" "TCGATTTGCAGCTA" "TCTAACACCAGTTG"
## [141] "TGATAAACTCCGTC" "TGCACAGACGACAT" "TGCCACTGCGATAC" "TGCTGAGAGAGCAG"
## [145] "TGGAACACAAACAG" "TGGTAGACCCTCAC" "TGTAATGACACAAC" "TGTAATGAGGTAAA"
## [149] "TTACTCGATCTACT" "TTAGTCTGCCAACA" "TTCCAAACTCCCAC" "TTCCCACTTGAGGG"
## [153] "TTCTAGTGGAGAGC" "TTCTGATGGAGACG" "TTGTCATGGACGGA"
```

Example 33 (r):
```r
# How can I extract expression matrix for all NK cells (perhaps, to load into another package)
nk.raw.data <- as.matrix(GetAssayData(pbmc, slot = "counts")[, WhichCells(pbmc, ident = "NK")])

# Can I create a Seurat object based on expression of a feature or value in object metadata?
subset(pbmc, subset = MS4A1 > 1)
```

Example 34 (r):
```r
# How can I extract expression matrix for all NK cells (perhaps, to load into another package)
nk.raw.data <- as.matrix(GetAssayData(pbmc, slot = "counts")[, WhichCells(pbmc, ident = "NK")])

# Can I create a Seurat object based on expression of a feature or value in object metadata?
subset(pbmc, subset = MS4A1 > 1)
```

Example 35 (python):
```python
## An object of class Seurat 
## 13714 features across 414 samples within 1 assay 
## Active assay: RNA (13714 features)
##  2 dimensional reductions calculated: pca, umap
```

Example 36 (python):
```python
## An object of class Seurat 
## 13714 features across 414 samples within 1 assay 
## Active assay: RNA (13714 features)
##  2 dimensional reductions calculated: pca, umap
```

Example 37 (r):
```r
subset(pbmc, subset = replicate == "rep2")
```

Example 38 (r):
```r
subset(pbmc, subset = replicate == "rep2")
```

Example 39 (python):
```python
## An object of class Seurat 
## 13714 features across 1311 samples within 1 assay 
## Active assay: RNA (13714 features)
##  2 dimensional reductions calculated: pca, umap
```

Example 40 (python):
```python
## An object of class Seurat 
## 13714 features across 1311 samples within 1 assay 
## Active assay: RNA (13714 features)
##  2 dimensional reductions calculated: pca, umap
```

Example 41 (r):
```r
# Can I create a Seurat object of just the NK cells and B cells?
subset(pbmc, idents = c("NK", "B"))
```

Example 42 (r):
```r
# Can I create a Seurat object of just the NK cells and B cells?
subset(pbmc, idents = c("NK", "B"))
```

Example 43 (python):
```python
## An object of class Seurat 
## 13714 features across 499 samples within 1 assay 
## Active assay: RNA (13714 features)
##  2 dimensional reductions calculated: pca, umap
```

Example 44 (python):
```python
## An object of class Seurat 
## 13714 features across 499 samples within 1 assay 
## Active assay: RNA (13714 features)
##  2 dimensional reductions calculated: pca, umap
```

Example 45 (r):
```r
# Can I create a Seurat object of all cells except the NK cells and B cells?
subset(pbmc, idents = c("NK", "B"), invert = TRUE)
```

Example 46 (r):
```r
# Can I create a Seurat object of all cells except the NK cells and B cells?
subset(pbmc, idents = c("NK", "B"), invert = TRUE)
```

Example 47 (python):
```python
## An object of class Seurat 
## 13714 features across 2139 samples within 1 assay 
## Active assay: RNA (13714 features)
##  2 dimensional reductions calculated: pca, umap
```

Example 48 (python):
```python
## An object of class Seurat 
## 13714 features across 2139 samples within 1 assay 
## Active assay: RNA (13714 features)
##  2 dimensional reductions calculated: pca, umap
```

Example 49 (r):
```r
# note that if you wish to perform additional rounds of clustering after subsetting we recommend
# re-running FindVariableFeatures() and ScaleData()
```

Example 50 (r):
```r
# note that if you wish to perform additional rounds of clustering after subsetting we recommend
# re-running FindVariableFeatures() and ScaleData()
```

Example 51 (r):
```r
# How can I calculate the average expression of all cells within a cluster?
cluster.averages <- AverageExpression(pbmc)
head(cluster.averages[["RNA"]][, 1:5])
```

Example 52 (r):
```r
# How can I calculate the average expression of all cells within a cluster?
cluster.averages <- AverageExpression(pbmc)
head(cluster.averages[["RNA"]][, 1:5])
```

Example 53 (r):
```r
# Return this information as a Seurat object (enables downstream plotting and analysis) First,
# replace spaces with underscores '_' so ggplot2 doesn't fail
orig.levels <- levels(pbmc)
Idents(pbmc) <- gsub(pattern = " ", replacement = "_", x = Idents(pbmc))
orig.levels <- gsub(pattern = " ", replacement = "_", x = orig.levels)
levels(pbmc) <- orig.levels
cluster.averages <- AverageExpression(pbmc, return.seurat = TRUE)
cluster.averages
```

Example 54 (r):
```r
# Return this information as a Seurat object (enables downstream plotting and analysis) First,
# replace spaces with underscores '_' so ggplot2 doesn't fail
orig.levels <- levels(pbmc)
Idents(pbmc) <- gsub(pattern = " ", replacement = "_", x = Idents(pbmc))
orig.levels <- gsub(pattern = " ", replacement = "_", x = orig.levels)
levels(pbmc) <- orig.levels
cluster.averages <- AverageExpression(pbmc, return.seurat = TRUE)
cluster.averages
```

Example 55 (python):
```python
## An object of class Seurat 
## 13714 features across 9 samples within 1 assay 
## Active assay: RNA (13714 features)
```

Example 56 (python):
```python
## An object of class Seurat 
## 13714 features across 9 samples within 1 assay 
## Active assay: RNA (13714 features)
```

Example 57 (r):
```r
# How can I plot the average expression of NK cells vs. CD8 T cells?  Pass do.hover = T for an
# interactive plot to identify gene outliers
CellScatter(cluster.averages, cell1 = "NK", cell2 = "CD8_T")
```

Example 58 (r):
```r
# How can I plot the average expression of NK cells vs. CD8 T cells?  Pass do.hover = T for an
# interactive plot to identify gene outliers
CellScatter(cluster.averages, cell1 = "NK", cell2 = "CD8_T")
```

Example 59 (r):
```r
# How can I calculate expression averages separately for each replicate?
cluster.averages <- AverageExpression(pbmc, return.seurat = TRUE, add.ident = "replicate")
CellScatter(cluster.averages, cell1 = "CD8_T_rep1", cell2 = "CD8_T_rep2")
```

Example 60 (r):
```r
# How can I calculate expression averages separately for each replicate?
cluster.averages <- AverageExpression(pbmc, return.seurat = TRUE, add.ident = "replicate")
CellScatter(cluster.averages, cell1 = "CD8_T_rep1", cell2 = "CD8_T_rep2")
```

Example 61 (r):
```r
# You can also plot heatmaps of these 'in silico' bulk datasets to visualize agreement between
# replicates
DoHeatmap(cluster.averages, features = unlist(TopFeatures(pbmc[["pca"]], balanced = TRUE)), size = 3, 
    draw.lines = FALSE)
```

Example 62 (r):
```r
# You can also plot heatmaps of these 'in silico' bulk datasets to visualize agreement between
# replicates
DoHeatmap(cluster.averages, features = unlist(TopFeatures(pbmc[["pca"]], balanced = TRUE)), size = 3, 
    draw.lines = FALSE)
```

---

## Seurat - Interaction Tips

**URL:** http://127.0.0.1:9173/seurat/archive/v3.2/interaction_vignette/index.html

**Contents:**
- Seurat - Interaction Tips
    - Compiled: October 02, 2020
  - Load in the data
  - Switch identity class between cluster ID and replicate
  - Tabulate cells by cluster ID, replicate, or both
  - Selecting particular cells and subsetting the Seurat object
  - Calculating the average gene expression within a cluster

This vignette demonstrates some useful features for interacting with the Seurat object. For demonstration purposes, we will be using the 2,700 PBMC object that is created in the first guided tutorial. You can download the pre-computed object here. To simulate the scenario where we have two replicates, we will randomly assign half the cells in each cluster to be from "rep1" and other half from "rep2".

**Examples:**

Example 1 (r):
```r
library(Seurat)
pbmc <- readRDS(file = "../data/pbmc3k_final.rds")

# pretend that cells were originally assigned to one of two replicates (we assign randomly here)
# if your cells do belong to multiple replicates, and you want to add this info to the Seurat
# object create a data frame with this information (similar to replicate.info below)
set.seed(42)
pbmc$replicate <- sample(c("rep1", "rep2"), size = ncol(pbmc), replace = TRUE)
```

Example 2 (r):
```r
library(Seurat)
pbmc <- readRDS(file = "../data/pbmc3k_final.rds")

# pretend that cells were originally assigned to one of two replicates (we assign randomly here)
# if your cells do belong to multiple replicates, and you want to add this info to the Seurat
# object create a data frame with this information (similar to replicate.info below)
set.seed(42)
pbmc$replicate <- sample(c("rep1", "rep2"), size = ncol(pbmc), replace = TRUE)
```

Example 3 (r):
```r
# Plot UMAP, coloring cells by cell type (currently stored in object@ident)
DimPlot(pbmc, reduction = "umap")
```

Example 4 (r):
```r
# Plot UMAP, coloring cells by cell type (currently stored in object@ident)
DimPlot(pbmc, reduction = "umap")
```

Example 5 (r):
```r
# How do I create a UMAP plot where cells are colored by replicate?  First, store the current
# identities in a new column of meta.data called CellType
pbmc$CellType <- Idents(pbmc)
# Next, switch the identity class of all cells to reflect replicate ID
Idents(pbmc) <- "replicate"
DimPlot(pbmc, reduction = "umap")
```

Example 6 (r):
```r
# How do I create a UMAP plot where cells are colored by replicate?  First, store the current
# identities in a new column of meta.data called CellType
pbmc$CellType <- Idents(pbmc)
# Next, switch the identity class of all cells to reflect replicate ID
Idents(pbmc) <- "replicate"
DimPlot(pbmc, reduction = "umap")
```

Example 7 (r):
```r
# alternately : DimPlot(pbmc, reduction = 'umap', group.by = 'replicate') you can pass the
# shape.by to label points by both replicate and cell type

# Switch back to cell type labels
Idents(pbmc) <- "CellType"
```

Example 8 (r):
```r
# alternately : DimPlot(pbmc, reduction = 'umap', group.by = 'replicate') you can pass the
# shape.by to label points by both replicate and cell type

# Switch back to cell type labels
Idents(pbmc) <- "CellType"
```

Example 9 (r):
```r
# How many cells are in each cluster
table(Idents(pbmc))
```

Example 10 (r):
```r
# How many cells are in each cluster
table(Idents(pbmc))
```

Example 11 (javascript):
```javascript
## 
##  Naive CD4 T Memory CD4 T   CD14+ Mono            B        CD8 T FCGR3A+ Mono 
##          697          483          480          344          271          162 
##           NK           DC     Platelet 
##          155           32           14
```

Example 12 (javascript):
```javascript
## 
##  Naive CD4 T Memory CD4 T   CD14+ Mono            B        CD8 T FCGR3A+ Mono 
##          697          483          480          344          271          162 
##           NK           DC     Platelet 
##          155           32           14
```

Example 13 (r):
```r
# How many cells are in each replicate?
table(pbmc$replicate)
```

Example 14 (r):
```r
# How many cells are in each replicate?
table(pbmc$replicate)
```

Example 15 (unknown):
```unknown
## 
## rep1 rep2 
## 1348 1290
```

Example 16 (unknown):
```unknown
## 
## rep1 rep2 
## 1348 1290
```

Example 17 (r):
```r
# What proportion of cells are in each cluster?
prop.table(table(Idents(pbmc)))
```

Example 18 (r):
```r
# What proportion of cells are in each cluster?
prop.table(table(Idents(pbmc)))
```

Example 19 (javascript):
```javascript
## 
##  Naive CD4 T Memory CD4 T   CD14+ Mono            B        CD8 T FCGR3A+ Mono 
##  0.264215315  0.183093252  0.181956027  0.130401820  0.102729340  0.061410159 
##           NK           DC     Platelet 
##  0.058756634  0.012130402  0.005307051
```

Example 20 (javascript):
```javascript
## 
##  Naive CD4 T Memory CD4 T   CD14+ Mono            B        CD8 T FCGR3A+ Mono 
##  0.264215315  0.183093252  0.181956027  0.130401820  0.102729340  0.061410159 
##           NK           DC     Platelet 
##  0.058756634  0.012130402  0.005307051
```

Example 21 (r):
```r
# How does cluster membership vary by replicate?
table(Idents(pbmc), pbmc$replicate)
```

Example 22 (r):
```r
# How does cluster membership vary by replicate?
table(Idents(pbmc), pbmc$replicate)
```

Example 23 (javascript):
```javascript
##               
##                rep1 rep2
##   Naive CD4 T   354  343
##   Memory CD4 T  249  234
##   CD14+ Mono    232  248
##   B             173  171
##   CD8 T         154  117
##   FCGR3A+ Mono   81   81
##   NK             81   74
##   DC             18   14
##   Platelet        6    8
```

Example 24 (javascript):
```javascript
##               
##                rep1 rep2
##   Naive CD4 T   354  343
##   Memory CD4 T  249  234
##   CD14+ Mono    232  248
##   B             173  171
##   CD8 T         154  117
##   FCGR3A+ Mono   81   81
##   NK             81   74
##   DC             18   14
##   Platelet        6    8
```

Example 25 (r):
```r
prop.table(table(Idents(pbmc), pbmc$replicate), margin = 2)
```

Example 26 (r):
```r
prop.table(table(Idents(pbmc), pbmc$replicate), margin = 2)
```

Example 27 (javascript):
```javascript
##               
##                       rep1        rep2
##   Naive CD4 T  0.262611276 0.265891473
##   Memory CD4 T 0.184718101 0.181395349
##   CD14+ Mono   0.172106825 0.192248062
##   B            0.128338279 0.132558140
##   CD8 T        0.114243323 0.090697674
##   FCGR3A+ Mono 0.060089021 0.062790698
##   NK           0.060089021 0.057364341
##   DC           0.013353116 0.010852713
##   Platelet     0.004451039 0.006201550
```

Example 28 (javascript):
```javascript
##               
##                       rep1        rep2
##   Naive CD4 T  0.262611276 0.265891473
##   Memory CD4 T 0.184718101 0.181395349
##   CD14+ Mono   0.172106825 0.192248062
##   B            0.128338279 0.132558140
##   CD8 T        0.114243323 0.090697674
##   FCGR3A+ Mono 0.060089021 0.062790698
##   NK           0.060089021 0.057364341
##   DC           0.013353116 0.010852713
##   Platelet     0.004451039 0.006201550
```

Example 29 (r):
```r
# What are the cell names of all NK cells?
WhichCells(pbmc, idents = "NK")
```

Example 30 (r):
```r
# What are the cell names of all NK cells?
WhichCells(pbmc, idents = "NK")
```

Example 31 (unknown):
```unknown
##   [1] "AAACCGTGTATGCG-1" "AAATTCGATTCTCA-1" "AACCTTACGCGAGA-1"
##   [4] "AACGCCCTCGTACA-1" "AACGTCGAGTATCG-1" "AAGATTACCTCAAG-1"
##   [7] "AAGCAAGAGCTTAG-1" "AAGCAAGAGGTGTT-1" "AAGTAGGATACAGC-1"
##  [10] "AATACTGAATTGGC-1" "AATCCTTGGTGAGG-1" "AATCTCTGCTTTAC-1"
##  [13] "ACAAATTGTTGCGA-1" "ACAACCGAGGGATG-1" "ACAATTGATGACTG-1"
##  [16] "ACACCCTGGTGTTG-1" "ACAGGTACTGGTGT-1" "ACCTGGCTAAGTAG-1"
##  [19] "ACGAACACCTTGTT-1" "ACGATCGAGGACTT-1" "ACGCAATGGTTCAG-1"
##  [22] "ACGCTGCTGTTCTT-1" "ACGGAACTCAGATC-1" "ACGTGATGTGACAC-1"
##  [25] "ACGTTGGAGCCAAT-1" "ACTGCCACTCCGTC-1" "ACTGGCCTTCAGTG-1"
##  [28] "ACTTCAACGTAGGG-1" "AGAACAGAAATGCC-1" "AGATATACCCGTAA-1"
##  [31] "AGATTCCTGTTCAG-1" "AGCCTCTGCCAATG-1" "AGCGATTGAGATCC-1"
##  [34] "AGGATGCTTTAGGC-1" "AGGGACGAGTCAAC-1" "AGTAATACATCACG-1"
##  [37] "AGTCACGATGAGCT-1" "AGTTTGCTACTGGT-1" "ATACCACTGCCAAT-1"
##  [40] "ATACTCTGGTATGC-1" "ATCCCGTGCAGTCA-1" "ATCTTTCTTGTCCC-1"
##  [43] "ATGAAGGACTTGCC-1" "ATGATAACTTCACT-1" "ATGATATGGTGCTA-1"
##  [46] "ATGGACACGCATCA-1" "ATGGGTACATCGGT-1" "ATTAACGATGAGAA-1"
##  [49] "ATTCCAACTTAGGC-1" "CAAGGTTGTCTGGA-1" "CAATCTACTGACTG-1"
##  [52] "CACCACTGGCGAAG-1" "CACGGGTGGAGGAC-1" "CAGATGACATTCTC-1"
##  [55] "CAGCAATGGAGGGT-1" "CAGCGGACCTTTAC-1" "CAGCTCTGTGTGGT-1"
##  [58] "CAGTTTACACACGT-1" "CATCAGGACTTCCG-1" "CATCAGGATAGCCA-1"
##  [61] "CATGAGACGTTGAC-1" "CATTACACCAACTG-1" "CATTTCGAGATACC-1"
##  [64] "CCTCGAACACTTTC-1" "CGACCACTAAAGTG-1" "CGACCACTGCCAAT-1"
##  [67] "CGAGGCTGACGCTA-1" "CGCCGAGAGCTTAG-1" "CGGCGAACGACAAA-1"
##  [70] "CGGCGAACTACTTC-1" "CGGGCATGTCTCTA-1" "CGTACCTGGCATCA-1"
##  [73] "CGTGTAGACGATAC-1" "CGTGTAGAGTTACG-1" "CGTGTAGATTCGGA-1"
##  [76] "CTAAACCTCTGACA-1" "CTAACGGAACCGAT-1" "CTACGCACTGGTCA-1"
##  [79] "CTACTCCTATGTCG-1" "CTAGTTACGAAACA-1" "CTATACTGCTACGA-1"
##  [82] "CTATACTGTCTCAT-1" "CTCGACTGGTTGAC-1" "CTGAGAACGTAAAG-1"
##  [85] "CTTTAGTGACGGGA-1" "GAACCAACTTCCGC-1" "GAAGTGCTAAACGA-1"
##  [88] "GAATGCACCTTCGC-1" "GAATTAACGTCGTA-1" "GACGGCACACGGGA-1"
##  [91] "GAGCGCTGAAGATG-1" "GAGGTACTGACACT-1" "GAGGTGGATCCTCG-1"
##  [94] "GATAGAGAAGGGTG-1" "GATCCCTGACCTTT-1" "GCACACCTGTGCTA-1"
##  [97] "GCACCACTTCCTTA-1" "GCACTAGAGTCGTA-1" "GCAGGGCTATCGAC-1"
## [100] "GCCGGAACGTTCTT-1" "GCCTACACAGTTCG-1" "GCGCATCTTGCTCC-1"
## [103] "GCGCGATGGTGCAT-1" "GGAAGGTGGCGAGA-1" "GGACGCTGTCCTCG-1"
## [106] "GGAGGCCTCGTTGA-1" "GGCAAGGAAAAAGC-1" "GGCATATGCTTATC-1"
## [109] "GGCCGAACTCTAGG-1" "GGCTAAACACCTGA-1" "GGGTTAACGTGCAT-1"
## [112] "GGTGGAGAAACGGG-1" "GTAGTGTGAGCGGA-1" "GTCGACCTGAATGA-1"
## [115] "GTGATTCTGGTTCA-1" "GTGTATCTAGTAGA-1" "GTTAAAACCGAGAG-1"
## [118] "GTTCAACTGGGACA-1" "GTTGACGATATCGG-1" "TAACTCACTCTACT-1"
## [121] "TAAGAGGACTTGTT-1" "TAATGCCTCGTCTC-1" "TACGGCCTGGGACA-1"
## [124] "TACTACTGATGTCG-1" "TACTCTGAATCGAC-1" "TACTGTTGAGGCGA-1"
## [127] "TAGCATCTCAGCTA-1" "TAGCCCACAGCTAC-1" "TAGGGACTGAACTC-1"
## [130] "TAGTGGTGAAGTGA-1" "TAGTTAGAACCACA-1" "TATGAATGGAGGAC-1"
## [133] "TATGGGTGCATCAG-1" "TATTTCCTGGAGGT-1" "TCAACACTGTTTGG-1"
## [136] "TCAGACGACGTTAG-1" "TCCCGAACACAGTC-1" "TCCTAAACCGCATA-1"
## [139] "TCGATTTGCAGCTA-1" "TCTAACACCAGTTG-1" "TGATAAACTCCGTC-1"
## [142] "TGCACAGACGACAT-1" "TGCCACTGCGATAC-1" "TGCTGAGAGAGCAG-1"
## [145] "TGGAACACAAACAG-1" "TGGTAGACCCTCAC-1" "TGTAATGACACAAC-1"
## [148] "TGTAATGAGGTAAA-1" "TTACTCGATCTACT-1" "TTAGTCTGCCAACA-1"
## [151] "TTCCAAACTCCCAC-1" "TTCCCACTTGAGGG-1" "TTCTAGTGGAGAGC-1"
## [154] "TTCTGATGGAGACG-1" "TTGTCATGGACGGA-1"
```

Example 32 (unknown):
```unknown
##   [1] "AAACCGTGTATGCG-1" "AAATTCGATTCTCA-1" "AACCTTACGCGAGA-1"
##   [4] "AACGCCCTCGTACA-1" "AACGTCGAGTATCG-1" "AAGATTACCTCAAG-1"
##   [7] "AAGCAAGAGCTTAG-1" "AAGCAAGAGGTGTT-1" "AAGTAGGATACAGC-1"
##  [10] "AATACTGAATTGGC-1" "AATCCTTGGTGAGG-1" "AATCTCTGCTTTAC-1"
##  [13] "ACAAATTGTTGCGA-1" "ACAACCGAGGGATG-1" "ACAATTGATGACTG-1"
##  [16] "ACACCCTGGTGTTG-1" "ACAGGTACTGGTGT-1" "ACCTGGCTAAGTAG-1"
##  [19] "ACGAACACCTTGTT-1" "ACGATCGAGGACTT-1" "ACGCAATGGTTCAG-1"
##  [22] "ACGCTGCTGTTCTT-1" "ACGGAACTCAGATC-1" "ACGTGATGTGACAC-1"
##  [25] "ACGTTGGAGCCAAT-1" "ACTGCCACTCCGTC-1" "ACTGGCCTTCAGTG-1"
##  [28] "ACTTCAACGTAGGG-1" "AGAACAGAAATGCC-1" "AGATATACCCGTAA-1"
##  [31] "AGATTCCTGTTCAG-1" "AGCCTCTGCCAATG-1" "AGCGATTGAGATCC-1"
##  [34] "AGGATGCTTTAGGC-1" "AGGGACGAGTCAAC-1" "AGTAATACATCACG-1"
##  [37] "AGTCACGATGAGCT-1" "AGTTTGCTACTGGT-1" "ATACCACTGCCAAT-1"
##  [40] "ATACTCTGGTATGC-1" "ATCCCGTGCAGTCA-1" "ATCTTTCTTGTCCC-1"
##  [43] "ATGAAGGACTTGCC-1" "ATGATAACTTCACT-1" "ATGATATGGTGCTA-1"
##  [46] "ATGGACACGCATCA-1" "ATGGGTACATCGGT-1" "ATTAACGATGAGAA-1"
##  [49] "ATTCCAACTTAGGC-1" "CAAGGTTGTCTGGA-1" "CAATCTACTGACTG-1"
##  [52] "CACCACTGGCGAAG-1" "CACGGGTGGAGGAC-1" "CAGATGACATTCTC-1"
##  [55] "CAGCAATGGAGGGT-1" "CAGCGGACCTTTAC-1" "CAGCTCTGTGTGGT-1"
##  [58] "CAGTTTACACACGT-1" "CATCAGGACTTCCG-1" "CATCAGGATAGCCA-1"
##  [61] "CATGAGACGTTGAC-1" "CATTACACCAACTG-1" "CATTTCGAGATACC-1"
##  [64] "CCTCGAACACTTTC-1" "CGACCACTAAAGTG-1" "CGACCACTGCCAAT-1"
##  [67] "CGAGGCTGACGCTA-1" "CGCCGAGAGCTTAG-1" "CGGCGAACGACAAA-1"
##  [70] "CGGCGAACTACTTC-1" "CGGGCATGTCTCTA-1" "CGTACCTGGCATCA-1"
##  [73] "CGTGTAGACGATAC-1" "CGTGTAGAGTTACG-1" "CGTGTAGATTCGGA-1"
##  [76] "CTAAACCTCTGACA-1" "CTAACGGAACCGAT-1" "CTACGCACTGGTCA-1"
##  [79] "CTACTCCTATGTCG-1" "CTAGTTACGAAACA-1" "CTATACTGCTACGA-1"
##  [82] "CTATACTGTCTCAT-1" "CTCGACTGGTTGAC-1" "CTGAGAACGTAAAG-1"
##  [85] "CTTTAGTGACGGGA-1" "GAACCAACTTCCGC-1" "GAAGTGCTAAACGA-1"
##  [88] "GAATGCACCTTCGC-1" "GAATTAACGTCGTA-1" "GACGGCACACGGGA-1"
##  [91] "GAGCGCTGAAGATG-1" "GAGGTACTGACACT-1" "GAGGTGGATCCTCG-1"
##  [94] "GATAGAGAAGGGTG-1" "GATCCCTGACCTTT-1" "GCACACCTGTGCTA-1"
##  [97] "GCACCACTTCCTTA-1" "GCACTAGAGTCGTA-1" "GCAGGGCTATCGAC-1"
## [100] "GCCGGAACGTTCTT-1" "GCCTACACAGTTCG-1" "GCGCATCTTGCTCC-1"
## [103] "GCGCGATGGTGCAT-1" "GGAAGGTGGCGAGA-1" "GGACGCTGTCCTCG-1"
## [106] "GGAGGCCTCGTTGA-1" "GGCAAGGAAAAAGC-1" "GGCATATGCTTATC-1"
## [109] "GGCCGAACTCTAGG-1" "GGCTAAACACCTGA-1" "GGGTTAACGTGCAT-1"
## [112] "GGTGGAGAAACGGG-1" "GTAGTGTGAGCGGA-1" "GTCGACCTGAATGA-1"
## [115] "GTGATTCTGGTTCA-1" "GTGTATCTAGTAGA-1" "GTTAAAACCGAGAG-1"
## [118] "GTTCAACTGGGACA-1" "GTTGACGATATCGG-1" "TAACTCACTCTACT-1"
## [121] "TAAGAGGACTTGTT-1" "TAATGCCTCGTCTC-1" "TACGGCCTGGGACA-1"
## [124] "TACTACTGATGTCG-1" "TACTCTGAATCGAC-1" "TACTGTTGAGGCGA-1"
## [127] "TAGCATCTCAGCTA-1" "TAGCCCACAGCTAC-1" "TAGGGACTGAACTC-1"
## [130] "TAGTGGTGAAGTGA-1" "TAGTTAGAACCACA-1" "TATGAATGGAGGAC-1"
## [133] "TATGGGTGCATCAG-1" "TATTTCCTGGAGGT-1" "TCAACACTGTTTGG-1"
## [136] "TCAGACGACGTTAG-1" "TCCCGAACACAGTC-1" "TCCTAAACCGCATA-1"
## [139] "TCGATTTGCAGCTA-1" "TCTAACACCAGTTG-1" "TGATAAACTCCGTC-1"
## [142] "TGCACAGACGACAT-1" "TGCCACTGCGATAC-1" "TGCTGAGAGAGCAG-1"
## [145] "TGGAACACAAACAG-1" "TGGTAGACCCTCAC-1" "TGTAATGACACAAC-1"
## [148] "TGTAATGAGGTAAA-1" "TTACTCGATCTACT-1" "TTAGTCTGCCAACA-1"
## [151] "TTCCAAACTCCCAC-1" "TTCCCACTTGAGGG-1" "TTCTAGTGGAGAGC-1"
## [154] "TTCTGATGGAGACG-1" "TTGTCATGGACGGA-1"
```

Example 33 (r):
```r
# How can I extract expression matrix for all NK cells (perhaps, to load into another package)
nk.raw.data <- as.matrix(GetAssayData(pbmc, slot = "counts")[, WhichCells(pbmc, ident = "NK")])

# Can I create a Seurat object based on expression of a feature or value in object metadata?
subset(pbmc, subset = MS4A1 > 1)
```

Example 34 (r):
```r
# How can I extract expression matrix for all NK cells (perhaps, to load into another package)
nk.raw.data <- as.matrix(GetAssayData(pbmc, slot = "counts")[, WhichCells(pbmc, ident = "NK")])

# Can I create a Seurat object based on expression of a feature or value in object metadata?
subset(pbmc, subset = MS4A1 > 1)
```

Example 35 (python):
```python
## An object of class Seurat 
## 13714 features across 414 samples within 1 assay 
## Active assay: RNA (13714 features, 2000 variable features)
##  2 dimensional reductions calculated: pca, umap
```

Example 36 (python):
```python
## An object of class Seurat 
## 13714 features across 414 samples within 1 assay 
## Active assay: RNA (13714 features, 2000 variable features)
##  2 dimensional reductions calculated: pca, umap
```

Example 37 (r):
```r
subset(pbmc, subset = replicate == "rep2")
```

Example 38 (r):
```r
subset(pbmc, subset = replicate == "rep2")
```

Example 39 (python):
```python
## An object of class Seurat 
## 13714 features across 1290 samples within 1 assay 
## Active assay: RNA (13714 features, 2000 variable features)
##  2 dimensional reductions calculated: pca, umap
```

Example 40 (python):
```python
## An object of class Seurat 
## 13714 features across 1290 samples within 1 assay 
## Active assay: RNA (13714 features, 2000 variable features)
##  2 dimensional reductions calculated: pca, umap
```

Example 41 (r):
```r
# Can I create a Seurat object of just the NK cells and B cells?
subset(pbmc, idents = c("NK", "B"))
```

Example 42 (r):
```r
# Can I create a Seurat object of just the NK cells and B cells?
subset(pbmc, idents = c("NK", "B"))
```

Example 43 (python):
```python
## An object of class Seurat 
## 13714 features across 499 samples within 1 assay 
## Active assay: RNA (13714 features, 2000 variable features)
##  2 dimensional reductions calculated: pca, umap
```

Example 44 (python):
```python
## An object of class Seurat 
## 13714 features across 499 samples within 1 assay 
## Active assay: RNA (13714 features, 2000 variable features)
##  2 dimensional reductions calculated: pca, umap
```

Example 45 (r):
```r
# Can I create a Seurat object of all cells except the NK cells and B cells?
subset(pbmc, idents = c("NK", "B"), invert = TRUE)
```

Example 46 (r):
```r
# Can I create a Seurat object of all cells except the NK cells and B cells?
subset(pbmc, idents = c("NK", "B"), invert = TRUE)
```

Example 47 (python):
```python
## An object of class Seurat 
## 13714 features across 2139 samples within 1 assay 
## Active assay: RNA (13714 features, 2000 variable features)
##  2 dimensional reductions calculated: pca, umap
```

Example 48 (python):
```python
## An object of class Seurat 
## 13714 features across 2139 samples within 1 assay 
## Active assay: RNA (13714 features, 2000 variable features)
##  2 dimensional reductions calculated: pca, umap
```

Example 49 (r):
```r
# note that if you wish to perform additional rounds of clustering after subsetting we recommend
# re-running FindVariableFeatures() and ScaleData()
```

Example 50 (r):
```r
# note that if you wish to perform additional rounds of clustering after subsetting we recommend
# re-running FindVariableFeatures() and ScaleData()
```

Example 51 (r):
```r
# How can I calculate the average expression of all cells within a cluster?
cluster.averages <- AverageExpression(pbmc)
head(cluster.averages[["RNA"]][, 1:5])
```

Example 52 (r):
```r
# How can I calculate the average expression of all cells within a cluster?
cluster.averages <- AverageExpression(pbmc)
head(cluster.averages[["RNA"]][, 1:5])
```

Example 53 (r):
```r
# Return this information as a Seurat object (enables downstream plotting and analysis) First,
# replace spaces with underscores '_' so ggplot2 doesn't fail
orig.levels <- levels(pbmc)
Idents(pbmc) <- gsub(pattern = " ", replacement = "_", x = Idents(pbmc))
orig.levels <- gsub(pattern = " ", replacement = "_", x = orig.levels)
levels(pbmc) <- orig.levels
cluster.averages <- AverageExpression(pbmc, return.seurat = TRUE)
cluster.averages
```

Example 54 (r):
```r
# Return this information as a Seurat object (enables downstream plotting and analysis) First,
# replace spaces with underscores '_' so ggplot2 doesn't fail
orig.levels <- levels(pbmc)
Idents(pbmc) <- gsub(pattern = " ", replacement = "_", x = Idents(pbmc))
orig.levels <- gsub(pattern = " ", replacement = "_", x = orig.levels)
levels(pbmc) <- orig.levels
cluster.averages <- AverageExpression(pbmc, return.seurat = TRUE)
cluster.averages
```

Example 55 (python):
```python
## An object of class Seurat 
## 13714 features across 9 samples within 1 assay 
## Active assay: RNA (13714 features, 0 variable features)
```

Example 56 (python):
```python
## An object of class Seurat 
## 13714 features across 9 samples within 1 assay 
## Active assay: RNA (13714 features, 0 variable features)
```

Example 57 (r):
```r
# How can I plot the average expression of NK cells vs. CD8 T cells?  Pass do.hover = T for an
# interactive plot to identify gene outliers
CellScatter(cluster.averages, cell1 = "NK", cell2 = "CD8_T")
```

Example 58 (r):
```r
# How can I plot the average expression of NK cells vs. CD8 T cells?  Pass do.hover = T for an
# interactive plot to identify gene outliers
CellScatter(cluster.averages, cell1 = "NK", cell2 = "CD8_T")
```

Example 59 (r):
```r
# How can I calculate expression averages separately for each replicate?
cluster.averages <- AverageExpression(pbmc, return.seurat = TRUE, add.ident = "replicate")
CellScatter(cluster.averages, cell1 = "CD8_T_rep1", cell2 = "CD8_T_rep2")
```

Example 60 (r):
```r
# How can I calculate expression averages separately for each replicate?
cluster.averages <- AverageExpression(pbmc, return.seurat = TRUE, add.ident = "replicate")
CellScatter(cluster.averages, cell1 = "CD8_T_rep1", cell2 = "CD8_T_rep2")
```

Example 61 (r):
```r
# You can also plot heatmaps of these 'in silico' bulk datasets to visualize agreement between
# replicates
DoHeatmap(cluster.averages, features = unlist(TopFeatures(pbmc[["pca"]], balanced = TRUE)), size = 3, 
    draw.lines = FALSE)
```

Example 62 (r):
```r
# You can also plot heatmaps of these 'in silico' bulk datasets to visualize agreement between
# replicates
DoHeatmap(cluster.averages, features = unlist(TopFeatures(pbmc[["pca"]], balanced = TRUE)), size = 3, 
    draw.lines = FALSE)
```

---

## Analysis, visualization, and integration of spatial datasets with Seurat • Seurat

**URL:** http://127.0.0.1:9173/seurat/archive/v4.3/spatial_vignette/index.html

**Contents:**
- Analysis, visualization, and integration of spatial datasets with Seurat
    - Compiled: 2023-03-23
- Overview
- 10x Visium
  - Dataset
  - Data preprocessing
  - Gene expression visualization
  - Dimensionality reduction, clustering, and visualization
  - Interactive plotting
  - Identification of Spatially Variable Features
  - Subset out anatomical regions
  - Integration with single-cell data
  - Working with multiple slices in Seurat
  - Acknowledgments
- Slide-seq
  - Dataset
  - Data preprocessing
  - Integration with a scRNA-seq reference
  - Identification of Spatially Variable Features
  - Spatial deconvolution using RCTD
- Contents

This tutorial demonstrates how to use Seurat (>=3.2) to analyze spatially-resolved RNA-seq data. While the analytical pipelines are similar to the Seurat workflow for single-cell RNA-seq analysis, we introduce updated interaction and visualization tools, with a particular emphasis on the integration of spatial and molecular information. This tutorial will cover the following tasks, which we believe will be common for many spatial analyses:

For our first vignette, we analyze a dataset generated with the Visium technology from 10x Genomics. We will be extending Seurat to work with additional data types in the near-future, including SLIDE-Seq, STARmap, and MERFISH.

First, we load Seurat and the other packages necessary for this vignette.

Here, we will be using a recently released dataset of sagital mouse brain slices generated using the Visium v1 chemistry. There are two serial anterior sections, and two (matched) serial posterior sections.

You can download the data here, and load it into Seurat using the Load10X_Spatial() function. This reads in the output of the spaceranger pipeline, and returns a Seurat object that contains both the spot-level expression data along with the associated image of the tissue slice. You can also use our SeuratData package for easy data access, as demonstrated below. After installing the dataset, you can type ?stxBrain to learn more.

How is the spatial data stored within Seurat? The visium data from 10x consists of the following data types:

The initial preprocessing steps that we perform on the spot by gene expression data are similar to a typical scRNA-seq experiment. We first need to normalize the data in order to account for variance in sequencing depth across data points. We note that the variance in molecular counts / spot can be substantial for spatial datasets, particularly if there are differences in cell density across the tissue. We see substantial heterogeneity here, which requires effective normalization.

These plots demonstrate that the variance in molecular counts across spots is not just technical in nature, but also is dependent on the tissue anatomy. For example, regions of the tissue that are depleted for neurons (such as the cortical white matter), reproducibly exhibit lower molecular counts. As a result, standard approaches (such as the LogNormalize() function), which force each data point to have the same underlying ‘size’ after normalization, can be problematic.

As an alternative, we recommend using sctransform (Hafemeister and Satija, Genome Biology 2019), which which builds regularized negative binomial models of gene expression in order to account for technical artifacts while preserving biological variance. For more details on sctransform, please see the paper here and the Seurat vignette here. sctransform normalizes the data, detects high-variance features, and stores the data in the SCT assay.

How do results compare to log-normalization? To explore the differences in normalization methods, we examine how both the sctransform and log normalization results correlate with the number of UMIs. For this comparison, we first rerun sctransform to store values for all genes and run a log-normalization procedure via NormalizeData().

In Seurat, we have functionality to explore and interact with the inherently visual nature of spatial data. The SpatialFeaturePlot() function in Seurat extends FeaturePlot(), and can overlay molecular data on top of tissue histology. For example, in this data set of the mouse brain, the gene Hpca is a strong hippocampus marker and Ttr is a marker of the choroid plexus.

The default parameters in Seurat emphasize the visualization of molecular data. However, you can also adjust the size of the spots (and their transparency) to improve the visualization of the histology image, by changing the following parameters:

We can then proceed to run dimensionality reduction and clustering on the RNA expression data, using the same workflow as we use for scRNA-seq analysis.

We can then visualize the results of the clustering either in UMAP space (with DimPlot()) or overlaid on the image with SpatialDimPlot().

As there are many colors, it can be challenging to visualize which voxel belongs to which cluster. We have a few strategies to help with this. Setting the label parameter places a colored box at the median of each cluster (see the plot above).

You can also use the cells.highlight parameter to demarcate particular cells of interest on a SpatialDimPlot(). This can be very useful for distinguishing the spatial localization of individual clusters, as we show below:

We have also built in a number of interactive plotting capabilities. Both SpatialDimPlot() and SpatialFeaturePlot() now have an interactive parameter, that when set to TRUE, will open up the Rstudio viewer pane with an interactive Shiny plot. The example below demonstrates an interactive SpatialDimPlot() in which you can hover over spots and view the cell name and current identity class (analogous to the previous do.hover behavior).

For SpatialFeaturePlot(), setting interactive to TRUE brings up an interactive pane in which you can adjust the transparency of the spots, the point size, as well as the Assay and feature being plotted. After exploring the data, selecting the done button will return the last active plot as a ggplot object.

The LinkedDimPlot() function links the UMAP representation to the tissue image representation and allows for interactive selection. For example, you can select a region in the UMAP plot and the corresponding spots in the image representation will be highlighted.

Seurat offers two workflows to identify molecular features that correlate with spatial location within a tissue. The first is to perform differential expression based on pre-annotated anatomical regions within the tissue, which may be determined either from unsupervised clustering or prior knowledge. This strategy works will in this case, as the clusters above exhibit clear spatial restriction.

An alternative approach, implemented in FindSpatiallyVariables(), is to search for features exhibiting spatial patterning in the absence of pre-annotation. The default method (method = 'markvariogram), is inspired by the Trendsceek, which models spatial transcriptomics data as a mark point process and computes a ‘variogram’, which identifies genes whose expression level is dependent on their spatial location. More specifically, this process calculates gamma(r) values measuring the dependence between two spots a certain “r” distance apart. By default, we use an r-value of ‘5’ in these analyses, and only compute these values for variable genes (where variation is calculated independently of spatial location) to save time.

We note that there are multiple methods in the literature to accomplish this task, including SpatialDE, and Splotch. We encourage interested users to explore these methods, and hope to add support for them in the near future.

Now we visualize the expression of the top 6 features identified by this measure.

As with single-cell objects, you can subset the object to focus on a subset of data. Here, we approximately subset the frontal cortex. This process also facilitates the integration of these data with a cortical scRNA-seq dataset in the next section. First, we take a subset of clusters, and then further segment based on exact positions. After subsetting, we can visualize the cortical cells either on the full image, or a cropped image.

At ~50um, spots from the visium assay will encompass the expression profiles of multiple cells. For the growing list of systems where scRNA-seq data is available, users may be interested to ‘deconvolute’ each of the spatial voxels to predict the underlying composition of cell types. In preparing this vignette, we tested a wide variety of decovonlution and integration methods, using a reference scRNA-seq dataset of ~14,000 adult mouse cortical cell taxonomy from the Allen Institute, generated with the SMART-Seq2 protocol. We consistently found superior performance using integration methods (as opposed to deconvolution methods), likely because of substantially different noise models that characterize spatial and single-cell datasets, and integration methods are specifiically designed to be robust to these differences. We therefore apply the ‘anchor’-based integration workflow introduced in Seurat v3, that enables the probabilistic transfer of annotations from a reference to a query set. We therefore follow the label transfer workflow introduced here, taking advantage of sctransform normalization, but anticipate new methods to be developed to accomplish this task.

We first load the data (download available here), pre-process the scRNA-seq reference, and then perform label transfer. The procedure outputs, for each spot, a probabilistic classification for each of the scRNA-seq derived classes. We add these predictions as a new assay in the Seurat object.

Now we get prediction scores for each spot for each class. Of particular interest in the frontal cortex region are the laminar excitatory neurons. Here we can distinguish between distinct sequential layers of these neuronal subtypes, for example:

Based on these prediction scores, we can also predict cell types whose location is spatially restricted. We use the same methods based on marked point processes to define spatially variable features, but use the cell type prediction scores as the “marks” rather than gene expression.

Finally, we show that our integrative procedure is capable of recovering the known spatial localization patterns of both neuronal and non-neuronal subsets, including laminar excitatory, layer-1 astrocytes, and the cortical grey matter.

This dataset of the mouse brain contains another slice corresponding to the other half of the brain. Here we read it in and perform the same initial normalization.

In order to work with multiple slices in the same Seurat object, we provide the merge function.

This then enables joint dimensional reduction and clustering on the underlying RNA expression data.

Finally, the data can be jointly visualized in a single UMAP plot. SpatialDimPlot() and SpatialFeaturePlot() will by default plot all slices as columns and groupings/features as rows.

We would like to thank Nigel Delaney and Stephen Williams for their helpful feedback and contributions to the new spatial Seurat code.

Here, we will be analyzing a dataset generated using Slide-seq v2 of the mouse hippocampus. This tutorial will follow much of the same structure as the spatial vignette for 10x Visium data but is tailored to give a demonstration specific to Slide-seq data.

You can use our SeuratData package for easy data access, as demonstrated below. After installing the dataset, you can type ?ssHippo to see the commands used to create the Seurat object.

The initial preprocessing steps for the bead by gene expression data are similar to other spatial Seurat analyses and to typical scRNA-seq experiments. Here, we note that many beads contain particularly low UMI counts but choose to keep all detected beads for downstream analysis.

We then normalize the data using sctransform and perform a standard scRNA-seq dimensionality reduction and clustering workflow.

We can then visualize the results of the clustering either in UMAP space (with DimPlot()) or in the bead coordinate space with SpatialDimPlot().

To facilitate cell-type annotation of the Slide-seq dataset, we are leveraging an existing mouse single-cell RNA-seq hippocampus dataset, produced in Saunders*, Macosko*, et al. 2018. The data is available for download as a processed Seurat object here, with the raw count matrices available on the DropViz website.

The original annotations from the paper are provided in the cell metadata of the Seurat object. These annotations are provided at several “resolutions”, from broad classes (ref$class) to subclusters within celltypes (ref$subcluster). For the purposes of this vignette, we’ll work off of a modification of the celltype annotations (ref$celltype) which we felt struck a good balance.

We’ll start by running the Seurat label transfer method to predict the major celltype for each bead.

We can then visualize the prediction scores for some of the major expected classes.

As mentioned in the Visium vignette, we can identify spatially variable features in two general ways: differential expression testing between pre-annotated anatomical regions or statistics that measure the dependence of a feature on spatial location.

Here, we demonstrate the latter with an implementation of Moran’s I available via FindSpatiallyVariableFeatures() by setting method = 'moransi'. Moran’s I computes an overall spatial autocorrelation and gives a statistic (similar to a correlation coefficient) that measures the dependence of a feature on spatial location. This allows us to rank features based on how spatially variable their expression is. In order to facilitate quick estimation of this statistic, we implemented a basic binning strategy that will draw a rectangular grid over Slide-seq puck and average the feature and location within each bin. The number of bins in the x and y direction are controlled by the x.cuts and y.cuts parameters respectively. Additionally, while not required, installing the optional Rfast2 package(install.packages('Rfast2')), will significantly decrease the runtime via a more efficient implementation.

Now we visualize the expression of the top 6 features identified by Moran’s I.

While FindTransferAnchors can be used to integrate spot-level data from spatial transcriptomic datasets, Seurat v5 also includes support for the Robust Cell Type Decomposition, a computational approach to deconvolve spot-level data from spatial datasets, when provided with an scRNA-seq reference. RCTD has been shown to accurately annotate spatial data from a variety of technologies, including SLIDE-seq, Visium, and the 10x Xenium in-situ spatial platform.

To run RCTD, we first install the spacexr package from GitHub which implements RCTD.

Counts, cluster, and spot information is extracted from the Seurat query and reference objects to construct Reference and SpatialRNA objects used by RCTD for annotation.

Using the reference and query object, we annotate the dataset and add the cell type labels to the query Seurat object. RCTD parallelizes well, so multiple cores can be specified for faster performance.

Next, plot the RCTD annotations. Because we ran RCTD in doublet mode, the algorithm assigns a first_type and second_type for each barcode or spot.

Developed by Paul Hoffman, Satija Lab and Collaborators.

Site built with pkgdown 2.0.7.

**Examples:**

Example 1 (unknown):
```unknown
vignettes/spatial_vignette.Rmd
```

Example 2 (unknown):
```unknown
spatial_vignette.Rmd
```

Example 3 (unknown):
```unknown
library(Seurat)
library(SeuratData)
library(ggplot2)
library(patchwork)
library(dplyr)
```

Example 4 (r):
```r
library(Seurat)
library(SeuratData)
library(ggplot2)
library(patchwork)
library(dplyr)
```

Example 5 (r):
```r
library(Seurat)
library(SeuratData)
library(ggplot2)
library(patchwork)
library(dplyr)
```

Example 6 (unknown):
```unknown
Load10X_Spatial()
```

Example 7 (unknown):
```unknown
InstallData("stxBrain")
```

Example 8 (r):
```r
InstallData("stxBrain")
```

Example 9 (r):
```r
InstallData("stxBrain")
```

Example 10 (unknown):
```unknown
brain <- LoadData("stxBrain", type = "anterior1")
```

Example 11 (r):
```r
brain <- LoadData("stxBrain", type = "anterior1")
```

Example 12 (r):
```r
brain <- LoadData("stxBrain", type = "anterior1")
```

Example 13 (unknown):
```unknown
plot1 <- VlnPlot(brain, features = "nCount_Spatial", pt.size = 0.1) + NoLegend()
plot2 <- SpatialFeaturePlot(brain, features = "nCount_Spatial") + theme(legend.position = "right")
wrap_plots(plot1, plot2)
```

Example 14 (r):
```r
plot1 <- VlnPlot(brain, features = "nCount_Spatial", pt.size = 0.1) + NoLegend()
plot2 <- SpatialFeaturePlot(brain, features = "nCount_Spatial") + theme(legend.position = "right")
wrap_plots(plot1, plot2)
```

Example 15 (r):
```r
plot1 <- VlnPlot(brain, features = "nCount_Spatial", pt.size = 0.1) + NoLegend()
plot2 <- SpatialFeaturePlot(brain, features = "nCount_Spatial") + theme(legend.position = "right")
wrap_plots(plot1, plot2)
```

Example 16 (unknown):
```unknown
LogNormalize()
```

Example 17 (unknown):
```unknown
brain <- SCTransform(brain, assay = "Spatial", verbose = FALSE)
```

Example 18 (r):
```r
brain <- SCTransform(brain, assay = "Spatial", verbose = FALSE)
```

Example 19 (r):
```r
brain <- SCTransform(brain, assay = "Spatial", verbose = FALSE)
```

Example 20 (unknown):
```unknown
NormalizeData()
```

Example 21 (unknown):
```unknown
# rerun normalization to store sctransform residuals for all genes
brain <- SCTransform(brain, assay = "Spatial", return.only.var.genes = FALSE, verbose = FALSE)
# also run standard log normalization for comparison
brain <- NormalizeData(brain, verbose = FALSE, assay = "Spatial")
```

Example 22 (r):
```r
# rerun normalization to store sctransform residuals for all genes
brain <- SCTransform(brain, assay = "Spatial", return.only.var.genes = FALSE, verbose = FALSE)
# also run standard log normalization for comparison
brain <- NormalizeData(brain, verbose = FALSE, assay = "Spatial")
```

Example 23 (r):
```r
# rerun normalization to store sctransform residuals for all genes
brain <- SCTransform(brain, assay = "Spatial", return.only.var.genes = FALSE, verbose = FALSE)
# also run standard log normalization for comparison
brain <- NormalizeData(brain, verbose = FALSE, assay = "Spatial")
```

Example 24 (unknown):
```unknown
# Computes the correlation of the log normalized data and sctransform residuals with the
# number of UMIs
brain <- GroupCorrelation(brain, group.assay = "Spatial", assay = "Spatial", slot = "data", do.plot = FALSE)
brain <- GroupCorrelation(brain, group.assay = "Spatial", assay = "SCT", slot = "scale.data", do.plot = FALSE)
```

Example 25 (r):
```r
# Computes the correlation of the log normalized data and sctransform residuals with the
# number of UMIs
brain <- GroupCorrelation(brain, group.assay = "Spatial", assay = "Spatial", slot = "data", do.plot = FALSE)
brain <- GroupCorrelation(brain, group.assay = "Spatial", assay = "SCT", slot = "scale.data", do.plot = FALSE)
```

Example 26 (r):
```r
# Computes the correlation of the log normalized data and sctransform residuals with the
# number of UMIs
brain <- GroupCorrelation(brain, group.assay = "Spatial", assay = "Spatial", slot = "data", do.plot = FALSE)
brain <- GroupCorrelation(brain, group.assay = "Spatial", assay = "SCT", slot = "scale.data", do.plot = FALSE)
```

Example 27 (unknown):
```unknown
p1 <- GroupCorrelationPlot(brain, assay = "Spatial", cor = "nCount_Spatial_cor") + ggtitle("Log Normalization") +
    theme(plot.title = element_text(hjust = 0.5))
p2 <- GroupCorrelationPlot(brain, assay = "SCT", cor = "nCount_Spatial_cor") + ggtitle("SCTransform Normalization") +
    theme(plot.title = element_text(hjust = 0.5))
p1 + p2
```

Example 28 (r):
```r
p1 <- GroupCorrelationPlot(brain, assay = "Spatial", cor = "nCount_Spatial_cor") + ggtitle("Log Normalization") +
    theme(plot.title = element_text(hjust = 0.5))
p2 <- GroupCorrelationPlot(brain, assay = "SCT", cor = "nCount_Spatial_cor") + ggtitle("SCTransform Normalization") +
    theme(plot.title = element_text(hjust = 0.5))
p1 + p2
```

Example 29 (r):
```r
p1 <- GroupCorrelationPlot(brain, assay = "Spatial", cor = "nCount_Spatial_cor") + ggtitle("Log Normalization") +
    theme(plot.title = element_text(hjust = 0.5))
p2 <- GroupCorrelationPlot(brain, assay = "SCT", cor = "nCount_Spatial_cor") + ggtitle("SCTransform Normalization") +
    theme(plot.title = element_text(hjust = 0.5))
p1 + p2
```

Example 30 (unknown):
```unknown
nCount_Spatial
```

Example 31 (unknown):
```unknown
SpatialFeaturePlot()
```

Example 32 (unknown):
```unknown
FeaturePlot()
```

Example 33 (unknown):
```unknown
SpatialFeaturePlot(brain, features = c("Hpca", "Ttr"))
```

Example 34 (r):
```r
SpatialFeaturePlot(brain, features = c("Hpca", "Ttr"))
```

Example 35 (r):
```r
SpatialFeaturePlot(brain, features = c("Hpca", "Ttr"))
```

Example 36 (python):
```python
library(ggplot2)
plot <- SpatialFeaturePlot(brain, features = c("Ttr")) + theme(legend.text = element_text(size = 0),
    legend.title = element_text(size = 20), legend.key.size = unit(1, "cm"))
jpeg(filename = "../output/images/spatial_vignette_ttr.jpg", height = 700, width = 1200, quality = 50)
print(plot)
dev.off()
```

Example 37 (r):
```r
library(ggplot2)
plot <- SpatialFeaturePlot(brain, features = c("Ttr")) + theme(legend.text = element_text(size = 0),
    legend.title = element_text(size = 20), legend.key.size = unit(1, "cm"))
jpeg(filename = "../output/images/spatial_vignette_ttr.jpg", height = 700, width = 1200, quality = 50)
print(plot)
dev.off()
```

Example 38 (r):
```r
library(ggplot2)
plot <- SpatialFeaturePlot(brain, features = c("Ttr")) + theme(legend.text = element_text(size = 0),
    legend.title = element_text(size = 20), legend.key.size = unit(1, "cm"))
jpeg(filename = "../output/images/spatial_vignette_ttr.jpg", height = 700, width = 1200, quality = 50)
print(plot)
dev.off()
```

Example 39 (unknown):
```unknown
## agg_png 
##       2
```

Example 40 (unknown):
```unknown
## agg_png 
##       2
```

Example 41 (unknown):
```unknown
pt.size.factor
```

Example 42 (unknown):
```unknown
p1 <- SpatialFeaturePlot(brain, features = "Ttr", pt.size.factor = 1)
p2 <- SpatialFeaturePlot(brain, features = "Ttr", alpha = c(0.1, 1))
p1 + p2
```

Example 43 (r):
```r
p1 <- SpatialFeaturePlot(brain, features = "Ttr", pt.size.factor = 1)
p2 <- SpatialFeaturePlot(brain, features = "Ttr", alpha = c(0.1, 1))
p1 + p2
```

Example 44 (r):
```r
p1 <- SpatialFeaturePlot(brain, features = "Ttr", pt.size.factor = 1)
p2 <- SpatialFeaturePlot(brain, features = "Ttr", alpha = c(0.1, 1))
p1 + p2
```

Example 45 (unknown):
```unknown
brain <- RunPCA(brain, assay = "SCT", verbose = FALSE)
brain <- FindNeighbors(brain, reduction = "pca", dims = 1:30)
brain <- FindClusters(brain, verbose = FALSE)
brain <- RunUMAP(brain, reduction = "pca", dims = 1:30)
```

Example 46 (r):
```r
brain <- RunPCA(brain, assay = "SCT", verbose = FALSE)
brain <- FindNeighbors(brain, reduction = "pca", dims = 1:30)
brain <- FindClusters(brain, verbose = FALSE)
brain <- RunUMAP(brain, reduction = "pca", dims = 1:30)
```

Example 47 (r):
```r
brain <- RunPCA(brain, assay = "SCT", verbose = FALSE)
brain <- FindNeighbors(brain, reduction = "pca", dims = 1:30)
brain <- FindClusters(brain, verbose = FALSE)
brain <- RunUMAP(brain, reduction = "pca", dims = 1:30)
```

Example 48 (unknown):
```unknown
SpatialDimPlot()
```

Example 49 (unknown):
```unknown
p1 <- DimPlot(brain, reduction = "umap", label = TRUE)
p2 <- SpatialDimPlot(brain, label = TRUE, label.size = 3)
p1 + p2
```

Example 50 (r):
```r
p1 <- DimPlot(brain, reduction = "umap", label = TRUE)
p2 <- SpatialDimPlot(brain, label = TRUE, label.size = 3)
p1 + p2
```

Example 51 (r):
```r
p1 <- DimPlot(brain, reduction = "umap", label = TRUE)
p2 <- SpatialDimPlot(brain, label = TRUE, label.size = 3)
p1 + p2
```

Example 52 (unknown):
```unknown
cells.highlight
```

Example 53 (unknown):
```unknown
SpatialDimPlot()
```

Example 54 (unknown):
```unknown
SpatialDimPlot(brain, cells.highlight = CellsByIdentities(object = brain, idents = c(2, 1, 4, 3,
    5, 8)), facet.highlight = TRUE, ncol = 3)
```

Example 55 (r):
```r
SpatialDimPlot(brain, cells.highlight = CellsByIdentities(object = brain, idents = c(2, 1, 4, 3,
    5, 8)), facet.highlight = TRUE, ncol = 3)
```

Example 56 (r):
```r
SpatialDimPlot(brain, cells.highlight = CellsByIdentities(object = brain, idents = c(2, 1, 4, 3,
    5, 8)), facet.highlight = TRUE, ncol = 3)
```

Example 57 (unknown):
```unknown
SpatialDimPlot()
```

Example 58 (unknown):
```unknown
SpatialFeaturePlot()
```

Example 59 (unknown):
```unknown
interactive
```

Example 60 (unknown):
```unknown
SpatialDimPlot()
```

Example 61 (unknown):
```unknown
SpatialDimPlot(brain, interactive = TRUE)
```

Example 62 (r):
```r
SpatialDimPlot(brain, interactive = TRUE)
```

Example 63 (r):
```r
SpatialDimPlot(brain, interactive = TRUE)
```

Example 64 (unknown):
```unknown
SpatialFeaturePlot()
```

Example 65 (unknown):
```unknown
SpatialFeaturePlot(brain, features = "Ttr", interactive = TRUE)
```

Example 66 (r):
```r
SpatialFeaturePlot(brain, features = "Ttr", interactive = TRUE)
```

Example 67 (r):
```r
SpatialFeaturePlot(brain, features = "Ttr", interactive = TRUE)
```

Example 68 (unknown):
```unknown
LinkedDimPlot()
```

Example 69 (unknown):
```unknown
LinkedDimPlot(brain)
```

Example 70 (r):
```r
LinkedDimPlot(brain)
```

Example 71 (r):
```r
LinkedDimPlot(brain)
```

Example 72 (unknown):
```unknown
de_markers <- FindMarkers(brain, ident.1 = 5, ident.2 = 6)
SpatialFeaturePlot(object = brain, features = rownames(de_markers)[1:3], alpha = c(0.1, 1), ncol = 3)
```

Example 73 (r):
```r
de_markers <- FindMarkers(brain, ident.1 = 5, ident.2 = 6)
SpatialFeaturePlot(object = brain, features = rownames(de_markers)[1:3], alpha = c(0.1, 1), ncol = 3)
```

Example 74 (r):
```r
de_markers <- FindMarkers(brain, ident.1 = 5, ident.2 = 6)
SpatialFeaturePlot(object = brain, features = rownames(de_markers)[1:3], alpha = c(0.1, 1), ncol = 3)
```

Example 75 (unknown):
```unknown
FindSpatiallyVariables()
```

Example 76 (unknown):
```unknown
method = 'markvariogram
```

Example 77 (unknown):
```unknown
brain <- FindSpatiallyVariableFeatures(brain, assay = "SCT", features = VariableFeatures(brain)[1:1000],
    selection.method = "moransi")
```

Example 78 (r):
```r
brain <- FindSpatiallyVariableFeatures(brain, assay = "SCT", features = VariableFeatures(brain)[1:1000],
    selection.method = "moransi")
```

Example 79 (r):
```r
brain <- FindSpatiallyVariableFeatures(brain, assay = "SCT", features = VariableFeatures(brain)[1:1000],
    selection.method = "moransi")
```

Example 80 (unknown):
```unknown
top.features <- head(SpatiallyVariableFeatures(brain, selection.method = "moransi"), 6)
SpatialFeaturePlot(brain, features = top.features, ncol = 3, alpha = c(0.1, 1))
```

Example 81 (r):
```r
top.features <- head(SpatiallyVariableFeatures(brain, selection.method = "moransi"), 6)
SpatialFeaturePlot(brain, features = top.features, ncol = 3, alpha = c(0.1, 1))
```

Example 82 (r):
```r
top.features <- head(SpatiallyVariableFeatures(brain, selection.method = "moransi"), 6)
SpatialFeaturePlot(brain, features = top.features, ncol = 3, alpha = c(0.1, 1))
```

Example 83 (unknown):
```unknown
cortex <- subset(brain, idents = c(1, 2, 3, 4, 6, 7))
# now remove additional cells, use SpatialDimPlots to visualize what to remove
# SpatialDimPlot(cortex,cells.highlight = WhichCells(cortex, expression = image_imagerow > 400
# | image_imagecol < 150))
cortex <- subset(cortex, anterior1_imagerow > 400 | anterior1_imagecol < 150, invert = TRUE)
cortex <- subset(cortex, anterior1_imagerow > 275 & anterior1_imagecol > 370, invert = TRUE)
cortex <- subset(cortex, anterior1_imagerow > 250 & anterior1_imagecol > 440, invert = TRUE)
```

Example 84 (r):
```r
cortex <- subset(brain, idents = c(1, 2, 3, 4, 6, 7))
# now remove additional cells, use SpatialDimPlots to visualize what to remove
# SpatialDimPlot(cortex,cells.highlight = WhichCells(cortex, expression = image_imagerow > 400
# | image_imagecol < 150))
cortex <- subset(cortex, anterior1_imagerow > 400 | anterior1_imagecol < 150, invert = TRUE)
cortex <- subset(cortex, anterior1_imagerow > 275 & anterior1_imagecol > 370, invert = TRUE)
cortex <- subset(cortex, anterior1_imagerow > 250 & anterior1_imagecol > 440, invert = TRUE)
```

Example 85 (r):
```r
cortex <- subset(brain, idents = c(1, 2, 3, 4, 6, 7))
# now remove additional cells, use SpatialDimPlots to visualize what to remove
# SpatialDimPlot(cortex,cells.highlight = WhichCells(cortex, expression = image_imagerow > 400
# | image_imagecol < 150))
cortex <- subset(cortex, anterior1_imagerow > 400 | anterior1_imagecol < 150, invert = TRUE)
cortex <- subset(cortex, anterior1_imagerow > 275 & anterior1_imagecol > 370, invert = TRUE)
cortex <- subset(cortex, anterior1_imagerow > 250 & anterior1_imagecol > 440, invert = TRUE)
```

Example 86 (unknown):
```unknown
p1 <- SpatialDimPlot(cortex, crop = TRUE, label = TRUE)
p2 <- SpatialDimPlot(cortex, crop = FALSE, label = TRUE, pt.size.factor = 1, label.size = 3)
p1 + p2
```

Example 87 (r):
```r
p1 <- SpatialDimPlot(cortex, crop = TRUE, label = TRUE)
p2 <- SpatialDimPlot(cortex, crop = FALSE, label = TRUE, pt.size.factor = 1, label.size = 3)
p1 + p2
```

Example 88 (r):
```r
p1 <- SpatialDimPlot(cortex, crop = TRUE, label = TRUE)
p2 <- SpatialDimPlot(cortex, crop = FALSE, label = TRUE, pt.size.factor = 1, label.size = 3)
p1 + p2
```

Example 89 (unknown):
```unknown
allen_reference <- readRDS("../data/allen_cortex.rds")
```

Example 90 (r):
```r
allen_reference <- readRDS("../data/allen_cortex.rds")
```

Example 91 (r):
```r
allen_reference <- readRDS("../data/allen_cortex.rds")
```

Example 92 (unknown):
```unknown
# note that setting ncells=3000 normalizes the full dataset but learns noise models on 3k
# cells this speeds up SCTransform dramatically with no loss in performance
library(dplyr)
allen_reference <- SCTransform(allen_reference, ncells = 3000, verbose = FALSE) %>%
    RunPCA(verbose = FALSE) %>%
    RunUMAP(dims = 1:30)
```

Example 93 (r):
```r
# note that setting ncells=3000 normalizes the full dataset but learns noise models on 3k
# cells this speeds up SCTransform dramatically with no loss in performance
library(dplyr)
allen_reference <- SCTransform(allen_reference, ncells = 3000, verbose = FALSE) %>%
    RunPCA(verbose = FALSE) %>%
    RunUMAP(dims = 1:30)
```

Example 94 (r):
```r
# note that setting ncells=3000 normalizes the full dataset but learns noise models on 3k
# cells this speeds up SCTransform dramatically with no loss in performance
library(dplyr)
allen_reference <- SCTransform(allen_reference, ncells = 3000, verbose = FALSE) %>%
    RunPCA(verbose = FALSE) %>%
    RunUMAP(dims = 1:30)
```

Example 95 (python):
```python
# After subsetting, we renormalize cortex
cortex <- SCTransform(cortex, assay = "Spatial", verbose = FALSE) %>%
    RunPCA(verbose = FALSE)
# the annotation is stored in the 'subclass' column of object metadata
DimPlot(allen_reference, group.by = "subclass", label = TRUE)
```

Example 96 (r):
```r
# After subsetting, we renormalize cortex
cortex <- SCTransform(cortex, assay = "Spatial", verbose = FALSE) %>%
    RunPCA(verbose = FALSE)
# the annotation is stored in the 'subclass' column of object metadata
DimPlot(allen_reference, group.by = "subclass", label = TRUE)
```

Example 97 (r):
```r
# After subsetting, we renormalize cortex
cortex <- SCTransform(cortex, assay = "Spatial", verbose = FALSE) %>%
    RunPCA(verbose = FALSE)
# the annotation is stored in the 'subclass' column of object metadata
DimPlot(allen_reference, group.by = "subclass", label = TRUE)
```

Example 98 (unknown):
```unknown
anchors <- FindTransferAnchors(reference = allen_reference, query = cortex, normalization.method = "SCT")
predictions.assay <- TransferData(anchorset = anchors, refdata = allen_reference$subclass, prediction.assay = TRUE,
    weight.reduction = cortex[["pca"]], dims = 1:30)
cortex[["predictions"]] <- predictions.assay
```

Example 99 (r):
```r
anchors <- FindTransferAnchors(reference = allen_reference, query = cortex, normalization.method = "SCT")
predictions.assay <- TransferData(anchorset = anchors, refdata = allen_reference$subclass, prediction.assay = TRUE,
    weight.reduction = cortex[["pca"]], dims = 1:30)
cortex[["predictions"]] <- predictions.assay
```

Example 100 (r):
```r
anchors <- FindTransferAnchors(reference = allen_reference, query = cortex, normalization.method = "SCT")
predictions.assay <- TransferData(anchorset = anchors, refdata = allen_reference$subclass, prediction.assay = TRUE,
    weight.reduction = cortex[["pca"]], dims = 1:30)
cortex[["predictions"]] <- predictions.assay
```

Example 101 (unknown):
```unknown
DefaultAssay(cortex) <- "predictions"
SpatialFeaturePlot(cortex, features = c("L2/3 IT", "L4"), pt.size.factor = 1.6, ncol = 2, crop = TRUE)
```

Example 102 (r):
```r
DefaultAssay(cortex) <- "predictions"
SpatialFeaturePlot(cortex, features = c("L2/3 IT", "L4"), pt.size.factor = 1.6, ncol = 2, crop = TRUE)
```

Example 103 (r):
```r
DefaultAssay(cortex) <- "predictions"
SpatialFeaturePlot(cortex, features = c("L2/3 IT", "L4"), pt.size.factor = 1.6, ncol = 2, crop = TRUE)
```

Example 104 (unknown):
```unknown
cortex <- FindSpatiallyVariableFeatures(cortex, assay = "predictions", selection.method = "moransi",
    features = rownames(cortex), r.metric = 5, slot = "data")
top.clusters <- head(SpatiallyVariableFeatures(cortex, selection.method = "moransi"), 4)
SpatialPlot(object = cortex, features = top.clusters, ncol = 2)
```

Example 105 (r):
```r
cortex <- FindSpatiallyVariableFeatures(cortex, assay = "predictions", selection.method = "moransi",
    features = rownames(cortex), r.metric = 5, slot = "data")
top.clusters <- head(SpatiallyVariableFeatures(cortex, selection.method = "moransi"), 4)
SpatialPlot(object = cortex, features = top.clusters, ncol = 2)
```

Example 106 (r):
```r
cortex <- FindSpatiallyVariableFeatures(cortex, assay = "predictions", selection.method = "moransi",
    features = rownames(cortex), r.metric = 5, slot = "data")
top.clusters <- head(SpatiallyVariableFeatures(cortex, selection.method = "moransi"), 4)
SpatialPlot(object = cortex, features = top.clusters, ncol = 2)
```

Example 107 (unknown):
```unknown
SpatialFeaturePlot(cortex, features = c("Astro", "L2/3 IT", "L4", "L5 PT", "L5 IT", "L6 CT", "L6 IT",
    "L6b", "Oligo"), pt.size.factor = 1, ncol = 2, crop = FALSE, alpha = c(0.1, 1))
```

Example 108 (r):
```r
SpatialFeaturePlot(cortex, features = c("Astro", "L2/3 IT", "L4", "L5 PT", "L5 IT", "L6 CT", "L6 IT",
    "L6b", "Oligo"), pt.size.factor = 1, ncol = 2, crop = FALSE, alpha = c(0.1, 1))
```

Example 109 (r):
```r
SpatialFeaturePlot(cortex, features = c("Astro", "L2/3 IT", "L4", "L5 PT", "L5 IT", "L6 CT", "L6 IT",
    "L6b", "Oligo"), pt.size.factor = 1, ncol = 2, crop = FALSE, alpha = c(0.1, 1))
```

Example 110 (unknown):
```unknown
brain2 <- LoadData("stxBrain", type = "posterior1")
brain2 <- SCTransform(brain2, assay = "Spatial", verbose = FALSE)
```

Example 111 (r):
```r
brain2 <- LoadData("stxBrain", type = "posterior1")
brain2 <- SCTransform(brain2, assay = "Spatial", verbose = FALSE)
```

Example 112 (r):
```r
brain2 <- LoadData("stxBrain", type = "posterior1")
brain2 <- SCTransform(brain2, assay = "Spatial", verbose = FALSE)
```

Example 113 (unknown):
```unknown
brain.merge <- merge(brain, brain2)
```

Example 114 (r):
```r
brain.merge <- merge(brain, brain2)
```

Example 115 (r):
```r
brain.merge <- merge(brain, brain2)
```

Example 116 (unknown):
```unknown
DefaultAssay(brain.merge) <- "SCT"
VariableFeatures(brain.merge) <- c(VariableFeatures(brain), VariableFeatures(brain2))
brain.merge <- RunPCA(brain.merge, verbose = FALSE)
brain.merge <- FindNeighbors(brain.merge, dims = 1:30)
brain.merge <- FindClusters(brain.merge, verbose = FALSE)
brain.merge <- RunUMAP(brain.merge, dims = 1:30)
```

Example 117 (r):
```r
DefaultAssay(brain.merge) <- "SCT"
VariableFeatures(brain.merge) <- c(VariableFeatures(brain), VariableFeatures(brain2))
brain.merge <- RunPCA(brain.merge, verbose = FALSE)
brain.merge <- FindNeighbors(brain.merge, dims = 1:30)
brain.merge <- FindClusters(brain.merge, verbose = FALSE)
brain.merge <- RunUMAP(brain.merge, dims = 1:30)
```

Example 118 (r):
```r
DefaultAssay(brain.merge) <- "SCT"
VariableFeatures(brain.merge) <- c(VariableFeatures(brain), VariableFeatures(brain2))
brain.merge <- RunPCA(brain.merge, verbose = FALSE)
brain.merge <- FindNeighbors(brain.merge, dims = 1:30)
brain.merge <- FindClusters(brain.merge, verbose = FALSE)
brain.merge <- RunUMAP(brain.merge, dims = 1:30)
```

Example 119 (unknown):
```unknown
SpatialDimPlot()
```

Example 120 (unknown):
```unknown
SpatialFeaturePlot()
```

Example 121 (unknown):
```unknown
DimPlot(brain.merge, reduction = "umap", group.by = c("ident", "orig.ident"))
```

Example 122 (r):
```r
DimPlot(brain.merge, reduction = "umap", group.by = c("ident", "orig.ident"))
```

Example 123 (r):
```r
DimPlot(brain.merge, reduction = "umap", group.by = c("ident", "orig.ident"))
```

Example 124 (unknown):
```unknown
SpatialDimPlot(brain.merge)
```

Example 125 (r):
```r
SpatialDimPlot(brain.merge)
```

Example 126 (r):
```r
SpatialDimPlot(brain.merge)
```

Example 127 (unknown):
```unknown
SpatialFeaturePlot(brain.merge, features = c("Hpca", "Plp1"))
```

Example 128 (r):
```r
SpatialFeaturePlot(brain.merge, features = c("Hpca", "Plp1"))
```

Example 129 (r):
```r
SpatialFeaturePlot(brain.merge, features = c("Hpca", "Plp1"))
```

Example 130 (unknown):
```unknown
InstallData("ssHippo")
```

Example 131 (r):
```r
InstallData("ssHippo")
```

Example 132 (r):
```r
InstallData("ssHippo")
```

Example 133 (unknown):
```unknown
slide.seq <- LoadData("ssHippo")
```

Example 134 (r):
```r
slide.seq <- LoadData("ssHippo")
```

Example 135 (r):
```r
slide.seq <- LoadData("ssHippo")
```

Example 136 (unknown):
```unknown
plot1 <- VlnPlot(slide.seq, features = "nCount_Spatial", pt.size = 0, log = TRUE) + NoLegend()
slide.seq$log_nCount_Spatial <- log(slide.seq$nCount_Spatial)
plot2 <- SpatialFeaturePlot(slide.seq, features = "log_nCount_Spatial") + theme(legend.position = "right")
wrap_plots(plot1, plot2)
```

Example 137 (r):
```r
plot1 <- VlnPlot(slide.seq, features = "nCount_Spatial", pt.size = 0, log = TRUE) + NoLegend()
slide.seq$log_nCount_Spatial <- log(slide.seq$nCount_Spatial)
plot2 <- SpatialFeaturePlot(slide.seq, features = "log_nCount_Spatial") + theme(legend.position = "right")
wrap_plots(plot1, plot2)
```

Example 138 (r):
```r
plot1 <- VlnPlot(slide.seq, features = "nCount_Spatial", pt.size = 0, log = TRUE) + NoLegend()
slide.seq$log_nCount_Spatial <- log(slide.seq$nCount_Spatial)
plot2 <- SpatialFeaturePlot(slide.seq, features = "log_nCount_Spatial") + theme(legend.position = "right")
wrap_plots(plot1, plot2)
```

Example 139 (unknown):
```unknown
slide.seq <- SCTransform(slide.seq, assay = "Spatial", ncells = 3000, verbose = FALSE)
slide.seq <- RunPCA(slide.seq)
slide.seq <- RunUMAP(slide.seq, dims = 1:30)
slide.seq <- FindNeighbors(slide.seq, dims = 1:30)
slide.seq <- FindClusters(slide.seq, resolution = 0.3, verbose = FALSE)
```

Example 140 (r):
```r
slide.seq <- SCTransform(slide.seq, assay = "Spatial", ncells = 3000, verbose = FALSE)
slide.seq <- RunPCA(slide.seq)
slide.seq <- RunUMAP(slide.seq, dims = 1:30)
slide.seq <- FindNeighbors(slide.seq, dims = 1:30)
slide.seq <- FindClusters(slide.seq, resolution = 0.3, verbose = FALSE)
```

Example 141 (r):
```r
slide.seq <- SCTransform(slide.seq, assay = "Spatial", ncells = 3000, verbose = FALSE)
slide.seq <- RunPCA(slide.seq)
slide.seq <- RunUMAP(slide.seq, dims = 1:30)
slide.seq <- FindNeighbors(slide.seq, dims = 1:30)
slide.seq <- FindClusters(slide.seq, resolution = 0.3, verbose = FALSE)
```

Example 142 (unknown):
```unknown
SpatialDimPlot()
```

Example 143 (unknown):
```unknown
plot1 <- DimPlot(slide.seq, reduction = "umap", label = TRUE)
plot2 <- SpatialDimPlot(slide.seq, stroke = 0)
plot1 + plot2
```

Example 144 (r):
```r
plot1 <- DimPlot(slide.seq, reduction = "umap", label = TRUE)
plot2 <- SpatialDimPlot(slide.seq, stroke = 0)
plot1 + plot2
```

Example 145 (r):
```r
plot1 <- DimPlot(slide.seq, reduction = "umap", label = TRUE)
plot2 <- SpatialDimPlot(slide.seq, stroke = 0)
plot1 + plot2
```

Example 146 (unknown):
```unknown
SpatialDimPlot(slide.seq, cells.highlight = CellsByIdentities(object = slide.seq, idents = c(1,
    6, 13)), facet.highlight = TRUE)
```

Example 147 (r):
```r
SpatialDimPlot(slide.seq, cells.highlight = CellsByIdentities(object = slide.seq, idents = c(1,
    6, 13)), facet.highlight = TRUE)
```

Example 148 (r):
```r
SpatialDimPlot(slide.seq, cells.highlight = CellsByIdentities(object = slide.seq, idents = c(1,
    6, 13)), facet.highlight = TRUE)
```

Example 149 (unknown):
```unknown
ref <- readRDS("../data/mouse_hippocampus_reference.rds")
ref <- UpdateSeuratObject(ref)
```

Example 150 (r):
```r
ref <- readRDS("../data/mouse_hippocampus_reference.rds")
ref <- UpdateSeuratObject(ref)
```

Example 151 (r):
```r
ref <- readRDS("../data/mouse_hippocampus_reference.rds")
ref <- UpdateSeuratObject(ref)
```

Example 152 (unknown):
```unknown
ref$subcluster
```

Example 153 (unknown):
```unknown
ref$celltype
```

Example 154 (unknown):
```unknown
anchors <- FindTransferAnchors(reference = ref, query = slide.seq, normalization.method = "SCT",
    npcs = 50)
predictions.assay <- TransferData(anchorset = anchors, refdata = ref$celltype, prediction.assay = TRUE,
    weight.reduction = slide.seq[["pca"]], dims = 1:50)
slide.seq[["predictions"]] <- predictions.assay
```

Example 155 (r):
```r
anchors <- FindTransferAnchors(reference = ref, query = slide.seq, normalization.method = "SCT",
    npcs = 50)
predictions.assay <- TransferData(anchorset = anchors, refdata = ref$celltype, prediction.assay = TRUE,
    weight.reduction = slide.seq[["pca"]], dims = 1:50)
slide.seq[["predictions"]] <- predictions.assay
```

Example 156 (r):
```r
anchors <- FindTransferAnchors(reference = ref, query = slide.seq, normalization.method = "SCT",
    npcs = 50)
predictions.assay <- TransferData(anchorset = anchors, refdata = ref$celltype, prediction.assay = TRUE,
    weight.reduction = slide.seq[["pca"]], dims = 1:50)
slide.seq[["predictions"]] <- predictions.assay
```

Example 157 (unknown):
```unknown
DefaultAssay(slide.seq) <- "predictions"
SpatialFeaturePlot(slide.seq, features = c("Dentate Principal cells", "CA3 Principal cells", "Entorhinal cortex",
    "Endothelial tip", "Ependymal", "Oligodendrocyte"), alpha = c(0.1, 1))
```

Example 158 (r):
```r
DefaultAssay(slide.seq) <- "predictions"
SpatialFeaturePlot(slide.seq, features = c("Dentate Principal cells", "CA3 Principal cells", "Entorhinal cortex",
    "Endothelial tip", "Ependymal", "Oligodendrocyte"), alpha = c(0.1, 1))
```

Example 159 (r):
```r
DefaultAssay(slide.seq) <- "predictions"
SpatialFeaturePlot(slide.seq, features = c("Dentate Principal cells", "CA3 Principal cells", "Entorhinal cortex",
    "Endothelial tip", "Ependymal", "Oligodendrocyte"), alpha = c(0.1, 1))
```

Example 160 (unknown):
```unknown
slide.seq$predicted.id <- GetTransferPredictions(slide.seq)
Idents(slide.seq) <- "predicted.id"
SpatialDimPlot(slide.seq, cells.highlight = CellsByIdentities(object = slide.seq, idents = c("CA3 Principal cells",
    "Dentate Principal cells", "Endothelial tip")), facet.highlight = TRUE)
```

Example 161 (r):
```r
slide.seq$predicted.id <- GetTransferPredictions(slide.seq)
Idents(slide.seq) <- "predicted.id"
SpatialDimPlot(slide.seq, cells.highlight = CellsByIdentities(object = slide.seq, idents = c("CA3 Principal cells",
    "Dentate Principal cells", "Endothelial tip")), facet.highlight = TRUE)
```

Example 162 (r):
```r
slide.seq$predicted.id <- GetTransferPredictions(slide.seq)
Idents(slide.seq) <- "predicted.id"
SpatialDimPlot(slide.seq, cells.highlight = CellsByIdentities(object = slide.seq, idents = c("CA3 Principal cells",
    "Dentate Principal cells", "Endothelial tip")), facet.highlight = TRUE)
```

Example 163 (unknown):
```unknown
FindSpatiallyVariableFeatures()
```

Example 164 (unknown):
```unknown
method = 'moransi'
```

Example 165 (unknown):
```unknown
install.packages('Rfast2')
```

Example 166 (unknown):
```unknown
DefaultAssay(slide.seq) <- "SCT"
slide.seq <- FindSpatiallyVariableFeatures(slide.seq, assay = "SCT", slot = "scale.data", features = VariableFeatures(slide.seq)[1:1000],
    selection.method = "moransi", x.cuts = 100, y.cuts = 100)
```

Example 167 (r):
```r
DefaultAssay(slide.seq) <- "SCT"
slide.seq <- FindSpatiallyVariableFeatures(slide.seq, assay = "SCT", slot = "scale.data", features = VariableFeatures(slide.seq)[1:1000],
    selection.method = "moransi", x.cuts = 100, y.cuts = 100)
```

Example 168 (r):
```r
DefaultAssay(slide.seq) <- "SCT"
slide.seq <- FindSpatiallyVariableFeatures(slide.seq, assay = "SCT", slot = "scale.data", features = VariableFeatures(slide.seq)[1:1000],
    selection.method = "moransi", x.cuts = 100, y.cuts = 100)
```

Example 169 (unknown):
```unknown
SpatialFeaturePlot(slide.seq, features = head(SpatiallyVariableFeatures(slide.seq, selection.method = "moransi"),
    6), ncol = 3, alpha = c(0.1, 1), max.cutoff = "q95")
```

Example 170 (r):
```r
SpatialFeaturePlot(slide.seq, features = head(SpatiallyVariableFeatures(slide.seq, selection.method = "moransi"),
    6), ncol = 3, alpha = c(0.1, 1), max.cutoff = "q95")
```

Example 171 (r):
```r
SpatialFeaturePlot(slide.seq, features = head(SpatiallyVariableFeatures(slide.seq, selection.method = "moransi"),
    6), ncol = 3, alpha = c(0.1, 1), max.cutoff = "q95")
```

Example 172 (unknown):
```unknown
FindTransferAnchors
```

Example 173 (unknown):
```unknown
devtools::install_github("dmcable/spacexr", build_vignettes = FALSE)
```

Example 174 (r):
```r
devtools::install_github("dmcable/spacexr", build_vignettes = FALSE)
```

Example 175 (r):
```r
devtools::install_github("dmcable/spacexr", build_vignettes = FALSE)
```

Example 176 (unknown):
```unknown
library(spacexr)

# set up reference
ref <- readRDS("../data/mouse_hippocampus_reference.rds")
ref <- UpdateSeuratObject(ref)
Idents(ref) <- "celltype"

# extract information to pass to the RCTD Reference function
counts <- ref[["RNA"]]$counts
cluster <- as.factor(ref$celltype)
names(cluster) <- colnames(ref)
nUMI <- ref$nCount_RNA
names(nUMI) <- colnames(ref)
reference <- Reference(counts, cluster, nUMI)

# set up query with the RCTD function SpatialRNA
slide.seq <- SeuratData::LoadData("ssHippo")
counts <- slide.seq[["Spatial"]]$counts
coords <- GetTissueCoordinates(slide.seq)
colnames(coords) <- c("x", "y")
coords[is.na(colnames(coords))] <- NULL
query <- SpatialRNA(coords, counts, colSums(counts))
```

Example 177 (r):
```r
library(spacexr)

# set up reference
ref <- readRDS("../data/mouse_hippocampus_reference.rds")
ref <- UpdateSeuratObject(ref)
Idents(ref) <- "celltype"

# extract information to pass to the RCTD Reference function
counts <- ref[["RNA"]]$counts
cluster <- as.factor(ref$celltype)
names(cluster) <- colnames(ref)
nUMI <- ref$nCount_RNA
names(nUMI) <- colnames(ref)
reference <- Reference(counts, cluster, nUMI)

# set up query with the RCTD function SpatialRNA
slide.seq <- SeuratData::LoadData("ssHippo")
counts <- slide.seq[["Spatial"]]$counts
coords <- GetTissueCoordinates(slide.seq)
colnames(coords) <- c("x", "y")
coords[is.na(colnames(coords))] <- NULL
query <- SpatialRNA(coords, counts, colSums(counts))
```

Example 178 (r):
```r
library(spacexr)

# set up reference
ref <- readRDS("../data/mouse_hippocampus_reference.rds")
ref <- UpdateSeuratObject(ref)
Idents(ref) <- "celltype"

# extract information to pass to the RCTD Reference function
counts <- ref[["RNA"]]$counts
cluster <- as.factor(ref$celltype)
names(cluster) <- colnames(ref)
nUMI <- ref$nCount_RNA
names(nUMI) <- colnames(ref)
reference <- Reference(counts, cluster, nUMI)

# set up query with the RCTD function SpatialRNA
slide.seq <- SeuratData::LoadData("ssHippo")
counts <- slide.seq[["Spatial"]]$counts
coords <- GetTissueCoordinates(slide.seq)
colnames(coords) <- c("x", "y")
coords[is.na(colnames(coords))] <- NULL
query <- SpatialRNA(coords, counts, colSums(counts))
```

Example 179 (python):
```python
RCTD <- create.RCTD(query, reference, max_cores = 8)
RCTD <- run.RCTD(RCTD, doublet_mode = "doublet")
slide.seq <- AddMetaData(slide.seq, metadata = RCTD@results$results_df)
```

Example 180 (r):
```r
RCTD <- create.RCTD(query, reference, max_cores = 8)
RCTD <- run.RCTD(RCTD, doublet_mode = "doublet")
slide.seq <- AddMetaData(slide.seq, metadata = RCTD@results$results_df)
```

Example 181 (r):
```r
RCTD <- create.RCTD(query, reference, max_cores = 8)
RCTD <- run.RCTD(RCTD, doublet_mode = "doublet")
slide.seq <- AddMetaData(slide.seq, metadata = RCTD@results$results_df)
```

Example 182 (unknown):
```unknown
second_type
```

Example 183 (unknown):
```unknown
p1 <- SpatialDimPlot(slide.seq, group.by = "first_type")
p2 <- SpatialDimPlot(slide.seq, group.by = "second_type")
p1 | p2
```

Example 184 (r):
```r
p1 <- SpatialDimPlot(slide.seq, group.by = "first_type")
p2 <- SpatialDimPlot(slide.seq, group.by = "second_type")
p1 | p2
```

Example 185 (r):
```r
p1 <- SpatialDimPlot(slide.seq, group.by = "first_type")
p2 <- SpatialDimPlot(slide.seq, group.by = "second_type")
p1 | p2
```

Example 186 (unknown):
```unknown
write.csv(x = t(as.data.frame(all_times)), file = "../output/timings/spatial_vignette_times.csv")
```

Example 187 (r):
```r
write.csv(x = t(as.data.frame(all_times)), file = "../output/timings/spatial_vignette_times.csv")
```

Example 188 (r):
```r
write.csv(x = t(as.data.frame(all_times)), file = "../output/timings/spatial_vignette_times.csv")
```

Example 189 (unknown):
```unknown
sessionInfo()
```

Example 190 (r):
```r
sessionInfo()
```

Example 191 (r):
```r
sessionInfo()
```

Example 192 (unknown):
```unknown
## R version 4.2.2 Patched (2022-11-10 r83330)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.6 LTS
## 
## Matrix products: default
## BLAS:   /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.9.0
## LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.9.0
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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       
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
##  [1] spacexr_2.2.0             vembedr_0.1.5            
##  [3] htmltools_0.5.5           dplyr_1.1.1              
##  [5] patchwork_1.1.2           ggplot2_3.4.1            
##  [7] stxBrain.SeuratData_0.1.1 ssHippo.SeuratData_3.1.4 
##  [9] pbmcsca.SeuratData_3.0.0  pbmcref.SeuratData_1.0.0 
## [11] pbmc3k.SeuratData_3.1.4   SeuratData_0.2.2.9001    
## [13] Seurat_4.9.9.9039         SeuratObject_4.9.9.9077  
## [15] sp_1.6-0                 
## 
## loaded via a namespace (and not attached):
##   [1] spam_2.9-1             systemfonts_1.0.4      plyr_1.8.8            
##   [4] igraph_1.4.1           lazyeval_0.2.2         splines_4.2.2         
##   [7] RcppHNSW_0.4.1         listenv_0.9.0          scattermore_0.8       
##  [10] digest_0.6.31          foreach_1.5.2          fansi_1.0.4           
##  [13] magrittr_2.0.3         memoise_2.0.1          doParallel_1.0.17     
##  [16] tensor_1.5             cluster_2.1.4          ROCR_1.0-11           
##  [19] limma_3.54.1           globals_0.16.2         matrixStats_0.63.0    
##  [22] pkgdown_2.0.7          spatstat.sparse_3.0-1  colorspace_2.1-0      
##  [25] rappdirs_0.3.3         ggrepel_0.9.3          textshaping_0.3.6     
##  [28] xfun_0.37              crayon_1.5.2           jsonlite_1.8.4        
##  [31] progressr_0.13.0       spatstat.data_3.0-1    iterators_1.0.14      
##  [34] survival_3.5-5         zoo_1.8-11             glue_1.6.2            
##  [37] polyclip_1.10-4        gtable_0.3.3           leiden_0.4.3          
##  [40] RcppZiggurat_0.1.6     future.apply_1.10.0    abind_1.4-5           
##  [43] scales_1.2.1           spatstat.random_3.1-4  miniUI_0.1.1.1        
##  [46] Rcpp_1.0.10            viridisLite_0.4.1      xtable_1.8-4          
##  [49] reticulate_1.28        dotCall64_1.0-2        Rfast2_0.1.4          
##  [52] htmlwidgets_1.6.2      httr_1.4.5             RColorBrewer_1.1-3    
##  [55] ellipsis_0.3.2         ica_1.0-3              farver_2.1.1          
##  [58] pkgconfig_2.0.3        sass_0.4.5             uwot_0.1.14           
##  [61] deldir_1.0-6           utf8_1.2.3             labeling_0.4.2        
##  [64] tidyselect_1.2.0       rlang_1.1.0            reshape2_1.4.4        
##  [67] later_1.3.0            munsell_0.5.0          tools_4.2.2           
##  [70] cachem_1.0.7           cli_3.6.1              generics_0.1.3        
##  [73] ggridges_0.5.4         evaluate_0.20          stringr_1.5.0         
##  [76] fastmap_1.1.1          yaml_2.3.7             ragg_1.2.5            
##  [79] goftest_1.2-3          knitr_1.42             fs_1.6.1              
##  [82] fitdistrplus_1.1-8     purrr_1.0.1            RANN_2.6.1            
##  [85] pbapply_1.7-0          future_1.32.0          nlme_3.1-162          
##  [88] mime_0.12              formatR_1.14           ggrastr_1.0.1         
##  [91] compiler_4.2.2         beeswarm_0.4.0         plotly_4.10.1         
##  [94] png_0.1-8              spatstat.utils_3.0-2   tibble_3.2.1          
##  [97] bslib_0.4.2            stringi_1.7.12         highr_0.10            
## [100] desc_1.4.2             RSpectra_0.16-1        lattice_0.20-45       
## [103] Matrix_1.5-3           vctrs_0.6.1            pillar_1.9.0          
## [106] lifecycle_1.0.3        spatstat.geom_3.1-0    lmtest_0.9-40         
## [109] jquerylib_0.1.4        RcppAnnoy_0.0.20       data.table_1.14.8     
## [112] cowplot_1.1.1          irlba_2.3.5.1          httpuv_1.6.9          
## [115] R6_2.5.1               promises_1.2.0.1       KernSmooth_2.23-20    
## [118] gridExtra_2.3          vipor_0.4.5            parallelly_1.35.0     
## [121] codetools_0.2-19       assertthat_0.2.1       fastDummies_1.6.3     
## [124] MASS_7.3-58.2          rprojroot_2.0.3        withr_2.5.0           
## [127] presto_1.0.0           sctransform_0.3.5.9002 parallel_4.2.2        
## [130] quadprog_1.5-8         grid_4.2.2             tidyr_1.3.0           
## [133] Rfast_2.0.7            rmarkdown_2.20         Rtsne_0.16            
## [136] spatstat.explore_3.1-0 shiny_1.7.4            ggbeeswarm_0.7.1
```

Example 193 (unknown):
```unknown
## R version 4.2.2 Patched (2022-11-10 r83330)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.6 LTS
## 
## Matrix products: default
## BLAS:   /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.9.0
## LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.9.0
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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       
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
##  [1] spacexr_2.2.0             vembedr_0.1.5            
##  [3] htmltools_0.5.5           dplyr_1.1.1              
##  [5] patchwork_1.1.2           ggplot2_3.4.1            
##  [7] stxBrain.SeuratData_0.1.1 ssHippo.SeuratData_3.1.4 
##  [9] pbmcsca.SeuratData_3.0.0  pbmcref.SeuratData_1.0.0 
## [11] pbmc3k.SeuratData_3.1.4   SeuratData_0.2.2.9001    
## [13] Seurat_4.9.9.9039         SeuratObject_4.9.9.9077  
## [15] sp_1.6-0                 
## 
## loaded via a namespace (and not attached):
##   [1] spam_2.9-1             systemfonts_1.0.4      plyr_1.8.8            
##   [4] igraph_1.4.1           lazyeval_0.2.2         splines_4.2.2         
##   [7] RcppHNSW_0.4.1         listenv_0.9.0          scattermore_0.8       
##  [10] digest_0.6.31          foreach_1.5.2          fansi_1.0.4           
##  [13] magrittr_2.0.3         memoise_2.0.1          doParallel_1.0.17     
##  [16] tensor_1.5             cluster_2.1.4          ROCR_1.0-11           
##  [19] limma_3.54.1           globals_0.16.2         matrixStats_0.63.0    
##  [22] pkgdown_2.0.7          spatstat.sparse_3.0-1  colorspace_2.1-0      
##  [25] rappdirs_0.3.3         ggrepel_0.9.3          textshaping_0.3.6     
##  [28] xfun_0.37              crayon_1.5.2           jsonlite_1.8.4        
##  [31] progressr_0.13.0       spatstat.data_3.0-1    iterators_1.0.14      
##  [34] survival_3.5-5         zoo_1.8-11             glue_1.6.2            
##  [37] polyclip_1.10-4        gtable_0.3.3           leiden_0.4.3          
##  [40] RcppZiggurat_0.1.6     future.apply_1.10.0    abind_1.4-5           
##  [43] scales_1.2.1           spatstat.random_3.1-4  miniUI_0.1.1.1        
##  [46] Rcpp_1.0.10            viridisLite_0.4.1      xtable_1.8-4          
##  [49] reticulate_1.28        dotCall64_1.0-2        Rfast2_0.1.4          
##  [52] htmlwidgets_1.6.2      httr_1.4.5             RColorBrewer_1.1-3    
##  [55] ellipsis_0.3.2         ica_1.0-3              farver_2.1.1          
##  [58] pkgconfig_2.0.3        sass_0.4.5             uwot_0.1.14           
##  [61] deldir_1.0-6           utf8_1.2.3             labeling_0.4.2        
##  [64] tidyselect_1.2.0       rlang_1.1.0            reshape2_1.4.4        
##  [67] later_1.3.0            munsell_0.5.0          tools_4.2.2           
##  [70] cachem_1.0.7           cli_3.6.1              generics_0.1.3        
##  [73] ggridges_0.5.4         evaluate_0.20          stringr_1.5.0         
##  [76] fastmap_1.1.1          yaml_2.3.7             ragg_1.2.5            
##  [79] goftest_1.2-3          knitr_1.42             fs_1.6.1              
##  [82] fitdistrplus_1.1-8     purrr_1.0.1            RANN_2.6.1            
##  [85] pbapply_1.7-0          future_1.32.0          nlme_3.1-162          
##  [88] mime_0.12              formatR_1.14           ggrastr_1.0.1         
##  [91] compiler_4.2.2         beeswarm_0.4.0         plotly_4.10.1         
##  [94] png_0.1-8              spatstat.utils_3.0-2   tibble_3.2.1          
##  [97] bslib_0.4.2            stringi_1.7.12         highr_0.10            
## [100] desc_1.4.2             RSpectra_0.16-1        lattice_0.20-45       
## [103] Matrix_1.5-3           vctrs_0.6.1            pillar_1.9.0          
## [106] lifecycle_1.0.3        spatstat.geom_3.1-0    lmtest_0.9-40         
## [109] jquerylib_0.1.4        RcppAnnoy_0.0.20       data.table_1.14.8     
## [112] cowplot_1.1.1          irlba_2.3.5.1          httpuv_1.6.9          
## [115] R6_2.5.1               promises_1.2.0.1       KernSmooth_2.23-20    
## [118] gridExtra_2.3          vipor_0.4.5            parallelly_1.35.0     
## [121] codetools_0.2-19       assertthat_0.2.1       fastDummies_1.6.3     
## [124] MASS_7.3-58.2          rprojroot_2.0.3        withr_2.5.0           
## [127] presto_1.0.0           sctransform_0.3.5.9002 parallel_4.2.2        
## [130] quadprog_1.5-8         grid_4.2.2             tidyr_1.3.0           
## [133] Rfast_2.0.7            rmarkdown_2.20         Rtsne_0.16            
## [136] spatstat.explore_3.1-0 shiny_1.7.4            ggbeeswarm_0.7.1
```

---

## Seurat - Dimensional Reduction Vignette

**URL:** http://127.0.0.1:9173/seurat/archive/v2.4/dim_reduction_vignette/index.html

**Contents:**
- Seurat - Dimensional Reduction Vignette
    - Compiled: March 24, 2018
  - Load in the data
  - Explore the new dimensional reduction structure
  - Storing a new dimensional reduction calculation
  - Changes to PCA

This vignette demonstrates how to store and interact with dimensional reduction information (such as the output from RunPCA) in Seurat v2.0. For demonstration purposes, we will be using the 2,700 PBMC object that is created in the first guided tutorial. You can download the pre-computed object here.

In Seurat v2.0, storing and interacting with dimensional reduction information has been generalized and clarified. Each dimensional reduction procedure is stored in the object@dr slot, as an element of a named list. For example, after running a principle component analysis with RunPCA, object@dr$pca will contain the results of the PCA. By adding new elements to the list, users can add additional, and custom, dimensional reductions. Each stored dimensional reduction contains the following slots:

To access these slots, we provide the following functions: GetCellEmbeddings, GetGeneLoadings, GetDimReduction

Seurat provides RunPCA (pca), RunICA (ica), RunTSNE (tsne), and RunDiffusionMap (dmap), representing dimensional reduction techniques commonly applied to scRNA-seq data. When using these functions, all slots are filled automatically.

We also allow users to add the results of a custom dimensional reduction technique (for example, multi-dimensional scaling (MDS), or zero-inflated factor analysis), that is computed separately. All you need is a matrix with each cell’s coordinates in low-dimensional space, as shown below.

Though not incorporated as part of the Seurat package, its easy to run multidimensional scaling (MDS) in R. If you were interested in running MDS and storing the output in your Seurat object:

In Seurat v2.0, we have switched all PCA calculations to be performed via the irlba package to enable calculation of partial PCAs (i.e. only calculate the first X PCs). While this is an approximate algorithm, it performs remarkably similar to running a full PCA and has significant savings in terms of computation time and resources. These savings become necessary when running Seurat on increasingly large datasets. We also allow the user to decide whether to weight the PCs by the percent of the variance they explain (the weight.by.var parameter). For large datasets containing rare cell types, we often see improved results by setting this to FALSE, as this prevents the initial PCs (which often explain a disproportionate amount of variance) from masking rare cell types or subtle sources of heterogeneity that appear in later PCs.

**Examples:**

Example 1 (r):
```r
library(Seurat)
pbmc <- readRDS(file = "~/Projects/datasets/pbmc3k_final.rds")
```

Example 2 (r):
```r
library(Seurat)
pbmc <- readRDS(file = "~/Projects/datasets/pbmc3k_final.rds")
```

Example 3 (unknown):
```unknown
object@dr$pca
```

Example 4 (unknown):
```unknown
GetCellEmbeddings
```

Example 5 (unknown):
```unknown
GetGeneLoadings
```

Example 6 (unknown):
```unknown
GetDimReduction
```

Example 7 (r):
```r
head(x = GetCellEmbeddings(object = pbmc, reduction.type = "pca", dims.use = 1:5))
```

Example 8 (r):
```r
head(x = GetCellEmbeddings(object = pbmc, reduction.type = "pca", dims.use = 1:5))
```

Example 9 (unknown):
```unknown
##                       PC1        PC2         PC3        PC4         PC5
## AAACATACAACCAC   5.569384 -0.2601651  0.07208744  2.8327852 -0.05418562
## AAACATTGAGCTAC   7.216456 -7.4833577 -0.27232060 -7.9844621  2.99848095
## AAACATTGATCAGC   2.706629  1.5814099  0.54774967  2.2393826 -1.79540785
## AAACCGTGCTTCCG -10.134042  1.3678993 -1.32082569 -0.6694909 -2.91299684
## AAACCGTGTATGCG  -1.099311  8.1505284 -1.42908065 -4.2245213  1.96205909
## AAACGCACTGGTAC   1.455335 -1.9453261 -0.83467716  2.3035974  1.73324749
```

Example 10 (unknown):
```unknown
##                       PC1        PC2         PC3        PC4         PC5
## AAACATACAACCAC   5.569384 -0.2601651  0.07208744  2.8327852 -0.05418562
## AAACATTGAGCTAC   7.216456 -7.4833577 -0.27232060 -7.9844621  2.99848095
## AAACATTGATCAGC   2.706629  1.5814099  0.54774967  2.2393826 -1.79540785
## AAACCGTGCTTCCG -10.134042  1.3678993 -1.32082569 -0.6694909 -2.91299684
## AAACCGTGTATGCG  -1.099311  8.1505284 -1.42908065 -4.2245213  1.96205909
## AAACGCACTGGTAC   1.455335 -1.9453261 -0.83467716  2.3035974  1.73324749
```

Example 11 (r):
```r
head(x = GetGeneLoadings(object = pbmc, reduction.type = "pca", dims.use = 1:5))
```

Example 12 (r):
```r
head(x = GetGeneLoadings(object = pbmc, reduction.type = "pca", dims.use = 1:5))
```

Example 13 (unknown):
```unknown
##                   PC1          PC2           PC3          PC4
## TNFRSF4   0.026010991  0.003256709  0.0018341968  0.036271503
## CPSF3L    0.008282783  0.009079823 -0.0007640280 -0.008883533
## ATAD3C    0.003307989  0.003211707  0.0004175542  0.001693306
## C1orf86  -0.010653986 -0.000264935 -0.0070123176 -0.002372739
## RER1     -0.013715242  0.027391985 -0.0107780157 -0.006205270
## TNFRSF25  0.026637414  0.010852550  0.0024332223  0.033597921
##                    PC5
## TNFRSF4  -0.0168098228
## CPSF3L    0.0063828472
## ATAD3C    0.0003844082
## C1orf86   0.0038661887
## RER1     -0.0182815126
## TNFRSF25 -0.0205302367
```

Example 14 (unknown):
```unknown
##                   PC1          PC2           PC3          PC4
## TNFRSF4   0.026010991  0.003256709  0.0018341968  0.036271503
## CPSF3L    0.008282783  0.009079823 -0.0007640280 -0.008883533
## ATAD3C    0.003307989  0.003211707  0.0004175542  0.001693306
## C1orf86  -0.010653986 -0.000264935 -0.0070123176 -0.002372739
## RER1     -0.013715242  0.027391985 -0.0107780157 -0.006205270
## TNFRSF25  0.026637414  0.010852550  0.0024332223  0.033597921
##                    PC5
## TNFRSF4  -0.0168098228
## CPSF3L    0.0063828472
## ATAD3C    0.0003844082
## C1orf86   0.0038661887
## RER1     -0.0182815126
## TNFRSF25 -0.0205302367
```

Example 15 (r):
```r
# We also provide shortcut functions for common dimensional reduction
# techniques like PCA PCAEmbed and PCALoad() will pull the PCA cell
# embeddings and gene loadings respectively
head(x = GetDimReduction(object = pbmc, reduction.type = "pca", slot = "sdev"))
```

Example 16 (r):
```r
# We also provide shortcut functions for common dimensional reduction
# techniques like PCA PCAEmbed and PCALoad() will pull the PCA cell
# embeddings and gene loadings respectively
head(x = GetDimReduction(object = pbmc, reduction.type = "pca", slot = "sdev"))
```

Example 17 (unknown):
```unknown
## [1] 5.666584 4.326466 3.952192 3.638124 2.191529 1.996551
```

Example 18 (unknown):
```unknown
## [1] 5.666584 4.326466 3.952192 3.638124 2.191529 1.996551
```

Example 19 (unknown):
```unknown
RunDiffusionMap
```

Example 20 (r):
```r
# Before running MDS, we first calculate a distance matrix between all pairs
# of cells.  Here we use a simple euclidean distance metric on all genes,
# using object@scale.data as input
d <- dist(x = t(x = pbmc@scale.data))
# Run the MDS procedure, k determines the number of dimensions
mds <- cmdscale(d = d, k = 2)
# cmdscale returns the cell embeddings, we first label the columns to ensure
# downstream consistency
colnames(x = mds) <- paste0("MDS", 1:2)
# We will now store this as a new dimensional reduction called 'mds'
pbmc <- SetDimReduction(object = pbmc, reduction.type = "mds", slot = "cell.embeddings", 
    new.data = mds)
pbmc <- SetDimReduction(object = pbmc, reduction.type = "mds", slot = "key", 
    new.data = "MDS")

# We can now use this as you would any other dimensional reduction in all
# downstream functions (similar to PCAPlot, but generalized for any
# reduction)
DimPlot(object = pbmc, reduction.use = "mds", pt.size = 0.5)
```

Example 21 (r):
```r
# Before running MDS, we first calculate a distance matrix between all pairs
# of cells.  Here we use a simple euclidean distance metric on all genes,
# using object@scale.data as input
d <- dist(x = t(x = pbmc@scale.data))
# Run the MDS procedure, k determines the number of dimensions
mds <- cmdscale(d = d, k = 2)
# cmdscale returns the cell embeddings, we first label the columns to ensure
# downstream consistency
colnames(x = mds) <- paste0("MDS", 1:2)
# We will now store this as a new dimensional reduction called 'mds'
pbmc <- SetDimReduction(object = pbmc, reduction.type = "mds", slot = "cell.embeddings", 
    new.data = mds)
pbmc <- SetDimReduction(object = pbmc, reduction.type = "mds", slot = "key", 
    new.data = "MDS")

# We can now use this as you would any other dimensional reduction in all
# downstream functions (similar to PCAPlot, but generalized for any
# reduction)
DimPlot(object = pbmc, reduction.use = "mds", pt.size = 0.5)
```

Example 22 (r):
```r
# If you wold like to observe genes that are strongly correlated with the
# first MDS coordinate (similar to ProjectPCA, but generalized for any
# reduction):
pbmc <- ProjectDim(object = pbmc, reduction.type = "mds")
```

Example 23 (r):
```r
# If you wold like to observe genes that are strongly correlated with the
# first MDS coordinate (similar to ProjectPCA, but generalized for any
# reduction):
pbmc <- ProjectDim(object = pbmc, reduction.type = "mds")
```

Example 24 (unknown):
```unknown
## [1] "MDS1"
##  [1] "RPS27A"  "MALAT1"  "RPS27"   "RPL23A"  "RPSA"    "RPS3A"   "RPL3"   
##  [8] "RPL9"    "RPS6"    "RPL21"   "RPS3"    "LTB"     "RPL13A"  "RPS15A" 
## [15] "RPS12"   "RPS25"   "RPS18"   "CD3D"    "RPL31"   "RPL30"   "PTPRCAP"
## [22] "LDHB"    "IL32"    "RPS23"   "RPLP2"   "RPL27A"  "RPS29"   "RPL13"  
## [29] "EEF1A1"  "CD3E"   
## [1] ""
##  [1] "CST3"     "TYROBP"   "FTL"      "FCER1G"   "LST1"     "S100A9"  
##  [7] "FTH1"     "AIF1"     "FCN1"     "LYZ"      "TYMP"     "LGALS1"  
## [13] "CFD"      "S100A8"   "CD68"     "LGALS2"   "CTSS"     "SERPINA1"
## [19] "SAT1"     "IFITM3"   "SPI1"     "PSAP"     "IFI30"    "CFP"     
## [25] "S100A11"  "NPC2"     "COTL1"    "GRN"      "GSTP1"    "GPX1"    
## [1] ""
## [1] ""
## [1] "MDS2"
##  [1] "NKG7"   "CST7"   "GZMB"   "PRF1"   "GZMA"   "FGFBP2" "GNLY"  
##  [8] "CTSW"   "B2M"    "CCL5"   "SPON2"  "GZMH"   "CCL4"   "HLA-C" 
## [15] "KLRD1"  "FCGR3A" "CLIC3"  "GZMM"   "CD247"  "XCL2"   "AKR1C3"
## [22] "TTC38"  "S1PR5"  "HOPX"   "HLA-A"  "PRSS23" "APMAP"  "GPR56" 
## [29] "TPST2"  "MATK"  
## [1] ""
##  [1] "RPL32"    "RPL18A"   "RPL11"    "RPL13"    "RPS2"     "RPL12"   
##  [7] "RPL28"    "RPL10"    "RPS9"     "RPL8"     "RPL13A"   "RPS18"   
## [13] "RPLP1"    "HLA-DRA"  "RPLP2"    "RPL29"    "RPS15"    "RPS12"   
## [19] "CD79A"    "RPS16"    "RPS14"    "RPL19"    "RPS11"    "RPS23"   
## [25] "RPS5"     "RPS28"    "RPS27"    "FAU"      "HLA-DQA1" "HLA-DQB1"
## [1] ""
## [1] ""
```

Example 25 (unknown):
```unknown
## [1] "MDS1"
##  [1] "RPS27A"  "MALAT1"  "RPS27"   "RPL23A"  "RPSA"    "RPS3A"   "RPL3"   
##  [8] "RPL9"    "RPS6"    "RPL21"   "RPS3"    "LTB"     "RPL13A"  "RPS15A" 
## [15] "RPS12"   "RPS25"   "RPS18"   "CD3D"    "RPL31"   "RPL30"   "PTPRCAP"
## [22] "LDHB"    "IL32"    "RPS23"   "RPLP2"   "RPL27A"  "RPS29"   "RPL13"  
## [29] "EEF1A1"  "CD3E"   
## [1] ""
##  [1] "CST3"     "TYROBP"   "FTL"      "FCER1G"   "LST1"     "S100A9"  
##  [7] "FTH1"     "AIF1"     "FCN1"     "LYZ"      "TYMP"     "LGALS1"  
## [13] "CFD"      "S100A8"   "CD68"     "LGALS2"   "CTSS"     "SERPINA1"
## [19] "SAT1"     "IFITM3"   "SPI1"     "PSAP"     "IFI30"    "CFP"     
## [25] "S100A11"  "NPC2"     "COTL1"    "GRN"      "GSTP1"    "GPX1"    
## [1] ""
## [1] ""
## [1] "MDS2"
##  [1] "NKG7"   "CST7"   "GZMB"   "PRF1"   "GZMA"   "FGFBP2" "GNLY"  
##  [8] "CTSW"   "B2M"    "CCL5"   "SPON2"  "GZMH"   "CCL4"   "HLA-C" 
## [15] "KLRD1"  "FCGR3A" "CLIC3"  "GZMM"   "CD247"  "XCL2"   "AKR1C3"
## [22] "TTC38"  "S1PR5"  "HOPX"   "HLA-A"  "PRSS23" "APMAP"  "GPR56" 
## [29] "TPST2"  "MATK"  
## [1] ""
##  [1] "RPL32"    "RPL18A"   "RPL11"    "RPL13"    "RPS2"     "RPL12"   
##  [7] "RPL28"    "RPL10"    "RPS9"     "RPL8"     "RPL13A"   "RPS18"   
## [13] "RPLP1"    "HLA-DRA"  "RPLP2"    "RPL29"    "RPS15"    "RPS12"   
## [19] "CD79A"    "RPS16"    "RPS14"    "RPL19"    "RPS11"    "RPS23"   
## [25] "RPS5"     "RPS28"    "RPS27"    "FAU"      "HLA-DQA1" "HLA-DQB1"
## [1] ""
## [1] ""
```

Example 26 (r):
```r
# Display the results as a heatmap (similar to PCHeatmap, but generalized
# for any dimensional reduction)
DimHeatmap(object = pbmc, reduction.type = "mds", dim.use = 1, cells.use = 500, 
    use.full = TRUE, do.balanced = TRUE, label.columns = FALSE, remove.key = TRUE)
```

Example 27 (r):
```r
# Display the results as a heatmap (similar to PCHeatmap, but generalized
# for any dimensional reduction)
DimHeatmap(object = pbmc, reduction.type = "mds", dim.use = 1, cells.use = 500, 
    use.full = TRUE, do.balanced = TRUE, label.columns = FALSE, remove.key = TRUE)
```

Example 28 (r):
```r
# Explore how the first MDS dimension is distributed across clusters
VlnPlot(object = pbmc, features.plot = "MDS1", x.lab.rot = TRUE)
```

Example 29 (r):
```r
# Explore how the first MDS dimension is distributed across clusters
VlnPlot(object = pbmc, features.plot = "MDS1", x.lab.rot = TRUE)
```

Example 30 (r):
```r
# See how the first MDS dimension is correlated with the first PC dimension
GenePlot(object = pbmc, gene1 = "MDS1", gene2 = "PC1")
```

Example 31 (r):
```r
# See how the first MDS dimension is correlated with the first PC dimension
GenePlot(object = pbmc, gene1 = "MDS1", gene2 = "PC1")
```

---

## Seurat - Interaction Tips

**URL:** http://127.0.0.1:9173/seurat/archive/v3.1/interaction_vignette/index.html

**Contents:**
- Seurat - Interaction Tips
    - Compiled: April 17, 2020
  - Load in the data
  - Switch identity class between cluster ID and replicate
  - Tabulate cells by cluster ID, replicate, or both
  - Selecting particular cells and subsetting the Seurat object
  - Calculating the average gene expression within a cluster

This vignette demonstrates some useful features for interacting with the Seurat object. For demonstration purposes, we will be using the 2,700 PBMC object that is created in the first guided tutorial. You can download the pre-computed object here. To simulate the scenario where we have two replicates, we will randomly assign half the cells in each cluster to be from “rep1” and other half from “rep2”.

**Examples:**

Example 1 (r):
```r
library(Seurat)
pbmc <- readRDS(file = "../data/pbmc3k_final.rds")

# pretend that cells were originally assigned to one of two replicates (we assign randomly here)
# if your cells do belong to multiple replicates, and you want to add this info to the Seurat
# object create a data frame with this information (similar to replicate.info below)
set.seed(42)
pbmc$replicate <- sample(c("rep1", "rep2"), size = ncol(pbmc), replace = TRUE)
```

Example 2 (r):
```r
library(Seurat)
pbmc <- readRDS(file = "../data/pbmc3k_final.rds")

# pretend that cells were originally assigned to one of two replicates (we assign randomly here)
# if your cells do belong to multiple replicates, and you want to add this info to the Seurat
# object create a data frame with this information (similar to replicate.info below)
set.seed(42)
pbmc$replicate <- sample(c("rep1", "rep2"), size = ncol(pbmc), replace = TRUE)
```

Example 3 (r):
```r
# Plot UMAP, coloring cells by cell type (currently stored in object@ident)
DimPlot(pbmc, reduction = "umap")
```

Example 4 (r):
```r
# Plot UMAP, coloring cells by cell type (currently stored in object@ident)
DimPlot(pbmc, reduction = "umap")
```

Example 5 (r):
```r
# How do I create a UMAP plot where cells are colored by replicate?  First, store the current
# identities in a new column of meta.data called CellType
pbmc$CellType <- Idents(pbmc)
# Next, switch the identity class of all cells to reflect replicate ID
Idents(pbmc) <- "replicate"
DimPlot(pbmc, reduction = "umap")
```

Example 6 (r):
```r
# How do I create a UMAP plot where cells are colored by replicate?  First, store the current
# identities in a new column of meta.data called CellType
pbmc$CellType <- Idents(pbmc)
# Next, switch the identity class of all cells to reflect replicate ID
Idents(pbmc) <- "replicate"
DimPlot(pbmc, reduction = "umap")
```

Example 7 (r):
```r
# alternately : DimPlot(pbmc, reduction = 'umap', group.by = 'replicate') you can pass the
# shape.by to label points by both replicate and cell type

# Switch back to cell type labels
Idents(pbmc) <- "CellType"
```

Example 8 (r):
```r
# alternately : DimPlot(pbmc, reduction = 'umap', group.by = 'replicate') you can pass the
# shape.by to label points by both replicate and cell type

# Switch back to cell type labels
Idents(pbmc) <- "CellType"
```

Example 9 (r):
```r
# How many cells are in each cluster
table(Idents(pbmc))
```

Example 10 (r):
```r
# How many cells are in each cluster
table(Idents(pbmc))
```

Example 11 (javascript):
```javascript
## 
##  Naive CD4 T Memory CD4 T   CD14+ Mono            B        CD8 T FCGR3A+ Mono 
##          697          483          480          344          271          162 
##           NK           DC     Platelet 
##          155           32           14
```

Example 12 (javascript):
```javascript
## 
##  Naive CD4 T Memory CD4 T   CD14+ Mono            B        CD8 T FCGR3A+ Mono 
##          697          483          480          344          271          162 
##           NK           DC     Platelet 
##          155           32           14
```

Example 13 (r):
```r
# How many cells are in each replicate?
table(pbmc$replicate)
```

Example 14 (r):
```r
# How many cells are in each replicate?
table(pbmc$replicate)
```

Example 15 (unknown):
```unknown
## 
## rep1 rep2 
## 1348 1290
```

Example 16 (unknown):
```unknown
## 
## rep1 rep2 
## 1348 1290
```

Example 17 (r):
```r
# What proportion of cells are in each cluster?
prop.table(table(Idents(pbmc)))
```

Example 18 (r):
```r
# What proportion of cells are in each cluster?
prop.table(table(Idents(pbmc)))
```

Example 19 (javascript):
```javascript
## 
##  Naive CD4 T Memory CD4 T   CD14+ Mono            B        CD8 T FCGR3A+ Mono 
##  0.264215315  0.183093252  0.181956027  0.130401820  0.102729340  0.061410159 
##           NK           DC     Platelet 
##  0.058756634  0.012130402  0.005307051
```

Example 20 (javascript):
```javascript
## 
##  Naive CD4 T Memory CD4 T   CD14+ Mono            B        CD8 T FCGR3A+ Mono 
##  0.264215315  0.183093252  0.181956027  0.130401820  0.102729340  0.061410159 
##           NK           DC     Platelet 
##  0.058756634  0.012130402  0.005307051
```

Example 21 (r):
```r
# How does cluster membership vary by replicate?
table(Idents(pbmc), pbmc$replicate)
```

Example 22 (r):
```r
# How does cluster membership vary by replicate?
table(Idents(pbmc), pbmc$replicate)
```

Example 23 (javascript):
```javascript
##               
##                rep1 rep2
##   Naive CD4 T   354  343
##   Memory CD4 T  249  234
##   CD14+ Mono    232  248
##   B             173  171
##   CD8 T         154  117
##   FCGR3A+ Mono   81   81
##   NK             81   74
##   DC             18   14
##   Platelet        6    8
```

Example 24 (javascript):
```javascript
##               
##                rep1 rep2
##   Naive CD4 T   354  343
##   Memory CD4 T  249  234
##   CD14+ Mono    232  248
##   B             173  171
##   CD8 T         154  117
##   FCGR3A+ Mono   81   81
##   NK             81   74
##   DC             18   14
##   Platelet        6    8
```

Example 25 (r):
```r
prop.table(table(Idents(pbmc), pbmc$replicate), margin = 2)
```

Example 26 (r):
```r
prop.table(table(Idents(pbmc), pbmc$replicate), margin = 2)
```

Example 27 (javascript):
```javascript
##               
##                       rep1        rep2
##   Naive CD4 T  0.262611276 0.265891473
##   Memory CD4 T 0.184718101 0.181395349
##   CD14+ Mono   0.172106825 0.192248062
##   B            0.128338279 0.132558140
##   CD8 T        0.114243323 0.090697674
##   FCGR3A+ Mono 0.060089021 0.062790698
##   NK           0.060089021 0.057364341
##   DC           0.013353116 0.010852713
##   Platelet     0.004451039 0.006201550
```

Example 28 (javascript):
```javascript
##               
##                       rep1        rep2
##   Naive CD4 T  0.262611276 0.265891473
##   Memory CD4 T 0.184718101 0.181395349
##   CD14+ Mono   0.172106825 0.192248062
##   B            0.128338279 0.132558140
##   CD8 T        0.114243323 0.090697674
##   FCGR3A+ Mono 0.060089021 0.062790698
##   NK           0.060089021 0.057364341
##   DC           0.013353116 0.010852713
##   Platelet     0.004451039 0.006201550
```

Example 29 (r):
```r
# What are the cell names of all NK cells?
WhichCells(pbmc, idents = "NK")
```

Example 30 (r):
```r
# What are the cell names of all NK cells?
WhichCells(pbmc, idents = "NK")
```

Example 31 (unknown):
```unknown
##   [1] "AAACCGTGTATGCG-1" "AAATTCGATTCTCA-1" "AACCTTACGCGAGA-1"
##   [4] "AACGCCCTCGTACA-1" "AACGTCGAGTATCG-1" "AAGATTACCTCAAG-1"
##   [7] "AAGCAAGAGCTTAG-1" "AAGCAAGAGGTGTT-1" "AAGTAGGATACAGC-1"
##  [10] "AATACTGAATTGGC-1" "AATCCTTGGTGAGG-1" "AATCTCTGCTTTAC-1"
##  [13] "ACAAATTGTTGCGA-1" "ACAACCGAGGGATG-1" "ACAATTGATGACTG-1"
##  [16] "ACACCCTGGTGTTG-1" "ACAGGTACTGGTGT-1" "ACCTGGCTAAGTAG-1"
##  [19] "ACGAACACCTTGTT-1" "ACGATCGAGGACTT-1" "ACGCAATGGTTCAG-1"
##  [22] "ACGCTGCTGTTCTT-1" "ACGGAACTCAGATC-1" "ACGTGATGTGACAC-1"
##  [25] "ACGTTGGAGCCAAT-1" "ACTGCCACTCCGTC-1" "ACTGGCCTTCAGTG-1"
##  [28] "ACTTCAACGTAGGG-1" "AGAACAGAAATGCC-1" "AGATATACCCGTAA-1"
##  [31] "AGATTCCTGTTCAG-1" "AGCCTCTGCCAATG-1" "AGCGATTGAGATCC-1"
##  [34] "AGGATGCTTTAGGC-1" "AGGGACGAGTCAAC-1" "AGTAATACATCACG-1"
##  [37] "AGTCACGATGAGCT-1" "AGTTTGCTACTGGT-1" "ATACCACTGCCAAT-1"
##  [40] "ATACTCTGGTATGC-1" "ATCCCGTGCAGTCA-1" "ATCTTTCTTGTCCC-1"
##  [43] "ATGAAGGACTTGCC-1" "ATGATAACTTCACT-1" "ATGATATGGTGCTA-1"
##  [46] "ATGGACACGCATCA-1" "ATGGGTACATCGGT-1" "ATTAACGATGAGAA-1"
##  [49] "ATTCCAACTTAGGC-1" "CAAGGTTGTCTGGA-1" "CAATCTACTGACTG-1"
##  [52] "CACCACTGGCGAAG-1" "CACGGGTGGAGGAC-1" "CAGATGACATTCTC-1"
##  [55] "CAGCAATGGAGGGT-1" "CAGCGGACCTTTAC-1" "CAGCTCTGTGTGGT-1"
##  [58] "CAGTTTACACACGT-1" "CATCAGGACTTCCG-1" "CATCAGGATAGCCA-1"
##  [61] "CATGAGACGTTGAC-1" "CATTACACCAACTG-1" "CATTTCGAGATACC-1"
##  [64] "CCTCGAACACTTTC-1" "CGACCACTAAAGTG-1" "CGACCACTGCCAAT-1"
##  [67] "CGAGGCTGACGCTA-1" "CGCCGAGAGCTTAG-1" "CGGCGAACGACAAA-1"
##  [70] "CGGCGAACTACTTC-1" "CGGGCATGTCTCTA-1" "CGTACCTGGCATCA-1"
##  [73] "CGTGTAGACGATAC-1" "CGTGTAGAGTTACG-1" "CGTGTAGATTCGGA-1"
##  [76] "CTAAACCTCTGACA-1" "CTAACGGAACCGAT-1" "CTACGCACTGGTCA-1"
##  [79] "CTACTCCTATGTCG-1" "CTAGTTACGAAACA-1" "CTATACTGCTACGA-1"
##  [82] "CTATACTGTCTCAT-1" "CTCGACTGGTTGAC-1" "CTGAGAACGTAAAG-1"
##  [85] "CTTTAGTGACGGGA-1" "GAACCAACTTCCGC-1" "GAAGTGCTAAACGA-1"
##  [88] "GAATGCACCTTCGC-1" "GAATTAACGTCGTA-1" "GACGGCACACGGGA-1"
##  [91] "GAGCGCTGAAGATG-1" "GAGGTACTGACACT-1" "GAGGTGGATCCTCG-1"
##  [94] "GATAGAGAAGGGTG-1" "GATCCCTGACCTTT-1" "GCACACCTGTGCTA-1"
##  [97] "GCACCACTTCCTTA-1" "GCACTAGAGTCGTA-1" "GCAGGGCTATCGAC-1"
## [100] "GCCGGAACGTTCTT-1" "GCCTACACAGTTCG-1" "GCGCATCTTGCTCC-1"
## [103] "GCGCGATGGTGCAT-1" "GGAAGGTGGCGAGA-1" "GGACGCTGTCCTCG-1"
## [106] "GGAGGCCTCGTTGA-1" "GGCAAGGAAAAAGC-1" "GGCATATGCTTATC-1"
## [109] "GGCCGAACTCTAGG-1" "GGCTAAACACCTGA-1" "GGGTTAACGTGCAT-1"
## [112] "GGTGGAGAAACGGG-1" "GTAGTGTGAGCGGA-1" "GTCGACCTGAATGA-1"
## [115] "GTGATTCTGGTTCA-1" "GTGTATCTAGTAGA-1" "GTTAAAACCGAGAG-1"
## [118] "GTTCAACTGGGACA-1" "GTTGACGATATCGG-1" "TAACTCACTCTACT-1"
## [121] "TAAGAGGACTTGTT-1" "TAATGCCTCGTCTC-1" "TACGGCCTGGGACA-1"
## [124] "TACTACTGATGTCG-1" "TACTCTGAATCGAC-1" "TACTGTTGAGGCGA-1"
## [127] "TAGCATCTCAGCTA-1" "TAGCCCACAGCTAC-1" "TAGGGACTGAACTC-1"
## [130] "TAGTGGTGAAGTGA-1" "TAGTTAGAACCACA-1" "TATGAATGGAGGAC-1"
## [133] "TATGGGTGCATCAG-1" "TATTTCCTGGAGGT-1" "TCAACACTGTTTGG-1"
## [136] "TCAGACGACGTTAG-1" "TCCCGAACACAGTC-1" "TCCTAAACCGCATA-1"
## [139] "TCGATTTGCAGCTA-1" "TCTAACACCAGTTG-1" "TGATAAACTCCGTC-1"
## [142] "TGCACAGACGACAT-1" "TGCCACTGCGATAC-1" "TGCTGAGAGAGCAG-1"
## [145] "TGGAACACAAACAG-1" "TGGTAGACCCTCAC-1" "TGTAATGACACAAC-1"
## [148] "TGTAATGAGGTAAA-1" "TTACTCGATCTACT-1" "TTAGTCTGCCAACA-1"
## [151] "TTCCAAACTCCCAC-1" "TTCCCACTTGAGGG-1" "TTCTAGTGGAGAGC-1"
## [154] "TTCTGATGGAGACG-1" "TTGTCATGGACGGA-1"
```

Example 32 (unknown):
```unknown
##   [1] "AAACCGTGTATGCG-1" "AAATTCGATTCTCA-1" "AACCTTACGCGAGA-1"
##   [4] "AACGCCCTCGTACA-1" "AACGTCGAGTATCG-1" "AAGATTACCTCAAG-1"
##   [7] "AAGCAAGAGCTTAG-1" "AAGCAAGAGGTGTT-1" "AAGTAGGATACAGC-1"
##  [10] "AATACTGAATTGGC-1" "AATCCTTGGTGAGG-1" "AATCTCTGCTTTAC-1"
##  [13] "ACAAATTGTTGCGA-1" "ACAACCGAGGGATG-1" "ACAATTGATGACTG-1"
##  [16] "ACACCCTGGTGTTG-1" "ACAGGTACTGGTGT-1" "ACCTGGCTAAGTAG-1"
##  [19] "ACGAACACCTTGTT-1" "ACGATCGAGGACTT-1" "ACGCAATGGTTCAG-1"
##  [22] "ACGCTGCTGTTCTT-1" "ACGGAACTCAGATC-1" "ACGTGATGTGACAC-1"
##  [25] "ACGTTGGAGCCAAT-1" "ACTGCCACTCCGTC-1" "ACTGGCCTTCAGTG-1"
##  [28] "ACTTCAACGTAGGG-1" "AGAACAGAAATGCC-1" "AGATATACCCGTAA-1"
##  [31] "AGATTCCTGTTCAG-1" "AGCCTCTGCCAATG-1" "AGCGATTGAGATCC-1"
##  [34] "AGGATGCTTTAGGC-1" "AGGGACGAGTCAAC-1" "AGTAATACATCACG-1"
##  [37] "AGTCACGATGAGCT-1" "AGTTTGCTACTGGT-1" "ATACCACTGCCAAT-1"
##  [40] "ATACTCTGGTATGC-1" "ATCCCGTGCAGTCA-1" "ATCTTTCTTGTCCC-1"
##  [43] "ATGAAGGACTTGCC-1" "ATGATAACTTCACT-1" "ATGATATGGTGCTA-1"
##  [46] "ATGGACACGCATCA-1" "ATGGGTACATCGGT-1" "ATTAACGATGAGAA-1"
##  [49] "ATTCCAACTTAGGC-1" "CAAGGTTGTCTGGA-1" "CAATCTACTGACTG-1"
##  [52] "CACCACTGGCGAAG-1" "CACGGGTGGAGGAC-1" "CAGATGACATTCTC-1"
##  [55] "CAGCAATGGAGGGT-1" "CAGCGGACCTTTAC-1" "CAGCTCTGTGTGGT-1"
##  [58] "CAGTTTACACACGT-1" "CATCAGGACTTCCG-1" "CATCAGGATAGCCA-1"
##  [61] "CATGAGACGTTGAC-1" "CATTACACCAACTG-1" "CATTTCGAGATACC-1"
##  [64] "CCTCGAACACTTTC-1" "CGACCACTAAAGTG-1" "CGACCACTGCCAAT-1"
##  [67] "CGAGGCTGACGCTA-1" "CGCCGAGAGCTTAG-1" "CGGCGAACGACAAA-1"
##  [70] "CGGCGAACTACTTC-1" "CGGGCATGTCTCTA-1" "CGTACCTGGCATCA-1"
##  [73] "CGTGTAGACGATAC-1" "CGTGTAGAGTTACG-1" "CGTGTAGATTCGGA-1"
##  [76] "CTAAACCTCTGACA-1" "CTAACGGAACCGAT-1" "CTACGCACTGGTCA-1"
##  [79] "CTACTCCTATGTCG-1" "CTAGTTACGAAACA-1" "CTATACTGCTACGA-1"
##  [82] "CTATACTGTCTCAT-1" "CTCGACTGGTTGAC-1" "CTGAGAACGTAAAG-1"
##  [85] "CTTTAGTGACGGGA-1" "GAACCAACTTCCGC-1" "GAAGTGCTAAACGA-1"
##  [88] "GAATGCACCTTCGC-1" "GAATTAACGTCGTA-1" "GACGGCACACGGGA-1"
##  [91] "GAGCGCTGAAGATG-1" "GAGGTACTGACACT-1" "GAGGTGGATCCTCG-1"
##  [94] "GATAGAGAAGGGTG-1" "GATCCCTGACCTTT-1" "GCACACCTGTGCTA-1"
##  [97] "GCACCACTTCCTTA-1" "GCACTAGAGTCGTA-1" "GCAGGGCTATCGAC-1"
## [100] "GCCGGAACGTTCTT-1" "GCCTACACAGTTCG-1" "GCGCATCTTGCTCC-1"
## [103] "GCGCGATGGTGCAT-1" "GGAAGGTGGCGAGA-1" "GGACGCTGTCCTCG-1"
## [106] "GGAGGCCTCGTTGA-1" "GGCAAGGAAAAAGC-1" "GGCATATGCTTATC-1"
## [109] "GGCCGAACTCTAGG-1" "GGCTAAACACCTGA-1" "GGGTTAACGTGCAT-1"
## [112] "GGTGGAGAAACGGG-1" "GTAGTGTGAGCGGA-1" "GTCGACCTGAATGA-1"
## [115] "GTGATTCTGGTTCA-1" "GTGTATCTAGTAGA-1" "GTTAAAACCGAGAG-1"
## [118] "GTTCAACTGGGACA-1" "GTTGACGATATCGG-1" "TAACTCACTCTACT-1"
## [121] "TAAGAGGACTTGTT-1" "TAATGCCTCGTCTC-1" "TACGGCCTGGGACA-1"
## [124] "TACTACTGATGTCG-1" "TACTCTGAATCGAC-1" "TACTGTTGAGGCGA-1"
## [127] "TAGCATCTCAGCTA-1" "TAGCCCACAGCTAC-1" "TAGGGACTGAACTC-1"
## [130] "TAGTGGTGAAGTGA-1" "TAGTTAGAACCACA-1" "TATGAATGGAGGAC-1"
## [133] "TATGGGTGCATCAG-1" "TATTTCCTGGAGGT-1" "TCAACACTGTTTGG-1"
## [136] "TCAGACGACGTTAG-1" "TCCCGAACACAGTC-1" "TCCTAAACCGCATA-1"
## [139] "TCGATTTGCAGCTA-1" "TCTAACACCAGTTG-1" "TGATAAACTCCGTC-1"
## [142] "TGCACAGACGACAT-1" "TGCCACTGCGATAC-1" "TGCTGAGAGAGCAG-1"
## [145] "TGGAACACAAACAG-1" "TGGTAGACCCTCAC-1" "TGTAATGACACAAC-1"
## [148] "TGTAATGAGGTAAA-1" "TTACTCGATCTACT-1" "TTAGTCTGCCAACA-1"
## [151] "TTCCAAACTCCCAC-1" "TTCCCACTTGAGGG-1" "TTCTAGTGGAGAGC-1"
## [154] "TTCTGATGGAGACG-1" "TTGTCATGGACGGA-1"
```

Example 33 (r):
```r
# How can I extract expression matrix for all NK cells (perhaps, to load into another package)
nk.raw.data <- as.matrix(GetAssayData(pbmc, slot = "counts")[, WhichCells(pbmc, ident = "NK")])

# Can I create a Seurat object based on expression of a feature or value in object metadata?
subset(pbmc, subset = MS4A1 > 1)
```

Example 34 (r):
```r
# How can I extract expression matrix for all NK cells (perhaps, to load into another package)
nk.raw.data <- as.matrix(GetAssayData(pbmc, slot = "counts")[, WhichCells(pbmc, ident = "NK")])

# Can I create a Seurat object based on expression of a feature or value in object metadata?
subset(pbmc, subset = MS4A1 > 1)
```

Example 35 (python):
```python
## An object of class Seurat 
## 13714 features across 414 samples within 1 assay 
## Active assay: RNA (13714 features, 2000 variable features)
##  2 dimensional reductions calculated: pca, umap
```

Example 36 (python):
```python
## An object of class Seurat 
## 13714 features across 414 samples within 1 assay 
## Active assay: RNA (13714 features, 2000 variable features)
##  2 dimensional reductions calculated: pca, umap
```

Example 37 (r):
```r
subset(pbmc, subset = replicate == "rep2")
```

Example 38 (r):
```r
subset(pbmc, subset = replicate == "rep2")
```

Example 39 (python):
```python
## An object of class Seurat 
## 13714 features across 1290 samples within 1 assay 
## Active assay: RNA (13714 features, 2000 variable features)
##  2 dimensional reductions calculated: pca, umap
```

Example 40 (python):
```python
## An object of class Seurat 
## 13714 features across 1290 samples within 1 assay 
## Active assay: RNA (13714 features, 2000 variable features)
##  2 dimensional reductions calculated: pca, umap
```

Example 41 (r):
```r
# Can I create a Seurat object of just the NK cells and B cells?
subset(pbmc, idents = c("NK", "B"))
```

Example 42 (r):
```r
# Can I create a Seurat object of just the NK cells and B cells?
subset(pbmc, idents = c("NK", "B"))
```

Example 43 (python):
```python
## An object of class Seurat 
## 13714 features across 499 samples within 1 assay 
## Active assay: RNA (13714 features, 2000 variable features)
##  2 dimensional reductions calculated: pca, umap
```

Example 44 (python):
```python
## An object of class Seurat 
## 13714 features across 499 samples within 1 assay 
## Active assay: RNA (13714 features, 2000 variable features)
##  2 dimensional reductions calculated: pca, umap
```

Example 45 (r):
```r
# Can I create a Seurat object of all cells except the NK cells and B cells?
subset(pbmc, idents = c("NK", "B"), invert = TRUE)
```

Example 46 (r):
```r
# Can I create a Seurat object of all cells except the NK cells and B cells?
subset(pbmc, idents = c("NK", "B"), invert = TRUE)
```

Example 47 (python):
```python
## An object of class Seurat 
## 13714 features across 2139 samples within 1 assay 
## Active assay: RNA (13714 features, 2000 variable features)
##  2 dimensional reductions calculated: pca, umap
```

Example 48 (python):
```python
## An object of class Seurat 
## 13714 features across 2139 samples within 1 assay 
## Active assay: RNA (13714 features, 2000 variable features)
##  2 dimensional reductions calculated: pca, umap
```

Example 49 (r):
```r
# note that if you wish to perform additional rounds of clustering after subsetting we recommend
# re-running FindVariableFeatures() and ScaleData()
```

Example 50 (r):
```r
# note that if you wish to perform additional rounds of clustering after subsetting we recommend
# re-running FindVariableFeatures() and ScaleData()
```

Example 51 (r):
```r
# How can I calculate the average expression of all cells within a cluster?
cluster.averages <- AverageExpression(pbmc)
head(cluster.averages[["RNA"]][, 1:5])
```

Example 52 (r):
```r
# How can I calculate the average expression of all cells within a cluster?
cluster.averages <- AverageExpression(pbmc)
head(cluster.averages[["RNA"]][, 1:5])
```

Example 53 (r):
```r
# Return this information as a Seurat object (enables downstream plotting and analysis) First,
# replace spaces with underscores '_' so ggplot2 doesn't fail
orig.levels <- levels(pbmc)
Idents(pbmc) <- gsub(pattern = " ", replacement = "_", x = Idents(pbmc))
orig.levels <- gsub(pattern = " ", replacement = "_", x = orig.levels)
levels(pbmc) <- orig.levels
cluster.averages <- AverageExpression(pbmc, return.seurat = TRUE)
cluster.averages
```

Example 54 (r):
```r
# Return this information as a Seurat object (enables downstream plotting and analysis) First,
# replace spaces with underscores '_' so ggplot2 doesn't fail
orig.levels <- levels(pbmc)
Idents(pbmc) <- gsub(pattern = " ", replacement = "_", x = Idents(pbmc))
orig.levels <- gsub(pattern = " ", replacement = "_", x = orig.levels)
levels(pbmc) <- orig.levels
cluster.averages <- AverageExpression(pbmc, return.seurat = TRUE)
cluster.averages
```

Example 55 (python):
```python
## An object of class Seurat 
## 13714 features across 9 samples within 1 assay 
## Active assay: RNA (13714 features, 0 variable features)
```

Example 56 (python):
```python
## An object of class Seurat 
## 13714 features across 9 samples within 1 assay 
## Active assay: RNA (13714 features, 0 variable features)
```

Example 57 (r):
```r
# How can I plot the average expression of NK cells vs. CD8 T cells?  Pass do.hover = T for an
# interactive plot to identify gene outliers
CellScatter(cluster.averages, cell1 = "NK", cell2 = "CD8_T")
```

Example 58 (r):
```r
# How can I plot the average expression of NK cells vs. CD8 T cells?  Pass do.hover = T for an
# interactive plot to identify gene outliers
CellScatter(cluster.averages, cell1 = "NK", cell2 = "CD8_T")
```

Example 59 (r):
```r
# How can I calculate expression averages separately for each replicate?
cluster.averages <- AverageExpression(pbmc, return.seurat = TRUE, add.ident = "replicate")
CellScatter(cluster.averages, cell1 = "CD8_T_rep1", cell2 = "CD8_T_rep2")
```

Example 60 (r):
```r
# How can I calculate expression averages separately for each replicate?
cluster.averages <- AverageExpression(pbmc, return.seurat = TRUE, add.ident = "replicate")
CellScatter(cluster.averages, cell1 = "CD8_T_rep1", cell2 = "CD8_T_rep2")
```

Example 61 (r):
```r
# You can also plot heatmaps of these 'in silico' bulk datasets to visualize agreement between
# replicates
DoHeatmap(cluster.averages, features = unlist(TopFeatures(pbmc[["pca"]], balanced = TRUE)), size = 3, 
    draw.lines = FALSE)
```

Example 62 (r):
```r
# You can also plot heatmaps of these 'in silico' bulk datasets to visualize agreement between
# replicates
DoHeatmap(cluster.averages, features = unlist(TopFeatures(pbmc[["pca"]], balanced = TRUE)), size = 3, 
    draw.lines = FALSE)
```

---

## Analysis, visualization, and integration of Visium HD spatial datasets with Seurat • Seurat

**URL:** http://127.0.0.1:9173/articles_cell_cycle_vignette.html

**Contents:**
- Cell-Cycle Scoring and Regression
    - Compiled: 2023-10-31
- Assign Cell-Cycle Scores
- Regress out cell cycle scores during data scaling
- Alternate Workflow
- Contents

We demonstrate how to mitigate the effects of cell cycle heterogeneity in scRNA-seq data by calculating cell cycle phase scores based on canonical markers, and regressing these out of the data during pre-processing. We demonstrate this on a dataset of murine hematopoietic progenitors (Nestorowa et al., Blood 2016).You can download the files needed to run this vignette here.

If we run a PCA on our object, using the variable genes we found in FindVariableFeatures() above, we see that while most of the variance can be explained by lineage, PC8 and PC10 are split on cell-cycle genes including TOP2A and MKI67. We will attempt to regress this signal from the data, so that cell-cycle heterogeneity does not contribute to PCA or downstream analysis.

First, we assign each cell a score, based on its expression of G2/M and S phase markers. These marker sets should be anticorrelated in their expression levels, and cells expressing neither are likely not cycling and in G1 phase.

We assign scores in the CellCycleScoring() function, which stores S and G2/M scores in object meta data, along with the predicted classification of each cell in either G2M, S or G1 phase. CellCycleScoring() can also set the identity of the Seurat object to the cell-cycle phase by passing set.ident = TRUE (the original identities are stored as old.ident). Please note that Seurat does not use the discrete classifications (G2M/G1/S) in downstream cell cycle regression. Instead, it uses the quantitative scores for G2M and S phase. However, we provide our predicted classifications in case they are of interest.

We score single cells based on the scoring strategy described in Tirosh et al. 2016. See ?AddModuleScore() in Seurat for more information, this function can be used to calculate supervised module scores for any gene list.

We now attempt to subtract (‘regress out’) this source of heterogeneity from the data. For users of Seurat v1.4, this was implemented in RegressOut. However, as the results of this procedure are stored in the scaled data slot (therefore overwriting the output of ScaleData()), we now merge this functionality into the ScaleData() function itself.

For each gene, Seurat models the relationship between gene expression and the S and G2M cell cycle scores. The scaled residuals of this model represent a ‘corrected’ expression matrix, that can be used downstream for dimensional reduction.

As the best cell cycle markers are extremely well conserved across tissues and species, we have found this procedure to work robustly and reliably on diverse datasets.

The procedure above removes all signal associated with cell cycle. In some cases, we’ve found that this can negatively impact downstream analysis, particularly in differentiating processes (like murine hematopoiesis), where stem cells are quiescent and differentiated cells are proliferating (or vice versa). In this case, regressing out all cell cycle effects can blur the distinction between stem and progenitor cells as well.

As an alternative, we suggest regressing out the difference between the G2M and S phase scores. This means that signals separating non-cycling cells and cycling cells will be maintained, but differences in cell cycle phase among proliferating cells (which are often uninteresting), will be regressed out of the data

Developed by Rahul Satija, Satija Lab and Collaborators.

Site built with pkgdown 2.0.7.

**Examples:**

Example 1 (unknown):
```unknown
vignettes/cell_cycle_vignette.Rmd
```

Example 2 (unknown):
```unknown
cell_cycle_vignette.Rmd
```

Example 3 (python):
```python
library(Seurat)

# Read in the expression matrix The first row is a header row, the first column is rownames
exp.mat <- read.table(file = "/brahms/shared/vignette-data/cell_cycle_vignette_files/nestorawa_forcellcycle_expressionMatrix.txt",
    header = TRUE, as.is = TRUE, row.names = 1)

# A list of cell cycle markers, from Tirosh et al, 2015, is loaded with Seurat.  We can
# segregate this list into markers of G2/M phase and markers of S phase
s.genes <- cc.genes$s.genes
g2m.genes <- cc.genes$g2m.genes

# Create our Seurat object and complete the initalization steps
marrow <- CreateSeuratObject(counts = Matrix::Matrix(as.matrix(exp.mat), sparse = T))
marrow <- NormalizeData(marrow)
marrow <- FindVariableFeatures(marrow, selection.method = "vst")
marrow <- ScaleData(marrow, features = rownames(marrow))
```

Example 4 (r):
```r
library(Seurat)

# Read in the expression matrix The first row is a header row, the first column is rownames
exp.mat <- read.table(file = "/brahms/shared/vignette-data/cell_cycle_vignette_files/nestorawa_forcellcycle_expressionMatrix.txt",
    header = TRUE, as.is = TRUE, row.names = 1)

# A list of cell cycle markers, from Tirosh et al, 2015, is loaded with Seurat.  We can
# segregate this list into markers of G2/M phase and markers of S phase
s.genes <- cc.genes$s.genes
g2m.genes <- cc.genes$g2m.genes

# Create our Seurat object and complete the initalization steps
marrow <- CreateSeuratObject(counts = Matrix::Matrix(as.matrix(exp.mat), sparse = T))
marrow <- NormalizeData(marrow)
marrow <- FindVariableFeatures(marrow, selection.method = "vst")
marrow <- ScaleData(marrow, features = rownames(marrow))
```

Example 5 (r):
```r
library(Seurat)

# Read in the expression matrix The first row is a header row, the first column is rownames
exp.mat <- read.table(file = "/brahms/shared/vignette-data/cell_cycle_vignette_files/nestorawa_forcellcycle_expressionMatrix.txt",
    header = TRUE, as.is = TRUE, row.names = 1)

# A list of cell cycle markers, from Tirosh et al, 2015, is loaded with Seurat.  We can
# segregate this list into markers of G2/M phase and markers of S phase
s.genes <- cc.genes$s.genes
g2m.genes <- cc.genes$g2m.genes

# Create our Seurat object and complete the initalization steps
marrow <- CreateSeuratObject(counts = Matrix::Matrix(as.matrix(exp.mat), sparse = T))
marrow <- NormalizeData(marrow)
marrow <- FindVariableFeatures(marrow, selection.method = "vst")
marrow <- ScaleData(marrow, features = rownames(marrow))
```

Example 6 (unknown):
```unknown
FindVariableFeatures()
```

Example 7 (unknown):
```unknown
marrow <- RunPCA(marrow, features = VariableFeatures(marrow), ndims.print = 6:10, nfeatures.print = 10)
```

Example 8 (r):
```r
marrow <- RunPCA(marrow, features = VariableFeatures(marrow), ndims.print = 6:10, nfeatures.print = 10)
```

Example 9 (r):
```r
marrow <- RunPCA(marrow, features = VariableFeatures(marrow), ndims.print = 6:10, nfeatures.print = 10)
```

Example 10 (unknown):
```unknown
## PC_ 6 
## Positive:  SELL, ARL6IP1, CCL9, CD34, ADGRL4, BPIFC, NUSAP1, FAM64A, CD244, C030034L19RIK 
## Negative:  LY6C2, AA467197, CYBB, MGST2, ITGB2, PF4, CD74, ATP1B1, GP1BB, TREM3 
## PC_ 7 
## Positive:  F13A1, LY86, CFP, IRF8, CSF1R, TIFAB, IFI209, CCR2, TNS4, MS4A6C 
## Negative:  HDC, CPA3, PGLYRP1, MS4A3, NKG7, UBE2C, CCNB1, NUSAP1, PLK1, FUT8 
## PC_ 8 
## Positive:  NUSAP1, UBE2C, KIF23, PLK1, CENPF, FAM64A, CCNB1, H2AFX, ID2, CDC20 
## Negative:  WFDC17, SLC35D3, ADGRL4, VLDLR, CD33, H2AFY, P2RY14, IFI206, CCL9, CD34 
## PC_ 9 
## Positive:  IGKC, JCHAIN, LY6D, MZB1, CD74, IGLC2, FCRLA, IGKV4-50, IGHM, IGHV9-1 
## Negative:  SLC2A6, HBA-A1, HBA-A2, IGHV8-7, FCER1G, F13A1, HBB-BS, PLD4, HBB-BT, IGFBP4 
## PC_ 10 
## Positive:  H2AFX, FAM64A, ZFP383, NUSAP1, CDC25B, CENPF, GBP10, TOP2A, GBP6, GFRA1 
## Negative:  CTSW, XKRX, PRR5L, RORA, MBOAT4, A630014C17RIK, ZFP105, COL9A3, CLEC2I, TRAT1
```

Example 11 (unknown):
```unknown
## PC_ 6 
## Positive:  SELL, ARL6IP1, CCL9, CD34, ADGRL4, BPIFC, NUSAP1, FAM64A, CD244, C030034L19RIK 
## Negative:  LY6C2, AA467197, CYBB, MGST2, ITGB2, PF4, CD74, ATP1B1, GP1BB, TREM3 
## PC_ 7 
## Positive:  F13A1, LY86, CFP, IRF8, CSF1R, TIFAB, IFI209, CCR2, TNS4, MS4A6C 
## Negative:  HDC, CPA3, PGLYRP1, MS4A3, NKG7, UBE2C, CCNB1, NUSAP1, PLK1, FUT8 
## PC_ 8 
## Positive:  NUSAP1, UBE2C, KIF23, PLK1, CENPF, FAM64A, CCNB1, H2AFX, ID2, CDC20 
## Negative:  WFDC17, SLC35D3, ADGRL4, VLDLR, CD33, H2AFY, P2RY14, IFI206, CCL9, CD34 
## PC_ 9 
## Positive:  IGKC, JCHAIN, LY6D, MZB1, CD74, IGLC2, FCRLA, IGKV4-50, IGHM, IGHV9-1 
## Negative:  SLC2A6, HBA-A1, HBA-A2, IGHV8-7, FCER1G, F13A1, HBB-BS, PLD4, HBB-BT, IGFBP4 
## PC_ 10 
## Positive:  H2AFX, FAM64A, ZFP383, NUSAP1, CDC25B, CENPF, GBP10, TOP2A, GBP6, GFRA1 
## Negative:  CTSW, XKRX, PRR5L, RORA, MBOAT4, A630014C17RIK, ZFP105, COL9A3, CLEC2I, TRAT1
```

Example 12 (unknown):
```unknown
DimHeatmap(marrow, dims = c(8, 10))
```

Example 13 (r):
```r
DimHeatmap(marrow, dims = c(8, 10))
```

Example 14 (r):
```r
DimHeatmap(marrow, dims = c(8, 10))
```

Example 15 (unknown):
```unknown
CellCycleScoring()
```

Example 16 (unknown):
```unknown
CellCycleScoring()
```

Example 17 (unknown):
```unknown
set.ident = TRUE
```

Example 18 (unknown):
```unknown
marrow <- CellCycleScoring(marrow, s.features = s.genes, g2m.features = g2m.genes, set.ident = TRUE)

# view cell cycle scores and phase assignments
head(marrow[[]])
```

Example 19 (r):
```r
marrow <- CellCycleScoring(marrow, s.features = s.genes, g2m.features = g2m.genes, set.ident = TRUE)

# view cell cycle scores and phase assignments
head(marrow[[]])
```

Example 20 (r):
```r
marrow <- CellCycleScoring(marrow, s.features = s.genes, g2m.features = g2m.genes, set.ident = TRUE)

# view cell cycle scores and phase assignments
head(marrow[[]])
```

Example 21 (unknown):
```unknown
##          orig.ident nCount_RNA nFeature_RNA     S.Score  G2M.Score Phase
## Prog_013       Prog    2563089        10211 -0.14248691 -0.4680395    G1
## Prog_019       Prog    3030620         9991 -0.16915786  0.5851766   G2M
## Prog_031       Prog    1293487        10192 -0.34627038 -0.3971879    G1
## Prog_037       Prog    1357987         9599 -0.44270212  0.6820229   G2M
## Prog_008       Prog    4079891        10540  0.55854051  0.1284359     S
## Prog_014       Prog    2569783        10788  0.07116218  0.3166073   G2M
##          old.ident
## Prog_013      Prog
## Prog_019      Prog
## Prog_031      Prog
## Prog_037      Prog
## Prog_008      Prog
## Prog_014      Prog
```

Example 22 (unknown):
```unknown
##          orig.ident nCount_RNA nFeature_RNA     S.Score  G2M.Score Phase
## Prog_013       Prog    2563089        10211 -0.14248691 -0.4680395    G1
## Prog_019       Prog    3030620         9991 -0.16915786  0.5851766   G2M
## Prog_031       Prog    1293487        10192 -0.34627038 -0.3971879    G1
## Prog_037       Prog    1357987         9599 -0.44270212  0.6820229   G2M
## Prog_008       Prog    4079891        10540  0.55854051  0.1284359     S
## Prog_014       Prog    2569783        10788  0.07116218  0.3166073   G2M
##          old.ident
## Prog_013      Prog
## Prog_019      Prog
## Prog_031      Prog
## Prog_037      Prog
## Prog_008      Prog
## Prog_014      Prog
```

Example 23 (unknown):
```unknown
# Visualize the distribution of cell cycle markers across
RidgePlot(marrow, features = c("PCNA", "TOP2A", "MCM6", "MKI67"), ncol = 2)
```

Example 24 (r):
```r
# Visualize the distribution of cell cycle markers across
RidgePlot(marrow, features = c("PCNA", "TOP2A", "MCM6", "MKI67"), ncol = 2)
```

Example 25 (r):
```r
# Visualize the distribution of cell cycle markers across
RidgePlot(marrow, features = c("PCNA", "TOP2A", "MCM6", "MKI67"), ncol = 2)
```

Example 26 (unknown):
```unknown
# Running a PCA on cell cycle genes reveals, unsurprisingly, that cells separate entirely by
# phase
marrow <- RunPCA(marrow, features = c(s.genes, g2m.genes))
DimPlot(marrow)
```

Example 27 (r):
```r
# Running a PCA on cell cycle genes reveals, unsurprisingly, that cells separate entirely by
# phase
marrow <- RunPCA(marrow, features = c(s.genes, g2m.genes))
DimPlot(marrow)
```

Example 28 (r):
```r
# Running a PCA on cell cycle genes reveals, unsurprisingly, that cells separate entirely by
# phase
marrow <- RunPCA(marrow, features = c(s.genes, g2m.genes))
DimPlot(marrow)
```

Example 29 (unknown):
```unknown
library(ggplot2)
plot <- DimPlot(marrow) + theme(axis.title = element_text(size = 18), legend.text = element_text(size = 18)) +
    guides(colour = guide_legend(override.aes = list(size = 10)))
ggsave(filename = "../output/images/cell_cycle_vignette.jpg", height = 7, width = 12, plot = plot,
    quality = 50)
```

Example 30 (r):
```r
library(ggplot2)
plot <- DimPlot(marrow) + theme(axis.title = element_text(size = 18), legend.text = element_text(size = 18)) +
    guides(colour = guide_legend(override.aes = list(size = 10)))
ggsave(filename = "../output/images/cell_cycle_vignette.jpg", height = 7, width = 12, plot = plot,
    quality = 50)
```

Example 31 (r):
```r
library(ggplot2)
plot <- DimPlot(marrow) + theme(axis.title = element_text(size = 18), legend.text = element_text(size = 18)) +
    guides(colour = guide_legend(override.aes = list(size = 10)))
ggsave(filename = "../output/images/cell_cycle_vignette.jpg", height = 7, width = 12, plot = plot,
    quality = 50)
```

Example 32 (unknown):
```unknown
?AddModuleScore()
```

Example 33 (unknown):
```unknown
ScaleData()
```

Example 34 (unknown):
```unknown
ScaleData()
```

Example 35 (unknown):
```unknown
marrow <- ScaleData(marrow, vars.to.regress = c("S.Score", "G2M.Score"), features = rownames(marrow))
```

Example 36 (r):
```r
marrow <- ScaleData(marrow, vars.to.regress = c("S.Score", "G2M.Score"), features = rownames(marrow))
```

Example 37 (r):
```r
marrow <- ScaleData(marrow, vars.to.regress = c("S.Score", "G2M.Score"), features = rownames(marrow))
```

Example 38 (unknown):
```unknown
# Now, a PCA on the variable genes no longer returns components associated with cell cycle
marrow <- RunPCA(marrow, features = VariableFeatures(marrow), nfeatures.print = 10)
```

Example 39 (r):
```r
# Now, a PCA on the variable genes no longer returns components associated with cell cycle
marrow <- RunPCA(marrow, features = VariableFeatures(marrow), nfeatures.print = 10)
```

Example 40 (r):
```r
# Now, a PCA on the variable genes no longer returns components associated with cell cycle
marrow <- RunPCA(marrow, features = VariableFeatures(marrow), nfeatures.print = 10)
```

Example 41 (unknown):
```unknown
## PC_ 1 
## Positive:  BLVRB, CAR2, KLF1, AQP1, CES2G, ERMAP, CAR1, FAM132A, RHD, SPHK1 
## Negative:  TMSB4X, H2AFY, CORO1A, PLAC8, EMB, MPO, PRTN3, CD34, LCP1, BC035044 
## PC_ 2 
## Positive:  ANGPT1, ADGRG1, MEIS1, ITGA2B, MPL, DAPP1, APOE, RAB37, GATA2, F2R 
## Negative:  LY6C2, ELANE, HP, IGSF6, ANXA3, CTSG, CLEC12A, TIFAB, SLPI, ALAS1 
## PC_ 3 
## Positive:  APOE, GATA2, NKG7, MUC13, MS4A3, RAB44, HDC, CPA3, FCGR3, TUBA8 
## Negative:  FLT3, DNTT, LSP1, WFDC17, MYL10, GIMAP6, LAX1, GPR171, TBXA2R, SATB1 
## PC_ 4 
## Positive:  CSRP3, ST8SIA6, DNTT, MPEG1, SCIN, LGALS1, CMAH, RGL1, APOE, MFSD2B 
## Negative:  PROCR, MPL, HLF, MMRN1, SERPINA3G, ESAM, GSTM1, D630039A03RIK, MYL10, LY6A 
## PC_ 5 
## Positive:  CPA3, LMO4, IKZF2, IFITM1, FUT8, MS4A2, SIGLECF, CSRP3, HDC, RAB44 
## Negative:  PF4, GP1BB, SDPR, F2RL2, RAB27B, SLC14A1, TREML1, PBX1, F2R, TUBA8
```

Example 42 (unknown):
```unknown
## PC_ 1 
## Positive:  BLVRB, CAR2, KLF1, AQP1, CES2G, ERMAP, CAR1, FAM132A, RHD, SPHK1 
## Negative:  TMSB4X, H2AFY, CORO1A, PLAC8, EMB, MPO, PRTN3, CD34, LCP1, BC035044 
## PC_ 2 
## Positive:  ANGPT1, ADGRG1, MEIS1, ITGA2B, MPL, DAPP1, APOE, RAB37, GATA2, F2R 
## Negative:  LY6C2, ELANE, HP, IGSF6, ANXA3, CTSG, CLEC12A, TIFAB, SLPI, ALAS1 
## PC_ 3 
## Positive:  APOE, GATA2, NKG7, MUC13, MS4A3, RAB44, HDC, CPA3, FCGR3, TUBA8 
## Negative:  FLT3, DNTT, LSP1, WFDC17, MYL10, GIMAP6, LAX1, GPR171, TBXA2R, SATB1 
## PC_ 4 
## Positive:  CSRP3, ST8SIA6, DNTT, MPEG1, SCIN, LGALS1, CMAH, RGL1, APOE, MFSD2B 
## Negative:  PROCR, MPL, HLF, MMRN1, SERPINA3G, ESAM, GSTM1, D630039A03RIK, MYL10, LY6A 
## PC_ 5 
## Positive:  CPA3, LMO4, IKZF2, IFITM1, FUT8, MS4A2, SIGLECF, CSRP3, HDC, RAB44 
## Negative:  PF4, GP1BB, SDPR, F2RL2, RAB27B, SLC14A1, TREML1, PBX1, F2R, TUBA8
```

Example 43 (unknown):
```unknown
# When running a PCA on only cell cycle genes, cells no longer separate by cell-cycle phase
marrow <- RunPCA(marrow, features = c(s.genes, g2m.genes))
DimPlot(marrow)
```

Example 44 (r):
```r
# When running a PCA on only cell cycle genes, cells no longer separate by cell-cycle phase
marrow <- RunPCA(marrow, features = c(s.genes, g2m.genes))
DimPlot(marrow)
```

Example 45 (r):
```r
# When running a PCA on only cell cycle genes, cells no longer separate by cell-cycle phase
marrow <- RunPCA(marrow, features = c(s.genes, g2m.genes))
DimPlot(marrow)
```

Example 46 (unknown):
```unknown
marrow$CC.Difference <- marrow$S.Score - marrow$G2M.Score
marrow <- ScaleData(marrow, vars.to.regress = "CC.Difference", features = rownames(marrow))
```

Example 47 (r):
```r
marrow$CC.Difference <- marrow$S.Score - marrow$G2M.Score
marrow <- ScaleData(marrow, vars.to.regress = "CC.Difference", features = rownames(marrow))
```

Example 48 (r):
```r
marrow$CC.Difference <- marrow$S.Score - marrow$G2M.Score
marrow <- ScaleData(marrow, vars.to.regress = "CC.Difference", features = rownames(marrow))
```

Example 49 (unknown):
```unknown
# cell cycle effects strongly mitigated in PCA
marrow <- RunPCA(marrow, features = VariableFeatures(marrow), nfeatures.print = 10)
```

Example 50 (r):
```r
# cell cycle effects strongly mitigated in PCA
marrow <- RunPCA(marrow, features = VariableFeatures(marrow), nfeatures.print = 10)
```

Example 51 (r):
```r
# cell cycle effects strongly mitigated in PCA
marrow <- RunPCA(marrow, features = VariableFeatures(marrow), nfeatures.print = 10)
```

Example 52 (unknown):
```unknown
## PC_ 1 
## Positive:  BLVRB, KLF1, ERMAP, FAM132A, CAR2, RHD, CES2G, SPHK1, AQP1, SLC38A5 
## Negative:  TMSB4X, CORO1A, PLAC8, H2AFY, LAPTM5, CD34, LCP1, TMEM176B, IGFBP4, EMB 
## PC_ 2 
## Positive:  APOE, GATA2, RAB37, ANGPT1, ADGRG1, MEIS1, MPL, F2R, PDZK1IP1, DAPP1 
## Negative:  CTSG, ELANE, LY6C2, HP, CLEC12A, ANXA3, IGSF6, TIFAB, SLPI, MPO 
## PC_ 3 
## Positive:  APOE, GATA2, NKG7, MUC13, ITGA2B, TUBA8, CPA3, RAB44, SLC18A2, CD9 
## Negative:  DNTT, FLT3, WFDC17, LSP1, MYL10, LAX1, GIMAP6, IGHM, CD24A, MN1 
## PC_ 4 
## Positive:  CSRP3, ST8SIA6, SCIN, LGALS1, APOE, ITGB7, MFSD2B, RGL1, DNTT, IGHV1-23 
## Negative:  MPL, MMRN1, PROCR, HLF, SERPINA3G, ESAM, PTGS1, D630039A03RIK, NDN, PPIC 
## PC_ 5 
## Positive:  GP1BB, PF4, SDPR, F2RL2, TREML1, RAB27B, SLC14A1, PBX1, PLEK, TUBA8 
## Negative:  HDC, LMO4, CSRP3, IFITM1, FCGR3, HLF, CPA3, PROCR, PGLYRP1, IKZF2
```

Example 53 (unknown):
```unknown
## PC_ 1 
## Positive:  BLVRB, KLF1, ERMAP, FAM132A, CAR2, RHD, CES2G, SPHK1, AQP1, SLC38A5 
## Negative:  TMSB4X, CORO1A, PLAC8, H2AFY, LAPTM5, CD34, LCP1, TMEM176B, IGFBP4, EMB 
## PC_ 2 
## Positive:  APOE, GATA2, RAB37, ANGPT1, ADGRG1, MEIS1, MPL, F2R, PDZK1IP1, DAPP1 
## Negative:  CTSG, ELANE, LY6C2, HP, CLEC12A, ANXA3, IGSF6, TIFAB, SLPI, MPO 
## PC_ 3 
## Positive:  APOE, GATA2, NKG7, MUC13, ITGA2B, TUBA8, CPA3, RAB44, SLC18A2, CD9 
## Negative:  DNTT, FLT3, WFDC17, LSP1, MYL10, LAX1, GIMAP6, IGHM, CD24A, MN1 
## PC_ 4 
## Positive:  CSRP3, ST8SIA6, SCIN, LGALS1, APOE, ITGB7, MFSD2B, RGL1, DNTT, IGHV1-23 
## Negative:  MPL, MMRN1, PROCR, HLF, SERPINA3G, ESAM, PTGS1, D630039A03RIK, NDN, PPIC 
## PC_ 5 
## Positive:  GP1BB, PF4, SDPR, F2RL2, TREML1, RAB27B, SLC14A1, PBX1, PLEK, TUBA8 
## Negative:  HDC, LMO4, CSRP3, IFITM1, FCGR3, HLF, CPA3, PROCR, PGLYRP1, IKZF2
```

Example 54 (python):
```python
# when running a PCA on cell cycle genes, actively proliferating cells remain distinct from G1
# cells however, within actively proliferating cells, G2M and S phase cells group together
marrow <- RunPCA(marrow, features = c(s.genes, g2m.genes))
DimPlot(marrow)
```

Example 55 (r):
```r
# when running a PCA on cell cycle genes, actively proliferating cells remain distinct from G1
# cells however, within actively proliferating cells, G2M and S phase cells group together
marrow <- RunPCA(marrow, features = c(s.genes, g2m.genes))
DimPlot(marrow)
```

Example 56 (r):
```r
# when running a PCA on cell cycle genes, actively proliferating cells remain distinct from G1
# cells however, within actively proliferating cells, G2M and S phase cells group together
marrow <- RunPCA(marrow, features = c(s.genes, g2m.genes))
DimPlot(marrow)
```

Example 57 (unknown):
```unknown
sessionInfo()
```

Example 58 (r):
```r
sessionInfo()
```

Example 59 (r):
```r
sessionInfo()
```

Example 60 (unknown):
```unknown
## R version 4.2.2 Patched (2022-11-10 r83330)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.6 LTS
## 
## Matrix products: default
## BLAS:   /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.9.0
## LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.9.0
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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       
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
## [1] ggplot2_3.4.4      Seurat_5.0.0       SeuratObject_5.0.0 sp_2.1-1          
## 
## loaded via a namespace (and not attached):
##   [1] ggbeeswarm_0.7.1       Rtsne_0.16             colorspace_2.1-0      
##   [4] deldir_1.0-9           ellipsis_0.3.2         ggridges_0.5.4        
##   [7] rprojroot_2.0.3        RcppHNSW_0.5.0         fs_1.6.3              
##  [10] spatstat.data_3.0-3    farver_2.1.1           leiden_0.4.3          
##  [13] listenv_0.9.0          ggrepel_0.9.4          RSpectra_0.16-1       
##  [16] fansi_1.0.5            codetools_0.2-19       splines_4.2.2         
##  [19] cachem_1.0.8           knitr_1.45             polyclip_1.10-6       
##  [22] spam_2.10-0            jsonlite_1.8.7         ica_1.0-3             
##  [25] cluster_2.1.4          png_0.1-8              uwot_0.1.16           
##  [28] spatstat.sparse_3.0-3  sctransform_0.4.1      shiny_1.7.5.1         
##  [31] compiler_4.2.2         httr_1.4.7             Matrix_1.6-1.1        
##  [34] fastmap_1.1.1          lazyeval_0.2.2         cli_3.6.1             
##  [37] later_1.3.1            formatR_1.14           htmltools_0.5.6.1     
##  [40] tools_4.2.2            igraph_1.5.1           dotCall64_1.1-0       
##  [43] gtable_0.3.4           glue_1.6.2             reshape2_1.4.4        
##  [46] RANN_2.6.1             dplyr_1.1.3            Rcpp_1.0.11           
##  [49] scattermore_1.2        jquerylib_0.1.4        pkgdown_2.0.7         
##  [52] vctrs_0.6.4            nlme_3.1-162           spatstat.explore_3.2-5
##  [55] progressr_0.14.0       lmtest_0.9-40          spatstat.random_3.2-1 
##  [58] xfun_0.40              stringr_1.5.0          globals_0.16.2        
##  [61] mime_0.12              miniUI_0.1.1.1         lifecycle_1.0.3       
##  [64] irlba_2.3.5.1          goftest_1.2-3          future_1.33.0         
##  [67] MASS_7.3-58.2          zoo_1.8-12             scales_1.2.1          
##  [70] spatstat.utils_3.0-4   ragg_1.2.5             promises_1.2.1        
##  [73] parallel_4.2.2         RColorBrewer_1.1-3     yaml_2.3.7            
##  [76] gridExtra_2.3          memoise_2.0.1          reticulate_1.34.0     
##  [79] pbapply_1.7-2          ggrastr_1.0.1          sass_0.4.7            
##  [82] stringi_1.7.12         highr_0.10             desc_1.4.2            
##  [85] fastDummies_1.7.3      rlang_1.1.1            pkgconfig_2.0.3       
##  [88] systemfonts_1.0.4      matrixStats_1.0.0      evaluate_0.22         
##  [91] lattice_0.21-9         tensor_1.5             ROCR_1.0-11           
##  [94] purrr_1.0.2            labeling_0.4.3         patchwork_1.1.3       
##  [97] htmlwidgets_1.6.2      cowplot_1.1.1          tidyselect_1.2.0      
## [100] parallelly_1.36.0      RcppAnnoy_0.0.21       plyr_1.8.9            
## [103] magrittr_2.0.3         R6_2.5.1               generics_0.1.3        
## [106] withr_2.5.2            pillar_1.9.0           fitdistrplus_1.1-11   
## [109] abind_1.4-5            survival_3.5-7         tibble_3.2.1          
## [112] future.apply_1.11.0    KernSmooth_2.23-22     utf8_1.2.4            
## [115] spatstat.geom_3.2-7    plotly_4.10.3          rmarkdown_2.25        
## [118] grid_4.2.2             data.table_1.14.8      digest_0.6.33         
## [121] xtable_1.8-4           tidyr_1.3.0            httpuv_1.6.12         
## [124] textshaping_0.3.6      munsell_0.5.0          beeswarm_0.4.0        
## [127] viridisLite_0.4.2      vipor_0.4.5            bslib_0.5.1
```

Example 61 (unknown):
```unknown
## R version 4.2.2 Patched (2022-11-10 r83330)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.6 LTS
## 
## Matrix products: default
## BLAS:   /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.9.0
## LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.9.0
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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       
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
## [1] ggplot2_3.4.4      Seurat_5.0.0       SeuratObject_5.0.0 sp_2.1-1          
## 
## loaded via a namespace (and not attached):
##   [1] ggbeeswarm_0.7.1       Rtsne_0.16             colorspace_2.1-0      
##   [4] deldir_1.0-9           ellipsis_0.3.2         ggridges_0.5.4        
##   [7] rprojroot_2.0.3        RcppHNSW_0.5.0         fs_1.6.3              
##  [10] spatstat.data_3.0-3    farver_2.1.1           leiden_0.4.3          
##  [13] listenv_0.9.0          ggrepel_0.9.4          RSpectra_0.16-1       
##  [16] fansi_1.0.5            codetools_0.2-19       splines_4.2.2         
##  [19] cachem_1.0.8           knitr_1.45             polyclip_1.10-6       
##  [22] spam_2.10-0            jsonlite_1.8.7         ica_1.0-3             
##  [25] cluster_2.1.4          png_0.1-8              uwot_0.1.16           
##  [28] spatstat.sparse_3.0-3  sctransform_0.4.1      shiny_1.7.5.1         
##  [31] compiler_4.2.2         httr_1.4.7             Matrix_1.6-1.1        
##  [34] fastmap_1.1.1          lazyeval_0.2.2         cli_3.6.1             
##  [37] later_1.3.1            formatR_1.14           htmltools_0.5.6.1     
##  [40] tools_4.2.2            igraph_1.5.1           dotCall64_1.1-0       
##  [43] gtable_0.3.4           glue_1.6.2             reshape2_1.4.4        
##  [46] RANN_2.6.1             dplyr_1.1.3            Rcpp_1.0.11           
##  [49] scattermore_1.2        jquerylib_0.1.4        pkgdown_2.0.7         
##  [52] vctrs_0.6.4            nlme_3.1-162           spatstat.explore_3.2-5
##  [55] progressr_0.14.0       lmtest_0.9-40          spatstat.random_3.2-1 
##  [58] xfun_0.40              stringr_1.5.0          globals_0.16.2        
##  [61] mime_0.12              miniUI_0.1.1.1         lifecycle_1.0.3       
##  [64] irlba_2.3.5.1          goftest_1.2-3          future_1.33.0         
##  [67] MASS_7.3-58.2          zoo_1.8-12             scales_1.2.1          
##  [70] spatstat.utils_3.0-4   ragg_1.2.5             promises_1.2.1        
##  [73] parallel_4.2.2         RColorBrewer_1.1-3     yaml_2.3.7            
##  [76] gridExtra_2.3          memoise_2.0.1          reticulate_1.34.0     
##  [79] pbapply_1.7-2          ggrastr_1.0.1          sass_0.4.7            
##  [82] stringi_1.7.12         highr_0.10             desc_1.4.2            
##  [85] fastDummies_1.7.3      rlang_1.1.1            pkgconfig_2.0.3       
##  [88] systemfonts_1.0.4      matrixStats_1.0.0      evaluate_0.22         
##  [91] lattice_0.21-9         tensor_1.5             ROCR_1.0-11           
##  [94] purrr_1.0.2            labeling_0.4.3         patchwork_1.1.3       
##  [97] htmlwidgets_1.6.2      cowplot_1.1.1          tidyselect_1.2.0      
## [100] parallelly_1.36.0      RcppAnnoy_0.0.21       plyr_1.8.9            
## [103] magrittr_2.0.3         R6_2.5.1               generics_0.1.3        
## [106] withr_2.5.2            pillar_1.9.0           fitdistrplus_1.1-11   
## [109] abind_1.4-5            survival_3.5-7         tibble_3.2.1          
## [112] future.apply_1.11.0    KernSmooth_2.23-22     utf8_1.2.4            
## [115] spatstat.geom_3.2-7    plotly_4.10.3          rmarkdown_2.25        
## [118] grid_4.2.2             data.table_1.14.8      digest_0.6.33         
## [121] xtable_1.8-4           tidyr_1.3.0            httpuv_1.6.12         
## [124] textshaping_0.3.6      munsell_0.5.0          beeswarm_0.4.0        
## [127] viridisLite_0.4.2      vipor_0.4.5            bslib_0.5.1
```

---

## Analysis, visualization, and integration of Visium HD spatial datasets with Seurat • Seurat

**URL:** http://127.0.0.1:9173/seurat/articles/seurat5_atacseq_integration_vignette/index.html

**Contents:**
- Integrating scRNA-seq and scATAC-seq data
    - Compiled: October 31, 2023
- Load in data and process each modality individually
- Identifying anchors between scRNA-seq and scATAC-seq datasets
- Annotate scATAC-seq cells via label transfer
- Co-embedding scRNA-seq and scATAC-seq datasets
- Contents

Single-cell transcriptomics has transformed our ability to characterize cell states, but deep biological understanding requires more than a taxonomic listing of clusters. As new methods arise to measure distinct cellular modalities, a key analytical challenge is to integrate these datasets to better understand cellular identity and function. For example, users may perform scRNA-seq and scATAC-seq experiments on the same biological system and to consistently annotate both datasets with the same set of cell type labels. This analysis is particularly challenging as scATAC-seq datasets are difficult to annotate, due to both the sparsity of genomic data collected at single-cell resolution, and the lack of interpretable gene markers in scRNA-seq data.

In Stuart*, Butler* et al, 2019, we introduce methods to integrate scRNA-seq and scATAC-seq datasets collected from the same biological system, and demonstrate these methods in this vignette. In particular, we demonstrate the following analyses:

This vignette makes extensive use of the Signac package, recently developed for the analysis of chromatin datasets collected at single-cell resolution, including scATAC-seq. Please see the Signac website for additional vignettes and documentation for analyzing scATAC-seq data.

We demonstrate these methods using a publicly available ~12,000 human PBMC ‘multiome’ dataset from 10x Genomics. In this dataset, scRNA-seq and scATAC-seq profiles were simultaneously collected in the same cells. For the purposes of this vignette, we treat the datasets as originating from two different experiments and integrate them together. Since they were originally measured in the same cells, this provides a ground truth that we can use to assess the accuracy of integration. We emphasize that our use of the multiome dataset here is for demonstration and evaluation purposes, and that users should apply these methods to scRNA-seq and scATAC-seq datasets that are collected separately. We provide a separate weighted nearest neighbors vignette (WNN) that describes analysis strategies for multi-omic single-cell data.

The PBMC multiome dataset is available from 10x genomics. To facilitate easy loading and exploration, it is also available as part of our SeuratData package. We load the RNA and ATAC data in separately, and pretend that these profiles were measured in separate experiments. We annotated these cells in our WNN vignette, and the annotations are also included in SeuratData.

Now we plot the results from both modalities. Cells have been previously annotated based on transcriptomic state. We will predict annotations for the scATAC-seq cells.

In order to identify ‘anchors’ between scRNA-seq and scATAC-seq experiments, we first generate a rough estimate of the transcriptional activity of each gene by quantifying ATAC-seq counts in the 2 kb-upstream region and gene body, using the GeneActivity() function in the Signac package. The ensuing gene activity scores from the scATAC-seq data are then used as input for canonical correlation analysis, along with the gene expression quantifications from scRNA-seq. We perform this quantification for all genes identified as being highly variable from the scRNA-seq dataset.

After identifying anchors, we can transfer annotations from the scRNA-seq dataset onto the scATAC-seq cells. The annotations are stored in the seurat_annotations field, and are provided as input to the refdata parameter. The output will contain a matrix with predictions and confidence scores for each ATAC-seq cell.

Why do you choose different (non-default) values for reduction and weight.reduction?

In FindTransferAnchors(), we typically project the PCA structure from the reference onto the query when transferring between scRNA-seq datasets. However, when transferring across modalities we find that CCA better captures the shared feature correlation structure and therefore set reduction = 'cca' here. Additionally, by default in TransferData() we use the same projected PCA structure to compute the weights of the local neighborhood of anchors that influence each cell’s prediction. In the case of scRNA-seq to scATAC-seq transfer, we use the low dimensional space learned by computing an LSI on the ATAC-seq data to compute these weights as this better captures the internal structure of the ATAC-seq data.

After performing transfer, the ATAC-seq cells have predicted annotations (transferred from the scRNA-seq dataset) stored in the predicted.id field. Since these cells were measured with the multiome kit, we also have a ground-truth annotation that can be used for evaluation. You can see that the predicted and actual annotations are extremely similar.

In this example, the annotation for an scATAC-seq profile is correctly predicted via scRNA-seq integration ~90% of the time. In addition, the prediction.score.max field quantifies the uncertainty associated with our predicted annotations. We can see that cells that are correctly annotated are typically associated with high prediction scores (>90%), while cells that are incorrectly annotated are associated with sharply lower prediction scores (<50%). Incorrect assignments also tend to reflect closely related cell types (i.e. Intermediate vs. Naive B cells).

In addition to transferring labels across modalities, it is also possible to visualize scRNA-seq and scATAC-seq cells on the same plot. We emphasize that this step is primarily for visualization, and is an optional step. Typically, when we perform integrative analysis between scRNA-seq and scATAC-seq datasets, we focus primarily on label transfer as described above. We demonstrate our workflows for co-embedding below, and again highlight that this is for demonstration purposes, especially as in this particular case both the scRNA-seq profiles and scATAC-seq profiles were actually measured in the same cells.

In order to perform co-embedding, we first ‘impute’ RNA expression into the scATAC-seq cells based on the previously computed anchors, and then merge the datasets.

Developed by Rahul Satija, Satija Lab and Collaborators.

Site built with pkgdown 2.0.7.

**Examples:**

Example 1 (unknown):
```unknown
vignettes/seurat5_atacseq_integration_vignette.Rmd
```

Example 2 (unknown):
```unknown
seurat5_atacseq_integration_vignette.Rmd
```

Example 3 (unknown):
```unknown
library(SeuratData)
# install the dataset and load requirements
InstallData("pbmcMultiome")
```

Example 4 (r):
```r
library(SeuratData)
# install the dataset and load requirements
InstallData("pbmcMultiome")
```

Example 5 (r):
```r
library(SeuratData)
# install the dataset and load requirements
InstallData("pbmcMultiome")
```

Example 6 (unknown):
```unknown
library(Seurat)
library(Signac)
library(EnsDb.Hsapiens.v86)
library(ggplot2)
library(cowplot)
```

Example 7 (r):
```r
library(Seurat)
library(Signac)
library(EnsDb.Hsapiens.v86)
library(ggplot2)
library(cowplot)
```

Example 8 (r):
```r
library(Seurat)
library(Signac)
library(EnsDb.Hsapiens.v86)
library(ggplot2)
library(cowplot)
```

Example 9 (unknown):
```unknown
# load both modalities
pbmc.rna <- LoadData("pbmcMultiome", "pbmc.rna")
pbmc.atac <- LoadData("pbmcMultiome", "pbmc.atac")

pbmc.rna[["RNA"]] <- as(pbmc.rna[["RNA"]], Class = "Assay5")
# repeat QC steps performed in the WNN vignette
pbmc.rna <- subset(pbmc.rna, seurat_annotations != "filtered")
pbmc.atac <- subset(pbmc.atac, seurat_annotations != "filtered")

# Perform standard analysis of each modality independently RNA analysis
pbmc.rna <- NormalizeData(pbmc.rna)
pbmc.rna <- FindVariableFeatures(pbmc.rna)
pbmc.rna <- ScaleData(pbmc.rna)
pbmc.rna <- RunPCA(pbmc.rna)
pbmc.rna <- RunUMAP(pbmc.rna, dims = 1:30)

# ATAC analysis add gene annotation information
annotations <- GetGRangesFromEnsDb(ensdb = EnsDb.Hsapiens.v86)
seqlevelsStyle(annotations) <- "UCSC"
genome(annotations) <- "hg38"
Annotation(pbmc.atac) <- annotations

# We exclude the first dimension as this is typically correlated with sequencing depth
pbmc.atac <- RunTFIDF(pbmc.atac)
pbmc.atac <- FindTopFeatures(pbmc.atac, min.cutoff = "q0")
pbmc.atac <- RunSVD(pbmc.atac)
pbmc.atac <- RunUMAP(pbmc.atac, reduction = "lsi", dims = 2:30, reduction.name = "umap.atac", reduction.key = "atacUMAP_")
```

Example 10 (r):
```r
# load both modalities
pbmc.rna <- LoadData("pbmcMultiome", "pbmc.rna")
pbmc.atac <- LoadData("pbmcMultiome", "pbmc.atac")

pbmc.rna[["RNA"]] <- as(pbmc.rna[["RNA"]], Class = "Assay5")
# repeat QC steps performed in the WNN vignette
pbmc.rna <- subset(pbmc.rna, seurat_annotations != "filtered")
pbmc.atac <- subset(pbmc.atac, seurat_annotations != "filtered")

# Perform standard analysis of each modality independently RNA analysis
pbmc.rna <- NormalizeData(pbmc.rna)
pbmc.rna <- FindVariableFeatures(pbmc.rna)
pbmc.rna <- ScaleData(pbmc.rna)
pbmc.rna <- RunPCA(pbmc.rna)
pbmc.rna <- RunUMAP(pbmc.rna, dims = 1:30)

# ATAC analysis add gene annotation information
annotations <- GetGRangesFromEnsDb(ensdb = EnsDb.Hsapiens.v86)
seqlevelsStyle(annotations) <- "UCSC"
genome(annotations) <- "hg38"
Annotation(pbmc.atac) <- annotations

# We exclude the first dimension as this is typically correlated with sequencing depth
pbmc.atac <- RunTFIDF(pbmc.atac)
pbmc.atac <- FindTopFeatures(pbmc.atac, min.cutoff = "q0")
pbmc.atac <- RunSVD(pbmc.atac)
pbmc.atac <- RunUMAP(pbmc.atac, reduction = "lsi", dims = 2:30, reduction.name = "umap.atac", reduction.key = "atacUMAP_")
```

Example 11 (r):
```r
# load both modalities
pbmc.rna <- LoadData("pbmcMultiome", "pbmc.rna")
pbmc.atac <- LoadData("pbmcMultiome", "pbmc.atac")

pbmc.rna[["RNA"]] <- as(pbmc.rna[["RNA"]], Class = "Assay5")
# repeat QC steps performed in the WNN vignette
pbmc.rna <- subset(pbmc.rna, seurat_annotations != "filtered")
pbmc.atac <- subset(pbmc.atac, seurat_annotations != "filtered")

# Perform standard analysis of each modality independently RNA analysis
pbmc.rna <- NormalizeData(pbmc.rna)
pbmc.rna <- FindVariableFeatures(pbmc.rna)
pbmc.rna <- ScaleData(pbmc.rna)
pbmc.rna <- RunPCA(pbmc.rna)
pbmc.rna <- RunUMAP(pbmc.rna, dims = 1:30)

# ATAC analysis add gene annotation information
annotations <- GetGRangesFromEnsDb(ensdb = EnsDb.Hsapiens.v86)
seqlevelsStyle(annotations) <- "UCSC"
genome(annotations) <- "hg38"
Annotation(pbmc.atac) <- annotations

# We exclude the first dimension as this is typically correlated with sequencing depth
pbmc.atac <- RunTFIDF(pbmc.atac)
pbmc.atac <- FindTopFeatures(pbmc.atac, min.cutoff = "q0")
pbmc.atac <- RunSVD(pbmc.atac)
pbmc.atac <- RunUMAP(pbmc.atac, reduction = "lsi", dims = 2:30, reduction.name = "umap.atac", reduction.key = "atacUMAP_")
```

Example 12 (unknown):
```unknown
p1 <- DimPlot(pbmc.rna, group.by = "seurat_annotations", label = TRUE) + NoLegend() + ggtitle("RNA")
p2 <- DimPlot(pbmc.atac, group.by = "orig.ident", label = FALSE) + NoLegend() + ggtitle("ATAC")
p1 + p2
```

Example 13 (r):
```r
p1 <- DimPlot(pbmc.rna, group.by = "seurat_annotations", label = TRUE) + NoLegend() + ggtitle("RNA")
p2 <- DimPlot(pbmc.atac, group.by = "orig.ident", label = FALSE) + NoLegend() + ggtitle("ATAC")
p1 + p2
```

Example 14 (r):
```r
p1 <- DimPlot(pbmc.rna, group.by = "seurat_annotations", label = TRUE) + NoLegend() + ggtitle("RNA")
p2 <- DimPlot(pbmc.atac, group.by = "orig.ident", label = FALSE) + NoLegend() + ggtitle("ATAC")
p1 + p2
```

Example 15 (unknown):
```unknown
plot <- (p1 + p2) & xlab("UMAP 1") & ylab("UMAP 2") & theme(axis.title = element_text(size = 18))
ggsave(filename = "../output/images/atacseq_integration_vignette.jpg", height = 7, width = 12, plot = plot,
    quality = 50)
```

Example 16 (r):
```r
plot <- (p1 + p2) & xlab("UMAP 1") & ylab("UMAP 2") & theme(axis.title = element_text(size = 18))
ggsave(filename = "../output/images/atacseq_integration_vignette.jpg", height = 7, width = 12, plot = plot,
    quality = 50)
```

Example 17 (r):
```r
plot <- (p1 + p2) & xlab("UMAP 1") & ylab("UMAP 2") & theme(axis.title = element_text(size = 18))
ggsave(filename = "../output/images/atacseq_integration_vignette.jpg", height = 7, width = 12, plot = plot,
    quality = 50)
```

Example 18 (unknown):
```unknown
GeneActivity()
```

Example 19 (unknown):
```unknown
# quantify gene activity
gene.activities <- GeneActivity(pbmc.atac, features = VariableFeatures(pbmc.rna))
```

Example 20 (r):
```r
# quantify gene activity
gene.activities <- GeneActivity(pbmc.atac, features = VariableFeatures(pbmc.rna))
```

Example 21 (r):
```r
# quantify gene activity
gene.activities <- GeneActivity(pbmc.atac, features = VariableFeatures(pbmc.rna))
```

Example 22 (unknown):
```unknown
# add gene activities as a new assay
pbmc.atac[["ACTIVITY"]] <- CreateAssayObject(counts = gene.activities)

# normalize gene activities
DefaultAssay(pbmc.atac) <- "ACTIVITY"
pbmc.atac <- NormalizeData(pbmc.atac)
pbmc.atac <- ScaleData(pbmc.atac, features = rownames(pbmc.atac))
```

Example 23 (r):
```r
# add gene activities as a new assay
pbmc.atac[["ACTIVITY"]] <- CreateAssayObject(counts = gene.activities)

# normalize gene activities
DefaultAssay(pbmc.atac) <- "ACTIVITY"
pbmc.atac <- NormalizeData(pbmc.atac)
pbmc.atac <- ScaleData(pbmc.atac, features = rownames(pbmc.atac))
```

Example 24 (r):
```r
# add gene activities as a new assay
pbmc.atac[["ACTIVITY"]] <- CreateAssayObject(counts = gene.activities)

# normalize gene activities
DefaultAssay(pbmc.atac) <- "ACTIVITY"
pbmc.atac <- NormalizeData(pbmc.atac)
pbmc.atac <- ScaleData(pbmc.atac, features = rownames(pbmc.atac))
```

Example 25 (unknown):
```unknown
# Identify anchors
transfer.anchors <- FindTransferAnchors(reference = pbmc.rna, query = pbmc.atac, features = VariableFeatures(object = pbmc.rna),
    reference.assay = "RNA", query.assay = "ACTIVITY", reduction = "cca")
```

Example 26 (r):
```r
# Identify anchors
transfer.anchors <- FindTransferAnchors(reference = pbmc.rna, query = pbmc.atac, features = VariableFeatures(object = pbmc.rna),
    reference.assay = "RNA", query.assay = "ACTIVITY", reduction = "cca")
```

Example 27 (r):
```r
# Identify anchors
transfer.anchors <- FindTransferAnchors(reference = pbmc.rna, query = pbmc.atac, features = VariableFeatures(object = pbmc.rna),
    reference.assay = "RNA", query.assay = "ACTIVITY", reduction = "cca")
```

Example 28 (unknown):
```unknown
seurat_annotations
```

Example 29 (python):
```python
celltype.predictions <- TransferData(anchorset = transfer.anchors, refdata = pbmc.rna$seurat_annotations,
    weight.reduction = pbmc.atac[["lsi"]], dims = 2:30)

pbmc.atac <- AddMetaData(pbmc.atac, metadata = celltype.predictions)
```

Example 30 (r):
```r
celltype.predictions <- TransferData(anchorset = transfer.anchors, refdata = pbmc.rna$seurat_annotations,
    weight.reduction = pbmc.atac[["lsi"]], dims = 2:30)

pbmc.atac <- AddMetaData(pbmc.atac, metadata = celltype.predictions)
```

Example 31 (r):
```r
celltype.predictions <- TransferData(anchorset = transfer.anchors, refdata = pbmc.rna$seurat_annotations,
    weight.reduction = pbmc.atac[["lsi"]], dims = 2:30)

pbmc.atac <- AddMetaData(pbmc.atac, metadata = celltype.predictions)
```

Example 32 (unknown):
```unknown
FindTransferAnchors()
```

Example 33 (unknown):
```unknown
reduction = 'cca'
```

Example 34 (unknown):
```unknown
TransferData()
```

Example 35 (unknown):
```unknown
predicted.id
```

Example 36 (unknown):
```unknown
pbmc.atac$annotation_correct <- pbmc.atac$predicted.id == pbmc.atac$seurat_annotations
p1 <- DimPlot(pbmc.atac, group.by = "predicted.id", label = TRUE) + NoLegend() + ggtitle("Predicted annotation")
p2 <- DimPlot(pbmc.atac, group.by = "seurat_annotations", label = TRUE) + NoLegend() + ggtitle("Ground-truth annotation")
p1 | p2
```

Example 37 (r):
```r
pbmc.atac$annotation_correct <- pbmc.atac$predicted.id == pbmc.atac$seurat_annotations
p1 <- DimPlot(pbmc.atac, group.by = "predicted.id", label = TRUE) + NoLegend() + ggtitle("Predicted annotation")
p2 <- DimPlot(pbmc.atac, group.by = "seurat_annotations", label = TRUE) + NoLegend() + ggtitle("Ground-truth annotation")
p1 | p2
```

Example 38 (r):
```r
pbmc.atac$annotation_correct <- pbmc.atac$predicted.id == pbmc.atac$seurat_annotations
p1 <- DimPlot(pbmc.atac, group.by = "predicted.id", label = TRUE) + NoLegend() + ggtitle("Predicted annotation")
p2 <- DimPlot(pbmc.atac, group.by = "seurat_annotations", label = TRUE) + NoLegend() + ggtitle("Ground-truth annotation")
p1 | p2
```

Example 39 (unknown):
```unknown
prediction.score.max
```

Example 40 (unknown):
```unknown
predictions <- table(pbmc.atac$seurat_annotations, pbmc.atac$predicted.id)
predictions <- predictions/rowSums(predictions)  # normalize for number of cells in each cell type
predictions <- as.data.frame(predictions)
p1 <- ggplot(predictions, aes(Var1, Var2, fill = Freq)) + geom_tile() + scale_fill_gradient(name = "Fraction of cells",
    low = "#ffffc8", high = "#7d0025") + xlab("Cell type annotation (RNA)") + ylab("Predicted cell type label (ATAC)") +
    theme_cowplot() + theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust = 1))

correct <- length(which(pbmc.atac$seurat_annotations == pbmc.atac$predicted.id))
incorrect <- length(which(pbmc.atac$seurat_annotations != pbmc.atac$predicted.id))
data <- FetchData(pbmc.atac, vars = c("prediction.score.max", "annotation_correct"))
p2 <- ggplot(data, aes(prediction.score.max, fill = annotation_correct, colour = annotation_correct)) +
    geom_density(alpha = 0.5) + theme_cowplot() + scale_fill_discrete(name = "Annotation Correct",
    labels = c(paste0("FALSE (n = ", incorrect, ")"), paste0("TRUE (n = ", correct, ")"))) + scale_color_discrete(name = "Annotation Correct",
    labels = c(paste0("FALSE (n = ", incorrect, ")"), paste0("TRUE (n = ", correct, ")"))) + xlab("Prediction Score")
p1 + p2
```

Example 41 (r):
```r
predictions <- table(pbmc.atac$seurat_annotations, pbmc.atac$predicted.id)
predictions <- predictions/rowSums(predictions)  # normalize for number of cells in each cell type
predictions <- as.data.frame(predictions)
p1 <- ggplot(predictions, aes(Var1, Var2, fill = Freq)) + geom_tile() + scale_fill_gradient(name = "Fraction of cells",
    low = "#ffffc8", high = "#7d0025") + xlab("Cell type annotation (RNA)") + ylab("Predicted cell type label (ATAC)") +
    theme_cowplot() + theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust = 1))

correct <- length(which(pbmc.atac$seurat_annotations == pbmc.atac$predicted.id))
incorrect <- length(which(pbmc.atac$seurat_annotations != pbmc.atac$predicted.id))
data <- FetchData(pbmc.atac, vars = c("prediction.score.max", "annotation_correct"))
p2 <- ggplot(data, aes(prediction.score.max, fill = annotation_correct, colour = annotation_correct)) +
    geom_density(alpha = 0.5) + theme_cowplot() + scale_fill_discrete(name = "Annotation Correct",
    labels = c(paste0("FALSE (n = ", incorrect, ")"), paste0("TRUE (n = ", correct, ")"))) + scale_color_discrete(name = "Annotation Correct",
    labels = c(paste0("FALSE (n = ", incorrect, ")"), paste0("TRUE (n = ", correct, ")"))) + xlab("Prediction Score")
p1 + p2
```

Example 42 (r):
```r
predictions <- table(pbmc.atac$seurat_annotations, pbmc.atac$predicted.id)
predictions <- predictions/rowSums(predictions)  # normalize for number of cells in each cell type
predictions <- as.data.frame(predictions)
p1 <- ggplot(predictions, aes(Var1, Var2, fill = Freq)) + geom_tile() + scale_fill_gradient(name = "Fraction of cells",
    low = "#ffffc8", high = "#7d0025") + xlab("Cell type annotation (RNA)") + ylab("Predicted cell type label (ATAC)") +
    theme_cowplot() + theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust = 1))

correct <- length(which(pbmc.atac$seurat_annotations == pbmc.atac$predicted.id))
incorrect <- length(which(pbmc.atac$seurat_annotations != pbmc.atac$predicted.id))
data <- FetchData(pbmc.atac, vars = c("prediction.score.max", "annotation_correct"))
p2 <- ggplot(data, aes(prediction.score.max, fill = annotation_correct, colour = annotation_correct)) +
    geom_density(alpha = 0.5) + theme_cowplot() + scale_fill_discrete(name = "Annotation Correct",
    labels = c(paste0("FALSE (n = ", incorrect, ")"), paste0("TRUE (n = ", correct, ")"))) + scale_color_discrete(name = "Annotation Correct",
    labels = c(paste0("FALSE (n = ", incorrect, ")"), paste0("TRUE (n = ", correct, ")"))) + xlab("Prediction Score")
p1 + p2
```

Example 43 (python):
```python
# note that we restrict the imputation to variable genes from scRNA-seq, but could impute the
# full transcriptome if we wanted to
genes.use <- VariableFeatures(pbmc.rna)
refdata <- GetAssayData(pbmc.rna, assay = "RNA", slot = "data")[genes.use, ]

# refdata (input) contains a scRNA-seq expression matrix for the scRNA-seq cells.  imputation
# (output) will contain an imputed scRNA-seq matrix for each of the ATAC cells
imputation <- TransferData(anchorset = transfer.anchors, refdata = refdata, weight.reduction = pbmc.atac[["lsi"]],
    dims = 2:30)
pbmc.atac[["RNA"]] <- imputation

coembed <- merge(x = pbmc.rna, y = pbmc.atac)

# Finally, we run PCA and UMAP on this combined object, to visualize the co-embedding of both
# datasets
coembed <- ScaleData(coembed, features = genes.use, do.scale = FALSE)
coembed <- RunPCA(coembed, features = genes.use, verbose = FALSE)
coembed <- RunUMAP(coembed, dims = 1:30)

DimPlot(coembed, group.by = c("orig.ident", "seurat_annotations"))
```

Example 44 (r):
```r
# note that we restrict the imputation to variable genes from scRNA-seq, but could impute the
# full transcriptome if we wanted to
genes.use <- VariableFeatures(pbmc.rna)
refdata <- GetAssayData(pbmc.rna, assay = "RNA", slot = "data")[genes.use, ]

# refdata (input) contains a scRNA-seq expression matrix for the scRNA-seq cells.  imputation
# (output) will contain an imputed scRNA-seq matrix for each of the ATAC cells
imputation <- TransferData(anchorset = transfer.anchors, refdata = refdata, weight.reduction = pbmc.atac[["lsi"]],
    dims = 2:30)
pbmc.atac[["RNA"]] <- imputation

coembed <- merge(x = pbmc.rna, y = pbmc.atac)

# Finally, we run PCA and UMAP on this combined object, to visualize the co-embedding of both
# datasets
coembed <- ScaleData(coembed, features = genes.use, do.scale = FALSE)
coembed <- RunPCA(coembed, features = genes.use, verbose = FALSE)
coembed <- RunUMAP(coembed, dims = 1:30)

DimPlot(coembed, group.by = c("orig.ident", "seurat_annotations"))
```

Example 45 (r):
```r
# note that we restrict the imputation to variable genes from scRNA-seq, but could impute the
# full transcriptome if we wanted to
genes.use <- VariableFeatures(pbmc.rna)
refdata <- GetAssayData(pbmc.rna, assay = "RNA", slot = "data")[genes.use, ]

# refdata (input) contains a scRNA-seq expression matrix for the scRNA-seq cells.  imputation
# (output) will contain an imputed scRNA-seq matrix for each of the ATAC cells
imputation <- TransferData(anchorset = transfer.anchors, refdata = refdata, weight.reduction = pbmc.atac[["lsi"]],
    dims = 2:30)
pbmc.atac[["RNA"]] <- imputation

coembed <- merge(x = pbmc.rna, y = pbmc.atac)

# Finally, we run PCA and UMAP on this combined object, to visualize the co-embedding of both
# datasets
coembed <- ScaleData(coembed, features = genes.use, do.scale = FALSE)
coembed <- RunPCA(coembed, features = genes.use, verbose = FALSE)
coembed <- RunUMAP(coembed, dims = 1:30)

DimPlot(coembed, group.by = c("orig.ident", "seurat_annotations"))
```

Example 46 (unknown):
```unknown
sessionInfo()
```

Example 47 (r):
```r
sessionInfo()
```

Example 48 (r):
```r
sessionInfo()
```

Example 49 (unknown):
```unknown
## R version 4.2.2 Patched (2022-11-10 r83330)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.6 LTS
## 
## Matrix products: default
## BLAS:   /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.9.0
## LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.9.0
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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       
## 
## attached base packages:
## [1] stats4    stats     graphics  grDevices utils     datasets  methods  
## [8] base     
## 
## other attached packages:
##  [1] cowplot_1.1.1                 ggplot2_3.4.4                
##  [3] EnsDb.Hsapiens.v86_2.99.0     ensembldb_2.22.0             
##  [5] AnnotationFilter_1.22.0       GenomicFeatures_1.50.4       
##  [7] AnnotationDbi_1.60.2          Biobase_2.58.0               
##  [9] GenomicRanges_1.50.2          GenomeInfoDb_1.34.9          
## [11] IRanges_2.32.0                S4Vectors_0.36.2             
## [13] BiocGenerics_0.44.0           Signac_1.12.9000             
## [15] Seurat_5.0.1                  SeuratObject_5.0.1           
## [17] sp_2.1-1                      thp1.eccite.SeuratData_3.1.5 
## [19] stxBrain.SeuratData_0.1.1     ssHippo.SeuratData_3.1.4     
## [21] pbmcsca.SeuratData_3.0.0      pbmcref.SeuratData_1.0.0     
## [23] pbmcMultiome.SeuratData_0.1.4 pbmc3k.SeuratData_3.1.4      
## [25] panc8.SeuratData_3.0.2        ifnb.SeuratData_3.0.0        
## [27] hcabm40k.SeuratData_3.0.0     cbmc.SeuratData_3.1.4        
## [29] bmcite.SeuratData_0.3.0       SeuratData_0.2.2.9001        
## 
## loaded via a namespace (and not attached):
##   [1] rappdirs_0.3.3              rtracklayer_1.58.0         
##   [3] scattermore_1.2             ragg_1.2.5                 
##   [5] tidyr_1.3.0                 bit64_4.0.5                
##   [7] knitr_1.45                  irlba_2.3.5.1              
##   [9] DelayedArray_0.24.0         data.table_1.14.8          
##  [11] rpart_4.1.19                KEGGREST_1.38.0            
##  [13] RCurl_1.98-1.12             generics_0.1.3             
##  [15] RSQLite_2.3.1               RANN_2.6.1                 
##  [17] future_1.33.0               bit_4.0.5                  
##  [19] spatstat.data_3.0-3         xml2_1.3.5                 
##  [21] httpuv_1.6.12               SummarizedExperiment_1.28.0
##  [23] xfun_0.40                   hms_1.1.3                  
##  [25] jquerylib_0.1.4             evaluate_0.22              
##  [27] promises_1.2.1              fansi_1.0.5                
##  [29] restfulr_0.0.15             progress_1.2.2             
##  [31] dbplyr_2.3.4                igraph_1.5.1               
##  [33] DBI_1.1.3                   htmlwidgets_1.6.2          
##  [35] spatstat.geom_3.2-7         purrr_1.0.2                
##  [37] ellipsis_0.3.2              RSpectra_0.16-1            
##  [39] dplyr_1.1.3                 backports_1.4.1            
##  [41] biomaRt_2.54.1              deldir_1.0-9               
##  [43] MatrixGenerics_1.10.0       vctrs_0.6.4                
##  [45] ROCR_1.0-11                 abind_1.4-5                
##  [47] cachem_1.0.8                withr_2.5.2                
##  [49] BSgenome_1.66.3             progressr_0.14.0           
##  [51] checkmate_2.2.0             sctransform_0.4.1          
##  [53] GenomicAlignments_1.34.1    prettyunits_1.1.1          
##  [55] goftest_1.2-3               cluster_2.1.4              
##  [57] dotCall64_1.1-0             lazyeval_0.2.2             
##  [59] crayon_1.5.2                spatstat.explore_3.2-5     
##  [61] labeling_0.4.3              pkgconfig_2.0.3            
##  [63] nlme_3.1-162                ProtGenerics_1.30.0        
##  [65] nnet_7.3-18                 rlang_1.1.1                
##  [67] globals_0.16.2              lifecycle_1.0.3            
##  [69] miniUI_0.1.1.1              filelock_1.0.2             
##  [71] fastDummies_1.7.3           BiocFileCache_2.6.1        
##  [73] dichromat_2.0-0.1           rprojroot_2.0.3            
##  [75] polyclip_1.10-6             RcppHNSW_0.5.0             
##  [77] matrixStats_1.0.0           lmtest_0.9-40              
##  [79] Matrix_1.6-1.1              zoo_1.8-12                 
##  [81] base64enc_0.1-3             ggridges_0.5.4             
##  [83] png_0.1-8                   viridisLite_0.4.2          
##  [85] rjson_0.2.21                bitops_1.0-7               
##  [87] KernSmooth_2.23-22          spam_2.10-0                
##  [89] Biostrings_2.66.0           blob_1.2.4                 
##  [91] stringr_1.5.0               parallelly_1.36.0          
##  [93] spatstat.random_3.2-1       scales_1.2.1               
##  [95] memoise_2.0.1               magrittr_2.0.3             
##  [97] plyr_1.8.9                  ica_1.0-3                  
##  [99] zlibbioc_1.44.0             compiler_4.2.2             
## [101] BiocIO_1.8.0                RColorBrewer_1.1-3         
## [103] fitdistrplus_1.1-11         Rsamtools_2.14.0           
## [105] cli_3.6.1                   XVector_0.38.0             
## [107] listenv_0.9.0               patchwork_1.1.3            
## [109] pbapply_1.7-2               htmlTable_2.4.1            
## [111] formatR_1.14                Formula_1.2-5              
## [113] MASS_7.3-58.2               tidyselect_1.2.0           
## [115] stringi_1.7.12              textshaping_0.3.6          
## [117] highr_0.10                  yaml_2.3.7                 
## [119] ggrepel_0.9.4               grid_4.2.2                 
## [121] VariantAnnotation_1.44.1    sass_0.4.7                 
## [123] fastmatch_1.1-4             tools_4.2.2                
## [125] future.apply_1.11.0         parallel_4.2.2             
## [127] rstudioapi_0.14             foreign_0.8-84             
## [129] gridExtra_2.3               farver_2.1.1               
## [131] Rtsne_0.16                  digest_0.6.33              
## [133] shiny_1.7.5.1               Rcpp_1.0.11                
## [135] later_1.3.1                 RcppAnnoy_0.0.21           
## [137] httr_1.4.7                  biovizBase_1.46.0          
## [139] colorspace_2.1-0            XML_3.99-0.14              
## [141] fs_1.6.3                    tensor_1.5                 
## [143] reticulate_1.34.0           splines_4.2.2              
## [145] uwot_0.1.16                 RcppRoll_0.3.0             
## [147] spatstat.utils_3.0-4        pkgdown_2.0.7              
## [149] plotly_4.10.3               systemfonts_1.0.4          
## [151] xtable_1.8-4                jsonlite_1.8.7             
## [153] R6_2.5.1                    Hmisc_5.1-1                
## [155] pillar_1.9.0                htmltools_0.5.6.1          
## [157] mime_0.12                   glue_1.6.2                 
## [159] fastmap_1.1.1               BiocParallel_1.32.6        
## [161] codetools_0.2-19            utf8_1.2.4                 
## [163] lattice_0.21-9              bslib_0.5.1                
## [165] spatstat.sparse_3.0-3       tibble_3.2.1               
## [167] curl_5.1.0                  leiden_0.4.3               
## [169] survival_3.5-7              rmarkdown_2.25             
## [171] desc_1.4.2                  munsell_0.5.0              
## [173] GenomeInfoDbData_1.2.9      reshape2_1.4.4             
## [175] gtable_0.3.4
```

Example 50 (unknown):
```unknown
## R version 4.2.2 Patched (2022-11-10 r83330)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.6 LTS
## 
## Matrix products: default
## BLAS:   /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.9.0
## LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.9.0
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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       
## 
## attached base packages:
## [1] stats4    stats     graphics  grDevices utils     datasets  methods  
## [8] base     
## 
## other attached packages:
##  [1] cowplot_1.1.1                 ggplot2_3.4.4                
##  [3] EnsDb.Hsapiens.v86_2.99.0     ensembldb_2.22.0             
##  [5] AnnotationFilter_1.22.0       GenomicFeatures_1.50.4       
##  [7] AnnotationDbi_1.60.2          Biobase_2.58.0               
##  [9] GenomicRanges_1.50.2          GenomeInfoDb_1.34.9          
## [11] IRanges_2.32.0                S4Vectors_0.36.2             
## [13] BiocGenerics_0.44.0           Signac_1.12.9000             
## [15] Seurat_5.0.1                  SeuratObject_5.0.1           
## [17] sp_2.1-1                      thp1.eccite.SeuratData_3.1.5 
## [19] stxBrain.SeuratData_0.1.1     ssHippo.SeuratData_3.1.4     
## [21] pbmcsca.SeuratData_3.0.0      pbmcref.SeuratData_1.0.0     
## [23] pbmcMultiome.SeuratData_0.1.4 pbmc3k.SeuratData_3.1.4      
## [25] panc8.SeuratData_3.0.2        ifnb.SeuratData_3.0.0        
## [27] hcabm40k.SeuratData_3.0.0     cbmc.SeuratData_3.1.4        
## [29] bmcite.SeuratData_0.3.0       SeuratData_0.2.2.9001        
## 
## loaded via a namespace (and not attached):
##   [1] rappdirs_0.3.3              rtracklayer_1.58.0         
##   [3] scattermore_1.2             ragg_1.2.5                 
##   [5] tidyr_1.3.0                 bit64_4.0.5                
##   [7] knitr_1.45                  irlba_2.3.5.1              
##   [9] DelayedArray_0.24.0         data.table_1.14.8          
##  [11] rpart_4.1.19                KEGGREST_1.38.0            
##  [13] RCurl_1.98-1.12             generics_0.1.3             
##  [15] RSQLite_2.3.1               RANN_2.6.1                 
##  [17] future_1.33.0               bit_4.0.5                  
##  [19] spatstat.data_3.0-3         xml2_1.3.5                 
##  [21] httpuv_1.6.12               SummarizedExperiment_1.28.0
##  [23] xfun_0.40                   hms_1.1.3                  
##  [25] jquerylib_0.1.4             evaluate_0.22              
##  [27] promises_1.2.1              fansi_1.0.5                
##  [29] restfulr_0.0.15             progress_1.2.2             
##  [31] dbplyr_2.3.4                igraph_1.5.1               
##  [33] DBI_1.1.3                   htmlwidgets_1.6.2          
##  [35] spatstat.geom_3.2-7         purrr_1.0.2                
##  [37] ellipsis_0.3.2              RSpectra_0.16-1            
##  [39] dplyr_1.1.3                 backports_1.4.1            
##  [41] biomaRt_2.54.1              deldir_1.0-9               
##  [43] MatrixGenerics_1.10.0       vctrs_0.6.4                
##  [45] ROCR_1.0-11                 abind_1.4-5                
##  [47] cachem_1.0.8                withr_2.5.2                
##  [49] BSgenome_1.66.3             progressr_0.14.0           
##  [51] checkmate_2.2.0             sctransform_0.4.1          
##  [53] GenomicAlignments_1.34.1    prettyunits_1.1.1          
##  [55] goftest_1.2-3               cluster_2.1.4              
##  [57] dotCall64_1.1-0             lazyeval_0.2.2             
##  [59] crayon_1.5.2                spatstat.explore_3.2-5     
##  [61] labeling_0.4.3              pkgconfig_2.0.3            
##  [63] nlme_3.1-162                ProtGenerics_1.30.0        
##  [65] nnet_7.3-18                 rlang_1.1.1                
##  [67] globals_0.16.2              lifecycle_1.0.3            
##  [69] miniUI_0.1.1.1              filelock_1.0.2             
##  [71] fastDummies_1.7.3           BiocFileCache_2.6.1        
##  [73] dichromat_2.0-0.1           rprojroot_2.0.3            
##  [75] polyclip_1.10-6             RcppHNSW_0.5.0             
##  [77] matrixStats_1.0.0           lmtest_0.9-40              
##  [79] Matrix_1.6-1.1              zoo_1.8-12                 
##  [81] base64enc_0.1-3             ggridges_0.5.4             
##  [83] png_0.1-8                   viridisLite_0.4.2          
##  [85] rjson_0.2.21                bitops_1.0-7               
##  [87] KernSmooth_2.23-22          spam_2.10-0                
##  [89] Biostrings_2.66.0           blob_1.2.4                 
##  [91] stringr_1.5.0               parallelly_1.36.0          
##  [93] spatstat.random_3.2-1       scales_1.2.1               
##  [95] memoise_2.0.1               magrittr_2.0.3             
##  [97] plyr_1.8.9                  ica_1.0-3                  
##  [99] zlibbioc_1.44.0             compiler_4.2.2             
## [101] BiocIO_1.8.0                RColorBrewer_1.1-3         
## [103] fitdistrplus_1.1-11         Rsamtools_2.14.0           
## [105] cli_3.6.1                   XVector_0.38.0             
## [107] listenv_0.9.0               patchwork_1.1.3            
## [109] pbapply_1.7-2               htmlTable_2.4.1            
## [111] formatR_1.14                Formula_1.2-5              
## [113] MASS_7.3-58.2               tidyselect_1.2.0           
## [115] stringi_1.7.12              textshaping_0.3.6          
## [117] highr_0.10                  yaml_2.3.7                 
## [119] ggrepel_0.9.4               grid_4.2.2                 
## [121] VariantAnnotation_1.44.1    sass_0.4.7                 
## [123] fastmatch_1.1-4             tools_4.2.2                
## [125] future.apply_1.11.0         parallel_4.2.2             
## [127] rstudioapi_0.14             foreign_0.8-84             
## [129] gridExtra_2.3               farver_2.1.1               
## [131] Rtsne_0.16                  digest_0.6.33              
## [133] shiny_1.7.5.1               Rcpp_1.0.11                
## [135] later_1.3.1                 RcppAnnoy_0.0.21           
## [137] httr_1.4.7                  biovizBase_1.46.0          
## [139] colorspace_2.1-0            XML_3.99-0.14              
## [141] fs_1.6.3                    tensor_1.5                 
## [143] reticulate_1.34.0           splines_4.2.2              
## [145] uwot_0.1.16                 RcppRoll_0.3.0             
## [147] spatstat.utils_3.0-4        pkgdown_2.0.7              
## [149] plotly_4.10.3               systemfonts_1.0.4          
## [151] xtable_1.8-4                jsonlite_1.8.7             
## [153] R6_2.5.1                    Hmisc_5.1-1                
## [155] pillar_1.9.0                htmltools_0.5.6.1          
## [157] mime_0.12                   glue_1.6.2                 
## [159] fastmap_1.1.1               BiocParallel_1.32.6        
## [161] codetools_0.2-19            utf8_1.2.4                 
## [163] lattice_0.21-9              bslib_0.5.1                
## [165] spatstat.sparse_3.0-3       tibble_3.2.1               
## [167] curl_5.1.0                  leiden_0.4.3               
## [169] survival_3.5-7              rmarkdown_2.25             
## [171] desc_1.4.2                  munsell_0.5.0              
## [173] GenomeInfoDbData_1.2.9      reshape2_1.4.4             
## [175] gtable_0.3.4
```

---

## Analysis, visualization, and integration of Visium HD spatial datasets with Seurat • Seurat

**URL:** http://127.0.0.1:9173/seurat/articles/sctransform_vignette/index.html

**Contents:**
- Using sctransform in Seurat
    - Saket Choudhary, Christoph Hafemeister & Rahul Satija
    - Compiled: 2023-10-31
- Load data and create Seurat object
- Apply sctransform normalization
- Perform dimensionality reduction by PCA and UMAP embedding
- Contents

Biological heterogeneity in single-cell RNA-seq data is often confounded by technical factors including sequencing depth. The number of molecules detected in each cell can vary significantly between cells, even within the same celltype. Interpretation of scRNA-seq data requires effective pre-processing and normalization to remove this technical variability.

In our manuscript we introduce a modeling framework for the normalization and variance stabilization of molecular count data from scRNA-seq experiments. This procedure omits the need for heuristic steps including pseudocount addition or log-transformation and improves common downstream analytical tasks such as variable gene selection, dimensional reduction, and differential expression. We named this method sctransform.

Inspired by important and rigorous work from Lause et al, we released an updated manuscript and updated the sctransform software to a v2 version, which is now the default in Seurat v5.

Why can we choose more PCs when using sctransform?

In the standard Seurat workflow we focus on 10 PCs for this dataset, though we highlight that the results are similar with higher settings for this parameter. Interestingly, we’ve found that when using sctransform, we often benefit by pushing this parameter even higher. We believe this is because the sctransform workflow performs more effective normalization, strongly removing technical effects from the data.

Even after standard log-normalization, variation in sequencing depth is still a confounding factor (see Figure 1), and this effect can subtly influence higher PCs. In sctransform, this effect is substantially mitigated (see Figure 3). This means that higher PCs are more likely to represent subtle, but biologically relevant, sources of heterogeneity – so including them may improve downstream analysis.

In addition, sctransform returns 3,000 variable features by default, instead of 2,000. The rationale is similar, the additional variable features are less likely to be driven by technical differences across cells, and instead may represent more subtle biological fluctuations. In general, we find that results produced with sctransform are less dependent on these parameters (indeed, we achieve nearly identical results when using all genes in the transcriptome, though this does reduce computational efficiency). This can help users generate more robust results, and in addition, enables the application of standard analysis pipelines with identical parameter settings that can quickly be applied to new datasets:

For example, the following code replicates the full end-to-end workflow, in a single command:

Where are normalized values stored for sctransform?

The results of sctransfrom are stored in the “SCT” assay. You can learn more about multi-assay data and commands in Seurat in our vignette, command cheat sheet, or developer guide.

Users can individually annotate clusters based on canonical markers. However, the sctransform normalization reveals sharper biological distinctions compared to the standard Seurat workflow, in a few ways:

Developed by Rahul Satija, Satija Lab and Collaborators.

Site built with pkgdown 2.0.7.

**Examples:**

Example 1 (unknown):
```unknown
vignettes/sctransform_vignette.Rmd
```

Example 2 (unknown):
```unknown
sctransform_vignette.Rmd
```

Example 3 (unknown):
```unknown
sctransform
```

Example 4 (unknown):
```unknown
library(Seurat)
library(ggplot2)
library(sctransform)
```

Example 5 (r):
```r
library(Seurat)
library(ggplot2)
library(sctransform)
```

Example 6 (r):
```r
library(Seurat)
library(ggplot2)
library(sctransform)
```

Example 7 (unknown):
```unknown
pbmc_data <- Read10X(data.dir = "/brahms/shared/vignette-data/pbmc3k/filtered_gene_bc_matrices/hg19/")
pbmc <- CreateSeuratObject(counts = pbmc_data)
```

Example 8 (r):
```r
pbmc_data <- Read10X(data.dir = "/brahms/shared/vignette-data/pbmc3k/filtered_gene_bc_matrices/hg19/")
pbmc <- CreateSeuratObject(counts = pbmc_data)
```

Example 9 (r):
```r
pbmc_data <- Read10X(data.dir = "/brahms/shared/vignette-data/pbmc3k/filtered_gene_bc_matrices/hg19/")
pbmc <- CreateSeuratObject(counts = pbmc_data)
```

Example 10 (unknown):
```unknown
NormalizeData()
```

Example 11 (unknown):
```unknown
ScaleData()
```

Example 12 (unknown):
```unknown
FindVariableFeatures()
```

Example 13 (unknown):
```unknown
vst.flavor = 'v1'
```

Example 14 (unknown):
```unknown
# store mitochondrial percentage in object meta data
pbmc <- PercentageFeatureSet(pbmc, pattern = "^MT-", col.name = "percent.mt")

# run sctransform
pbmc <- SCTransform(pbmc, vars.to.regress = "percent.mt", verbose = FALSE)
```

Example 15 (r):
```r
# store mitochondrial percentage in object meta data
pbmc <- PercentageFeatureSet(pbmc, pattern = "^MT-", col.name = "percent.mt")

# run sctransform
pbmc <- SCTransform(pbmc, vars.to.regress = "percent.mt", verbose = FALSE)
```

Example 16 (r):
```r
# store mitochondrial percentage in object meta data
pbmc <- PercentageFeatureSet(pbmc, pattern = "^MT-", col.name = "percent.mt")

# run sctransform
pbmc <- SCTransform(pbmc, vars.to.regress = "percent.mt", verbose = FALSE)
```

Example 17 (unknown):
```unknown
# These are now standard steps in the Seurat workflow for visualization and clustering
pbmc <- RunPCA(pbmc, verbose = FALSE)
pbmc <- RunUMAP(pbmc, dims = 1:30, verbose = FALSE)

pbmc <- FindNeighbors(pbmc, dims = 1:30, verbose = FALSE)
pbmc <- FindClusters(pbmc, verbose = FALSE)
DimPlot(pbmc, label = TRUE)
```

Example 18 (r):
```r
# These are now standard steps in the Seurat workflow for visualization and clustering
pbmc <- RunPCA(pbmc, verbose = FALSE)
pbmc <- RunUMAP(pbmc, dims = 1:30, verbose = FALSE)

pbmc <- FindNeighbors(pbmc, dims = 1:30, verbose = FALSE)
pbmc <- FindClusters(pbmc, verbose = FALSE)
DimPlot(pbmc, label = TRUE)
```

Example 19 (r):
```r
# These are now standard steps in the Seurat workflow for visualization and clustering
pbmc <- RunPCA(pbmc, verbose = FALSE)
pbmc <- RunUMAP(pbmc, dims = 1:30, verbose = FALSE)

pbmc <- FindNeighbors(pbmc, dims = 1:30, verbose = FALSE)
pbmc <- FindClusters(pbmc, verbose = FALSE)
DimPlot(pbmc, label = TRUE)
```

Example 20 (unknown):
```unknown
pbmc <- CreateSeuratObject(pbmc_data) %>%
    PercentageFeatureSet(pattern = "^MT-", col.name = "percent.mt") %>%
    SCTransform(vars.to.regress = "percent.mt") %>%
    RunPCA() %>%
    FindNeighbors(dims = 1:30) %>%
    RunUMAP(dims = 1:30) %>%
    FindClusters()
```

Example 21 (r):
```r
pbmc <- CreateSeuratObject(pbmc_data) %>%
    PercentageFeatureSet(pattern = "^MT-", col.name = "percent.mt") %>%
    SCTransform(vars.to.regress = "percent.mt") %>%
    RunPCA() %>%
    FindNeighbors(dims = 1:30) %>%
    RunUMAP(dims = 1:30) %>%
    FindClusters()
```

Example 22 (r):
```r
pbmc <- CreateSeuratObject(pbmc_data) %>%
    PercentageFeatureSet(pattern = "^MT-", col.name = "percent.mt") %>%
    SCTransform(vars.to.regress = "percent.mt") %>%
    RunPCA() %>%
    FindNeighbors(dims = 1:30) %>%
    RunUMAP(dims = 1:30) %>%
    FindClusters()
```

Example 23 (unknown):
```unknown
pbmc[["SCT"]]$scale.data
```

Example 24 (unknown):
```unknown
SCTransform()
```

Example 25 (unknown):
```unknown
pbmc[["SCT"]]$counts
```

Example 26 (unknown):
```unknown
pbmc[["SCT"]]$data
```

Example 27 (unknown):
```unknown
# These are now standard steps in the Seurat workflow for visualization and clustering
# Visualize canonical marker genes as violin plots.
VlnPlot(pbmc, features = c("CD8A", "GZMK", "CCL5", "S100A4", "ANXA1", "CCR7", "ISG15", "CD3D"),
    pt.size = 0.2, ncol = 4)
```

Example 28 (r):
```r
# These are now standard steps in the Seurat workflow for visualization and clustering
# Visualize canonical marker genes as violin plots.
VlnPlot(pbmc, features = c("CD8A", "GZMK", "CCL5", "S100A4", "ANXA1", "CCR7", "ISG15", "CD3D"),
    pt.size = 0.2, ncol = 4)
```

Example 29 (r):
```r
# These are now standard steps in the Seurat workflow for visualization and clustering
# Visualize canonical marker genes as violin plots.
VlnPlot(pbmc, features = c("CD8A", "GZMK", "CCL5", "S100A4", "ANXA1", "CCR7", "ISG15", "CD3D"),
    pt.size = 0.2, ncol = 4)
```

Example 30 (unknown):
```unknown
# Visualize canonical marker genes on the sctransform embedding.
FeaturePlot(pbmc, features = c("CD8A", "GZMK", "CCL5", "S100A4", "ANXA1", "CCR7"), pt.size = 0.2,
    ncol = 3)
```

Example 31 (r):
```r
# Visualize canonical marker genes on the sctransform embedding.
FeaturePlot(pbmc, features = c("CD8A", "GZMK", "CCL5", "S100A4", "ANXA1", "CCR7"), pt.size = 0.2,
    ncol = 3)
```

Example 32 (r):
```r
# Visualize canonical marker genes on the sctransform embedding.
FeaturePlot(pbmc, features = c("CD8A", "GZMK", "CCL5", "S100A4", "ANXA1", "CCR7"), pt.size = 0.2,
    ncol = 3)
```

Example 33 (unknown):
```unknown
FeaturePlot(pbmc, features = c("CD3D", "ISG15", "TCL1A", "FCER2", "XCL1", "FCGR3A"), pt.size = 0.2,
    ncol = 3)
```

Example 34 (r):
```r
FeaturePlot(pbmc, features = c("CD3D", "ISG15", "TCL1A", "FCER2", "XCL1", "FCGR3A"), pt.size = 0.2,
    ncol = 3)
```

Example 35 (r):
```r
FeaturePlot(pbmc, features = c("CD3D", "ISG15", "TCL1A", "FCER2", "XCL1", "FCGR3A"), pt.size = 0.2,
    ncol = 3)
```

Example 36 (unknown):
```unknown
sessionInfo()
```

Example 37 (r):
```r
sessionInfo()
```

Example 38 (r):
```r
sessionInfo()
```

Example 39 (unknown):
```unknown
## R version 4.2.2 Patched (2022-11-10 r83330)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.6 LTS
## 
## Matrix products: default
## BLAS:   /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.9.0
## LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.9.0
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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       
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
## [1] sctransform_0.4.1  ggplot2_3.4.4      Seurat_5.0.0       SeuratObject_5.0.0
## [5] sp_2.1-1          
## 
## loaded via a namespace (and not attached):
##   [1] spam_2.10-0                 systemfonts_1.0.4          
##   [3] plyr_1.8.9                  igraph_1.5.1               
##   [5] lazyeval_0.2.2              splines_4.2.2              
##   [7] RcppHNSW_0.5.0              listenv_0.9.0              
##   [9] scattermore_1.2             GenomeInfoDb_1.34.9        
##  [11] digest_0.6.33               htmltools_0.5.6.1          
##  [13] fansi_1.0.5                 magrittr_2.0.3             
##  [15] memoise_2.0.1               tensor_1.5                 
##  [17] cluster_2.1.4               ROCR_1.0-11                
##  [19] globals_0.16.2              matrixStats_1.0.0          
##  [21] R.utils_2.12.2              pkgdown_2.0.7              
##  [23] spatstat.sparse_3.0-3       colorspace_2.1-0           
##  [25] ggrepel_0.9.4               textshaping_0.3.6          
##  [27] xfun_0.40                   dplyr_1.1.3                
##  [29] RCurl_1.98-1.12             jsonlite_1.8.7             
##  [31] progressr_0.14.0            spatstat.data_3.0-3        
##  [33] survival_3.5-7              zoo_1.8-12                 
##  [35] glue_1.6.2                  polyclip_1.10-6            
##  [37] gtable_0.3.4                zlibbioc_1.44.0            
##  [39] XVector_0.38.0              leiden_0.4.3               
##  [41] DelayedArray_0.24.0         future.apply_1.11.0        
##  [43] BiocGenerics_0.44.0         abind_1.4-5                
##  [45] scales_1.2.1                spatstat.random_3.2-1      
##  [47] miniUI_0.1.1.1              Rcpp_1.0.11                
##  [49] viridisLite_0.4.2           xtable_1.8-4               
##  [51] reticulate_1.34.0           dotCall64_1.1-0            
##  [53] stats4_4.2.2                htmlwidgets_1.6.2          
##  [55] httr_1.4.7                  RColorBrewer_1.1-3         
##  [57] ellipsis_0.3.2              ica_1.0-3                  
##  [59] farver_2.1.1                pkgconfig_2.0.3            
##  [61] R.methodsS3_1.8.2           sass_0.4.7                 
##  [63] uwot_0.1.16                 deldir_1.0-9               
##  [65] utf8_1.2.4                  labeling_0.4.3             
##  [67] tidyselect_1.2.0            rlang_1.1.1                
##  [69] reshape2_1.4.4              later_1.3.1                
##  [71] munsell_0.5.0               tools_4.2.2                
##  [73] cachem_1.0.8                cli_3.6.1                  
##  [75] generics_0.1.3              ggridges_0.5.4             
##  [77] evaluate_0.22               stringr_1.5.0              
##  [79] fastmap_1.1.1               yaml_2.3.7                 
##  [81] ragg_1.2.5                  goftest_1.2-3              
##  [83] knitr_1.45                  fs_1.6.3                   
##  [85] fitdistrplus_1.1-11         purrr_1.0.2                
##  [87] RANN_2.6.1                  sparseMatrixStats_1.10.0   
##  [89] pbapply_1.7-2               future_1.33.0              
##  [91] nlme_3.1-162                mime_0.12                  
##  [93] formatR_1.14                ggrastr_1.0.1              
##  [95] R.oo_1.25.0                 compiler_4.2.2             
##  [97] beeswarm_0.4.0              plotly_4.10.3              
##  [99] png_0.1-8                   spatstat.utils_3.0-4       
## [101] tibble_3.2.1                bslib_0.5.1                
## [103] glmGamPoi_1.10.2            stringi_1.7.12             
## [105] highr_0.10                  desc_1.4.2                 
## [107] RSpectra_0.16-1             lattice_0.21-9             
## [109] Matrix_1.6-1.1              vctrs_0.6.4                
## [111] pillar_1.9.0                lifecycle_1.0.3            
## [113] spatstat.geom_3.2-7         lmtest_0.9-40              
## [115] jquerylib_0.1.4             RcppAnnoy_0.0.21           
## [117] bitops_1.0-7                data.table_1.14.8          
## [119] cowplot_1.1.1               irlba_2.3.5.1              
## [121] GenomicRanges_1.50.2        httpuv_1.6.12              
## [123] patchwork_1.1.3             R6_2.5.1                   
## [125] promises_1.2.1              KernSmooth_2.23-22         
## [127] gridExtra_2.3               vipor_0.4.5                
## [129] IRanges_2.32.0              parallelly_1.36.0          
## [131] codetools_0.2-19            fastDummies_1.7.3          
## [133] MASS_7.3-58.2               SummarizedExperiment_1.28.0
## [135] rprojroot_2.0.3             withr_2.5.2                
## [137] GenomeInfoDbData_1.2.9      S4Vectors_0.36.2           
## [139] parallel_4.2.2              grid_4.2.2                 
## [141] tidyr_1.3.0                 DelayedMatrixStats_1.20.0  
## [143] rmarkdown_2.25              MatrixGenerics_1.10.0      
## [145] Rtsne_0.16                  spatstat.explore_3.2-5     
## [147] Biobase_2.58.0              shiny_1.7.5.1              
## [149] ggbeeswarm_0.7.1
```

Example 40 (unknown):
```unknown
## R version 4.2.2 Patched (2022-11-10 r83330)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.6 LTS
## 
## Matrix products: default
## BLAS:   /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.9.0
## LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.9.0
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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       
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
## [1] sctransform_0.4.1  ggplot2_3.4.4      Seurat_5.0.0       SeuratObject_5.0.0
## [5] sp_2.1-1          
## 
## loaded via a namespace (and not attached):
##   [1] spam_2.10-0                 systemfonts_1.0.4          
##   [3] plyr_1.8.9                  igraph_1.5.1               
##   [5] lazyeval_0.2.2              splines_4.2.2              
##   [7] RcppHNSW_0.5.0              listenv_0.9.0              
##   [9] scattermore_1.2             GenomeInfoDb_1.34.9        
##  [11] digest_0.6.33               htmltools_0.5.6.1          
##  [13] fansi_1.0.5                 magrittr_2.0.3             
##  [15] memoise_2.0.1               tensor_1.5                 
##  [17] cluster_2.1.4               ROCR_1.0-11                
##  [19] globals_0.16.2              matrixStats_1.0.0          
##  [21] R.utils_2.12.2              pkgdown_2.0.7              
##  [23] spatstat.sparse_3.0-3       colorspace_2.1-0           
##  [25] ggrepel_0.9.4               textshaping_0.3.6          
##  [27] xfun_0.40                   dplyr_1.1.3                
##  [29] RCurl_1.98-1.12             jsonlite_1.8.7             
##  [31] progressr_0.14.0            spatstat.data_3.0-3        
##  [33] survival_3.5-7              zoo_1.8-12                 
##  [35] glue_1.6.2                  polyclip_1.10-6            
##  [37] gtable_0.3.4                zlibbioc_1.44.0            
##  [39] XVector_0.38.0              leiden_0.4.3               
##  [41] DelayedArray_0.24.0         future.apply_1.11.0        
##  [43] BiocGenerics_0.44.0         abind_1.4-5                
##  [45] scales_1.2.1                spatstat.random_3.2-1      
##  [47] miniUI_0.1.1.1              Rcpp_1.0.11                
##  [49] viridisLite_0.4.2           xtable_1.8-4               
##  [51] reticulate_1.34.0           dotCall64_1.1-0            
##  [53] stats4_4.2.2                htmlwidgets_1.6.2          
##  [55] httr_1.4.7                  RColorBrewer_1.1-3         
##  [57] ellipsis_0.3.2              ica_1.0-3                  
##  [59] farver_2.1.1                pkgconfig_2.0.3            
##  [61] R.methodsS3_1.8.2           sass_0.4.7                 
##  [63] uwot_0.1.16                 deldir_1.0-9               
##  [65] utf8_1.2.4                  labeling_0.4.3             
##  [67] tidyselect_1.2.0            rlang_1.1.1                
##  [69] reshape2_1.4.4              later_1.3.1                
##  [71] munsell_0.5.0               tools_4.2.2                
##  [73] cachem_1.0.8                cli_3.6.1                  
##  [75] generics_0.1.3              ggridges_0.5.4             
##  [77] evaluate_0.22               stringr_1.5.0              
##  [79] fastmap_1.1.1               yaml_2.3.7                 
##  [81] ragg_1.2.5                  goftest_1.2-3              
##  [83] knitr_1.45                  fs_1.6.3                   
##  [85] fitdistrplus_1.1-11         purrr_1.0.2                
##  [87] RANN_2.6.1                  sparseMatrixStats_1.10.0   
##  [89] pbapply_1.7-2               future_1.33.0              
##  [91] nlme_3.1-162                mime_0.12                  
##  [93] formatR_1.14                ggrastr_1.0.1              
##  [95] R.oo_1.25.0                 compiler_4.2.2             
##  [97] beeswarm_0.4.0              plotly_4.10.3              
##  [99] png_0.1-8                   spatstat.utils_3.0-4       
## [101] tibble_3.2.1                bslib_0.5.1                
## [103] glmGamPoi_1.10.2            stringi_1.7.12             
## [105] highr_0.10                  desc_1.4.2                 
## [107] RSpectra_0.16-1             lattice_0.21-9             
## [109] Matrix_1.6-1.1              vctrs_0.6.4                
## [111] pillar_1.9.0                lifecycle_1.0.3            
## [113] spatstat.geom_3.2-7         lmtest_0.9-40              
## [115] jquerylib_0.1.4             RcppAnnoy_0.0.21           
## [117] bitops_1.0-7                data.table_1.14.8          
## [119] cowplot_1.1.1               irlba_2.3.5.1              
## [121] GenomicRanges_1.50.2        httpuv_1.6.12              
## [123] patchwork_1.1.3             R6_2.5.1                   
## [125] promises_1.2.1              KernSmooth_2.23-22         
## [127] gridExtra_2.3               vipor_0.4.5                
## [129] IRanges_2.32.0              parallelly_1.36.0          
## [131] codetools_0.2-19            fastDummies_1.7.3          
## [133] MASS_7.3-58.2               SummarizedExperiment_1.28.0
## [135] rprojroot_2.0.3             withr_2.5.2                
## [137] GenomeInfoDbData_1.2.9      S4Vectors_0.36.2           
## [139] parallel_4.2.2              grid_4.2.2                 
## [141] tidyr_1.3.0                 DelayedMatrixStats_1.20.0  
## [143] rmarkdown_2.25              MatrixGenerics_1.10.0      
## [145] Rtsne_0.16                  spatstat.explore_3.2-5     
## [147] Biobase_2.58.0              shiny_1.7.5.1              
## [149] ggbeeswarm_0.7.1
```

---

## Parallelization in Seurat with future • Seurat

**URL:** http://127.0.0.1:9173/seurat/archive/v4.3/future_vignette/index.html

**Contents:**
- Parallelization in Seurat with future
    - Compiled: March 27, 2023
- How to use parallelization in Seurat
- ‘Futurized’ functions in Seurat
- Comparison of sequential vs. parallel
- Frequently asked questions
- Contents

In Seurat, we have chosen to use the future framework for parallelization. In this vignette, we will demonstrate how you can take advantage of the future implementation of certain Seurat functions from a user’s perspective. If you are interested in learning more about the future framework beyond what is described here, please see the package vignettes here for a comprehensive and detailed description.How to use parallelization in SeuratTo access the parallel version of functions in Seurat, you need to load the future package and set the plan. The plan will specify how the function is executed. The default behavior is to evaluate in a non-parallelized fashion (sequentially). To achieve parallel (asynchronous) behavior, we typically recommend the “multiprocess” strategy. By default, this uses all available cores but you can set the workers parameter to limit the number of concurrently active futures. library(future) # check the current active plan plan()## sequential: ## - args: function (..., envir = parent.frame()) ## - tweaked: FALSE ## - call: NULL # change the current plan to access parallelization plan("multiprocess", workers = 4) plan()## sequential: ## - args: function (..., workers = 4, envir = parent.frame()) ## - tweaked: TRUE ## - call: plan("multiprocess", workers = 4)‘Futurized’ functions in SeuratThe following functions have been written to take advantage of the future framework and will be parallelized if the current plan is set appropriately. Importantly, the way you call the function shouldn’t change.NormalizeData()ScaleData()JackStraw()FindMarkers()FindIntegrationAnchors()FindClusters() - if clustering over multiple resolutionsFor example, to run the parallel version of FindMarkers(), you simply need to set the plan and call the function as usual. library(Seurat) pbmc <- readRDS("../data/pbmc3k_final.rds") # Enable parallelization plan("multiprocess", workers = 4) markers <- FindMarkers(pbmc, ident.1 = "NK", verbose = FALSE)Comparison of sequential vs. parallelHere we’ll perform a brief comparison the runtimes for the same function calls with and without parallelization. Note that while we expect that using a parallelized strategy will decrease the runtimes of the functions listed above, the magnitude of that decrease will depend on many factors (e.g. the size of the dataset, the number of workers, specs of the system, the future strategy, etc). The following benchmarks were performed on a desktop computer running Ubuntu 16.04.5 LTS with an Intel(R) Core(TM) i7-6800K CPU @ 3.40GHz and 96 GB of RAM.Click to see bencharking code timing.comparisons <- data.frame(fxn = character(), time = numeric(), strategy = character()) plan("sequential") start <- Sys.time() pbmc <- ScaleData(pbmc, vars.to.regress = "percent.mt", verbose = FALSE) end <- Sys.time() timing.comparisons <- rbind(timing.comparisons, data.frame(fxn = "ScaleData", time = as.numeric(end - start, units = "secs"), strategy = "sequential")) start <- Sys.time() markers <- FindMarkers(pbmc, ident.1 = "NK", verbose = FALSE) end <- Sys.time() timing.comparisons <- rbind(timing.comparisons, data.frame(fxn = "FindMarkers", time = as.numeric(end - start, units = "secs"), strategy = "sequential")) plan("multiprocess", workers = 4) start <- Sys.time() pbmc <- ScaleData(pbmc, vars.to.regress = "percent.mt", verbose = FALSE) end <- Sys.time() timing.comparisons <- rbind(timing.comparisons, data.frame(fxn = "ScaleData", time = as.numeric(end - start, units = "secs"), strategy = "multiprocess")) start <- Sys.time() markers <- FindMarkers(pbmc, ident.1 = "NK", verbose = FALSE) end <- Sys.time() timing.comparisons <- rbind(timing.comparisons, data.frame(fxn = "FindMarkers", time = as.numeric(end - start, units = "secs"), strategy = "multiprocess")) library(ggplot2) library(cowplot) ggplot(timing.comparisons, aes(fxn, time)) + geom_bar(aes(fill = strategy), stat = "identity", position = "dodge") + ylab("Time(s)") + xlab("Function") + theme_cowplot()Frequently asked questionsWhere did my progress bar go?Unfortunately, the when running these functions in any of the parallel plan modes you will lose the progress bar. This is due to some technical limitations in the future framework and R generally. If you want to monitor function progress, you’ll need to forgo parallelization and use plan("sequential").What should I do if I keep seeing the following error?Error in getGlobalsAndPackages(expr, envir = envir, globals = TRUE) : The total size of the X globals that need to be exported for the future expression ('FUN()') is X GiB. This exceeds the maximum allowed size of 500.00 MiB (option 'future.globals.maxSize'). The X largest globals are ... For certain functions, each worker needs access to certain global variables. If these are larger than the default limit, you will see this error. To get around this, you can set options(future.globals.maxSize = X), where X is the maximum allowed size in bytes. So to set it to 1GB, you would run options(future.globals.maxSize = 1000 * 1024^2). Note that this will increase your RAM usage so set this number mindfully.Session Info sessionInfo()## R version 4.2.0 (2022-04-22) ## Platform: x86_64-pc-linux-gnu (64-bit) ## Running under: Ubuntu 20.04.5 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/liblapack.so.3 ## ## locale: ## [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C ## [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8 ## [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 ## ## attached base packages: ## [1] stats graphics grDevices utils datasets methods base ## ## other attached packages: ## [1] cowplot_1.1.1 ggplot2_3.4.1 SeuratObject_4.1.3 Seurat_4.3.0 ## [5] future_1.31.0 ## ## loaded via a namespace (and not attached): ## [1] Rtsne_0.16 colorspace_2.1-0 deldir_1.0-6 ## [4] ellipsis_0.3.2 ggridges_0.5.4 rprojroot_2.0.3 ## [7] fs_1.6.1 spatstat.data_3.0-0 farver_2.1.1 ## [10] leiden_0.4.3 listenv_0.9.0 ggrepel_0.9.3 ## [13] fansi_1.0.4 codetools_0.2-18 splines_4.2.0 ## [16] cachem_1.0.7 knitr_1.42 polyclip_1.10-4 ## [19] jsonlite_1.8.4 ica_1.0-3 cluster_2.1.3 ## [22] png_0.1-8 uwot_0.1.14 spatstat.sparse_3.0-0 ## [25] shiny_1.7.4 sctransform_0.3.5 compiler_4.2.0 ## [28] httr_1.4.5 Matrix_1.5-3 fastmap_1.1.1 ## [31] lazyeval_0.2.2 limma_3.54.1 cli_3.6.0 ## [34] later_1.3.0 formatR_1.14 htmltools_0.5.4 ## [37] tools_4.2.0 igraph_1.4.1 gtable_0.3.1 ## [40] glue_1.6.2 RANN_2.6.1 reshape2_1.4.4 ## [43] dplyr_1.1.0 Rcpp_1.0.10 scattermore_0.8 ## [46] jquerylib_0.1.4 pkgdown_2.0.7 vctrs_0.5.2 ## [49] nlme_3.1-157 spatstat.explore_3.0-6 progressr_0.13.0 ## [52] lmtest_0.9-40 spatstat.random_3.1-3 xfun_0.37 ## [55] stringr_1.5.0 globals_0.16.2 mime_0.12 ## [58] miniUI_0.1.1.1 lifecycle_1.0.3 irlba_2.3.5.1 ## [61] goftest_1.2-3 MASS_7.3-56 zoo_1.8-11 ## [64] scales_1.2.1 ragg_1.2.5 promises_1.2.0.1 ## [67] spatstat.utils_3.0-1 parallel_4.2.0 RColorBrewer_1.1-3 ## [70] yaml_2.3.7 memoise_2.0.1 reticulate_1.28 ## [73] pbapply_1.7-0 gridExtra_2.3 sass_0.4.5 ## [76] stringi_1.7.12 highr_0.10 desc_1.4.2 ## [79] rlang_1.0.6 pkgconfig_2.0.3 systemfonts_1.0.4 ## [82] matrixStats_0.63.0 evaluate_0.20 lattice_0.20-45 ## [85] tensor_1.5 ROCR_1.0-11 purrr_1.0.1 ## [88] labeling_0.4.2 patchwork_1.1.2 htmlwidgets_1.6.1 ## [91] tidyselect_1.2.0 parallelly_1.34.0 RcppAnnoy_0.0.20 ## [94] plyr_1.8.8 magrittr_2.0.3 R6_2.5.1 ## [97] generics_0.1.3 withr_2.5.0 pillar_1.8.1 ## [100] fitdistrplus_1.1-8 abind_1.4-5 survival_3.3-1 ## [103] sp_1.6-0 tibble_3.1.8 future.apply_1.10.0 ## [106] KernSmooth_2.23-20 utf8_1.2.3 spatstat.geom_3.0-6 ## [109] plotly_4.10.1 rmarkdown_2.20 grid_4.2.0 ## [112] data.table_1.14.8 digest_0.6.31 xtable_1.8-4 ## [115] tidyr_1.3.0 httpuv_1.6.9 textshaping_0.3.6 ## [118] munsell_0.5.0 viridisLite_0.4.1 bslib_0.4.2

To access the parallel version of functions in Seurat, you need to load the future package and set the plan. The plan will specify how the function is executed. The default behavior is to evaluate in a non-parallelized fashion (sequentially). To achieve parallel (asynchronous) behavior, we typically recommend the “multiprocess” strategy. By default, this uses all available cores but you can set the workers parameter to limit the number of concurrently active futures. library(future) # check the current active plan plan()## sequential: ## - args: function (..., envir = parent.frame()) ## - tweaked: FALSE ## - call: NULL # change the current plan to access parallelization plan("multiprocess", workers = 4) plan()## sequential: ## - args: function (..., workers = 4, envir = parent.frame()) ## - tweaked: TRUE ## - call: plan("multiprocess", workers = 4)

The following functions have been written to take advantage of the future framework and will be parallelized if the current plan is set appropriately. Importantly, the way you call the function shouldn’t change.NormalizeData()ScaleData()JackStraw()FindMarkers()FindIntegrationAnchors()FindClusters() - if clustering over multiple resolutionsFor example, to run the parallel version of FindMarkers(), you simply need to set the plan and call the function as usual. library(Seurat) pbmc <- readRDS("../data/pbmc3k_final.rds") # Enable parallelization plan("multiprocess", workers = 4) markers <- FindMarkers(pbmc, ident.1 = "NK", verbose = FALSE)

For example, to run the parallel version of FindMarkers(), you simply need to set the plan and call the function as usual. library(Seurat) pbmc <- readRDS("../data/pbmc3k_final.rds") # Enable parallelization plan("multiprocess", workers = 4) markers <- FindMarkers(pbmc, ident.1 = "NK", verbose = FALSE)

Here we’ll perform a brief comparison the runtimes for the same function calls with and without parallelization. Note that while we expect that using a parallelized strategy will decrease the runtimes of the functions listed above, the magnitude of that decrease will depend on many factors (e.g. the size of the dataset, the number of workers, specs of the system, the future strategy, etc). The following benchmarks were performed on a desktop computer running Ubuntu 16.04.5 LTS with an Intel(R) Core(TM) i7-6800K CPU @ 3.40GHz and 96 GB of RAM.Click to see bencharking code timing.comparisons <- data.frame(fxn = character(), time = numeric(), strategy = character()) plan("sequential") start <- Sys.time() pbmc <- ScaleData(pbmc, vars.to.regress = "percent.mt", verbose = FALSE) end <- Sys.time() timing.comparisons <- rbind(timing.comparisons, data.frame(fxn = "ScaleData", time = as.numeric(end - start, units = "secs"), strategy = "sequential")) start <- Sys.time() markers <- FindMarkers(pbmc, ident.1 = "NK", verbose = FALSE) end <- Sys.time() timing.comparisons <- rbind(timing.comparisons, data.frame(fxn = "FindMarkers", time = as.numeric(end - start, units = "secs"), strategy = "sequential")) plan("multiprocess", workers = 4) start <- Sys.time() pbmc <- ScaleData(pbmc, vars.to.regress = "percent.mt", verbose = FALSE) end <- Sys.time() timing.comparisons <- rbind(timing.comparisons, data.frame(fxn = "ScaleData", time = as.numeric(end - start, units = "secs"), strategy = "multiprocess")) start <- Sys.time() markers <- FindMarkers(pbmc, ident.1 = "NK", verbose = FALSE) end <- Sys.time() timing.comparisons <- rbind(timing.comparisons, data.frame(fxn = "FindMarkers", time = as.numeric(end - start, units = "secs"), strategy = "multiprocess")) library(ggplot2) library(cowplot) ggplot(timing.comparisons, aes(fxn, time)) + geom_bar(aes(fill = strategy), stat = "identity", position = "dodge") + ylab("Time(s)") + xlab("Function") + theme_cowplot()

timing.comparisons <- data.frame(fxn = character(), time = numeric(), strategy = character()) plan("sequential") start <- Sys.time() pbmc <- ScaleData(pbmc, vars.to.regress = "percent.mt", verbose = FALSE) end <- Sys.time() timing.comparisons <- rbind(timing.comparisons, data.frame(fxn = "ScaleData", time = as.numeric(end - start, units = "secs"), strategy = "sequential")) start <- Sys.time() markers <- FindMarkers(pbmc, ident.1 = "NK", verbose = FALSE) end <- Sys.time() timing.comparisons <- rbind(timing.comparisons, data.frame(fxn = "FindMarkers", time = as.numeric(end - start, units = "secs"), strategy = "sequential")) plan("multiprocess", workers = 4) start <- Sys.time() pbmc <- ScaleData(pbmc, vars.to.regress = "percent.mt", verbose = FALSE) end <- Sys.time() timing.comparisons <- rbind(timing.comparisons, data.frame(fxn = "ScaleData", time = as.numeric(end - start, units = "secs"), strategy = "multiprocess")) start <- Sys.time() markers <- FindMarkers(pbmc, ident.1 = "NK", verbose = FALSE) end <- Sys.time() timing.comparisons <- rbind(timing.comparisons, data.frame(fxn = "FindMarkers", time = as.numeric(end - start, units = "secs"), strategy = "multiprocess"))

Where did my progress bar go?Unfortunately, the when running these functions in any of the parallel plan modes you will lose the progress bar. This is due to some technical limitations in the future framework and R generally. If you want to monitor function progress, you’ll need to forgo parallelization and use plan("sequential").What should I do if I keep seeing the following error?

What should I do if I keep seeing the following error?

For certain functions, each worker needs access to certain global variables. If these are larger than the default limit, you will see this error. To get around this, you can set options(future.globals.maxSize = X), where X is the maximum allowed size in bytes. So to set it to 1GB, you would run options(future.globals.maxSize = 1000 * 1024^2). Note that this will increase your RAM usage so set this number mindfully.Session Info sessionInfo()## R version 4.2.0 (2022-04-22) ## Platform: x86_64-pc-linux-gnu (64-bit) ## Running under: Ubuntu 20.04.5 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/liblapack.so.3 ## ## locale: ## [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C ## [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8 ## [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 ## ## attached base packages: ## [1] stats graphics grDevices utils datasets methods base ## ## other attached packages: ## [1] cowplot_1.1.1 ggplot2_3.4.1 SeuratObject_4.1.3 Seurat_4.3.0 ## [5] future_1.31.0 ## ## loaded via a namespace (and not attached): ## [1] Rtsne_0.16 colorspace_2.1-0 deldir_1.0-6 ## [4] ellipsis_0.3.2 ggridges_0.5.4 rprojroot_2.0.3 ## [7] fs_1.6.1 spatstat.data_3.0-0 farver_2.1.1 ## [10] leiden_0.4.3 listenv_0.9.0 ggrepel_0.9.3 ## [13] fansi_1.0.4 codetools_0.2-18 splines_4.2.0 ## [16] cachem_1.0.7 knitr_1.42 polyclip_1.10-4 ## [19] jsonlite_1.8.4 ica_1.0-3 cluster_2.1.3 ## [22] png_0.1-8 uwot_0.1.14 spatstat.sparse_3.0-0 ## [25] shiny_1.7.4 sctransform_0.3.5 compiler_4.2.0 ## [28] httr_1.4.5 Matrix_1.5-3 fastmap_1.1.1 ## [31] lazyeval_0.2.2 limma_3.54.1 cli_3.6.0 ## [34] later_1.3.0 formatR_1.14 htmltools_0.5.4 ## [37] tools_4.2.0 igraph_1.4.1 gtable_0.3.1 ## [40] glue_1.6.2 RANN_2.6.1 reshape2_1.4.4 ## [43] dplyr_1.1.0 Rcpp_1.0.10 scattermore_0.8 ## [46] jquerylib_0.1.4 pkgdown_2.0.7 vctrs_0.5.2 ## [49] nlme_3.1-157 spatstat.explore_3.0-6 progressr_0.13.0 ## [52] lmtest_0.9-40 spatstat.random_3.1-3 xfun_0.37 ## [55] stringr_1.5.0 globals_0.16.2 mime_0.12 ## [58] miniUI_0.1.1.1 lifecycle_1.0.3 irlba_2.3.5.1 ## [61] goftest_1.2-3 MASS_7.3-56 zoo_1.8-11 ## [64] scales_1.2.1 ragg_1.2.5 promises_1.2.0.1 ## [67] spatstat.utils_3.0-1 parallel_4.2.0 RColorBrewer_1.1-3 ## [70] yaml_2.3.7 memoise_2.0.1 reticulate_1.28 ## [73] pbapply_1.7-0 gridExtra_2.3 sass_0.4.5 ## [76] stringi_1.7.12 highr_0.10 desc_1.4.2 ## [79] rlang_1.0.6 pkgconfig_2.0.3 systemfonts_1.0.4 ## [82] matrixStats_0.63.0 evaluate_0.20 lattice_0.20-45 ## [85] tensor_1.5 ROCR_1.0-11 purrr_1.0.1 ## [88] labeling_0.4.2 patchwork_1.1.2 htmlwidgets_1.6.1 ## [91] tidyselect_1.2.0 parallelly_1.34.0 RcppAnnoy_0.0.20 ## [94] plyr_1.8.8 magrittr_2.0.3 R6_2.5.1 ## [97] generics_0.1.3 withr_2.5.0 pillar_1.8.1 ## [100] fitdistrplus_1.1-8 abind_1.4-5 survival_3.3-1 ## [103] sp_1.6-0 tibble_3.1.8 future.apply_1.10.0 ## [106] KernSmooth_2.23-20 utf8_1.2.3 spatstat.geom_3.0-6 ## [109] plotly_4.10.1 rmarkdown_2.20 grid_4.2.0 ## [112] data.table_1.14.8 digest_0.6.31 xtable_1.8-4 ## [115] tidyr_1.3.0 httpuv_1.6.9 textshaping_0.3.6 ## [118] munsell_0.5.0 viridisLite_0.4.1 bslib_0.4.2

sessionInfo()## R version 4.2.0 (2022-04-22) ## Platform: x86_64-pc-linux-gnu (64-bit) ## Running under: Ubuntu 20.04.5 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/liblapack.so.3 ## ## locale: ## [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C ## [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8 ## [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 ## ## attached base packages: ## [1] stats graphics grDevices utils datasets methods base ## ## other attached packages: ## [1] cowplot_1.1.1 ggplot2_3.4.1 SeuratObject_4.1.3 Seurat_4.3.0 ## [5] future_1.31.0 ## ## loaded via a namespace (and not attached): ## [1] Rtsne_0.16 colorspace_2.1-0 deldir_1.0-6 ## [4] ellipsis_0.3.2 ggridges_0.5.4 rprojroot_2.0.3 ## [7] fs_1.6.1 spatstat.data_3.0-0 farver_2.1.1 ## [10] leiden_0.4.3 listenv_0.9.0 ggrepel_0.9.3 ## [13] fansi_1.0.4 codetools_0.2-18 splines_4.2.0 ## [16] cachem_1.0.7 knitr_1.42 polyclip_1.10-4 ## [19] jsonlite_1.8.4 ica_1.0-3 cluster_2.1.3 ## [22] png_0.1-8 uwot_0.1.14 spatstat.sparse_3.0-0 ## [25] shiny_1.7.4 sctransform_0.3.5 compiler_4.2.0 ## [28] httr_1.4.5 Matrix_1.5-3 fastmap_1.1.1 ## [31] lazyeval_0.2.2 limma_3.54.1 cli_3.6.0 ## [34] later_1.3.0 formatR_1.14 htmltools_0.5.4 ## [37] tools_4.2.0 igraph_1.4.1 gtable_0.3.1 ## [40] glue_1.6.2 RANN_2.6.1 reshape2_1.4.4 ## [43] dplyr_1.1.0 Rcpp_1.0.10 scattermore_0.8 ## [46] jquerylib_0.1.4 pkgdown_2.0.7 vctrs_0.5.2 ## [49] nlme_3.1-157 spatstat.explore_3.0-6 progressr_0.13.0 ## [52] lmtest_0.9-40 spatstat.random_3.1-3 xfun_0.37 ## [55] stringr_1.5.0 globals_0.16.2 mime_0.12 ## [58] miniUI_0.1.1.1 lifecycle_1.0.3 irlba_2.3.5.1 ## [61] goftest_1.2-3 MASS_7.3-56 zoo_1.8-11 ## [64] scales_1.2.1 ragg_1.2.5 promises_1.2.0.1 ## [67] spatstat.utils_3.0-1 parallel_4.2.0 RColorBrewer_1.1-3 ## [70] yaml_2.3.7 memoise_2.0.1 reticulate_1.28 ## [73] pbapply_1.7-0 gridExtra_2.3 sass_0.4.5 ## [76] stringi_1.7.12 highr_0.10 desc_1.4.2 ## [79] rlang_1.0.6 pkgconfig_2.0.3 systemfonts_1.0.4 ## [82] matrixStats_0.63.0 evaluate_0.20 lattice_0.20-45 ## [85] tensor_1.5 ROCR_1.0-11 purrr_1.0.1 ## [88] labeling_0.4.2 patchwork_1.1.2 htmlwidgets_1.6.1 ## [91] tidyselect_1.2.0 parallelly_1.34.0 RcppAnnoy_0.0.20 ## [94] plyr_1.8.8 magrittr_2.0.3 R6_2.5.1 ## [97] generics_0.1.3 withr_2.5.0 pillar_1.8.1 ## [100] fitdistrplus_1.1-8 abind_1.4-5 survival_3.3-1 ## [103] sp_1.6-0 tibble_3.1.8 future.apply_1.10.0 ## [106] KernSmooth_2.23-20 utf8_1.2.3 spatstat.geom_3.0-6 ## [109] plotly_4.10.1 rmarkdown_2.20 grid_4.2.0 ## [112] data.table_1.14.8 digest_0.6.31 xtable_1.8-4 ## [115] tidyr_1.3.0 httpuv_1.6.9 textshaping_0.3.6 ## [118] munsell_0.5.0 viridisLite_0.4.1 bslib_0.4.2

Developed by Paul Hoffman, Satija Lab and Collaborators.

Developed by Paul Hoffman, Satija Lab and Collaborators.

Site built with pkgdown 2.0.7.

Site built with pkgdown 2.0.7.

**Examples:**

Example 1 (unknown):
```unknown
vignettes/future_vignette.Rmd
```

Example 2 (unknown):
```unknown
future_vignette.Rmd
```

Example 3 (unknown):
```unknown
library(future)
# check the current active plan
plan()
```

Example 4 (r):
```r
library(future)
# check the current active plan
plan()
```

Example 5 (r):
```r
library(future)
# check the current active plan
plan()
```

Example 6 (unknown):
```unknown
## sequential:
## - args: function (..., envir = parent.frame())
## - tweaked: FALSE
## - call: NULL
```

Example 7 (unknown):
```unknown
## sequential:
## - args: function (..., envir = parent.frame())
## - tweaked: FALSE
## - call: NULL
```

Example 8 (unknown):
```unknown
# change the current plan to access parallelization
plan("multiprocess", workers = 4)
plan()
```

Example 9 (r):
```r
# change the current plan to access parallelization
plan("multiprocess", workers = 4)
plan()
```

Example 10 (r):
```r
# change the current plan to access parallelization
plan("multiprocess", workers = 4)
plan()
```

Example 11 (unknown):
```unknown
## sequential:
## - args: function (..., workers = 4, envir = parent.frame())
## - tweaked: TRUE
## - call: plan("multiprocess", workers = 4)
```

Example 12 (unknown):
```unknown
## sequential:
## - args: function (..., workers = 4, envir = parent.frame())
## - tweaked: TRUE
## - call: plan("multiprocess", workers = 4)
```

Example 13 (unknown):
```unknown
NormalizeData()
```

Example 14 (unknown):
```unknown
ScaleData()
```

Example 15 (unknown):
```unknown
JackStraw()
```

Example 16 (unknown):
```unknown
FindMarkers()
```

Example 17 (unknown):
```unknown
FindIntegrationAnchors()
```

Example 18 (unknown):
```unknown
FindClusters()
```

Example 19 (unknown):
```unknown
FindMarkers()
```

Example 20 (unknown):
```unknown
library(Seurat)
pbmc <- readRDS("../data/pbmc3k_final.rds")

# Enable parallelization
plan("multiprocess", workers = 4)
markers <- FindMarkers(pbmc, ident.1 = "NK", verbose = FALSE)
```

Example 21 (r):
```r
library(Seurat)
pbmc <- readRDS("../data/pbmc3k_final.rds")

# Enable parallelization
plan("multiprocess", workers = 4)
markers <- FindMarkers(pbmc, ident.1 = "NK", verbose = FALSE)
```

Example 22 (r):
```r
library(Seurat)
pbmc <- readRDS("../data/pbmc3k_final.rds")

# Enable parallelization
plan("multiprocess", workers = 4)
markers <- FindMarkers(pbmc, ident.1 = "NK", verbose = FALSE)
```

Example 23 (unknown):
```unknown
timing.comparisons <- data.frame(fxn = character(), time = numeric(), strategy = character())
plan("sequential")
start <- Sys.time()
pbmc <- ScaleData(pbmc, vars.to.regress = "percent.mt", verbose = FALSE)
end <- Sys.time()
timing.comparisons <- rbind(timing.comparisons, data.frame(fxn = "ScaleData", time = as.numeric(end -
    start, units = "secs"), strategy = "sequential"))

start <- Sys.time()
markers <- FindMarkers(pbmc, ident.1 = "NK", verbose = FALSE)
end <- Sys.time()
timing.comparisons <- rbind(timing.comparisons, data.frame(fxn = "FindMarkers", time = as.numeric(end -
    start, units = "secs"), strategy = "sequential"))

plan("multiprocess", workers = 4)
start <- Sys.time()
pbmc <- ScaleData(pbmc, vars.to.regress = "percent.mt", verbose = FALSE)
end <- Sys.time()
timing.comparisons <- rbind(timing.comparisons, data.frame(fxn = "ScaleData", time = as.numeric(end -
    start, units = "secs"), strategy = "multiprocess"))

start <- Sys.time()
markers <- FindMarkers(pbmc, ident.1 = "NK", verbose = FALSE)
end <- Sys.time()
timing.comparisons <- rbind(timing.comparisons, data.frame(fxn = "FindMarkers", time = as.numeric(end -
    start, units = "secs"), strategy = "multiprocess"))
```

Example 24 (r):
```r
timing.comparisons <- data.frame(fxn = character(), time = numeric(), strategy = character())
plan("sequential")
start <- Sys.time()
pbmc <- ScaleData(pbmc, vars.to.regress = "percent.mt", verbose = FALSE)
end <- Sys.time()
timing.comparisons <- rbind(timing.comparisons, data.frame(fxn = "ScaleData", time = as.numeric(end -
    start, units = "secs"), strategy = "sequential"))

start <- Sys.time()
markers <- FindMarkers(pbmc, ident.1 = "NK", verbose = FALSE)
end <- Sys.time()
timing.comparisons <- rbind(timing.comparisons, data.frame(fxn = "FindMarkers", time = as.numeric(end -
    start, units = "secs"), strategy = "sequential"))

plan("multiprocess", workers = 4)
start <- Sys.time()
pbmc <- ScaleData(pbmc, vars.to.regress = "percent.mt", verbose = FALSE)
end <- Sys.time()
timing.comparisons <- rbind(timing.comparisons, data.frame(fxn = "ScaleData", time = as.numeric(end -
    start, units = "secs"), strategy = "multiprocess"))

start <- Sys.time()
markers <- FindMarkers(pbmc, ident.1 = "NK", verbose = FALSE)
end <- Sys.time()
timing.comparisons <- rbind(timing.comparisons, data.frame(fxn = "FindMarkers", time = as.numeric(end -
    start, units = "secs"), strategy = "multiprocess"))
```

Example 25 (r):
```r
timing.comparisons <- data.frame(fxn = character(), time = numeric(), strategy = character())
plan("sequential")
start <- Sys.time()
pbmc <- ScaleData(pbmc, vars.to.regress = "percent.mt", verbose = FALSE)
end <- Sys.time()
timing.comparisons <- rbind(timing.comparisons, data.frame(fxn = "ScaleData", time = as.numeric(end -
    start, units = "secs"), strategy = "sequential"))

start <- Sys.time()
markers <- FindMarkers(pbmc, ident.1 = "NK", verbose = FALSE)
end <- Sys.time()
timing.comparisons <- rbind(timing.comparisons, data.frame(fxn = "FindMarkers", time = as.numeric(end -
    start, units = "secs"), strategy = "sequential"))

plan("multiprocess", workers = 4)
start <- Sys.time()
pbmc <- ScaleData(pbmc, vars.to.regress = "percent.mt", verbose = FALSE)
end <- Sys.time()
timing.comparisons <- rbind(timing.comparisons, data.frame(fxn = "ScaleData", time = as.numeric(end -
    start, units = "secs"), strategy = "multiprocess"))

start <- Sys.time()
markers <- FindMarkers(pbmc, ident.1 = "NK", verbose = FALSE)
end <- Sys.time()
timing.comparisons <- rbind(timing.comparisons, data.frame(fxn = "FindMarkers", time = as.numeric(end -
    start, units = "secs"), strategy = "multiprocess"))
```

Example 26 (unknown):
```unknown
library(ggplot2)
library(cowplot)
ggplot(timing.comparisons, aes(fxn, time)) + geom_bar(aes(fill = strategy), stat = "identity", position = "dodge") +
    ylab("Time(s)") + xlab("Function") + theme_cowplot()
```

Example 27 (r):
```r
library(ggplot2)
library(cowplot)
ggplot(timing.comparisons, aes(fxn, time)) + geom_bar(aes(fill = strategy), stat = "identity", position = "dodge") +
    ylab("Time(s)") + xlab("Function") + theme_cowplot()
```

Example 28 (r):
```r
library(ggplot2)
library(cowplot)
ggplot(timing.comparisons, aes(fxn, time)) + geom_bar(aes(fill = strategy), stat = "identity", position = "dodge") +
    ylab("Time(s)") + xlab("Function") + theme_cowplot()
```

Example 29 (unknown):
```unknown
plan("sequential")
```

Example 30 (unknown):
```unknown
Error in getGlobalsAndPackages(expr, envir = envir, globals = TRUE) : 
  The total size of the X globals that need to be exported for the future expression ('FUN()') is X GiB. 
  This exceeds the maximum allowed size of 500.00 MiB (option 'future.globals.maxSize'). The X largest globals are ...
```

Example 31 (unknown):
```unknown
Error in getGlobalsAndPackages(expr, envir = envir, globals = TRUE) : 
  The total size of the X globals that need to be exported for the future expression ('FUN()') is X GiB. 
  This exceeds the maximum allowed size of 500.00 MiB (option 'future.globals.maxSize'). The X largest globals are ...
```

Example 32 (unknown):
```unknown
options(future.globals.maxSize = X)
```

Example 33 (unknown):
```unknown
options(future.globals.maxSize = 1000 * 1024^2)
```

Example 34 (unknown):
```unknown
sessionInfo()
```

Example 35 (r):
```r
sessionInfo()
```

Example 36 (r):
```r
sessionInfo()
```

Example 37 (unknown):
```unknown
## R version 4.2.0 (2022-04-22)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.5 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/liblapack.so.3
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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       
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
## [1] cowplot_1.1.1      ggplot2_3.4.1      SeuratObject_4.1.3 Seurat_4.3.0      
## [5] future_1.31.0     
## 
## loaded via a namespace (and not attached):
##   [1] Rtsne_0.16             colorspace_2.1-0       deldir_1.0-6          
##   [4] ellipsis_0.3.2         ggridges_0.5.4         rprojroot_2.0.3       
##   [7] fs_1.6.1               spatstat.data_3.0-0    farver_2.1.1          
##  [10] leiden_0.4.3           listenv_0.9.0          ggrepel_0.9.3         
##  [13] fansi_1.0.4            codetools_0.2-18       splines_4.2.0         
##  [16] cachem_1.0.7           knitr_1.42             polyclip_1.10-4       
##  [19] jsonlite_1.8.4         ica_1.0-3              cluster_2.1.3         
##  [22] png_0.1-8              uwot_0.1.14            spatstat.sparse_3.0-0 
##  [25] shiny_1.7.4            sctransform_0.3.5      compiler_4.2.0        
##  [28] httr_1.4.5             Matrix_1.5-3           fastmap_1.1.1         
##  [31] lazyeval_0.2.2         limma_3.54.1           cli_3.6.0             
##  [34] later_1.3.0            formatR_1.14           htmltools_0.5.4       
##  [37] tools_4.2.0            igraph_1.4.1           gtable_0.3.1          
##  [40] glue_1.6.2             RANN_2.6.1             reshape2_1.4.4        
##  [43] dplyr_1.1.0            Rcpp_1.0.10            scattermore_0.8       
##  [46] jquerylib_0.1.4        pkgdown_2.0.7          vctrs_0.5.2           
##  [49] nlme_3.1-157           spatstat.explore_3.0-6 progressr_0.13.0      
##  [52] lmtest_0.9-40          spatstat.random_3.1-3  xfun_0.37             
##  [55] stringr_1.5.0          globals_0.16.2         mime_0.12             
##  [58] miniUI_0.1.1.1         lifecycle_1.0.3        irlba_2.3.5.1         
##  [61] goftest_1.2-3          MASS_7.3-56            zoo_1.8-11            
##  [64] scales_1.2.1           ragg_1.2.5             promises_1.2.0.1      
##  [67] spatstat.utils_3.0-1   parallel_4.2.0         RColorBrewer_1.1-3    
##  [70] yaml_2.3.7             memoise_2.0.1          reticulate_1.28       
##  [73] pbapply_1.7-0          gridExtra_2.3          sass_0.4.5            
##  [76] stringi_1.7.12         highr_0.10             desc_1.4.2            
##  [79] rlang_1.0.6            pkgconfig_2.0.3        systemfonts_1.0.4     
##  [82] matrixStats_0.63.0     evaluate_0.20          lattice_0.20-45       
##  [85] tensor_1.5             ROCR_1.0-11            purrr_1.0.1           
##  [88] labeling_0.4.2         patchwork_1.1.2        htmlwidgets_1.6.1     
##  [91] tidyselect_1.2.0       parallelly_1.34.0      RcppAnnoy_0.0.20      
##  [94] plyr_1.8.8             magrittr_2.0.3         R6_2.5.1              
##  [97] generics_0.1.3         withr_2.5.0            pillar_1.8.1          
## [100] fitdistrplus_1.1-8     abind_1.4-5            survival_3.3-1        
## [103] sp_1.6-0               tibble_3.1.8           future.apply_1.10.0   
## [106] KernSmooth_2.23-20     utf8_1.2.3             spatstat.geom_3.0-6   
## [109] plotly_4.10.1          rmarkdown_2.20         grid_4.2.0            
## [112] data.table_1.14.8      digest_0.6.31          xtable_1.8-4          
## [115] tidyr_1.3.0            httpuv_1.6.9           textshaping_0.3.6     
## [118] munsell_0.5.0          viridisLite_0.4.1      bslib_0.4.2
```

Example 38 (unknown):
```unknown
## R version 4.2.0 (2022-04-22)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.5 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/liblapack.so.3
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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       
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
## [1] cowplot_1.1.1      ggplot2_3.4.1      SeuratObject_4.1.3 Seurat_4.3.0      
## [5] future_1.31.0     
## 
## loaded via a namespace (and not attached):
##   [1] Rtsne_0.16             colorspace_2.1-0       deldir_1.0-6          
##   [4] ellipsis_0.3.2         ggridges_0.5.4         rprojroot_2.0.3       
##   [7] fs_1.6.1               spatstat.data_3.0-0    farver_2.1.1          
##  [10] leiden_0.4.3           listenv_0.9.0          ggrepel_0.9.3         
##  [13] fansi_1.0.4            codetools_0.2-18       splines_4.2.0         
##  [16] cachem_1.0.7           knitr_1.42             polyclip_1.10-4       
##  [19] jsonlite_1.8.4         ica_1.0-3              cluster_2.1.3         
##  [22] png_0.1-8              uwot_0.1.14            spatstat.sparse_3.0-0 
##  [25] shiny_1.7.4            sctransform_0.3.5      compiler_4.2.0        
##  [28] httr_1.4.5             Matrix_1.5-3           fastmap_1.1.1         
##  [31] lazyeval_0.2.2         limma_3.54.1           cli_3.6.0             
##  [34] later_1.3.0            formatR_1.14           htmltools_0.5.4       
##  [37] tools_4.2.0            igraph_1.4.1           gtable_0.3.1          
##  [40] glue_1.6.2             RANN_2.6.1             reshape2_1.4.4        
##  [43] dplyr_1.1.0            Rcpp_1.0.10            scattermore_0.8       
##  [46] jquerylib_0.1.4        pkgdown_2.0.7          vctrs_0.5.2           
##  [49] nlme_3.1-157           spatstat.explore_3.0-6 progressr_0.13.0      
##  [52] lmtest_0.9-40          spatstat.random_3.1-3  xfun_0.37             
##  [55] stringr_1.5.0          globals_0.16.2         mime_0.12             
##  [58] miniUI_0.1.1.1         lifecycle_1.0.3        irlba_2.3.5.1         
##  [61] goftest_1.2-3          MASS_7.3-56            zoo_1.8-11            
##  [64] scales_1.2.1           ragg_1.2.5             promises_1.2.0.1      
##  [67] spatstat.utils_3.0-1   parallel_4.2.0         RColorBrewer_1.1-3    
##  [70] yaml_2.3.7             memoise_2.0.1          reticulate_1.28       
##  [73] pbapply_1.7-0          gridExtra_2.3          sass_0.4.5            
##  [76] stringi_1.7.12         highr_0.10             desc_1.4.2            
##  [79] rlang_1.0.6            pkgconfig_2.0.3        systemfonts_1.0.4     
##  [82] matrixStats_0.63.0     evaluate_0.20          lattice_0.20-45       
##  [85] tensor_1.5             ROCR_1.0-11            purrr_1.0.1           
##  [88] labeling_0.4.2         patchwork_1.1.2        htmlwidgets_1.6.1     
##  [91] tidyselect_1.2.0       parallelly_1.34.0      RcppAnnoy_0.0.20      
##  [94] plyr_1.8.8             magrittr_2.0.3         R6_2.5.1              
##  [97] generics_0.1.3         withr_2.5.0            pillar_1.8.1          
## [100] fitdistrplus_1.1-8     abind_1.4-5            survival_3.3-1        
## [103] sp_1.6-0               tibble_3.1.8           future.apply_1.10.0   
## [106] KernSmooth_2.23-20     utf8_1.2.3             spatstat.geom_3.0-6   
## [109] plotly_4.10.1          rmarkdown_2.20         grid_4.2.0            
## [112] data.table_1.14.8      digest_0.6.31          xtable_1.8-4          
## [115] tidyr_1.3.0            httpuv_1.6.9           textshaping_0.3.6     
## [118] munsell_0.5.0          viridisLite_0.4.1      bslib_0.4.2
```

---

## Analysis, visualization, and integration of Visium HD spatial datasets with Seurat • Seurat

**URL:** http://127.0.0.1:9173/seurat/articles/visualization_vignette/index.html

**Contents:**
- Data visualization methods in Seurat
    - Compiled: 2023-10-31
- Five visualizations of marker feature expression
- New additions to FeaturePlot
- Updated and expanded visualization functions
- Applying themes to plots
- Interactive plotting features
- Plotting Accessories
- Contents

We’ll demonstrate visualization techniques in Seurat using our previously computed Seurat object from the 2,700 PBMC tutorial. You can download this dataset from SeuratData

In addition to changes to FeaturePlot(), several other plotting functions have been updated and expanded with new features and taking over the role of now-deprecated functions

With Seurat, all plotting functions return ggplot2-based plots by default, allowing one to easily capture and manipulate plots just like any other ggplot2-based plot.

Seurat utilizes R’s plotly graphing library to create interactive plots. This interactive plotting feature works with any ggplot2-based scatter plots (requires a geom_point layer). To use, simply make a ggplot2-based scatter plot (such as DimPlot() or FeaturePlot()) and pass the resulting plot to HoverLocator()

Another interactive feature provided by Seurat is being able to manually select cells for further investigation. We have found this particularly useful for small clusters that do not always separate using unbiased clustering, but which look tantalizingly distinct. You can now select these cells by creating a ggplot2-based scatter plot (such as with DimPlot() or FeaturePlot(), and passing the returned plot to CellSelector(). CellSelector() will return a vector with the names of the points selected, so that you can then set them to a new identity class and perform differential expression.

For example, let’s pretend that DCs had merged with monocytes in the clustering, but we wanted to see what was unique about them based on their position in the tSNE plot.

We can then change the identity of these cells to turn them into their own mini-cluster.

Using CellSelector to Automatically Assign Cell Identities

In addition to returning a vector of cell names, CellSelector() can also take the selected cells and assign a new identity to them, returning a Seurat object with the identity classes already set. This is done by passing the Seurat object used to make the plot into CellSelector(), as well as an identity class. As an example, we’re going to select the same set of cells as before, and set their identity class to “selected”

Along with new functions add interactive functionality to plots, Seurat provides new accessory functions for manipulating and combining plots.

Plotting multiple plots was previously achieved with the CombinePlot() function. We are deprecating this functionality in favor of the patchwork system. Below is a brief demonstration but please see the patchwork package website here for more details and examples.

Developed by Rahul Satija, Satija Lab and Collaborators.

Site built with pkgdown 2.0.7.

**Examples:**

Example 1 (unknown):
```unknown
vignettes/visualization_vignette.Rmd
```

Example 2 (unknown):
```unknown
visualization_vignette.Rmd
```

Example 3 (unknown):
```unknown
SeuratData::InstallData("pbmc3k")
```

Example 4 (r):
```r
SeuratData::InstallData("pbmc3k")
```

Example 5 (r):
```r
SeuratData::InstallData("pbmc3k")
```

Example 6 (unknown):
```unknown
library(Seurat)
library(SeuratData)
library(ggplot2)
library(patchwork)
pbmc3k.final <- LoadData("pbmc3k", type = "pbmc3k.final")
pbmc3k.final$groups <- sample(c("group1", "group2"), size = ncol(pbmc3k.final), replace = TRUE)
features <- c("LYZ", "CCL5", "IL32", "PTPRCAP", "FCGR3A", "PF4")
pbmc3k.final
```

Example 7 (r):
```r
library(Seurat)
library(SeuratData)
library(ggplot2)
library(patchwork)
pbmc3k.final <- LoadData("pbmc3k", type = "pbmc3k.final")
pbmc3k.final$groups <- sample(c("group1", "group2"), size = ncol(pbmc3k.final), replace = TRUE)
features <- c("LYZ", "CCL5", "IL32", "PTPRCAP", "FCGR3A", "PF4")
pbmc3k.final
```

Example 8 (r):
```r
library(Seurat)
library(SeuratData)
library(ggplot2)
library(patchwork)
pbmc3k.final <- LoadData("pbmc3k", type = "pbmc3k.final")
pbmc3k.final$groups <- sample(c("group1", "group2"), size = ncol(pbmc3k.final), replace = TRUE)
features <- c("LYZ", "CCL5", "IL32", "PTPRCAP", "FCGR3A", "PF4")
pbmc3k.final
```

Example 9 (python):
```python
## An object of class Seurat 
## 13714 features across 2638 samples within 1 assay 
## Active assay: RNA (13714 features, 2000 variable features)
##  3 layers present: data, counts, scale.data
##  2 dimensional reductions calculated: pca, umap
```

Example 10 (python):
```python
## An object of class Seurat 
## 13714 features across 2638 samples within 1 assay 
## Active assay: RNA (13714 features, 2000 variable features)
##  3 layers present: data, counts, scale.data
##  2 dimensional reductions calculated: pca, umap
```

Example 11 (python):
```python
# Ridge plots - from ggridges. Visualize single cell expression distributions in each cluster
RidgePlot(pbmc3k.final, features = features, ncol = 2)
```

Example 12 (r):
```r
# Ridge plots - from ggridges. Visualize single cell expression distributions in each cluster
RidgePlot(pbmc3k.final, features = features, ncol = 2)
```

Example 13 (r):
```r
# Ridge plots - from ggridges. Visualize single cell expression distributions in each cluster
RidgePlot(pbmc3k.final, features = features, ncol = 2)
```

Example 14 (unknown):
```unknown
# Violin plot - Visualize single cell expression distributions in each cluster
VlnPlot(pbmc3k.final, features = features)
```

Example 15 (r):
```r
# Violin plot - Visualize single cell expression distributions in each cluster
VlnPlot(pbmc3k.final, features = features)
```

Example 16 (r):
```r
# Violin plot - Visualize single cell expression distributions in each cluster
VlnPlot(pbmc3k.final, features = features)
```

Example 17 (unknown):
```unknown
# Feature plot - visualize feature expression in low-dimensional space
FeaturePlot(pbmc3k.final, features = features)
```

Example 18 (r):
```r
# Feature plot - visualize feature expression in low-dimensional space
FeaturePlot(pbmc3k.final, features = features)
```

Example 19 (r):
```r
# Feature plot - visualize feature expression in low-dimensional space
FeaturePlot(pbmc3k.final, features = features)
```

Example 20 (unknown):
```unknown
# Dot plots - the size of the dot corresponds to the percentage of cells expressing the
# feature in each cluster. The color represents the average expression level
DotPlot(pbmc3k.final, features = features) + RotatedAxis()
```

Example 21 (r):
```r
# Dot plots - the size of the dot corresponds to the percentage of cells expressing the
# feature in each cluster. The color represents the average expression level
DotPlot(pbmc3k.final, features = features) + RotatedAxis()
```

Example 22 (r):
```r
# Dot plots - the size of the dot corresponds to the percentage of cells expressing the
# feature in each cluster. The color represents the average expression level
DotPlot(pbmc3k.final, features = features) + RotatedAxis()
```

Example 23 (unknown):
```unknown
# Single cell heatmap of feature expression
DoHeatmap(subset(pbmc3k.final, downsample = 100), features = features, size = 3)
```

Example 24 (r):
```r
# Single cell heatmap of feature expression
DoHeatmap(subset(pbmc3k.final, downsample = 100), features = features, size = 3)
```

Example 25 (r):
```r
# Single cell heatmap of feature expression
DoHeatmap(subset(pbmc3k.final, downsample = 100), features = features, size = 3)
```

Example 26 (unknown):
```unknown
FeaturePlot
```

Example 27 (unknown):
```unknown
# Plot a legend to map colors to expression levels
FeaturePlot(pbmc3k.final, features = "MS4A1")
```

Example 28 (r):
```r
# Plot a legend to map colors to expression levels
FeaturePlot(pbmc3k.final, features = "MS4A1")
```

Example 29 (r):
```r
# Plot a legend to map colors to expression levels
FeaturePlot(pbmc3k.final, features = "MS4A1")
```

Example 30 (unknown):
```unknown
# Adjust the contrast in the plot
FeaturePlot(pbmc3k.final, features = "MS4A1", min.cutoff = 1, max.cutoff = 3)
```

Example 31 (r):
```r
# Adjust the contrast in the plot
FeaturePlot(pbmc3k.final, features = "MS4A1", min.cutoff = 1, max.cutoff = 3)
```

Example 32 (r):
```r
# Adjust the contrast in the plot
FeaturePlot(pbmc3k.final, features = "MS4A1", min.cutoff = 1, max.cutoff = 3)
```

Example 33 (unknown):
```unknown
# Calculate feature-specific contrast levels based on quantiles of non-zero expression.
# Particularly useful when plotting multiple markers
FeaturePlot(pbmc3k.final, features = c("MS4A1", "PTPRCAP"), min.cutoff = "q10", max.cutoff = "q90")
```

Example 34 (r):
```r
# Calculate feature-specific contrast levels based on quantiles of non-zero expression.
# Particularly useful when plotting multiple markers
FeaturePlot(pbmc3k.final, features = c("MS4A1", "PTPRCAP"), min.cutoff = "q10", max.cutoff = "q90")
```

Example 35 (r):
```r
# Calculate feature-specific contrast levels based on quantiles of non-zero expression.
# Particularly useful when plotting multiple markers
FeaturePlot(pbmc3k.final, features = c("MS4A1", "PTPRCAP"), min.cutoff = "q10", max.cutoff = "q90")
```

Example 36 (unknown):
```unknown
# Visualize co-expression of two features simultaneously
FeaturePlot(pbmc3k.final, features = c("MS4A1", "CD79A"), blend = TRUE)
```

Example 37 (r):
```r
# Visualize co-expression of two features simultaneously
FeaturePlot(pbmc3k.final, features = c("MS4A1", "CD79A"), blend = TRUE)
```

Example 38 (r):
```r
# Visualize co-expression of two features simultaneously
FeaturePlot(pbmc3k.final, features = c("MS4A1", "CD79A"), blend = TRUE)
```

Example 39 (unknown):
```unknown
# Split visualization to view expression by groups (replaces FeatureHeatmap)
FeaturePlot(pbmc3k.final, features = c("MS4A1", "CD79A"), split.by = "groups")
```

Example 40 (r):
```r
# Split visualization to view expression by groups (replaces FeatureHeatmap)
FeaturePlot(pbmc3k.final, features = c("MS4A1", "CD79A"), split.by = "groups")
```

Example 41 (r):
```r
# Split visualization to view expression by groups (replaces FeatureHeatmap)
FeaturePlot(pbmc3k.final, features = c("MS4A1", "CD79A"), split.by = "groups")
```

Example 42 (unknown):
```unknown
FeaturePlot()
```

Example 43 (python):
```python
# Violin plots can also be split on some variable. Simply add the splitting variable to object
# metadata and pass it to the split.by argument
VlnPlot(pbmc3k.final, features = "percent.mt", split.by = "groups")
```

Example 44 (r):
```r
# Violin plots can also be split on some variable. Simply add the splitting variable to object
# metadata and pass it to the split.by argument
VlnPlot(pbmc3k.final, features = "percent.mt", split.by = "groups")
```

Example 45 (r):
```r
# Violin plots can also be split on some variable. Simply add the splitting variable to object
# metadata and pass it to the split.by argument
VlnPlot(pbmc3k.final, features = "percent.mt", split.by = "groups")
```

Example 46 (unknown):
```unknown
# SplitDotPlotGG has been replaced with the `split.by` parameter for DotPlot
DotPlot(pbmc3k.final, features = features, split.by = "groups") + RotatedAxis()
```

Example 47 (r):
```r
# SplitDotPlotGG has been replaced with the `split.by` parameter for DotPlot
DotPlot(pbmc3k.final, features = features, split.by = "groups") + RotatedAxis()
```

Example 48 (r):
```r
# SplitDotPlotGG has been replaced with the `split.by` parameter for DotPlot
DotPlot(pbmc3k.final, features = features, split.by = "groups") + RotatedAxis()
```

Example 49 (unknown):
```unknown
# DimPlot replaces TSNEPlot, PCAPlot, etc. In addition, it will plot either 'umap', 'tsne', or
# 'pca' by default, in that order
DimPlot(pbmc3k.final)
```

Example 50 (r):
```r
# DimPlot replaces TSNEPlot, PCAPlot, etc. In addition, it will plot either 'umap', 'tsne', or
# 'pca' by default, in that order
DimPlot(pbmc3k.final)
```

Example 51 (r):
```r
# DimPlot replaces TSNEPlot, PCAPlot, etc. In addition, it will plot either 'umap', 'tsne', or
# 'pca' by default, in that order
DimPlot(pbmc3k.final)
```

Example 52 (unknown):
```unknown
pbmc3k.final.no.umap <- pbmc3k.final
pbmc3k.final.no.umap[["umap"]] <- NULL
DimPlot(pbmc3k.final.no.umap) + RotatedAxis()
```

Example 53 (r):
```r
pbmc3k.final.no.umap <- pbmc3k.final
pbmc3k.final.no.umap[["umap"]] <- NULL
DimPlot(pbmc3k.final.no.umap) + RotatedAxis()
```

Example 54 (r):
```r
pbmc3k.final.no.umap <- pbmc3k.final
pbmc3k.final.no.umap[["umap"]] <- NULL
DimPlot(pbmc3k.final.no.umap) + RotatedAxis()
```

Example 55 (unknown):
```unknown
# DoHeatmap now shows a grouping bar, splitting the heatmap into groups or clusters. This can
# be changed with the `group.by` parameter
DoHeatmap(pbmc3k.final, features = VariableFeatures(pbmc3k.final)[1:100], cells = 1:500, size = 4,
    angle = 90) + NoLegend()
```

Example 56 (r):
```r
# DoHeatmap now shows a grouping bar, splitting the heatmap into groups or clusters. This can
# be changed with the `group.by` parameter
DoHeatmap(pbmc3k.final, features = VariableFeatures(pbmc3k.final)[1:100], cells = 1:500, size = 4,
    angle = 90) + NoLegend()
```

Example 57 (r):
```r
# DoHeatmap now shows a grouping bar, splitting the heatmap into groups or clusters. This can
# be changed with the `group.by` parameter
DoHeatmap(pbmc3k.final, features = VariableFeatures(pbmc3k.final)[1:100], cells = 1:500, size = 4,
    angle = 90) + NoLegend()
```

Example 58 (unknown):
```unknown
baseplot <- DimPlot(pbmc3k.final, reduction = "umap")
# Add custom labels and titles
baseplot + labs(title = "Clustering of 2,700 PBMCs")
```

Example 59 (r):
```r
baseplot <- DimPlot(pbmc3k.final, reduction = "umap")
# Add custom labels and titles
baseplot + labs(title = "Clustering of 2,700 PBMCs")
```

Example 60 (r):
```r
baseplot <- DimPlot(pbmc3k.final, reduction = "umap")
# Add custom labels and titles
baseplot + labs(title = "Clustering of 2,700 PBMCs")
```

Example 61 (unknown):
```unknown
# Use community-created themes, overwriting the default Seurat-applied theme Install ggmin
# with remotes::install_github('sjessa/ggmin')
baseplot + ggmin::theme_powerpoint()
```

Example 62 (r):
```r
# Use community-created themes, overwriting the default Seurat-applied theme Install ggmin
# with remotes::install_github('sjessa/ggmin')
baseplot + ggmin::theme_powerpoint()
```

Example 63 (r):
```r
# Use community-created themes, overwriting the default Seurat-applied theme Install ggmin
# with remotes::install_github('sjessa/ggmin')
baseplot + ggmin::theme_powerpoint()
```

Example 64 (unknown):
```unknown
# Seurat also provides several built-in themes, such as DarkTheme; for more details see
# ?SeuratTheme
baseplot + DarkTheme()
```

Example 65 (r):
```r
# Seurat also provides several built-in themes, such as DarkTheme; for more details see
# ?SeuratTheme
baseplot + DarkTheme()
```

Example 66 (r):
```r
# Seurat also provides several built-in themes, such as DarkTheme; for more details see
# ?SeuratTheme
baseplot + DarkTheme()
```

Example 67 (unknown):
```unknown
# Chain themes together
baseplot + FontSize(x.title = 20, y.title = 20) + NoLegend()
```

Example 68 (r):
```r
# Chain themes together
baseplot + FontSize(x.title = 20, y.title = 20) + NoLegend()
```

Example 69 (r):
```r
# Chain themes together
baseplot + FontSize(x.title = 20, y.title = 20) + NoLegend()
```

Example 70 (unknown):
```unknown
FeaturePlot()
```

Example 71 (unknown):
```unknown
HoverLocator()
```

Example 72 (unknown):
```unknown
# Include additional data to display alongside cell names by passing in a data frame of
# information.  Works well when using FetchData
plot <- FeaturePlot(pbmc3k.final, features = "MS4A1")
HoverLocator(plot = plot, information = FetchData(pbmc3k.final, vars = c("ident", "PC_1", "nFeature_RNA")))
```

Example 73 (r):
```r
# Include additional data to display alongside cell names by passing in a data frame of
# information.  Works well when using FetchData
plot <- FeaturePlot(pbmc3k.final, features = "MS4A1")
HoverLocator(plot = plot, information = FetchData(pbmc3k.final, vars = c("ident", "PC_1", "nFeature_RNA")))
```

Example 74 (r):
```r
# Include additional data to display alongside cell names by passing in a data frame of
# information.  Works well when using FetchData
plot <- FeaturePlot(pbmc3k.final, features = "MS4A1")
HoverLocator(plot = plot, information = FetchData(pbmc3k.final, vars = c("ident", "PC_1", "nFeature_RNA")))
```

Example 75 (unknown):
```unknown
FeaturePlot()
```

Example 76 (unknown):
```unknown
CellSelector()
```

Example 77 (unknown):
```unknown
CellSelector()
```

Example 78 (unknown):
```unknown
pbmc3k.final <- RenameIdents(pbmc3k.final, DC = "CD14+ Mono")
plot <- DimPlot(pbmc3k.final, reduction = "umap")
select.cells <- CellSelector(plot = plot)
```

Example 79 (r):
```r
pbmc3k.final <- RenameIdents(pbmc3k.final, DC = "CD14+ Mono")
plot <- DimPlot(pbmc3k.final, reduction = "umap")
select.cells <- CellSelector(plot = plot)
```

Example 80 (r):
```r
pbmc3k.final <- RenameIdents(pbmc3k.final, DC = "CD14+ Mono")
plot <- DimPlot(pbmc3k.final, reduction = "umap")
select.cells <- CellSelector(plot = plot)
```

Example 81 (unknown):
```unknown
head(select.cells)
```

Example 82 (r):
```r
head(select.cells)
```

Example 83 (r):
```r
head(select.cells)
```

Example 84 (unknown):
```unknown
## [1] "AAGATTACCGCCTT" "AAGCCATGAACTGC" "AATTACGAATTCCT" "ACCCGTTGCTTCTA"
## [5] "ACGAGGGACAGGAG" "ACGTGATGCCATGA"
```

Example 85 (unknown):
```unknown
## [1] "AAGATTACCGCCTT" "AAGCCATGAACTGC" "AATTACGAATTCCT" "ACCCGTTGCTTCTA"
## [5] "ACGAGGGACAGGAG" "ACGTGATGCCATGA"
```

Example 86 (unknown):
```unknown
Idents(pbmc3k.final, cells = select.cells) <- "NewCells"

# Now, we find markers that are specific to the new cells, and find clear DC markers
newcells.markers <- FindMarkers(pbmc3k.final, ident.1 = "NewCells", ident.2 = "CD14+ Mono", min.diff.pct = 0.3,
    only.pos = TRUE)
head(newcells.markers)
```

Example 87 (r):
```r
Idents(pbmc3k.final, cells = select.cells) <- "NewCells"

# Now, we find markers that are specific to the new cells, and find clear DC markers
newcells.markers <- FindMarkers(pbmc3k.final, ident.1 = "NewCells", ident.2 = "CD14+ Mono", min.diff.pct = 0.3,
    only.pos = TRUE)
head(newcells.markers)
```

Example 88 (r):
```r
Idents(pbmc3k.final, cells = select.cells) <- "NewCells"

# Now, we find markers that are specific to the new cells, and find clear DC markers
newcells.markers <- FindMarkers(pbmc3k.final, ident.1 = "NewCells", ident.2 = "CD14+ Mono", min.diff.pct = 0.3,
    only.pos = TRUE)
head(newcells.markers)
```

Example 89 (unknown):
```unknown
##                 p_val avg_log2FC pct.1 pct.2    p_val_adj
## FCER1A   3.239004e-69   6.504163 0.800 0.017 4.441970e-65
## SERPINF1 7.761413e-36   5.456560 0.457 0.013 1.064400e-31
## HLA-DQB2 1.721094e-34   4.752397 0.429 0.010 2.360309e-30
## CD1C     2.304106e-33   4.929607 0.514 0.025 3.159851e-29
## ENHO     5.099765e-32   5.076634 0.400 0.010 6.993818e-28
## ITM2C    4.299994e-29   5.660234 0.371 0.010 5.897012e-25
```

Example 90 (unknown):
```unknown
##                 p_val avg_log2FC pct.1 pct.2    p_val_adj
## FCER1A   3.239004e-69   6.504163 0.800 0.017 4.441970e-65
## SERPINF1 7.761413e-36   5.456560 0.457 0.013 1.064400e-31
## HLA-DQB2 1.721094e-34   4.752397 0.429 0.010 2.360309e-30
## CD1C     2.304106e-33   4.929607 0.514 0.025 3.159851e-29
## ENHO     5.099765e-32   5.076634 0.400 0.010 6.993818e-28
## ITM2C    4.299994e-29   5.660234 0.371 0.010 5.897012e-25
```

Example 91 (unknown):
```unknown
CellSelector
```

Example 92 (unknown):
```unknown
CellSelector()
```

Example 93 (unknown):
```unknown
CellSelector()
```

Example 94 (unknown):
```unknown
pbmc3k.final <- CellSelector(plot = plot, object = pbmc3k.final, ident = "selected")
```

Example 95 (r):
```r
pbmc3k.final <- CellSelector(plot = plot, object = pbmc3k.final, ident = "selected")
```

Example 96 (r):
```r
pbmc3k.final <- CellSelector(plot = plot, object = pbmc3k.final, ident = "selected")
```

Example 97 (unknown):
```unknown
levels(pbmc3k.final)
```

Example 98 (r):
```r
levels(pbmc3k.final)
```

Example 99 (r):
```r
levels(pbmc3k.final)
```

Example 100 (unknown):
```unknown
## [1] "selected"     "Naive CD4 T"  "Memory CD4 T" "CD14+ Mono"   "B"           
## [6] "CD8 T"        "FCGR3A+ Mono" "NK"           "Platelet"
```

Example 101 (unknown):
```unknown
## [1] "selected"     "Naive CD4 T"  "Memory CD4 T" "CD14+ Mono"   "B"           
## [6] "CD8 T"        "FCGR3A+ Mono" "NK"           "Platelet"
```

Example 102 (unknown):
```unknown
# LabelClusters and LabelPoints will label clusters (a coloring variable) or individual points
# on a ggplot2-based scatter plot
plot <- DimPlot(pbmc3k.final, reduction = "pca") + NoLegend()
LabelClusters(plot = plot, id = "ident")
```

Example 103 (r):
```r
# LabelClusters and LabelPoints will label clusters (a coloring variable) or individual points
# on a ggplot2-based scatter plot
plot <- DimPlot(pbmc3k.final, reduction = "pca") + NoLegend()
LabelClusters(plot = plot, id = "ident")
```

Example 104 (r):
```r
# LabelClusters and LabelPoints will label clusters (a coloring variable) or individual points
# on a ggplot2-based scatter plot
plot <- DimPlot(pbmc3k.final, reduction = "pca") + NoLegend()
LabelClusters(plot = plot, id = "ident")
```

Example 105 (python):
```python
# Both functions support `repel`, which will intelligently stagger labels and draw connecting
# lines from the labels to the points or clusters
LabelPoints(plot = plot, points = TopCells(object = pbmc3k.final[["pca"]]), repel = TRUE)
```

Example 106 (r):
```r
# Both functions support `repel`, which will intelligently stagger labels and draw connecting
# lines from the labels to the points or clusters
LabelPoints(plot = plot, points = TopCells(object = pbmc3k.final[["pca"]]), repel = TRUE)
```

Example 107 (r):
```r
# Both functions support `repel`, which will intelligently stagger labels and draw connecting
# lines from the labels to the points or clusters
LabelPoints(plot = plot, points = TopCells(object = pbmc3k.final[["pca"]]), repel = TRUE)
```

Example 108 (unknown):
```unknown
CombinePlot()
```

Example 109 (unknown):
```unknown
plot1 <- DimPlot(pbmc3k.final)
# Create scatter plot with the Pearson correlation value as the title
plot2 <- FeatureScatter(pbmc3k.final, feature1 = "LYZ", feature2 = "CCL5")
# Combine two plots
plot1 + plot2
```

Example 110 (r):
```r
plot1 <- DimPlot(pbmc3k.final)
# Create scatter plot with the Pearson correlation value as the title
plot2 <- FeatureScatter(pbmc3k.final, feature1 = "LYZ", feature2 = "CCL5")
# Combine two plots
plot1 + plot2
```

Example 111 (r):
```r
plot1 <- DimPlot(pbmc3k.final)
# Create scatter plot with the Pearson correlation value as the title
plot2 <- FeatureScatter(pbmc3k.final, feature1 = "LYZ", feature2 = "CCL5")
# Combine two plots
plot1 + plot2
```

Example 112 (python):
```python
# Remove the legend from all plots
(plot1 + plot2) & NoLegend()
```

Example 113 (r):
```r
# Remove the legend from all plots
(plot1 + plot2) & NoLegend()
```

Example 114 (r):
```r
# Remove the legend from all plots
(plot1 + plot2) & NoLegend()
```

Example 115 (unknown):
```unknown
sessionInfo()
```

Example 116 (r):
```r
sessionInfo()
```

Example 117 (r):
```r
sessionInfo()
```

Example 118 (unknown):
```unknown
## R version 4.2.2 Patched (2022-11-10 r83330)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.6 LTS
## 
## Matrix products: default
## BLAS:   /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.9.0
## LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.9.0
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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       
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
##  [1] patchwork_1.1.3               ggplot2_3.4.4                
##  [3] thp1.eccite.SeuratData_3.1.5  stxBrain.SeuratData_0.1.1    
##  [5] ssHippo.SeuratData_3.1.4      pbmcsca.SeuratData_3.0.0     
##  [7] pbmcref.SeuratData_1.0.0      pbmcMultiome.SeuratData_0.1.4
##  [9] pbmc3k.SeuratData_3.1.4       panc8.SeuratData_3.0.2       
## [11] ifnb.SeuratData_3.0.0         hcabm40k.SeuratData_3.0.0    
## [13] cbmc.SeuratData_3.1.4         bmcite.SeuratData_0.3.0      
## [15] SeuratData_0.2.2.9001         Seurat_5.0.0                 
## [17] SeuratObject_5.0.0            sp_2.1-1                     
## 
## loaded via a namespace (and not attached):
##   [1] spam_2.10-0            systemfonts_1.0.4      plyr_1.8.9            
##   [4] igraph_1.5.1           lazyeval_0.2.2         splines_4.2.2         
##   [7] RcppHNSW_0.5.0         crosstalk_1.2.0        listenv_0.9.0         
##  [10] scattermore_1.2        digest_0.6.33          htmltools_0.5.6.1     
##  [13] fansi_1.0.5            magrittr_2.0.3         memoise_2.0.1         
##  [16] tensor_1.5             cluster_2.1.4          ROCR_1.0-11           
##  [19] limma_3.54.1           globals_0.16.2         matrixStats_1.0.0     
##  [22] pkgdown_2.0.7          spatstat.sparse_3.0-3  colorspace_2.1-0      
##  [25] rappdirs_0.3.3         ggrepel_0.9.4          textshaping_0.3.6     
##  [28] xfun_0.40              dplyr_1.1.3            crayon_1.5.2          
##  [31] jsonlite_1.8.7         progressr_0.14.0       spatstat.data_3.0-3   
##  [34] survival_3.5-7         zoo_1.8-12             glue_1.6.2            
##  [37] polyclip_1.10-6        gtable_0.3.4           leiden_0.4.3          
##  [40] future.apply_1.11.0    abind_1.4-5            scales_1.2.1          
##  [43] spatstat.random_3.2-1  miniUI_0.1.1.1         Rcpp_1.0.11           
##  [46] viridisLite_0.4.2      xtable_1.8-4           reticulate_1.34.0     
##  [49] dotCall64_1.1-0        ggmin_0.0.0.9000       htmlwidgets_1.6.2     
##  [52] httr_1.4.7             RColorBrewer_1.1-3     ellipsis_0.3.2        
##  [55] ica_1.0-3              farver_2.1.1           pkgconfig_2.0.3       
##  [58] sass_0.4.7             uwot_0.1.16            deldir_1.0-9          
##  [61] utf8_1.2.4             labeling_0.4.3         tidyselect_1.2.0      
##  [64] rlang_1.1.1            reshape2_1.4.4         later_1.3.1           
##  [67] munsell_0.5.0          tools_4.2.2            cachem_1.0.8          
##  [70] cli_3.6.1              generics_0.1.3         ggridges_0.5.4        
##  [73] evaluate_0.22          stringr_1.5.0          fastmap_1.1.1         
##  [76] yaml_2.3.7             ragg_1.2.5             goftest_1.2-3         
##  [79] knitr_1.45             fs_1.6.3               fitdistrplus_1.1-11   
##  [82] purrr_1.0.2            RANN_2.6.1             pbapply_1.7-2         
##  [85] future_1.33.0          nlme_3.1-162           mime_0.12             
##  [88] formatR_1.14           ggrastr_1.0.1          compiler_4.2.2        
##  [91] beeswarm_0.4.0         plotly_4.10.3          png_0.1-8             
##  [94] spatstat.utils_3.0-4   tibble_3.2.1           bslib_0.5.1           
##  [97] stringi_1.7.12         highr_0.10             desc_1.4.2            
## [100] RSpectra_0.16-1        lattice_0.21-9         Matrix_1.6-1.1        
## [103] vctrs_0.6.4            pillar_1.9.0           lifecycle_1.0.3       
## [106] spatstat.geom_3.2-7    lmtest_0.9-40          jquerylib_0.1.4       
## [109] RcppAnnoy_0.0.21       data.table_1.14.8      cowplot_1.1.1         
## [112] irlba_2.3.5.1          httpuv_1.6.12          R6_2.5.1              
## [115] promises_1.2.1         KernSmooth_2.23-22     gridExtra_2.3         
## [118] vipor_0.4.5            parallelly_1.36.0      codetools_0.2-19      
## [121] fastDummies_1.7.3      MASS_7.3-58.2          rprojroot_2.0.3       
## [124] withr_2.5.2            presto_1.0.0           sctransform_0.4.1     
## [127] parallel_4.2.2         grid_4.2.2             tidyr_1.3.0           
## [130] rmarkdown_2.25         Rtsne_0.16             spatstat.explore_3.2-5
## [133] shiny_1.7.5.1          ggbeeswarm_0.7.1
```

Example 119 (unknown):
```unknown
## R version 4.2.2 Patched (2022-11-10 r83330)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.6 LTS
## 
## Matrix products: default
## BLAS:   /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.9.0
## LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.9.0
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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       
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
##  [1] patchwork_1.1.3               ggplot2_3.4.4                
##  [3] thp1.eccite.SeuratData_3.1.5  stxBrain.SeuratData_0.1.1    
##  [5] ssHippo.SeuratData_3.1.4      pbmcsca.SeuratData_3.0.0     
##  [7] pbmcref.SeuratData_1.0.0      pbmcMultiome.SeuratData_0.1.4
##  [9] pbmc3k.SeuratData_3.1.4       panc8.SeuratData_3.0.2       
## [11] ifnb.SeuratData_3.0.0         hcabm40k.SeuratData_3.0.0    
## [13] cbmc.SeuratData_3.1.4         bmcite.SeuratData_0.3.0      
## [15] SeuratData_0.2.2.9001         Seurat_5.0.0                 
## [17] SeuratObject_5.0.0            sp_2.1-1                     
## 
## loaded via a namespace (and not attached):
##   [1] spam_2.10-0            systemfonts_1.0.4      plyr_1.8.9            
##   [4] igraph_1.5.1           lazyeval_0.2.2         splines_4.2.2         
##   [7] RcppHNSW_0.5.0         crosstalk_1.2.0        listenv_0.9.0         
##  [10] scattermore_1.2        digest_0.6.33          htmltools_0.5.6.1     
##  [13] fansi_1.0.5            magrittr_2.0.3         memoise_2.0.1         
##  [16] tensor_1.5             cluster_2.1.4          ROCR_1.0-11           
##  [19] limma_3.54.1           globals_0.16.2         matrixStats_1.0.0     
##  [22] pkgdown_2.0.7          spatstat.sparse_3.0-3  colorspace_2.1-0      
##  [25] rappdirs_0.3.3         ggrepel_0.9.4          textshaping_0.3.6     
##  [28] xfun_0.40              dplyr_1.1.3            crayon_1.5.2          
##  [31] jsonlite_1.8.7         progressr_0.14.0       spatstat.data_3.0-3   
##  [34] survival_3.5-7         zoo_1.8-12             glue_1.6.2            
##  [37] polyclip_1.10-6        gtable_0.3.4           leiden_0.4.3          
##  [40] future.apply_1.11.0    abind_1.4-5            scales_1.2.1          
##  [43] spatstat.random_3.2-1  miniUI_0.1.1.1         Rcpp_1.0.11           
##  [46] viridisLite_0.4.2      xtable_1.8-4           reticulate_1.34.0     
##  [49] dotCall64_1.1-0        ggmin_0.0.0.9000       htmlwidgets_1.6.2     
##  [52] httr_1.4.7             RColorBrewer_1.1-3     ellipsis_0.3.2        
##  [55] ica_1.0-3              farver_2.1.1           pkgconfig_2.0.3       
##  [58] sass_0.4.7             uwot_0.1.16            deldir_1.0-9          
##  [61] utf8_1.2.4             labeling_0.4.3         tidyselect_1.2.0      
##  [64] rlang_1.1.1            reshape2_1.4.4         later_1.3.1           
##  [67] munsell_0.5.0          tools_4.2.2            cachem_1.0.8          
##  [70] cli_3.6.1              generics_0.1.3         ggridges_0.5.4        
##  [73] evaluate_0.22          stringr_1.5.0          fastmap_1.1.1         
##  [76] yaml_2.3.7             ragg_1.2.5             goftest_1.2-3         
##  [79] knitr_1.45             fs_1.6.3               fitdistrplus_1.1-11   
##  [82] purrr_1.0.2            RANN_2.6.1             pbapply_1.7-2         
##  [85] future_1.33.0          nlme_3.1-162           mime_0.12             
##  [88] formatR_1.14           ggrastr_1.0.1          compiler_4.2.2        
##  [91] beeswarm_0.4.0         plotly_4.10.3          png_0.1-8             
##  [94] spatstat.utils_3.0-4   tibble_3.2.1           bslib_0.5.1           
##  [97] stringi_1.7.12         highr_0.10             desc_1.4.2            
## [100] RSpectra_0.16-1        lattice_0.21-9         Matrix_1.6-1.1        
## [103] vctrs_0.6.4            pillar_1.9.0           lifecycle_1.0.3       
## [106] spatstat.geom_3.2-7    lmtest_0.9-40          jquerylib_0.1.4       
## [109] RcppAnnoy_0.0.21       data.table_1.14.8      cowplot_1.1.1         
## [112] irlba_2.3.5.1          httpuv_1.6.12          R6_2.5.1              
## [115] promises_1.2.1         KernSmooth_2.23-22     gridExtra_2.3         
## [118] vipor_0.4.5            parallelly_1.36.0      codetools_0.2-19      
## [121] fastDummies_1.7.3      MASS_7.3-58.2          rprojroot_2.0.3       
## [124] withr_2.5.2            presto_1.0.0           sctransform_0.4.1     
## [127] parallel_4.2.2         grid_4.2.2             tidyr_1.3.0           
## [130] rmarkdown_2.25         Rtsne_0.16             spatstat.explore_3.2-5
## [133] shiny_1.7.5.1          ggbeeswarm_0.7.1
```

---

## Seurat - Interaction Tips • Seurat

**URL:** http://127.0.0.1:9173/seurat/archive/v4.3/interaction_vignette/index.html

**Contents:**
- Seurat - Interaction Tips
    - Compiled: March 27, 2023
- Load in the data
- Switch identity class between cluster ID and replicate
- Tabulate cells by cluster ID, replicate, or both
- Selecting particular cells and subsetting the Seurat object
- Calculating the average gene expression within a cluster
- Contents

This vignette demonstrates some useful features for interacting with the Seurat object. For demonstration purposes, we will be using the 2,700 PBMC object that is created in the first guided tutorial. You can load the data from our SeuratData package. To simulate the scenario where we have two replicates, we will randomly assign half the cells in each cluster to be from “rep1” and other half from “rep2”. library(Seurat) library(SeuratData) InstallData("pbmc3k") pbmc <- LoadData("pbmc3k", type = "pbmc3k.final") # pretend that cells were originally assigned to one of two replicates (we assign randomly # here) if your cells do belong to multiple replicates, and you want to add this info to the # Seurat object create a data frame with this information (similar to replicate.info below) set.seed(42) pbmc$replicate <- sample(c("rep1", "rep2"), size = ncol(pbmc), replace = TRUE)

# How do I create a UMAP plot where cells are colored by replicate? First, store the current # identities in a new column of meta.data called CellType pbmc$CellType <- Idents(pbmc) # Next, switch the identity class of all cells to reflect replicate ID Idents(pbmc) <- "replicate" DimPlot(pbmc, reduction = "umap") # alternately : DimPlot(pbmc, reduction = 'umap', group.by = 'replicate') you can pass the # shape.by to label points by both replicate and cell type # Switch back to cell type labels Idents(pbmc) <- "CellType"

# alternately : DimPlot(pbmc, reduction = 'umap', group.by = 'replicate') you can pass the # shape.by to label points by both replicate and cell type # Switch back to cell type labels Idents(pbmc) <- "CellType"

# How can I calculate expression averages separately for each replicate? cluster.averages <- AverageExpression(pbmc, return.seurat = TRUE, add.ident = "replicate") CellScatter(cluster.averages, cell1 = "CD8_T_rep1", cell2 = "CD8_T_rep2") # You can also plot heatmaps of these 'in silico' bulk datasets to visualize agreement between # replicates DoHeatmap(cluster.averages, features = unlist(TopFeatures(pbmc[["pca"]], balanced = TRUE)), size = 3, draw.lines = FALSE)Session Info sessionInfo()## R version 4.2.0 (2022-04-22) ## Platform: x86_64-pc-linux-gnu (64-bit) ## Running under: Ubuntu 20.04.5 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/liblapack.so.3 ## ## locale: ## [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C ## [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8 ## [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 ## ## attached base packages: ## [1] stats graphics grDevices utils datasets methods base ## ## other attached packages: ## [1] thp1.eccite.SeuratData_3.1.5 stxBrain.SeuratData_0.1.1 ## [3] ssHippo.SeuratData_3.1.4 pbmcsca.SeuratData_3.0.0 ## [5] pbmcMultiome.SeuratData_0.1.2 pbmc3k.SeuratData_3.1.4 ## [7] panc8.SeuratData_3.0.2 ifnb.SeuratData_3.1.0 ## [9] hcabm40k.SeuratData_3.0.0 bmcite.SeuratData_0.3.0 ## [11] SeuratData_0.2.2 SeuratObject_4.1.3 ## [13] Seurat_4.3.0 ## ## loaded via a namespace (and not attached): ## [1] systemfonts_1.0.4 plyr_1.8.8 igraph_1.4.1 ## [4] lazyeval_0.2.2 sp_1.6-0 splines_4.2.0 ## [7] listenv_0.9.0 scattermore_0.8 ggplot2_3.4.1 ## [10] digest_0.6.31 htmltools_0.5.4 fansi_1.0.4 ## [13] magrittr_2.0.3 memoise_2.0.1 tensor_1.5 ## [16] cluster_2.1.3 ROCR_1.0-11 globals_0.16.2 ## [19] matrixStats_0.63.0 pkgdown_2.0.7 spatstat.sparse_3.0-0 ## [22] colorspace_2.1-0 rappdirs_0.3.3 ggrepel_0.9.3 ## [25] textshaping_0.3.6 xfun_0.37 dplyr_1.1.0 ## [28] crayon_1.5.2 jsonlite_1.8.4 progressr_0.13.0 ## [31] spatstat.data_3.0-0 survival_3.3-1 zoo_1.8-11 ## [34] glue_1.6.2 polyclip_1.10-4 gtable_0.3.1 ## [37] leiden_0.4.3 future.apply_1.10.0 abind_1.4-5 ## [40] scales_1.2.1 spatstat.random_3.1-3 miniUI_0.1.1.1 ## [43] Rcpp_1.0.10 viridisLite_0.4.1 xtable_1.8-4 ## [46] reticulate_1.28 htmlwidgets_1.6.1 httr_1.4.5 ## [49] RColorBrewer_1.1-3 ellipsis_0.3.2 ica_1.0-3 ## [52] farver_2.1.1 pkgconfig_2.0.3 sass_0.4.5 ## [55] uwot_0.1.14 deldir_1.0-6 utf8_1.2.3 ## [58] tidyselect_1.2.0 labeling_0.4.2 rlang_1.0.6 ## [61] reshape2_1.4.4 later_1.3.0 munsell_0.5.0 ## [64] tools_4.2.0 cachem_1.0.7 cli_3.6.0 ## [67] generics_0.1.3 ggridges_0.5.4 evaluate_0.20 ## [70] stringr_1.5.0 fastmap_1.1.1 yaml_2.3.7 ## [73] ragg_1.2.5 goftest_1.2-3 knitr_1.42 ## [76] fs_1.6.1 fitdistrplus_1.1-8 purrr_1.0.1 ## [79] RANN_2.6.1 pbapply_1.7-0 future_1.31.0 ## [82] nlme_3.1-157 mime_0.12 formatR_1.14 ## [85] compiler_4.2.0 plotly_4.10.1 png_0.1-8 ## [88] spatstat.utils_3.0-1 tibble_3.1.8 bslib_0.4.2 ## [91] stringi_1.7.12 highr_0.10 desc_1.4.2 ## [94] lattice_0.20-45 Matrix_1.5-3 vctrs_0.5.2 ## [97] pillar_1.8.1 lifecycle_1.0.3 spatstat.geom_3.0-6 ## [100] lmtest_0.9-40 jquerylib_0.1.4 RcppAnnoy_0.0.20 ## [103] data.table_1.14.8 cowplot_1.1.1 irlba_2.3.5.1 ## [106] httpuv_1.6.9 patchwork_1.1.2 R6_2.5.1 ## [109] promises_1.2.0.1 KernSmooth_2.23-20 gridExtra_2.3 ## [112] parallelly_1.34.0 codetools_0.2-18 MASS_7.3-56 ## [115] rprojroot_2.0.3 withr_2.5.0 sctransform_0.3.5 ## [118] parallel_4.2.0 grid_4.2.0 tidyr_1.3.0 ## [121] rmarkdown_2.20 Rtsne_0.16 spatstat.explore_3.0-6 ## [124] shiny_1.7.4

# You can also plot heatmaps of these 'in silico' bulk datasets to visualize agreement between # replicates DoHeatmap(cluster.averages, features = unlist(TopFeatures(pbmc[["pca"]], balanced = TRUE)), size = 3, draw.lines = FALSE)Session Info sessionInfo()## R version 4.2.0 (2022-04-22) ## Platform: x86_64-pc-linux-gnu (64-bit) ## Running under: Ubuntu 20.04.5 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/liblapack.so.3 ## ## locale: ## [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C ## [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8 ## [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 ## ## attached base packages: ## [1] stats graphics grDevices utils datasets methods base ## ## other attached packages: ## [1] thp1.eccite.SeuratData_3.1.5 stxBrain.SeuratData_0.1.1 ## [3] ssHippo.SeuratData_3.1.4 pbmcsca.SeuratData_3.0.0 ## [5] pbmcMultiome.SeuratData_0.1.2 pbmc3k.SeuratData_3.1.4 ## [7] panc8.SeuratData_3.0.2 ifnb.SeuratData_3.1.0 ## [9] hcabm40k.SeuratData_3.0.0 bmcite.SeuratData_0.3.0 ## [11] SeuratData_0.2.2 SeuratObject_4.1.3 ## [13] Seurat_4.3.0 ## ## loaded via a namespace (and not attached): ## [1] systemfonts_1.0.4 plyr_1.8.8 igraph_1.4.1 ## [4] lazyeval_0.2.2 sp_1.6-0 splines_4.2.0 ## [7] listenv_0.9.0 scattermore_0.8 ggplot2_3.4.1 ## [10] digest_0.6.31 htmltools_0.5.4 fansi_1.0.4 ## [13] magrittr_2.0.3 memoise_2.0.1 tensor_1.5 ## [16] cluster_2.1.3 ROCR_1.0-11 globals_0.16.2 ## [19] matrixStats_0.63.0 pkgdown_2.0.7 spatstat.sparse_3.0-0 ## [22] colorspace_2.1-0 rappdirs_0.3.3 ggrepel_0.9.3 ## [25] textshaping_0.3.6 xfun_0.37 dplyr_1.1.0 ## [28] crayon_1.5.2 jsonlite_1.8.4 progressr_0.13.0 ## [31] spatstat.data_3.0-0 survival_3.3-1 zoo_1.8-11 ## [34] glue_1.6.2 polyclip_1.10-4 gtable_0.3.1 ## [37] leiden_0.4.3 future.apply_1.10.0 abind_1.4-5 ## [40] scales_1.2.1 spatstat.random_3.1-3 miniUI_0.1.1.1 ## [43] Rcpp_1.0.10 viridisLite_0.4.1 xtable_1.8-4 ## [46] reticulate_1.28 htmlwidgets_1.6.1 httr_1.4.5 ## [49] RColorBrewer_1.1-3 ellipsis_0.3.2 ica_1.0-3 ## [52] farver_2.1.1 pkgconfig_2.0.3 sass_0.4.5 ## [55] uwot_0.1.14 deldir_1.0-6 utf8_1.2.3 ## [58] tidyselect_1.2.0 labeling_0.4.2 rlang_1.0.6 ## [61] reshape2_1.4.4 later_1.3.0 munsell_0.5.0 ## [64] tools_4.2.0 cachem_1.0.7 cli_3.6.0 ## [67] generics_0.1.3 ggridges_0.5.4 evaluate_0.20 ## [70] stringr_1.5.0 fastmap_1.1.1 yaml_2.3.7 ## [73] ragg_1.2.5 goftest_1.2-3 knitr_1.42 ## [76] fs_1.6.1 fitdistrplus_1.1-8 purrr_1.0.1 ## [79] RANN_2.6.1 pbapply_1.7-0 future_1.31.0 ## [82] nlme_3.1-157 mime_0.12 formatR_1.14 ## [85] compiler_4.2.0 plotly_4.10.1 png_0.1-8 ## [88] spatstat.utils_3.0-1 tibble_3.1.8 bslib_0.4.2 ## [91] stringi_1.7.12 highr_0.10 desc_1.4.2 ## [94] lattice_0.20-45 Matrix_1.5-3 vctrs_0.5.2 ## [97] pillar_1.8.1 lifecycle_1.0.3 spatstat.geom_3.0-6 ## [100] lmtest_0.9-40 jquerylib_0.1.4 RcppAnnoy_0.0.20 ## [103] data.table_1.14.8 cowplot_1.1.1 irlba_2.3.5.1 ## [106] httpuv_1.6.9 patchwork_1.1.2 R6_2.5.1 ## [109] promises_1.2.0.1 KernSmooth_2.23-20 gridExtra_2.3 ## [112] parallelly_1.34.0 codetools_0.2-18 MASS_7.3-56 ## [115] rprojroot_2.0.3 withr_2.5.0 sctransform_0.3.5 ## [118] parallel_4.2.0 grid_4.2.0 tidyr_1.3.0 ## [121] rmarkdown_2.20 Rtsne_0.16 spatstat.explore_3.0-6 ## [124] shiny_1.7.4

Session Info sessionInfo()## R version 4.2.0 (2022-04-22) ## Platform: x86_64-pc-linux-gnu (64-bit) ## Running under: Ubuntu 20.04.5 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/liblapack.so.3 ## ## locale: ## [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C ## [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8 ## [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 ## ## attached base packages: ## [1] stats graphics grDevices utils datasets methods base ## ## other attached packages: ## [1] thp1.eccite.SeuratData_3.1.5 stxBrain.SeuratData_0.1.1 ## [3] ssHippo.SeuratData_3.1.4 pbmcsca.SeuratData_3.0.0 ## [5] pbmcMultiome.SeuratData_0.1.2 pbmc3k.SeuratData_3.1.4 ## [7] panc8.SeuratData_3.0.2 ifnb.SeuratData_3.1.0 ## [9] hcabm40k.SeuratData_3.0.0 bmcite.SeuratData_0.3.0 ## [11] SeuratData_0.2.2 SeuratObject_4.1.3 ## [13] Seurat_4.3.0 ## ## loaded via a namespace (and not attached): ## [1] systemfonts_1.0.4 plyr_1.8.8 igraph_1.4.1 ## [4] lazyeval_0.2.2 sp_1.6-0 splines_4.2.0 ## [7] listenv_0.9.0 scattermore_0.8 ggplot2_3.4.1 ## [10] digest_0.6.31 htmltools_0.5.4 fansi_1.0.4 ## [13] magrittr_2.0.3 memoise_2.0.1 tensor_1.5 ## [16] cluster_2.1.3 ROCR_1.0-11 globals_0.16.2 ## [19] matrixStats_0.63.0 pkgdown_2.0.7 spatstat.sparse_3.0-0 ## [22] colorspace_2.1-0 rappdirs_0.3.3 ggrepel_0.9.3 ## [25] textshaping_0.3.6 xfun_0.37 dplyr_1.1.0 ## [28] crayon_1.5.2 jsonlite_1.8.4 progressr_0.13.0 ## [31] spatstat.data_3.0-0 survival_3.3-1 zoo_1.8-11 ## [34] glue_1.6.2 polyclip_1.10-4 gtable_0.3.1 ## [37] leiden_0.4.3 future.apply_1.10.0 abind_1.4-5 ## [40] scales_1.2.1 spatstat.random_3.1-3 miniUI_0.1.1.1 ## [43] Rcpp_1.0.10 viridisLite_0.4.1 xtable_1.8-4 ## [46] reticulate_1.28 htmlwidgets_1.6.1 httr_1.4.5 ## [49] RColorBrewer_1.1-3 ellipsis_0.3.2 ica_1.0-3 ## [52] farver_2.1.1 pkgconfig_2.0.3 sass_0.4.5 ## [55] uwot_0.1.14 deldir_1.0-6 utf8_1.2.3 ## [58] tidyselect_1.2.0 labeling_0.4.2 rlang_1.0.6 ## [61] reshape2_1.4.4 later_1.3.0 munsell_0.5.0 ## [64] tools_4.2.0 cachem_1.0.7 cli_3.6.0 ## [67] generics_0.1.3 ggridges_0.5.4 evaluate_0.20 ## [70] stringr_1.5.0 fastmap_1.1.1 yaml_2.3.7 ## [73] ragg_1.2.5 goftest_1.2-3 knitr_1.42 ## [76] fs_1.6.1 fitdistrplus_1.1-8 purrr_1.0.1 ## [79] RANN_2.6.1 pbapply_1.7-0 future_1.31.0 ## [82] nlme_3.1-157 mime_0.12 formatR_1.14 ## [85] compiler_4.2.0 plotly_4.10.1 png_0.1-8 ## [88] spatstat.utils_3.0-1 tibble_3.1.8 bslib_0.4.2 ## [91] stringi_1.7.12 highr_0.10 desc_1.4.2 ## [94] lattice_0.20-45 Matrix_1.5-3 vctrs_0.5.2 ## [97] pillar_1.8.1 lifecycle_1.0.3 spatstat.geom_3.0-6 ## [100] lmtest_0.9-40 jquerylib_0.1.4 RcppAnnoy_0.0.20 ## [103] data.table_1.14.8 cowplot_1.1.1 irlba_2.3.5.1 ## [106] httpuv_1.6.9 patchwork_1.1.2 R6_2.5.1 ## [109] promises_1.2.0.1 KernSmooth_2.23-20 gridExtra_2.3 ## [112] parallelly_1.34.0 codetools_0.2-18 MASS_7.3-56 ## [115] rprojroot_2.0.3 withr_2.5.0 sctransform_0.3.5 ## [118] parallel_4.2.0 grid_4.2.0 tidyr_1.3.0 ## [121] rmarkdown_2.20 Rtsne_0.16 spatstat.explore_3.0-6 ## [124] shiny_1.7.4

sessionInfo()## R version 4.2.0 (2022-04-22) ## Platform: x86_64-pc-linux-gnu (64-bit) ## Running under: Ubuntu 20.04.5 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/liblapack.so.3 ## ## locale: ## [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C ## [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8 ## [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 ## ## attached base packages: ## [1] stats graphics grDevices utils datasets methods base ## ## other attached packages: ## [1] thp1.eccite.SeuratData_3.1.5 stxBrain.SeuratData_0.1.1 ## [3] ssHippo.SeuratData_3.1.4 pbmcsca.SeuratData_3.0.0 ## [5] pbmcMultiome.SeuratData_0.1.2 pbmc3k.SeuratData_3.1.4 ## [7] panc8.SeuratData_3.0.2 ifnb.SeuratData_3.1.0 ## [9] hcabm40k.SeuratData_3.0.0 bmcite.SeuratData_0.3.0 ## [11] SeuratData_0.2.2 SeuratObject_4.1.3 ## [13] Seurat_4.3.0 ## ## loaded via a namespace (and not attached): ## [1] systemfonts_1.0.4 plyr_1.8.8 igraph_1.4.1 ## [4] lazyeval_0.2.2 sp_1.6-0 splines_4.2.0 ## [7] listenv_0.9.0 scattermore_0.8 ggplot2_3.4.1 ## [10] digest_0.6.31 htmltools_0.5.4 fansi_1.0.4 ## [13] magrittr_2.0.3 memoise_2.0.1 tensor_1.5 ## [16] cluster_2.1.3 ROCR_1.0-11 globals_0.16.2 ## [19] matrixStats_0.63.0 pkgdown_2.0.7 spatstat.sparse_3.0-0 ## [22] colorspace_2.1-0 rappdirs_0.3.3 ggrepel_0.9.3 ## [25] textshaping_0.3.6 xfun_0.37 dplyr_1.1.0 ## [28] crayon_1.5.2 jsonlite_1.8.4 progressr_0.13.0 ## [31] spatstat.data_3.0-0 survival_3.3-1 zoo_1.8-11 ## [34] glue_1.6.2 polyclip_1.10-4 gtable_0.3.1 ## [37] leiden_0.4.3 future.apply_1.10.0 abind_1.4-5 ## [40] scales_1.2.1 spatstat.random_3.1-3 miniUI_0.1.1.1 ## [43] Rcpp_1.0.10 viridisLite_0.4.1 xtable_1.8-4 ## [46] reticulate_1.28 htmlwidgets_1.6.1 httr_1.4.5 ## [49] RColorBrewer_1.1-3 ellipsis_0.3.2 ica_1.0-3 ## [52] farver_2.1.1 pkgconfig_2.0.3 sass_0.4.5 ## [55] uwot_0.1.14 deldir_1.0-6 utf8_1.2.3 ## [58] tidyselect_1.2.0 labeling_0.4.2 rlang_1.0.6 ## [61] reshape2_1.4.4 later_1.3.0 munsell_0.5.0 ## [64] tools_4.2.0 cachem_1.0.7 cli_3.6.0 ## [67] generics_0.1.3 ggridges_0.5.4 evaluate_0.20 ## [70] stringr_1.5.0 fastmap_1.1.1 yaml_2.3.7 ## [73] ragg_1.2.5 goftest_1.2-3 knitr_1.42 ## [76] fs_1.6.1 fitdistrplus_1.1-8 purrr_1.0.1 ## [79] RANN_2.6.1 pbapply_1.7-0 future_1.31.0 ## [82] nlme_3.1-157 mime_0.12 formatR_1.14 ## [85] compiler_4.2.0 plotly_4.10.1 png_0.1-8 ## [88] spatstat.utils_3.0-1 tibble_3.1.8 bslib_0.4.2 ## [91] stringi_1.7.12 highr_0.10 desc_1.4.2 ## [94] lattice_0.20-45 Matrix_1.5-3 vctrs_0.5.2 ## [97] pillar_1.8.1 lifecycle_1.0.3 spatstat.geom_3.0-6 ## [100] lmtest_0.9-40 jquerylib_0.1.4 RcppAnnoy_0.0.20 ## [103] data.table_1.14.8 cowplot_1.1.1 irlba_2.3.5.1 ## [106] httpuv_1.6.9 patchwork_1.1.2 R6_2.5.1 ## [109] promises_1.2.0.1 KernSmooth_2.23-20 gridExtra_2.3 ## [112] parallelly_1.34.0 codetools_0.2-18 MASS_7.3-56 ## [115] rprojroot_2.0.3 withr_2.5.0 sctransform_0.3.5 ## [118] parallel_4.2.0 grid_4.2.0 tidyr_1.3.0 ## [121] rmarkdown_2.20 Rtsne_0.16 spatstat.explore_3.0-6 ## [124] shiny_1.7.4

Developed by Paul Hoffman, Satija Lab and Collaborators.

Developed by Paul Hoffman, Satija Lab and Collaborators.

Site built with pkgdown 2.0.7.

Site built with pkgdown 2.0.7.

**Examples:**

Example 1 (unknown):
```unknown
vignettes/interaction_vignette.Rmd
```

Example 2 (unknown):
```unknown
interaction_vignette.Rmd
```

Example 3 (unknown):
```unknown
library(Seurat)
library(SeuratData)
InstallData("pbmc3k")
pbmc <- LoadData("pbmc3k", type = "pbmc3k.final")

# pretend that cells were originally assigned to one of two replicates (we assign randomly
# here) if your cells do belong to multiple replicates, and you want to add this info to the
# Seurat object create a data frame with this information (similar to replicate.info below)
set.seed(42)
pbmc$replicate <- sample(c("rep1", "rep2"), size = ncol(pbmc), replace = TRUE)
```

Example 4 (r):
```r
library(Seurat)
library(SeuratData)
InstallData("pbmc3k")
pbmc <- LoadData("pbmc3k", type = "pbmc3k.final")

# pretend that cells were originally assigned to one of two replicates (we assign randomly
# here) if your cells do belong to multiple replicates, and you want to add this info to the
# Seurat object create a data frame with this information (similar to replicate.info below)
set.seed(42)
pbmc$replicate <- sample(c("rep1", "rep2"), size = ncol(pbmc), replace = TRUE)
```

Example 5 (r):
```r
library(Seurat)
library(SeuratData)
InstallData("pbmc3k")
pbmc <- LoadData("pbmc3k", type = "pbmc3k.final")

# pretend that cells were originally assigned to one of two replicates (we assign randomly
# here) if your cells do belong to multiple replicates, and you want to add this info to the
# Seurat object create a data frame with this information (similar to replicate.info below)
set.seed(42)
pbmc$replicate <- sample(c("rep1", "rep2"), size = ncol(pbmc), replace = TRUE)
```

Example 6 (unknown):
```unknown
# Plot UMAP, coloring cells by cell type (currently stored in object@ident)
DimPlot(pbmc, reduction = "umap")
```

Example 7 (r):
```r
# Plot UMAP, coloring cells by cell type (currently stored in object@ident)
DimPlot(pbmc, reduction = "umap")
```

Example 8 (r):
```r
# Plot UMAP, coloring cells by cell type (currently stored in object@ident)
DimPlot(pbmc, reduction = "umap")
```

Example 9 (python):
```python
# How do I create a UMAP plot where cells are colored by replicate?  First, store the current
# identities in a new column of meta.data called CellType
pbmc$CellType <- Idents(pbmc)
# Next, switch the identity class of all cells to reflect replicate ID
Idents(pbmc) <- "replicate"
DimPlot(pbmc, reduction = "umap")
```

Example 10 (r):
```r
# How do I create a UMAP plot where cells are colored by replicate?  First, store the current
# identities in a new column of meta.data called CellType
pbmc$CellType <- Idents(pbmc)
# Next, switch the identity class of all cells to reflect replicate ID
Idents(pbmc) <- "replicate"
DimPlot(pbmc, reduction = "umap")
```

Example 11 (r):
```r
# How do I create a UMAP plot where cells are colored by replicate?  First, store the current
# identities in a new column of meta.data called CellType
pbmc$CellType <- Idents(pbmc)
# Next, switch the identity class of all cells to reflect replicate ID
Idents(pbmc) <- "replicate"
DimPlot(pbmc, reduction = "umap")
```

Example 12 (unknown):
```unknown
# alternately : DimPlot(pbmc, reduction = 'umap', group.by = 'replicate') you can pass the
# shape.by to label points by both replicate and cell type

# Switch back to cell type labels
Idents(pbmc) <- "CellType"
```

Example 13 (r):
```r
# alternately : DimPlot(pbmc, reduction = 'umap', group.by = 'replicate') you can pass the
# shape.by to label points by both replicate and cell type

# Switch back to cell type labels
Idents(pbmc) <- "CellType"
```

Example 14 (r):
```r
# alternately : DimPlot(pbmc, reduction = 'umap', group.by = 'replicate') you can pass the
# shape.by to label points by both replicate and cell type

# Switch back to cell type labels
Idents(pbmc) <- "CellType"
```

Example 15 (unknown):
```unknown
# How many cells are in each cluster
table(Idents(pbmc))
```

Example 16 (r):
```r
# How many cells are in each cluster
table(Idents(pbmc))
```

Example 17 (r):
```r
# How many cells are in each cluster
table(Idents(pbmc))
```

Example 18 (javascript):
```javascript
## 
##  Naive CD4 T Memory CD4 T   CD14+ Mono            B        CD8 T FCGR3A+ Mono 
##          697          483          480          344          271          162 
##           NK           DC     Platelet 
##          155           32           14
```

Example 19 (javascript):
```javascript
## 
##  Naive CD4 T Memory CD4 T   CD14+ Mono            B        CD8 T FCGR3A+ Mono 
##          697          483          480          344          271          162 
##           NK           DC     Platelet 
##          155           32           14
```

Example 20 (unknown):
```unknown
# How many cells are in each replicate?
table(pbmc$replicate)
```

Example 21 (r):
```r
# How many cells are in each replicate?
table(pbmc$replicate)
```

Example 22 (r):
```r
# How many cells are in each replicate?
table(pbmc$replicate)
```

Example 23 (unknown):
```unknown
## 
## rep1 rep2 
## 1348 1290
```

Example 24 (unknown):
```unknown
## 
## rep1 rep2 
## 1348 1290
```

Example 25 (unknown):
```unknown
# What proportion of cells are in each cluster?
prop.table(table(Idents(pbmc)))
```

Example 26 (r):
```r
# What proportion of cells are in each cluster?
prop.table(table(Idents(pbmc)))
```

Example 27 (r):
```r
# What proportion of cells are in each cluster?
prop.table(table(Idents(pbmc)))
```

Example 28 (javascript):
```javascript
## 
##  Naive CD4 T Memory CD4 T   CD14+ Mono            B        CD8 T FCGR3A+ Mono 
##  0.264215315  0.183093252  0.181956027  0.130401820  0.102729340  0.061410159 
##           NK           DC     Platelet 
##  0.058756634  0.012130402  0.005307051
```

Example 29 (javascript):
```javascript
## 
##  Naive CD4 T Memory CD4 T   CD14+ Mono            B        CD8 T FCGR3A+ Mono 
##  0.264215315  0.183093252  0.181956027  0.130401820  0.102729340  0.061410159 
##           NK           DC     Platelet 
##  0.058756634  0.012130402  0.005307051
```

Example 30 (unknown):
```unknown
# How does cluster membership vary by replicate?
table(Idents(pbmc), pbmc$replicate)
```

Example 31 (r):
```r
# How does cluster membership vary by replicate?
table(Idents(pbmc), pbmc$replicate)
```

Example 32 (r):
```r
# How does cluster membership vary by replicate?
table(Idents(pbmc), pbmc$replicate)
```

Example 33 (javascript):
```javascript
##               
##                rep1 rep2
##   Naive CD4 T   354  343
##   Memory CD4 T  249  234
##   CD14+ Mono    232  248
##   B             173  171
##   CD8 T         154  117
##   FCGR3A+ Mono   81   81
##   NK             81   74
##   DC             18   14
##   Platelet        6    8
```

Example 34 (javascript):
```javascript
##               
##                rep1 rep2
##   Naive CD4 T   354  343
##   Memory CD4 T  249  234
##   CD14+ Mono    232  248
##   B             173  171
##   CD8 T         154  117
##   FCGR3A+ Mono   81   81
##   NK             81   74
##   DC             18   14
##   Platelet        6    8
```

Example 35 (unknown):
```unknown
prop.table(table(Idents(pbmc), pbmc$replicate), margin = 2)
```

Example 36 (r):
```r
prop.table(table(Idents(pbmc), pbmc$replicate), margin = 2)
```

Example 37 (r):
```r
prop.table(table(Idents(pbmc), pbmc$replicate), margin = 2)
```

Example 38 (javascript):
```javascript
##               
##                       rep1        rep2
##   Naive CD4 T  0.262611276 0.265891473
##   Memory CD4 T 0.184718101 0.181395349
##   CD14+ Mono   0.172106825 0.192248062
##   B            0.128338279 0.132558140
##   CD8 T        0.114243323 0.090697674
##   FCGR3A+ Mono 0.060089021 0.062790698
##   NK           0.060089021 0.057364341
##   DC           0.013353116 0.010852713
##   Platelet     0.004451039 0.006201550
```

Example 39 (javascript):
```javascript
##               
##                       rep1        rep2
##   Naive CD4 T  0.262611276 0.265891473
##   Memory CD4 T 0.184718101 0.181395349
##   CD14+ Mono   0.172106825 0.192248062
##   B            0.128338279 0.132558140
##   CD8 T        0.114243323 0.090697674
##   FCGR3A+ Mono 0.060089021 0.062790698
##   NK           0.060089021 0.057364341
##   DC           0.013353116 0.010852713
##   Platelet     0.004451039 0.006201550
```

Example 40 (unknown):
```unknown
# What are the cell names of all NK cells?
WhichCells(pbmc, idents = "NK")
```

Example 41 (r):
```r
# What are the cell names of all NK cells?
WhichCells(pbmc, idents = "NK")
```

Example 42 (r):
```r
# What are the cell names of all NK cells?
WhichCells(pbmc, idents = "NK")
```

Example 43 (unknown):
```unknown
##   [1] "AAACCGTGTATGCG" "AAATTCGATTCTCA" "AACCTTACGCGAGA" "AACGCCCTCGTACA"
##   [5] "AACGTCGAGTATCG" "AAGATTACCTCAAG" "AAGCAAGAGCTTAG" "AAGCAAGAGGTGTT"
##   [9] "AAGTAGGATACAGC" "AATACTGAATTGGC" "AATCCTTGGTGAGG" "AATCTCTGCTTTAC"
##  [13] "ACAAATTGTTGCGA" "ACAACCGAGGGATG" "ACAATTGATGACTG" "ACACCCTGGTGTTG"
##  [17] "ACAGGTACTGGTGT" "ACCTGGCTAAGTAG" "ACGAACACCTTGTT" "ACGATCGAGGACTT"
##  [21] "ACGCAATGGTTCAG" "ACGCTGCTGTTCTT" "ACGGAACTCAGATC" "ACGTGATGTGACAC"
##  [25] "ACGTTGGAGCCAAT" "ACTGCCACTCCGTC" "ACTGGCCTTCAGTG" "ACTTCAACGTAGGG"
##  [29] "AGAACAGAAATGCC" "AGATATACCCGTAA" "AGATTCCTGTTCAG" "AGCCTCTGCCAATG"
##  [33] "AGCGATTGAGATCC" "AGGATGCTTTAGGC" "AGGGACGAGTCAAC" "AGTAATACATCACG"
##  [37] "AGTCACGATGAGCT" "AGTTTGCTACTGGT" "ATACCACTGCCAAT" "ATACTCTGGTATGC"
##  [41] "ATCCCGTGCAGTCA" "ATCTTTCTTGTCCC" "ATGAAGGACTTGCC" "ATGATAACTTCACT"
##  [45] "ATGATATGGTGCTA" "ATGGACACGCATCA" "ATGGGTACATCGGT" "ATTAACGATGAGAA"
##  [49] "ATTCCAACTTAGGC" "CAAGGTTGTCTGGA" "CAATCTACTGACTG" "CACCACTGGCGAAG"
##  [53] "CACGGGTGGAGGAC" "CAGATGACATTCTC" "CAGCAATGGAGGGT" "CAGCGGACCTTTAC"
##  [57] "CAGCTCTGTGTGGT" "CAGTTTACACACGT" "CATCAGGACTTCCG" "CATCAGGATAGCCA"
##  [61] "CATGAGACGTTGAC" "CATTACACCAACTG" "CATTTCGAGATACC" "CCTCGAACACTTTC"
##  [65] "CGACCACTAAAGTG" "CGACCACTGCCAAT" "CGAGGCTGACGCTA" "CGCCGAGAGCTTAG"
##  [69] "CGGCGAACGACAAA" "CGGCGAACTACTTC" "CGGGCATGTCTCTA" "CGTACCTGGCATCA"
##  [73] "CGTGTAGACGATAC" "CGTGTAGAGTTACG" "CGTGTAGATTCGGA" "CTAAACCTCTGACA"
##  [77] "CTAACGGAACCGAT" "CTACGCACTGGTCA" "CTACTCCTATGTCG" "CTAGTTACGAAACA"
##  [81] "CTATACTGCTACGA" "CTATACTGTCTCAT" "CTCGACTGGTTGAC" "CTGAGAACGTAAAG"
##  [85] "CTTTAGTGACGGGA" "GAACCAACTTCCGC" "GAAGTGCTAAACGA" "GAATGCACCTTCGC"
##  [89] "GAATTAACGTCGTA" "GACGGCACACGGGA" "GAGCGCTGAAGATG" "GAGGTACTGACACT"
##  [93] "GAGGTGGATCCTCG" "GATAGAGAAGGGTG" "GATCCCTGACCTTT" "GCACACCTGTGCTA"
##  [97] "GCACCACTTCCTTA" "GCACTAGAGTCGTA" "GCAGGGCTATCGAC" "GCCGGAACGTTCTT"
## [101] "GCCTACACAGTTCG" "GCGCATCTTGCTCC" "GCGCGATGGTGCAT" "GGAAGGTGGCGAGA"
## [105] "GGACGCTGTCCTCG" "GGAGGCCTCGTTGA" "GGCAAGGAAAAAGC" "GGCATATGCTTATC"
## [109] "GGCCGAACTCTAGG" "GGCTAAACACCTGA" "GGGTTAACGTGCAT" "GGTGGAGAAACGGG"
## [113] "GTAGTGTGAGCGGA" "GTCGACCTGAATGA" "GTGATTCTGGTTCA" "GTGTATCTAGTAGA"
## [117] "GTTAAAACCGAGAG" "GTTCAACTGGGACA" "GTTGACGATATCGG" "TAACTCACTCTACT"
## [121] "TAAGAGGACTTGTT" "TAATGCCTCGTCTC" "TACGGCCTGGGACA" "TACTACTGATGTCG"
## [125] "TACTCTGAATCGAC" "TACTGTTGAGGCGA" "TAGCATCTCAGCTA" "TAGCCCACAGCTAC"
## [129] "TAGGGACTGAACTC" "TAGTGGTGAAGTGA" "TAGTTAGAACCACA" "TATGAATGGAGGAC"
## [133] "TATGGGTGCATCAG" "TATTTCCTGGAGGT" "TCAACACTGTTTGG" "TCAGACGACGTTAG"
## [137] "TCCCGAACACAGTC" "TCCTAAACCGCATA" "TCGATTTGCAGCTA" "TCTAACACCAGTTG"
## [141] "TGATAAACTCCGTC" "TGCACAGACGACAT" "TGCCACTGCGATAC" "TGCTGAGAGAGCAG"
## [145] "TGGAACACAAACAG" "TGGTAGACCCTCAC" "TGTAATGACACAAC" "TGTAATGAGGTAAA"
## [149] "TTACTCGATCTACT" "TTAGTCTGCCAACA" "TTCCAAACTCCCAC" "TTCCCACTTGAGGG"
## [153] "TTCTAGTGGAGAGC" "TTCTGATGGAGACG" "TTGTCATGGACGGA"
```

Example 44 (unknown):
```unknown
##   [1] "AAACCGTGTATGCG" "AAATTCGATTCTCA" "AACCTTACGCGAGA" "AACGCCCTCGTACA"
##   [5] "AACGTCGAGTATCG" "AAGATTACCTCAAG" "AAGCAAGAGCTTAG" "AAGCAAGAGGTGTT"
##   [9] "AAGTAGGATACAGC" "AATACTGAATTGGC" "AATCCTTGGTGAGG" "AATCTCTGCTTTAC"
##  [13] "ACAAATTGTTGCGA" "ACAACCGAGGGATG" "ACAATTGATGACTG" "ACACCCTGGTGTTG"
##  [17] "ACAGGTACTGGTGT" "ACCTGGCTAAGTAG" "ACGAACACCTTGTT" "ACGATCGAGGACTT"
##  [21] "ACGCAATGGTTCAG" "ACGCTGCTGTTCTT" "ACGGAACTCAGATC" "ACGTGATGTGACAC"
##  [25] "ACGTTGGAGCCAAT" "ACTGCCACTCCGTC" "ACTGGCCTTCAGTG" "ACTTCAACGTAGGG"
##  [29] "AGAACAGAAATGCC" "AGATATACCCGTAA" "AGATTCCTGTTCAG" "AGCCTCTGCCAATG"
##  [33] "AGCGATTGAGATCC" "AGGATGCTTTAGGC" "AGGGACGAGTCAAC" "AGTAATACATCACG"
##  [37] "AGTCACGATGAGCT" "AGTTTGCTACTGGT" "ATACCACTGCCAAT" "ATACTCTGGTATGC"
##  [41] "ATCCCGTGCAGTCA" "ATCTTTCTTGTCCC" "ATGAAGGACTTGCC" "ATGATAACTTCACT"
##  [45] "ATGATATGGTGCTA" "ATGGACACGCATCA" "ATGGGTACATCGGT" "ATTAACGATGAGAA"
##  [49] "ATTCCAACTTAGGC" "CAAGGTTGTCTGGA" "CAATCTACTGACTG" "CACCACTGGCGAAG"
##  [53] "CACGGGTGGAGGAC" "CAGATGACATTCTC" "CAGCAATGGAGGGT" "CAGCGGACCTTTAC"
##  [57] "CAGCTCTGTGTGGT" "CAGTTTACACACGT" "CATCAGGACTTCCG" "CATCAGGATAGCCA"
##  [61] "CATGAGACGTTGAC" "CATTACACCAACTG" "CATTTCGAGATACC" "CCTCGAACACTTTC"
##  [65] "CGACCACTAAAGTG" "CGACCACTGCCAAT" "CGAGGCTGACGCTA" "CGCCGAGAGCTTAG"
##  [69] "CGGCGAACGACAAA" "CGGCGAACTACTTC" "CGGGCATGTCTCTA" "CGTACCTGGCATCA"
##  [73] "CGTGTAGACGATAC" "CGTGTAGAGTTACG" "CGTGTAGATTCGGA" "CTAAACCTCTGACA"
##  [77] "CTAACGGAACCGAT" "CTACGCACTGGTCA" "CTACTCCTATGTCG" "CTAGTTACGAAACA"
##  [81] "CTATACTGCTACGA" "CTATACTGTCTCAT" "CTCGACTGGTTGAC" "CTGAGAACGTAAAG"
##  [85] "CTTTAGTGACGGGA" "GAACCAACTTCCGC" "GAAGTGCTAAACGA" "GAATGCACCTTCGC"
##  [89] "GAATTAACGTCGTA" "GACGGCACACGGGA" "GAGCGCTGAAGATG" "GAGGTACTGACACT"
##  [93] "GAGGTGGATCCTCG" "GATAGAGAAGGGTG" "GATCCCTGACCTTT" "GCACACCTGTGCTA"
##  [97] "GCACCACTTCCTTA" "GCACTAGAGTCGTA" "GCAGGGCTATCGAC" "GCCGGAACGTTCTT"
## [101] "GCCTACACAGTTCG" "GCGCATCTTGCTCC" "GCGCGATGGTGCAT" "GGAAGGTGGCGAGA"
## [105] "GGACGCTGTCCTCG" "GGAGGCCTCGTTGA" "GGCAAGGAAAAAGC" "GGCATATGCTTATC"
## [109] "GGCCGAACTCTAGG" "GGCTAAACACCTGA" "GGGTTAACGTGCAT" "GGTGGAGAAACGGG"
## [113] "GTAGTGTGAGCGGA" "GTCGACCTGAATGA" "GTGATTCTGGTTCA" "GTGTATCTAGTAGA"
## [117] "GTTAAAACCGAGAG" "GTTCAACTGGGACA" "GTTGACGATATCGG" "TAACTCACTCTACT"
## [121] "TAAGAGGACTTGTT" "TAATGCCTCGTCTC" "TACGGCCTGGGACA" "TACTACTGATGTCG"
## [125] "TACTCTGAATCGAC" "TACTGTTGAGGCGA" "TAGCATCTCAGCTA" "TAGCCCACAGCTAC"
## [129] "TAGGGACTGAACTC" "TAGTGGTGAAGTGA" "TAGTTAGAACCACA" "TATGAATGGAGGAC"
## [133] "TATGGGTGCATCAG" "TATTTCCTGGAGGT" "TCAACACTGTTTGG" "TCAGACGACGTTAG"
## [137] "TCCCGAACACAGTC" "TCCTAAACCGCATA" "TCGATTTGCAGCTA" "TCTAACACCAGTTG"
## [141] "TGATAAACTCCGTC" "TGCACAGACGACAT" "TGCCACTGCGATAC" "TGCTGAGAGAGCAG"
## [145] "TGGAACACAAACAG" "TGGTAGACCCTCAC" "TGTAATGACACAAC" "TGTAATGAGGTAAA"
## [149] "TTACTCGATCTACT" "TTAGTCTGCCAACA" "TTCCAAACTCCCAC" "TTCCCACTTGAGGG"
## [153] "TTCTAGTGGAGAGC" "TTCTGATGGAGACG" "TTGTCATGGACGGA"
```

Example 45 (python):
```python
# How can I extract expression matrix for all NK cells (perhaps, to load into another package)
nk.raw.data <- as.matrix(GetAssayData(pbmc, slot = "counts")[, WhichCells(pbmc, ident = "NK")])

# Can I create a Seurat object based on expression of a feature or value in object metadata?
subset(pbmc, subset = MS4A1 > 1)
```

Example 46 (r):
```r
# How can I extract expression matrix for all NK cells (perhaps, to load into another package)
nk.raw.data <- as.matrix(GetAssayData(pbmc, slot = "counts")[, WhichCells(pbmc, ident = "NK")])

# Can I create a Seurat object based on expression of a feature or value in object metadata?
subset(pbmc, subset = MS4A1 > 1)
```

Example 47 (r):
```r
# How can I extract expression matrix for all NK cells (perhaps, to load into another package)
nk.raw.data <- as.matrix(GetAssayData(pbmc, slot = "counts")[, WhichCells(pbmc, ident = "NK")])

# Can I create a Seurat object based on expression of a feature or value in object metadata?
subset(pbmc, subset = MS4A1 > 1)
```

Example 48 (python):
```python
## An object of class Seurat 
## 13714 features across 414 samples within 1 assay 
## Active assay: RNA (13714 features, 2000 variable features)
##  2 dimensional reductions calculated: pca, umap
```

Example 49 (python):
```python
## An object of class Seurat 
## 13714 features across 414 samples within 1 assay 
## Active assay: RNA (13714 features, 2000 variable features)
##  2 dimensional reductions calculated: pca, umap
```

Example 50 (unknown):
```unknown
subset(pbmc, subset = replicate == "rep2")
```

Example 51 (r):
```r
subset(pbmc, subset = replicate == "rep2")
```

Example 52 (r):
```r
subset(pbmc, subset = replicate == "rep2")
```

Example 53 (python):
```python
## An object of class Seurat 
## 13714 features across 1290 samples within 1 assay 
## Active assay: RNA (13714 features, 2000 variable features)
##  2 dimensional reductions calculated: pca, umap
```

Example 54 (python):
```python
## An object of class Seurat 
## 13714 features across 1290 samples within 1 assay 
## Active assay: RNA (13714 features, 2000 variable features)
##  2 dimensional reductions calculated: pca, umap
```

Example 55 (unknown):
```unknown
# Can I create a Seurat object of just the NK cells and B cells?
subset(pbmc, idents = c("NK", "B"))
```

Example 56 (r):
```r
# Can I create a Seurat object of just the NK cells and B cells?
subset(pbmc, idents = c("NK", "B"))
```

Example 57 (r):
```r
# Can I create a Seurat object of just the NK cells and B cells?
subset(pbmc, idents = c("NK", "B"))
```

Example 58 (python):
```python
## An object of class Seurat 
## 13714 features across 499 samples within 1 assay 
## Active assay: RNA (13714 features, 2000 variable features)
##  2 dimensional reductions calculated: pca, umap
```

Example 59 (python):
```python
## An object of class Seurat 
## 13714 features across 499 samples within 1 assay 
## Active assay: RNA (13714 features, 2000 variable features)
##  2 dimensional reductions calculated: pca, umap
```

Example 60 (unknown):
```unknown
# Can I create a Seurat object of all cells except the NK cells and B cells?
subset(pbmc, idents = c("NK", "B"), invert = TRUE)
```

Example 61 (r):
```r
# Can I create a Seurat object of all cells except the NK cells and B cells?
subset(pbmc, idents = c("NK", "B"), invert = TRUE)
```

Example 62 (r):
```r
# Can I create a Seurat object of all cells except the NK cells and B cells?
subset(pbmc, idents = c("NK", "B"), invert = TRUE)
```

Example 63 (python):
```python
## An object of class Seurat 
## 13714 features across 2139 samples within 1 assay 
## Active assay: RNA (13714 features, 2000 variable features)
##  2 dimensional reductions calculated: pca, umap
```

Example 64 (python):
```python
## An object of class Seurat 
## 13714 features across 2139 samples within 1 assay 
## Active assay: RNA (13714 features, 2000 variable features)
##  2 dimensional reductions calculated: pca, umap
```

Example 65 (unknown):
```unknown
# note that if you wish to perform additional rounds of clustering after subsetting we
# recommend re-running FindVariableFeatures() and ScaleData()
```

Example 66 (r):
```r
# note that if you wish to perform additional rounds of clustering after subsetting we
# recommend re-running FindVariableFeatures() and ScaleData()
```

Example 67 (r):
```r
# note that if you wish to perform additional rounds of clustering after subsetting we
# recommend re-running FindVariableFeatures() and ScaleData()
```

Example 68 (unknown):
```unknown
# How can I calculate the average expression of all cells within a cluster?
cluster.averages <- AverageExpression(pbmc)
head(cluster.averages[["RNA"]][, 1:5])
```

Example 69 (r):
```r
# How can I calculate the average expression of all cells within a cluster?
cluster.averages <- AverageExpression(pbmc)
head(cluster.averages[["RNA"]][, 1:5])
```

Example 70 (r):
```r
# How can I calculate the average expression of all cells within a cluster?
cluster.averages <- AverageExpression(pbmc)
head(cluster.averages[["RNA"]][, 1:5])
```

Example 71 (unknown):
```unknown
##               Naive CD4 T Memory CD4 T CD14+ Mono          B      CD8 T
## AL627309.1    0.006128664  0.005927264 0.04854338 0.00000000 0.02054586
## AP006222.2    0.000000000  0.008206078 0.01088471 0.00000000 0.01191488
## RP11-206L10.2 0.007453092  0.000000000 0.00000000 0.02065031 0.00000000
## RP11-206L10.9 0.000000000  0.000000000 0.01050116 0.00000000 0.00000000
## LINC00115     0.019118933  0.024690483 0.03753737 0.03888541 0.01948277
## NOC2L         0.497463190  0.359811462 0.27253750 0.58653489 0.55704897
```

Example 72 (unknown):
```unknown
##               Naive CD4 T Memory CD4 T CD14+ Mono          B      CD8 T
## AL627309.1    0.006128664  0.005927264 0.04854338 0.00000000 0.02054586
## AP006222.2    0.000000000  0.008206078 0.01088471 0.00000000 0.01191488
## RP11-206L10.2 0.007453092  0.000000000 0.00000000 0.02065031 0.00000000
## RP11-206L10.9 0.000000000  0.000000000 0.01050116 0.00000000 0.00000000
## LINC00115     0.019118933  0.024690483 0.03753737 0.03888541 0.01948277
## NOC2L         0.497463190  0.359811462 0.27253750 0.58653489 0.55704897
```

Example 73 (unknown):
```unknown
# Return this information as a Seurat object (enables downstream plotting and analysis) First,
# replace spaces with underscores '_' so ggplot2 doesn't fail
orig.levels <- levels(pbmc)
Idents(pbmc) <- gsub(pattern = " ", replacement = "_", x = Idents(pbmc))
orig.levels <- gsub(pattern = " ", replacement = "_", x = orig.levels)
levels(pbmc) <- orig.levels
cluster.averages <- AverageExpression(pbmc, return.seurat = TRUE)
cluster.averages
```

Example 74 (r):
```r
# Return this information as a Seurat object (enables downstream plotting and analysis) First,
# replace spaces with underscores '_' so ggplot2 doesn't fail
orig.levels <- levels(pbmc)
Idents(pbmc) <- gsub(pattern = " ", replacement = "_", x = Idents(pbmc))
orig.levels <- gsub(pattern = " ", replacement = "_", x = orig.levels)
levels(pbmc) <- orig.levels
cluster.averages <- AverageExpression(pbmc, return.seurat = TRUE)
cluster.averages
```

Example 75 (r):
```r
# Return this information as a Seurat object (enables downstream plotting and analysis) First,
# replace spaces with underscores '_' so ggplot2 doesn't fail
orig.levels <- levels(pbmc)
Idents(pbmc) <- gsub(pattern = " ", replacement = "_", x = Idents(pbmc))
orig.levels <- gsub(pattern = " ", replacement = "_", x = orig.levels)
levels(pbmc) <- orig.levels
cluster.averages <- AverageExpression(pbmc, return.seurat = TRUE)
cluster.averages
```

Example 76 (python):
```python
## An object of class Seurat 
## 13714 features across 9 samples within 1 assay 
## Active assay: RNA (13714 features, 0 variable features)
```

Example 77 (python):
```python
## An object of class Seurat 
## 13714 features across 9 samples within 1 assay 
## Active assay: RNA (13714 features, 0 variable features)
```

Example 78 (unknown):
```unknown
# How can I plot the average expression of NK cells vs. CD8 T cells?  Pass do.hover = T for an
# interactive plot to identify gene outliers
CellScatter(cluster.averages, cell1 = "NK", cell2 = "CD8_T")
```

Example 79 (r):
```r
# How can I plot the average expression of NK cells vs. CD8 T cells?  Pass do.hover = T for an
# interactive plot to identify gene outliers
CellScatter(cluster.averages, cell1 = "NK", cell2 = "CD8_T")
```

Example 80 (r):
```r
# How can I plot the average expression of NK cells vs. CD8 T cells?  Pass do.hover = T for an
# interactive plot to identify gene outliers
CellScatter(cluster.averages, cell1 = "NK", cell2 = "CD8_T")
```

Example 81 (unknown):
```unknown
# How can I calculate expression averages separately for each replicate?
cluster.averages <- AverageExpression(pbmc, return.seurat = TRUE, add.ident = "replicate")
CellScatter(cluster.averages, cell1 = "CD8_T_rep1", cell2 = "CD8_T_rep2")
```

Example 82 (r):
```r
# How can I calculate expression averages separately for each replicate?
cluster.averages <- AverageExpression(pbmc, return.seurat = TRUE, add.ident = "replicate")
CellScatter(cluster.averages, cell1 = "CD8_T_rep1", cell2 = "CD8_T_rep2")
```

Example 83 (r):
```r
# How can I calculate expression averages separately for each replicate?
cluster.averages <- AverageExpression(pbmc, return.seurat = TRUE, add.ident = "replicate")
CellScatter(cluster.averages, cell1 = "CD8_T_rep1", cell2 = "CD8_T_rep2")
```

Example 84 (unknown):
```unknown
# You can also plot heatmaps of these 'in silico' bulk datasets to visualize agreement between
# replicates
DoHeatmap(cluster.averages, features = unlist(TopFeatures(pbmc[["pca"]], balanced = TRUE)), size = 3,
    draw.lines = FALSE)
```

Example 85 (r):
```r
# You can also plot heatmaps of these 'in silico' bulk datasets to visualize agreement between
# replicates
DoHeatmap(cluster.averages, features = unlist(TopFeatures(pbmc[["pca"]], balanced = TRUE)), size = 3,
    draw.lines = FALSE)
```

Example 86 (r):
```r
# You can also plot heatmaps of these 'in silico' bulk datasets to visualize agreement between
# replicates
DoHeatmap(cluster.averages, features = unlist(TopFeatures(pbmc[["pca"]], balanced = TRUE)), size = 3,
    draw.lines = FALSE)
```

Example 87 (unknown):
```unknown
sessionInfo()
```

Example 88 (r):
```r
sessionInfo()
```

Example 89 (r):
```r
sessionInfo()
```

Example 90 (unknown):
```unknown
## R version 4.2.0 (2022-04-22)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.5 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/liblapack.so.3
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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       
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
##  [1] thp1.eccite.SeuratData_3.1.5  stxBrain.SeuratData_0.1.1    
##  [3] ssHippo.SeuratData_3.1.4      pbmcsca.SeuratData_3.0.0     
##  [5] pbmcMultiome.SeuratData_0.1.2 pbmc3k.SeuratData_3.1.4      
##  [7] panc8.SeuratData_3.0.2        ifnb.SeuratData_3.1.0        
##  [9] hcabm40k.SeuratData_3.0.0     bmcite.SeuratData_0.3.0      
## [11] SeuratData_0.2.2              SeuratObject_4.1.3           
## [13] Seurat_4.3.0                 
## 
## loaded via a namespace (and not attached):
##   [1] systemfonts_1.0.4      plyr_1.8.8             igraph_1.4.1          
##   [4] lazyeval_0.2.2         sp_1.6-0               splines_4.2.0         
##   [7] listenv_0.9.0          scattermore_0.8        ggplot2_3.4.1         
##  [10] digest_0.6.31          htmltools_0.5.4        fansi_1.0.4           
##  [13] magrittr_2.0.3         memoise_2.0.1          tensor_1.5            
##  [16] cluster_2.1.3          ROCR_1.0-11            globals_0.16.2        
##  [19] matrixStats_0.63.0     pkgdown_2.0.7          spatstat.sparse_3.0-0 
##  [22] colorspace_2.1-0       rappdirs_0.3.3         ggrepel_0.9.3         
##  [25] textshaping_0.3.6      xfun_0.37              dplyr_1.1.0           
##  [28] crayon_1.5.2           jsonlite_1.8.4         progressr_0.13.0      
##  [31] spatstat.data_3.0-0    survival_3.3-1         zoo_1.8-11            
##  [34] glue_1.6.2             polyclip_1.10-4        gtable_0.3.1          
##  [37] leiden_0.4.3           future.apply_1.10.0    abind_1.4-5           
##  [40] scales_1.2.1           spatstat.random_3.1-3  miniUI_0.1.1.1        
##  [43] Rcpp_1.0.10            viridisLite_0.4.1      xtable_1.8-4          
##  [46] reticulate_1.28        htmlwidgets_1.6.1      httr_1.4.5            
##  [49] RColorBrewer_1.1-3     ellipsis_0.3.2         ica_1.0-3             
##  [52] farver_2.1.1           pkgconfig_2.0.3        sass_0.4.5            
##  [55] uwot_0.1.14            deldir_1.0-6           utf8_1.2.3            
##  [58] tidyselect_1.2.0       labeling_0.4.2         rlang_1.0.6           
##  [61] reshape2_1.4.4         later_1.3.0            munsell_0.5.0         
##  [64] tools_4.2.0            cachem_1.0.7           cli_3.6.0             
##  [67] generics_0.1.3         ggridges_0.5.4         evaluate_0.20         
##  [70] stringr_1.5.0          fastmap_1.1.1          yaml_2.3.7            
##  [73] ragg_1.2.5             goftest_1.2-3          knitr_1.42            
##  [76] fs_1.6.1               fitdistrplus_1.1-8     purrr_1.0.1           
##  [79] RANN_2.6.1             pbapply_1.7-0          future_1.31.0         
##  [82] nlme_3.1-157           mime_0.12              formatR_1.14          
##  [85] compiler_4.2.0         plotly_4.10.1          png_0.1-8             
##  [88] spatstat.utils_3.0-1   tibble_3.1.8           bslib_0.4.2           
##  [91] stringi_1.7.12         highr_0.10             desc_1.4.2            
##  [94] lattice_0.20-45        Matrix_1.5-3           vctrs_0.5.2           
##  [97] pillar_1.8.1           lifecycle_1.0.3        spatstat.geom_3.0-6   
## [100] lmtest_0.9-40          jquerylib_0.1.4        RcppAnnoy_0.0.20      
## [103] data.table_1.14.8      cowplot_1.1.1          irlba_2.3.5.1         
## [106] httpuv_1.6.9           patchwork_1.1.2        R6_2.5.1              
## [109] promises_1.2.0.1       KernSmooth_2.23-20     gridExtra_2.3         
## [112] parallelly_1.34.0      codetools_0.2-18       MASS_7.3-56           
## [115] rprojroot_2.0.3        withr_2.5.0            sctransform_0.3.5     
## [118] parallel_4.2.0         grid_4.2.0             tidyr_1.3.0           
## [121] rmarkdown_2.20         Rtsne_0.16             spatstat.explore_3.0-6
## [124] shiny_1.7.4
```

Example 91 (unknown):
```unknown
## R version 4.2.0 (2022-04-22)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.5 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/liblapack.so.3
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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       
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
##  [1] thp1.eccite.SeuratData_3.1.5  stxBrain.SeuratData_0.1.1    
##  [3] ssHippo.SeuratData_3.1.4      pbmcsca.SeuratData_3.0.0     
##  [5] pbmcMultiome.SeuratData_0.1.2 pbmc3k.SeuratData_3.1.4      
##  [7] panc8.SeuratData_3.0.2        ifnb.SeuratData_3.1.0        
##  [9] hcabm40k.SeuratData_3.0.0     bmcite.SeuratData_0.3.0      
## [11] SeuratData_0.2.2              SeuratObject_4.1.3           
## [13] Seurat_4.3.0                 
## 
## loaded via a namespace (and not attached):
##   [1] systemfonts_1.0.4      plyr_1.8.8             igraph_1.4.1          
##   [4] lazyeval_0.2.2         sp_1.6-0               splines_4.2.0         
##   [7] listenv_0.9.0          scattermore_0.8        ggplot2_3.4.1         
##  [10] digest_0.6.31          htmltools_0.5.4        fansi_1.0.4           
##  [13] magrittr_2.0.3         memoise_2.0.1          tensor_1.5            
##  [16] cluster_2.1.3          ROCR_1.0-11            globals_0.16.2        
##  [19] matrixStats_0.63.0     pkgdown_2.0.7          spatstat.sparse_3.0-0 
##  [22] colorspace_2.1-0       rappdirs_0.3.3         ggrepel_0.9.3         
##  [25] textshaping_0.3.6      xfun_0.37              dplyr_1.1.0           
##  [28] crayon_1.5.2           jsonlite_1.8.4         progressr_0.13.0      
##  [31] spatstat.data_3.0-0    survival_3.3-1         zoo_1.8-11            
##  [34] glue_1.6.2             polyclip_1.10-4        gtable_0.3.1          
##  [37] leiden_0.4.3           future.apply_1.10.0    abind_1.4-5           
##  [40] scales_1.2.1           spatstat.random_3.1-3  miniUI_0.1.1.1        
##  [43] Rcpp_1.0.10            viridisLite_0.4.1      xtable_1.8-4          
##  [46] reticulate_1.28        htmlwidgets_1.6.1      httr_1.4.5            
##  [49] RColorBrewer_1.1-3     ellipsis_0.3.2         ica_1.0-3             
##  [52] farver_2.1.1           pkgconfig_2.0.3        sass_0.4.5            
##  [55] uwot_0.1.14            deldir_1.0-6           utf8_1.2.3            
##  [58] tidyselect_1.2.0       labeling_0.4.2         rlang_1.0.6           
##  [61] reshape2_1.4.4         later_1.3.0            munsell_0.5.0         
##  [64] tools_4.2.0            cachem_1.0.7           cli_3.6.0             
##  [67] generics_0.1.3         ggridges_0.5.4         evaluate_0.20         
##  [70] stringr_1.5.0          fastmap_1.1.1          yaml_2.3.7            
##  [73] ragg_1.2.5             goftest_1.2-3          knitr_1.42            
##  [76] fs_1.6.1               fitdistrplus_1.1-8     purrr_1.0.1           
##  [79] RANN_2.6.1             pbapply_1.7-0          future_1.31.0         
##  [82] nlme_3.1-157           mime_0.12              formatR_1.14          
##  [85] compiler_4.2.0         plotly_4.10.1          png_0.1-8             
##  [88] spatstat.utils_3.0-1   tibble_3.1.8           bslib_0.4.2           
##  [91] stringi_1.7.12         highr_0.10             desc_1.4.2            
##  [94] lattice_0.20-45        Matrix_1.5-3           vctrs_0.5.2           
##  [97] pillar_1.8.1           lifecycle_1.0.3        spatstat.geom_3.0-6   
## [100] lmtest_0.9-40          jquerylib_0.1.4        RcppAnnoy_0.0.20      
## [103] data.table_1.14.8      cowplot_1.1.1          irlba_2.3.5.1         
## [106] httpuv_1.6.9           patchwork_1.1.2        R6_2.5.1              
## [109] promises_1.2.0.1       KernSmooth_2.23-20     gridExtra_2.3         
## [112] parallelly_1.34.0      codetools_0.2-18       MASS_7.3-56           
## [115] rprojroot_2.0.3        withr_2.5.0            sctransform_0.3.5     
## [118] parallel_4.2.0         grid_4.2.0             tidyr_1.3.0           
## [121] rmarkdown_2.20         Rtsne_0.16             spatstat.explore_3.0-6
## [124] shiny_1.7.4
```

---

## Analysis, visualization, and integration of Visium HD spatial datasets with Seurat • Seurat

**URL:** http://127.0.0.1:9173/seurat/articles/integration_rpca/index.html

**Contents:**
- Fast integration using reciprocal PCA (RPCA)
    - Compiled: October 31, 2023
- Perform integration
- Modifying the strength of integration
- Performing integration on datasets normalized with SCTransform
- Contents

In this vignette, we present a slightly modified workflow for the integration of scRNA-seq datasets. Instead of utilizing canonical correlation analysis (‘CCA’) to identify anchors, we instead utilize reciprocal PCA (‘RPCA’). When determining anchors between any two datasets using RPCA, we project each dataset into the others PCA space and constrain the anchors by the same mutual neighborhood requirement. The commands for both workflows are largely identical, but the two methods may be applied in different context.

By identifying shared sources of variation between datasets, CCA is well-suited for identifying anchors when cell types are conserved, but there are very substantial differences in gene expression across experiments. CCA-based integration therefore enables integrative analysis when experimental conditions or disease states introduce very strong expression shifts, or when integrating datasets across modalities and species. However, CCA-based integration may also lead to overcorrection, especially when a large proportion of cells are non-overlapping across datasets.

RPCA-based integration runs significantly faster, and also represents a more conservative approach where cells in different biological states are less likely to ‘align’ after integration. We therefore recommend RPCA during integrative analysis where:

Below, we demonstrate the use of reciprocal PCA to align the same stimulated and resting datasets first analyzed in our introduction to scRNA-seq integration vignette. While the list of commands is nearly identical, this workflow requires users to run principal components analysis (PCA) individually on each dataset prior to integration. Users should also set the ‘reduction’ argument to ‘rpca’, when running FindIntegrationAnchors().

We then identify anchors using the FindIntegrationAnchors() function, which takes a list of Seurat objects as input, and use these anchors to integrate the two datasets together with IntegrateData().

Now we can run a single integrated analysis on all cells!

The results show that rpca-based integration is more conservative, and in this case, do not perfectly align a subset of cells (which are naive and memory T cells) across experiments. You can increase the strength of alignment by increasing the k.anchor parameter, which is set to 5 by default. Increasing this parameter to 20 will assist in aligning these populations.

Now that the datasets have been integrated, you can follow the previous steps in the introduction to scRNA-seq integration vignette to identify cell types and cell type-specific responses.

As an additional example, we repeat the analyses performed above, but normalize the datasets using SCTransform. We may choose to set the method parameter to glmGamPoi (install here) in order to enable faster estimation of regression parameters in SCTransform().

Developed by Rahul Satija, Satija Lab and Collaborators.

Site built with pkgdown 2.0.7.

**Examples:**

Example 1 (unknown):
```unknown
vignettes/integration_rpca.Rmd
```

Example 2 (unknown):
```unknown
integration_rpca.Rmd
```

Example 3 (unknown):
```unknown
FindIntegrationAnchors()
```

Example 4 (unknown):
```unknown
library(Seurat)
library(SeuratData)
# install dataset
InstallData("ifnb")
```

Example 5 (r):
```r
library(Seurat)
library(SeuratData)
# install dataset
InstallData("ifnb")
```

Example 6 (r):
```r
library(Seurat)
library(SeuratData)
# install dataset
InstallData("ifnb")
```

Example 7 (javascript):
```javascript
# load dataset
ifnb <- LoadData("ifnb")

# split the dataset into a list of two seurat objects (stim and CTRL)
ifnb.list <- SplitObject(ifnb, split.by = "stim")

# normalize and identify variable features for each dataset independently
ifnb.list <- lapply(X = ifnb.list, FUN = function(x) {
    x <- NormalizeData(x)
    x <- FindVariableFeatures(x, selection.method = "vst", nfeatures = 2000)
})

# select features that are repeatedly variable across datasets for integration run PCA on each
# dataset using these features
features <- SelectIntegrationFeatures(object.list = ifnb.list)
ifnb.list <- lapply(X = ifnb.list, FUN = function(x) {
    x <- ScaleData(x, features = features, verbose = FALSE)
    x <- RunPCA(x, features = features, verbose = FALSE)
})
```

Example 8 (r):
```r
# load dataset
ifnb <- LoadData("ifnb")

# split the dataset into a list of two seurat objects (stim and CTRL)
ifnb.list <- SplitObject(ifnb, split.by = "stim")

# normalize and identify variable features for each dataset independently
ifnb.list <- lapply(X = ifnb.list, FUN = function(x) {
    x <- NormalizeData(x)
    x <- FindVariableFeatures(x, selection.method = "vst", nfeatures = 2000)
})

# select features that are repeatedly variable across datasets for integration run PCA on each
# dataset using these features
features <- SelectIntegrationFeatures(object.list = ifnb.list)
ifnb.list <- lapply(X = ifnb.list, FUN = function(x) {
    x <- ScaleData(x, features = features, verbose = FALSE)
    x <- RunPCA(x, features = features, verbose = FALSE)
})
```

Example 9 (r):
```r
# load dataset
ifnb <- LoadData("ifnb")

# split the dataset into a list of two seurat objects (stim and CTRL)
ifnb.list <- SplitObject(ifnb, split.by = "stim")

# normalize and identify variable features for each dataset independently
ifnb.list <- lapply(X = ifnb.list, FUN = function(x) {
    x <- NormalizeData(x)
    x <- FindVariableFeatures(x, selection.method = "vst", nfeatures = 2000)
})

# select features that are repeatedly variable across datasets for integration run PCA on each
# dataset using these features
features <- SelectIntegrationFeatures(object.list = ifnb.list)
ifnb.list <- lapply(X = ifnb.list, FUN = function(x) {
    x <- ScaleData(x, features = features, verbose = FALSE)
    x <- RunPCA(x, features = features, verbose = FALSE)
})
```

Example 10 (unknown):
```unknown
FindIntegrationAnchors()
```

Example 11 (unknown):
```unknown
IntegrateData()
```

Example 12 (unknown):
```unknown
immune.anchors <- FindIntegrationAnchors(object.list = ifnb.list, anchor.features = features, reduction = "rpca")
```

Example 13 (r):
```r
immune.anchors <- FindIntegrationAnchors(object.list = ifnb.list, anchor.features = features, reduction = "rpca")
```

Example 14 (r):
```r
immune.anchors <- FindIntegrationAnchors(object.list = ifnb.list, anchor.features = features, reduction = "rpca")
```

Example 15 (unknown):
```unknown
# this command creates an 'integrated' data assay
immune.combined <- IntegrateData(anchorset = immune.anchors)
```

Example 16 (r):
```r
# this command creates an 'integrated' data assay
immune.combined <- IntegrateData(anchorset = immune.anchors)
```

Example 17 (r):
```r
# this command creates an 'integrated' data assay
immune.combined <- IntegrateData(anchorset = immune.anchors)
```

Example 18 (unknown):
```unknown
# specify that we will perform downstream analysis on the corrected data note that the
# original unmodified data still resides in the 'RNA' assay
DefaultAssay(immune.combined) <- "integrated"

# Run the standard workflow for visualization and clustering
immune.combined <- ScaleData(immune.combined, verbose = FALSE)
immune.combined <- RunPCA(immune.combined, npcs = 30, verbose = FALSE)
immune.combined <- RunUMAP(immune.combined, reduction = "pca", dims = 1:30)
immune.combined <- FindNeighbors(immune.combined, reduction = "pca", dims = 1:30)
immune.combined <- FindClusters(immune.combined, resolution = 0.5)
```

Example 19 (r):
```r
# specify that we will perform downstream analysis on the corrected data note that the
# original unmodified data still resides in the 'RNA' assay
DefaultAssay(immune.combined) <- "integrated"

# Run the standard workflow for visualization and clustering
immune.combined <- ScaleData(immune.combined, verbose = FALSE)
immune.combined <- RunPCA(immune.combined, npcs = 30, verbose = FALSE)
immune.combined <- RunUMAP(immune.combined, reduction = "pca", dims = 1:30)
immune.combined <- FindNeighbors(immune.combined, reduction = "pca", dims = 1:30)
immune.combined <- FindClusters(immune.combined, resolution = 0.5)
```

Example 20 (r):
```r
# specify that we will perform downstream analysis on the corrected data note that the
# original unmodified data still resides in the 'RNA' assay
DefaultAssay(immune.combined) <- "integrated"

# Run the standard workflow for visualization and clustering
immune.combined <- ScaleData(immune.combined, verbose = FALSE)
immune.combined <- RunPCA(immune.combined, npcs = 30, verbose = FALSE)
immune.combined <- RunUMAP(immune.combined, reduction = "pca", dims = 1:30)
immune.combined <- FindNeighbors(immune.combined, reduction = "pca", dims = 1:30)
immune.combined <- FindClusters(immune.combined, resolution = 0.5)
```

Example 21 (unknown):
```unknown
# Visualization
p1 <- DimPlot(immune.combined, reduction = "umap", group.by = "stim")
p2 <- DimPlot(immune.combined, reduction = "umap", group.by = "seurat_annotations", label = TRUE,
    repel = TRUE)
p1 + p2
```

Example 22 (r):
```r
# Visualization
p1 <- DimPlot(immune.combined, reduction = "umap", group.by = "stim")
p2 <- DimPlot(immune.combined, reduction = "umap", group.by = "seurat_annotations", label = TRUE,
    repel = TRUE)
p1 + p2
```

Example 23 (r):
```r
# Visualization
p1 <- DimPlot(immune.combined, reduction = "umap", group.by = "stim")
p2 <- DimPlot(immune.combined, reduction = "umap", group.by = "seurat_annotations", label = TRUE,
    repel = TRUE)
p1 + p2
```

Example 24 (unknown):
```unknown
immune.anchors <- FindIntegrationAnchors(object.list = ifnb.list, anchor.features = features, reduction = "rpca",
    k.anchor = 20)
immune.combined <- IntegrateData(anchorset = immune.anchors)

immune.combined <- ScaleData(immune.combined, verbose = FALSE)
immune.combined <- RunPCA(immune.combined, npcs = 30, verbose = FALSE)
immune.combined <- RunUMAP(immune.combined, reduction = "pca", dims = 1:30)
immune.combined <- FindNeighbors(immune.combined, reduction = "pca", dims = 1:30)
immune.combined <- FindClusters(immune.combined, resolution = 0.5)
```

Example 25 (r):
```r
immune.anchors <- FindIntegrationAnchors(object.list = ifnb.list, anchor.features = features, reduction = "rpca",
    k.anchor = 20)
immune.combined <- IntegrateData(anchorset = immune.anchors)

immune.combined <- ScaleData(immune.combined, verbose = FALSE)
immune.combined <- RunPCA(immune.combined, npcs = 30, verbose = FALSE)
immune.combined <- RunUMAP(immune.combined, reduction = "pca", dims = 1:30)
immune.combined <- FindNeighbors(immune.combined, reduction = "pca", dims = 1:30)
immune.combined <- FindClusters(immune.combined, resolution = 0.5)
```

Example 26 (r):
```r
immune.anchors <- FindIntegrationAnchors(object.list = ifnb.list, anchor.features = features, reduction = "rpca",
    k.anchor = 20)
immune.combined <- IntegrateData(anchorset = immune.anchors)

immune.combined <- ScaleData(immune.combined, verbose = FALSE)
immune.combined <- RunPCA(immune.combined, npcs = 30, verbose = FALSE)
immune.combined <- RunUMAP(immune.combined, reduction = "pca", dims = 1:30)
immune.combined <- FindNeighbors(immune.combined, reduction = "pca", dims = 1:30)
immune.combined <- FindClusters(immune.combined, resolution = 0.5)
```

Example 27 (unknown):
```unknown
## Modularity Optimizer version 1.3.0 by Ludo Waltman and Nees Jan van Eck
## 
## Number of nodes: 13999
## Number of edges: 594845
## 
## Running Louvain algorithm...
## Maximum modularity in 10 random starts: 0.9098
## Number of communities: 15
## Elapsed time: 2 seconds
```

Example 28 (unknown):
```unknown
## Modularity Optimizer version 1.3.0 by Ludo Waltman and Nees Jan van Eck
## 
## Number of nodes: 13999
## Number of edges: 594845
## 
## Running Louvain algorithm...
## Maximum modularity in 10 random starts: 0.9098
## Number of communities: 15
## Elapsed time: 2 seconds
```

Example 29 (unknown):
```unknown
# Visualization
p1 <- DimPlot(immune.combined, reduction = "umap", group.by = "stim")
p2 <- DimPlot(immune.combined, reduction = "umap", label = TRUE, repel = TRUE)
p1 + p2
```

Example 30 (r):
```r
# Visualization
p1 <- DimPlot(immune.combined, reduction = "umap", group.by = "stim")
p2 <- DimPlot(immune.combined, reduction = "umap", label = TRUE, repel = TRUE)
p1 + p2
```

Example 31 (r):
```r
# Visualization
p1 <- DimPlot(immune.combined, reduction = "umap", group.by = "stim")
p2 <- DimPlot(immune.combined, reduction = "umap", label = TRUE, repel = TRUE)
p1 + p2
```

Example 32 (unknown):
```unknown
library(ggplot2)
plot <- DimPlot(immune.combined, group.by = "stim") + xlab("UMAP 1") + ylab("UMAP 2") + theme(axis.title = element_text(size = 18),
    legend.text = element_text(size = 18)) + guides(colour = guide_legend(override.aes = list(size = 10)))
ggsave(filename = "../output/images/rpca_integration.jpg", height = 7, width = 12, plot = plot,
    quality = 50)
```

Example 33 (r):
```r
library(ggplot2)
plot <- DimPlot(immune.combined, group.by = "stim") + xlab("UMAP 1") + ylab("UMAP 2") + theme(axis.title = element_text(size = 18),
    legend.text = element_text(size = 18)) + guides(colour = guide_legend(override.aes = list(size = 10)))
ggsave(filename = "../output/images/rpca_integration.jpg", height = 7, width = 12, plot = plot,
    quality = 50)
```

Example 34 (r):
```r
library(ggplot2)
plot <- DimPlot(immune.combined, group.by = "stim") + xlab("UMAP 1") + ylab("UMAP 2") + theme(axis.title = element_text(size = 18),
    legend.text = element_text(size = 18)) + guides(colour = guide_legend(override.aes = list(size = 10)))
ggsave(filename = "../output/images/rpca_integration.jpg", height = 7, width = 12, plot = plot,
    quality = 50)
```

Example 35 (unknown):
```unknown
SCTransform()
```

Example 36 (unknown):
```unknown
ifnb <- LoadData("ifnb")
ifnb.list <- SplitObject(ifnb, split.by = "stim")
ifnb.list <- lapply(X = ifnb.list, FUN = SCTransform, method = "glmGamPoi")
features <- SelectIntegrationFeatures(object.list = ifnb.list, nfeatures = 3000)
ifnb.list <- PrepSCTIntegration(object.list = ifnb.list, anchor.features = features)
ifnb.list <- lapply(X = ifnb.list, FUN = RunPCA, features = features)
```

Example 37 (r):
```r
ifnb <- LoadData("ifnb")
ifnb.list <- SplitObject(ifnb, split.by = "stim")
ifnb.list <- lapply(X = ifnb.list, FUN = SCTransform, method = "glmGamPoi")
features <- SelectIntegrationFeatures(object.list = ifnb.list, nfeatures = 3000)
ifnb.list <- PrepSCTIntegration(object.list = ifnb.list, anchor.features = features)
ifnb.list <- lapply(X = ifnb.list, FUN = RunPCA, features = features)
```

Example 38 (r):
```r
ifnb <- LoadData("ifnb")
ifnb.list <- SplitObject(ifnb, split.by = "stim")
ifnb.list <- lapply(X = ifnb.list, FUN = SCTransform, method = "glmGamPoi")
features <- SelectIntegrationFeatures(object.list = ifnb.list, nfeatures = 3000)
ifnb.list <- PrepSCTIntegration(object.list = ifnb.list, anchor.features = features)
ifnb.list <- lapply(X = ifnb.list, FUN = RunPCA, features = features)
```

Example 39 (unknown):
```unknown
immune.anchors <- FindIntegrationAnchors(object.list = ifnb.list, normalization.method = "SCT",
    anchor.features = features, dims = 1:30, reduction = "rpca", k.anchor = 20)
immune.combined.sct <- IntegrateData(anchorset = immune.anchors, normalization.method = "SCT", dims = 1:30)
```

Example 40 (r):
```r
immune.anchors <- FindIntegrationAnchors(object.list = ifnb.list, normalization.method = "SCT",
    anchor.features = features, dims = 1:30, reduction = "rpca", k.anchor = 20)
immune.combined.sct <- IntegrateData(anchorset = immune.anchors, normalization.method = "SCT", dims = 1:30)
```

Example 41 (r):
```r
immune.anchors <- FindIntegrationAnchors(object.list = ifnb.list, normalization.method = "SCT",
    anchor.features = features, dims = 1:30, reduction = "rpca", k.anchor = 20)
immune.combined.sct <- IntegrateData(anchorset = immune.anchors, normalization.method = "SCT", dims = 1:30)
```

Example 42 (unknown):
```unknown
## [1] 1
## [1] 2
```

Example 43 (unknown):
```unknown
## [1] 1
## [1] 2
```

Example 44 (unknown):
```unknown
immune.combined.sct <- RunPCA(immune.combined.sct, verbose = FALSE)
immune.combined.sct <- RunUMAP(immune.combined.sct, reduction = "pca", dims = 1:30)
```

Example 45 (r):
```r
immune.combined.sct <- RunPCA(immune.combined.sct, verbose = FALSE)
immune.combined.sct <- RunUMAP(immune.combined.sct, reduction = "pca", dims = 1:30)
```

Example 46 (r):
```r
immune.combined.sct <- RunPCA(immune.combined.sct, verbose = FALSE)
immune.combined.sct <- RunUMAP(immune.combined.sct, reduction = "pca", dims = 1:30)
```

Example 47 (unknown):
```unknown
# Visualization
p1 <- DimPlot(immune.combined.sct, reduction = "umap", group.by = "stim")
p2 <- DimPlot(immune.combined.sct, reduction = "umap", group.by = "seurat_annotations", label = TRUE,
    repel = TRUE)
p1 + p2
```

Example 48 (r):
```r
# Visualization
p1 <- DimPlot(immune.combined.sct, reduction = "umap", group.by = "stim")
p2 <- DimPlot(immune.combined.sct, reduction = "umap", group.by = "seurat_annotations", label = TRUE,
    repel = TRUE)
p1 + p2
```

Example 49 (r):
```r
# Visualization
p1 <- DimPlot(immune.combined.sct, reduction = "umap", group.by = "stim")
p2 <- DimPlot(immune.combined.sct, reduction = "umap", group.by = "seurat_annotations", label = TRUE,
    repel = TRUE)
p1 + p2
```

Example 50 (unknown):
```unknown
sessionInfo()
```

Example 51 (r):
```r
sessionInfo()
```

Example 52 (r):
```r
sessionInfo()
```

Example 53 (unknown):
```unknown
## R version 4.2.2 Patched (2022-11-10 r83330)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.6 LTS
## 
## Matrix products: default
## BLAS:   /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.9.0
## LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.9.0
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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       
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
##  [1] ggplot2_3.4.4                 thp1.eccite.SeuratData_3.1.5 
##  [3] stxBrain.SeuratData_0.1.1     ssHippo.SeuratData_3.1.4     
##  [5] pbmcsca.SeuratData_3.0.0      pbmcref.SeuratData_1.0.0     
##  [7] pbmcMultiome.SeuratData_0.1.4 pbmc3k.SeuratData_3.1.4      
##  [9] panc8.SeuratData_3.0.2        ifnb.SeuratData_3.0.0        
## [11] hcabm40k.SeuratData_3.0.0     cbmc.SeuratData_3.1.4        
## [13] bmcite.SeuratData_0.3.0       SeuratData_0.2.2.9001        
## [15] Seurat_5.0.0                  SeuratObject_5.0.0           
## [17] sp_2.1-1                     
## 
## loaded via a namespace (and not attached):
##   [1] spam_2.10-0                 systemfonts_1.0.4          
##   [3] plyr_1.8.9                  igraph_1.5.1               
##   [5] lazyeval_0.2.2              splines_4.2.2              
##   [7] RcppHNSW_0.5.0              listenv_0.9.0              
##   [9] scattermore_1.2             GenomeInfoDb_1.34.9        
##  [11] digest_0.6.33               htmltools_0.5.6.1          
##  [13] fansi_1.0.5                 magrittr_2.0.3             
##  [15] memoise_2.0.1               tensor_1.5                 
##  [17] cluster_2.1.4               ROCR_1.0-11                
##  [19] globals_0.16.2              matrixStats_1.0.0          
##  [21] pkgdown_2.0.7               spatstat.sparse_3.0-3      
##  [23] colorspace_2.1-0            rappdirs_0.3.3             
##  [25] ggrepel_0.9.4               textshaping_0.3.6          
##  [27] xfun_0.40                   dplyr_1.1.3                
##  [29] RCurl_1.98-1.12             crayon_1.5.2               
##  [31] jsonlite_1.8.7              progressr_0.14.0           
##  [33] spatstat.data_3.0-3         survival_3.5-7             
##  [35] zoo_1.8-12                  glue_1.6.2                 
##  [37] polyclip_1.10-6             gtable_0.3.4               
##  [39] zlibbioc_1.44.0             XVector_0.38.0             
##  [41] leiden_0.4.3                DelayedArray_0.24.0        
##  [43] future.apply_1.11.0         BiocGenerics_0.44.0        
##  [45] abind_1.4-5                 scales_1.2.1               
##  [47] spatstat.random_3.2-1       miniUI_0.1.1.1             
##  [49] Rcpp_1.0.11                 viridisLite_0.4.2          
##  [51] xtable_1.8-4                reticulate_1.34.0          
##  [53] dotCall64_1.1-0             stats4_4.2.2               
##  [55] htmlwidgets_1.6.2           httr_1.4.7                 
##  [57] RColorBrewer_1.1-3          ellipsis_0.3.2             
##  [59] ica_1.0-3                   farver_2.1.1               
##  [61] pkgconfig_2.0.3             sass_0.4.7                 
##  [63] uwot_0.1.16                 deldir_1.0-9               
##  [65] utf8_1.2.4                  labeling_0.4.3             
##  [67] tidyselect_1.2.0            rlang_1.1.1                
##  [69] reshape2_1.4.4              later_1.3.1                
##  [71] munsell_0.5.0               tools_4.2.2                
##  [73] cachem_1.0.8                cli_3.6.1                  
##  [75] generics_0.1.3              ggridges_0.5.4             
##  [77] evaluate_0.22               stringr_1.5.0              
##  [79] fastmap_1.1.1               yaml_2.3.7                 
##  [81] ragg_1.2.5                  goftest_1.2-3              
##  [83] knitr_1.45                  fs_1.6.3                   
##  [85] fitdistrplus_1.1-11         purrr_1.0.2                
##  [87] RANN_2.6.1                  sparseMatrixStats_1.10.0   
##  [89] pbapply_1.7-2               future_1.33.0              
##  [91] nlme_3.1-162                mime_0.12                  
##  [93] formatR_1.14                compiler_4.2.2             
##  [95] plotly_4.10.3               png_0.1-8                  
##  [97] spatstat.utils_3.0-4        tibble_3.2.1               
##  [99] glmGamPoi_1.10.2            bslib_0.5.1                
## [101] stringi_1.7.12              highr_0.10                 
## [103] desc_1.4.2                  RSpectra_0.16-1            
## [105] lattice_0.21-9              Matrix_1.6-1.1             
## [107] vctrs_0.6.4                 pillar_1.9.0               
## [109] lifecycle_1.0.3             spatstat.geom_3.2-7        
## [111] lmtest_0.9-40               jquerylib_0.1.4            
## [113] RcppAnnoy_0.0.21            bitops_1.0-7               
## [115] data.table_1.14.8           cowplot_1.1.1              
## [117] irlba_2.3.5.1               GenomicRanges_1.50.2       
## [119] httpuv_1.6.12               patchwork_1.1.3            
## [121] R6_2.5.1                    promises_1.2.1             
## [123] KernSmooth_2.23-22          gridExtra_2.3              
## [125] IRanges_2.32.0              parallelly_1.36.0          
## [127] codetools_0.2-19            fastDummies_1.7.3          
## [129] MASS_7.3-58.2               SummarizedExperiment_1.28.0
## [131] rprojroot_2.0.3             withr_2.5.2                
## [133] sctransform_0.4.1           GenomeInfoDbData_1.2.9     
## [135] S4Vectors_0.36.2            parallel_4.2.2             
## [137] grid_4.2.2                  tidyr_1.3.0                
## [139] DelayedMatrixStats_1.20.0   rmarkdown_2.25             
## [141] MatrixGenerics_1.10.0       Rtsne_0.16                 
## [143] spatstat.explore_3.2-5      Biobase_2.58.0             
## [145] shiny_1.7.5.1
```

Example 54 (unknown):
```unknown
## R version 4.2.2 Patched (2022-11-10 r83330)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.6 LTS
## 
## Matrix products: default
## BLAS:   /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.9.0
## LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.9.0
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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       
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
##  [1] ggplot2_3.4.4                 thp1.eccite.SeuratData_3.1.5 
##  [3] stxBrain.SeuratData_0.1.1     ssHippo.SeuratData_3.1.4     
##  [5] pbmcsca.SeuratData_3.0.0      pbmcref.SeuratData_1.0.0     
##  [7] pbmcMultiome.SeuratData_0.1.4 pbmc3k.SeuratData_3.1.4      
##  [9] panc8.SeuratData_3.0.2        ifnb.SeuratData_3.0.0        
## [11] hcabm40k.SeuratData_3.0.0     cbmc.SeuratData_3.1.4        
## [13] bmcite.SeuratData_0.3.0       SeuratData_0.2.2.9001        
## [15] Seurat_5.0.0                  SeuratObject_5.0.0           
## [17] sp_2.1-1                     
## 
## loaded via a namespace (and not attached):
##   [1] spam_2.10-0                 systemfonts_1.0.4          
##   [3] plyr_1.8.9                  igraph_1.5.1               
##   [5] lazyeval_0.2.2              splines_4.2.2              
##   [7] RcppHNSW_0.5.0              listenv_0.9.0              
##   [9] scattermore_1.2             GenomeInfoDb_1.34.9        
##  [11] digest_0.6.33               htmltools_0.5.6.1          
##  [13] fansi_1.0.5                 magrittr_2.0.3             
##  [15] memoise_2.0.1               tensor_1.5                 
##  [17] cluster_2.1.4               ROCR_1.0-11                
##  [19] globals_0.16.2              matrixStats_1.0.0          
##  [21] pkgdown_2.0.7               spatstat.sparse_3.0-3      
##  [23] colorspace_2.1-0            rappdirs_0.3.3             
##  [25] ggrepel_0.9.4               textshaping_0.3.6          
##  [27] xfun_0.40                   dplyr_1.1.3                
##  [29] RCurl_1.98-1.12             crayon_1.5.2               
##  [31] jsonlite_1.8.7              progressr_0.14.0           
##  [33] spatstat.data_3.0-3         survival_3.5-7             
##  [35] zoo_1.8-12                  glue_1.6.2                 
##  [37] polyclip_1.10-6             gtable_0.3.4               
##  [39] zlibbioc_1.44.0             XVector_0.38.0             
##  [41] leiden_0.4.3                DelayedArray_0.24.0        
##  [43] future.apply_1.11.0         BiocGenerics_0.44.0        
##  [45] abind_1.4-5                 scales_1.2.1               
##  [47] spatstat.random_3.2-1       miniUI_0.1.1.1             
##  [49] Rcpp_1.0.11                 viridisLite_0.4.2          
##  [51] xtable_1.8-4                reticulate_1.34.0          
##  [53] dotCall64_1.1-0             stats4_4.2.2               
##  [55] htmlwidgets_1.6.2           httr_1.4.7                 
##  [57] RColorBrewer_1.1-3          ellipsis_0.3.2             
##  [59] ica_1.0-3                   farver_2.1.1               
##  [61] pkgconfig_2.0.3             sass_0.4.7                 
##  [63] uwot_0.1.16                 deldir_1.0-9               
##  [65] utf8_1.2.4                  labeling_0.4.3             
##  [67] tidyselect_1.2.0            rlang_1.1.1                
##  [69] reshape2_1.4.4              later_1.3.1                
##  [71] munsell_0.5.0               tools_4.2.2                
##  [73] cachem_1.0.8                cli_3.6.1                  
##  [75] generics_0.1.3              ggridges_0.5.4             
##  [77] evaluate_0.22               stringr_1.5.0              
##  [79] fastmap_1.1.1               yaml_2.3.7                 
##  [81] ragg_1.2.5                  goftest_1.2-3              
##  [83] knitr_1.45                  fs_1.6.3                   
##  [85] fitdistrplus_1.1-11         purrr_1.0.2                
##  [87] RANN_2.6.1                  sparseMatrixStats_1.10.0   
##  [89] pbapply_1.7-2               future_1.33.0              
##  [91] nlme_3.1-162                mime_0.12                  
##  [93] formatR_1.14                compiler_4.2.2             
##  [95] plotly_4.10.3               png_0.1-8                  
##  [97] spatstat.utils_3.0-4        tibble_3.2.1               
##  [99] glmGamPoi_1.10.2            bslib_0.5.1                
## [101] stringi_1.7.12              highr_0.10                 
## [103] desc_1.4.2                  RSpectra_0.16-1            
## [105] lattice_0.21-9              Matrix_1.6-1.1             
## [107] vctrs_0.6.4                 pillar_1.9.0               
## [109] lifecycle_1.0.3             spatstat.geom_3.2-7        
## [111] lmtest_0.9-40               jquerylib_0.1.4            
## [113] RcppAnnoy_0.0.21            bitops_1.0-7               
## [115] data.table_1.14.8           cowplot_1.1.1              
## [117] irlba_2.3.5.1               GenomicRanges_1.50.2       
## [119] httpuv_1.6.12               patchwork_1.1.3            
## [121] R6_2.5.1                    promises_1.2.1             
## [123] KernSmooth_2.23-22          gridExtra_2.3              
## [125] IRanges_2.32.0              parallelly_1.36.0          
## [127] codetools_0.2-19            fastDummies_1.7.3          
## [129] MASS_7.3-58.2               SummarizedExperiment_1.28.0
## [131] rprojroot_2.0.3             withr_2.5.2                
## [133] sctransform_0.4.1           GenomeInfoDbData_1.2.9     
## [135] S4Vectors_0.36.2            parallel_4.2.2             
## [137] grid_4.2.2                  tidyr_1.3.0                
## [139] DelayedMatrixStats_1.20.0   rmarkdown_2.25             
## [141] MatrixGenerics_1.10.0       Rtsne_0.16                 
## [143] spatstat.explore_3.2-5      Biobase_2.58.0             
## [145] shiny_1.7.5.1
```

---

## Demultiplexing with hashtag oligos (HTOs)

**URL:** http://127.0.0.1:9173/seurat/archive/v2.4/hashing_vignette/index.html

**Contents:**
- Demultiplexing with hashtag oligos (HTOs)
- 8-HTO dataset from human PBMCs
  - Basic setup
  - Adding HTO data as an independent assay
  - Demultiplex cells based on HTO enrichment
  - Visualize demultiplexing results
- 12-HTO dataset from four human cell lines
  - Create Seurat object, add HTO data and perform normalization
  - Demultiplex data
  - Visualize demultiplexing results
  - Visualize RNA clustering

Developed in collaboration with the Technology Innovation Group at NYGC, Cell Hashing uses oligo-tagged antibodies against ubuquitously expressed surface proteins to place a “sample barcode” on each single cell, enabling different samples to be multiplexed together and run in a single experiment. For more information, please refer to our preprint: https://www.biorxiv.org/content/early/2017/12/21/237693

This vignette will give a brief demonstration on how to work with data produced with Cell Hashing in Seurat. Applied to two datasets, we can successfully demultiplex cells to their the original sample-of-origin, and identify cross-sample doublets.

Setup Seurat object and add in the HTO data

You can read more about working with multi-modal data here

Here we use the Seurat function HTODemux() to assign single cells back to their sample origins.

Output from running HTODemux() is saved in the object metadata. We can visualize how many cells are classified as singlets, doublets and negative/ambiguous cells.

Visualize enrichment for selected HTOs with ridge plots

Visualize pairs of HTO signals to confirm mutual exclusivity in singlets

Compare number of UMIs for singlets, doublets and negative cells

Generate a two dimensional tSNE embedding for HTOs.Here we are grouping cells by singlets and doublets for simplicity.

Create an HTO heatmap, based on Figure 1C in the Cell Hashing paper.

Cluster and visualize cells using the usual scRNA-seq workflow, and examine for the potential presence of batch effects.

Distribution of selected HTOs grouped by classification, displayed by ridge plots

Visualize HTO signals in a heatmap

**Examples:**

Example 1 (r):
```r
library(Seurat)
```

Example 2 (r):
```r
library(Seurat)
```

Example 3 (r):
```r
setwd("~/Downloads/HTODemuxFiles/")
# Load in the UMI matrix
pbmc_umi_sparse <- readRDS("pbmc_umi_mtx.rds")

# For generating a hashtag count matrix from fastq files, please refer to https://github.com/Hoohm/CITE-seq-Count.
# Load in the HTO count matrix
pbmc_hto <- readRDS("pbmc_hto_mtx.rds")

# Select cell barcodes detected by both RNA and HTO
# In the example datasets we have already filtered the cells for you, but perform this step for clarity.
joint_bcs <- intersect(colnames(pbmc_umi_sparse),colnames(pbmc_hto))

# Subset RNA and HTO counts by joint cell barcodes
pbmc_umi_sparse <- pbmc_umi_sparse[,joint_bcs]
pbmc_hto <- as.matrix(pbmc_hto[,joint_bcs])

# Confirm that the HTO have the correct names
print (rownames(pbmc_hto))
```

Example 4 (r):
```r
setwd("~/Downloads/HTODemuxFiles/")
# Load in the UMI matrix
pbmc_umi_sparse <- readRDS("pbmc_umi_mtx.rds")

# For generating a hashtag count matrix from fastq files, please refer to https://github.com/Hoohm/CITE-seq-Count.
# Load in the HTO count matrix
pbmc_hto <- readRDS("pbmc_hto_mtx.rds")

# Select cell barcodes detected by both RNA and HTO
# In the example datasets we have already filtered the cells for you, but perform this step for clarity.
joint_bcs <- intersect(colnames(pbmc_umi_sparse),colnames(pbmc_hto))

# Subset RNA and HTO counts by joint cell barcodes
pbmc_umi_sparse <- pbmc_umi_sparse[,joint_bcs]
pbmc_hto <- as.matrix(pbmc_hto[,joint_bcs])

# Confirm that the HTO have the correct names
print (rownames(pbmc_hto))
```

Example 5 (unknown):
```unknown
## [1] "HTO_A" "HTO_B" "HTO_C" "HTO_D" "HTO_E" "HTO_F" "HTO_G" "HTO_H"
```

Example 6 (unknown):
```unknown
## [1] "HTO_A" "HTO_B" "HTO_C" "HTO_D" "HTO_E" "HTO_F" "HTO_G" "HTO_H"
```

Example 7 (r):
```r
# Setup Seurat object
pbmc_hashtag <- CreateSeuratObject(raw.data = pbmc_umi_sparse)

# Normalize RNA data with log normalization
pbmc_hashtag <- NormalizeData(pbmc_hashtag,display.progress = FALSE)
# Find and scale variable genes
pbmc_hashtag <- FindVariableGenes(pbmc_hashtag,do.plot = F,display.progress = FALSE)
pbmc_hashtag <- ScaleData(pbmc_hashtag,genes.use = pbmc_hashtag@var.genes,display.progress = FALSE)
```

Example 8 (r):
```r
# Setup Seurat object
pbmc_hashtag <- CreateSeuratObject(raw.data = pbmc_umi_sparse)

# Normalize RNA data with log normalization
pbmc_hashtag <- NormalizeData(pbmc_hashtag,display.progress = FALSE)
# Find and scale variable genes
pbmc_hashtag <- FindVariableGenes(pbmc_hashtag,do.plot = F,display.progress = FALSE)
pbmc_hashtag <- ScaleData(pbmc_hashtag,genes.use = pbmc_hashtag@var.genes,display.progress = FALSE)
```

Example 9 (r):
```r
# Add HTO data as a new assay independent from RNA
pbmc_hashtag <- SetAssayData(pbmc_hashtag,assay.type = "HTO",slot = "raw.data",new.data = pbmc_hto)
# Normalize HTO data, here we use centered log-ratio (CLR) transformation
pbmc_hashtag <- NormalizeData(pbmc_hashtag,assay.type = "HTO",normalization.method = "genesCLR",display.progress = FALSE)
```

Example 10 (r):
```r
# Add HTO data as a new assay independent from RNA
pbmc_hashtag <- SetAssayData(pbmc_hashtag,assay.type = "HTO",slot = "raw.data",new.data = pbmc_hto)
# Normalize HTO data, here we use centered log-ratio (CLR) transformation
pbmc_hashtag <- NormalizeData(pbmc_hashtag,assay.type = "HTO",normalization.method = "genesCLR",display.progress = FALSE)
```

Example 11 (r):
```r
# If you have a very large dataset we suggest using k_function = "clara". This is a k-medoid clustering function for large applications
# You can also play with additional parameters (see documentation for HTODemux()) to adjust the threshold for classification
# Here we are using the default settings
pbmc_hashtag <- HTODemux(pbmc_hashtag,assay.type = "HTO",positive_quantile =  0.99,print.output = FALSE)
```

Example 12 (r):
```r
# If you have a very large dataset we suggest using k_function = "clara". This is a k-medoid clustering function for large applications
# You can also play with additional parameters (see documentation for HTODemux()) to adjust the threshold for classification
# Here we are using the default settings
pbmc_hashtag <- HTODemux(pbmc_hashtag,assay.type = "HTO",positive_quantile =  0.99,print.output = FALSE)
```

Example 13 (r):
```r
# Global classification results
print (table(pbmc_hashtag@meta.data$hto_classification_global))
```

Example 14 (r):
```r
# Global classification results
print (table(pbmc_hashtag@meta.data$hto_classification_global))
```

Example 15 (javascript):
```javascript
## 
##  Doublet Negative  Singlet 
##     2598      346    13972
```

Example 16 (javascript):
```javascript
## 
##  Doublet Negative  Singlet 
##     2598      346    13972
```

Example 17 (r):
```r
# Group cells based on the max HTO signal
pbmc_hashtag <- SetAllIdent(pbmc_hashtag,id = "hash_maxID")
RidgePlot(pbmc_hashtag,features.plot = rownames(GetAssayData(pbmc_hashtag,assay.type = "HTO"))[1:2],nCol = 2)
```

Example 18 (r):
```r
# Group cells based on the max HTO signal
pbmc_hashtag <- SetAllIdent(pbmc_hashtag,id = "hash_maxID")
RidgePlot(pbmc_hashtag,features.plot = rownames(GetAssayData(pbmc_hashtag,assay.type = "HTO"))[1:2],nCol = 2)
```

Example 19 (r):
```r
GenePlot(pbmc_hashtag,"HTO_A","HTO_B",use.raw=FALSE,cex.use = 0.6,col.use = "black")
```

Example 20 (r):
```r
GenePlot(pbmc_hashtag,"HTO_A","HTO_B",use.raw=FALSE,cex.use = 0.6,col.use = "black")
```

Example 21 (r):
```r
pbmc_hashtag <- SetAllIdent(pbmc_hashtag,"hto_classification_global")
VlnPlot(pbmc_hashtag,"nUMI",point.size.use = 0.1,y.log = T)
```

Example 22 (r):
```r
pbmc_hashtag <- SetAllIdent(pbmc_hashtag,"hto_classification_global")
VlnPlot(pbmc_hashtag,"nUMI",point.size.use = 0.1,y.log = T)
```

Example 23 (r):
```r
#First, we will remove negative cells from the object
pbmc_hashtag <- SetAllIdent(pbmc_hashtag,"hto_classification_global")
pbmc_hashtag_subset <- SubsetData(pbmc_hashtag,ident.remove = "Negative")

# Calculate a distance matrix using HTO
hto_dist_mtx <- as.matrix(dist(t(GetAssayData(pbmc_hashtag_subset,assay.type = "HTO",slot = "data"))))

# Calculate tSNE embeddings with a distance matrix
pbmc_hashtag_subset <- RunTSNE(pbmc_hashtag_subset, distance.matrix = hto_dist_mtx,perplexity=100)
TSNEPlot(pbmc_hashtag_subset,pt.size = 0.2)
```

Example 24 (r):
```r
#First, we will remove negative cells from the object
pbmc_hashtag <- SetAllIdent(pbmc_hashtag,"hto_classification_global")
pbmc_hashtag_subset <- SubsetData(pbmc_hashtag,ident.remove = "Negative")

# Calculate a distance matrix using HTO
hto_dist_mtx <- as.matrix(dist(t(GetAssayData(pbmc_hashtag_subset,assay.type = "HTO",slot = "data"))))

# Calculate tSNE embeddings with a distance matrix
pbmc_hashtag_subset <- RunTSNE(pbmc_hashtag_subset, distance.matrix = hto_dist_mtx,perplexity=100)
TSNEPlot(pbmc_hashtag_subset,pt.size = 0.2)
```

Example 25 (r):
```r
#You can also visualize the more detailed classification result by running SetAllIdent(object,"hto_classification") beofre plotting. Here, you can see that each of the small clouds on the tSNE plot corresponds to one of the 28 possible doublet combinations.
```

Example 26 (r):
```r
#You can also visualize the more detailed classification result by running SetAllIdent(object,"hto_classification") beofre plotting. Here, you can see that each of the small clouds on the tSNE plot corresponds to one of the 28 possible doublet combinations.
```

Example 27 (r):
```r
#To increase the efficiency of plotting, you can subsample cells using the num.cells argument
HTOHeatmap(pbmc_hashtag,num.cells = 5000,batch.names = c("A","B","C","D","E","F","G","H"))
```

Example 28 (r):
```r
#To increase the efficiency of plotting, you can subsample cells using the num.cells argument
HTOHeatmap(pbmc_hashtag,num.cells = 5000,batch.names = c("A","B","C","D","E","F","G","H"))
```

Example 29 (r):
```r
# Extract the singlets
pbmc_hashtag <- SetAllIdent(pbmc_hashtag,id = "hto_classification_global")
pbmc_singlet <- SubsetData(pbmc_hashtag,ident.use = "Singlet")

# Select the top 1000 most variable genes
pbmc_singlet <- FindVariableGenes(pbmc_singlet,do.plot = F)

# Scaling RNA data, we only scale the variable genes here for efficiency
pbmc_singlet <- ScaleData(pbmc_singlet,genes.use = pbmc_singlet@var.genes,display.progress = FALSE)

# Run PCA
pbmc_singlet <- RunPCA(pbmc_singlet,pc.genes = pbmc_singlet@var.genes,pcs.print = 0)
```

Example 30 (r):
```r
# Extract the singlets
pbmc_hashtag <- SetAllIdent(pbmc_hashtag,id = "hto_classification_global")
pbmc_singlet <- SubsetData(pbmc_hashtag,ident.use = "Singlet")

# Select the top 1000 most variable genes
pbmc_singlet <- FindVariableGenes(pbmc_singlet,do.plot = F)

# Scaling RNA data, we only scale the variable genes here for efficiency
pbmc_singlet <- ScaleData(pbmc_singlet,genes.use = pbmc_singlet@var.genes,display.progress = FALSE)

# Run PCA
pbmc_singlet <- RunPCA(pbmc_singlet,pc.genes = pbmc_singlet@var.genes,pcs.print = 0)
```

Example 31 (r):
```r
# We select the top 10 PCs for clustering and tSNE based on PCElbowPlot
pbmc_singlet <- FindClusters(pbmc_singlet,reduction.type = "pca",dims.use = 1:10,print.output = F,resolution = 0.6)
pbmc_singlet <- RunTSNE(pbmc_singlet,reduction.use = "pca",dims.use = 1:10)

# Projecting singlet identities on TSNE visualization
TSNEPlot(pbmc_singlet,group.by = "hto_classification")
```

Example 32 (r):
```r
# We select the top 10 PCs for clustering and tSNE based on PCElbowPlot
pbmc_singlet <- FindClusters(pbmc_singlet,reduction.type = "pca",dims.use = 1:10,print.output = F,resolution = 0.6)
pbmc_singlet <- RunTSNE(pbmc_singlet,reduction.use = "pca",dims.use = 1:10)

# Projecting singlet identities on TSNE visualization
TSNEPlot(pbmc_singlet,group.by = "hto_classification")
```

Example 33 (r):
```r
setwd("~/Downloads/HTODemuxFiles/")

# Read in UMI count matrix for RNA
hto12_umi <- readRDS("hto12_umi_mtx.rds")

# Read in HTO count matrix
hto12_hto_raw <- readRDS("hto12_hto_mtx.rds")

# Select cell barcodes detected in both RNA and HTO
cells_use <- intersect(rownames(hto12_hto_raw),colnames(hto12_umi))

# Create Seurat object and add HTO data
hto12 <- CreateSeuratObject(hto12_umi[,cells_use],min.genes = 300)
hto12 <- SetAssayData(hto12,assay.type = "HTO",slot = "raw.data",new.data = t(hto12_hto_raw[hto12@cell.names,1:12]))

# Normalize data
hto12 <- NormalizeData(hto12,display.progress = FALSE)
hto12 <- NormalizeData(hto12,assay.type = "HTO",normalization.method = "genesCLR",display.progress = FALSE)
```

Example 34 (r):
```r
setwd("~/Downloads/HTODemuxFiles/")

# Read in UMI count matrix for RNA
hto12_umi <- readRDS("hto12_umi_mtx.rds")

# Read in HTO count matrix
hto12_hto_raw <- readRDS("hto12_hto_mtx.rds")

# Select cell barcodes detected in both RNA and HTO
cells_use <- intersect(rownames(hto12_hto_raw),colnames(hto12_umi))

# Create Seurat object and add HTO data
hto12 <- CreateSeuratObject(hto12_umi[,cells_use],min.genes = 300)
hto12 <- SetAssayData(hto12,assay.type = "HTO",slot = "raw.data",new.data = t(hto12_hto_raw[hto12@cell.names,1:12]))

# Normalize data
hto12 <- NormalizeData(hto12,display.progress = FALSE)
hto12 <- NormalizeData(hto12,assay.type = "HTO",normalization.method = "genesCLR",display.progress = FALSE)
```

Example 35 (r):
```r
hto12 <- HTODemux(hto12,assay.type = "HTO",positive_quantile =  0.99, print.output = TRUE)
```

Example 36 (r):
```r
hto12 <- HTODemux(hto12,assay.type = "HTO",positive_quantile =  0.99, print.output = TRUE)
```

Example 37 (javascript):
```javascript
## [1] "Cutoff for HEK_A : 4 reads"
## [1] "Cutoff for HEK_B : 8 reads"
## [1] "Cutoff for HEK_C : 6 reads"
## [1] "Cutoff for THP1_A : 19 reads"
## [1] "Cutoff for THP1_B : 13 reads"
## [1] "Cutoff for THP1_C : 13 reads"
## [1] "Cutoff for K562_A : 4 reads"
## [1] "Cutoff for K562_B : 9 reads"
## [1] "Cutoff for K562_C : 5 reads"
## [1] "Cutoff for KG1_A : 26 reads"
## [1] "Cutoff for KG1_B : 46 reads"
## [1] "Cutoff for KG1_C : 41 reads"
## 
##  Doublet Negative  Singlet 
##      889      318     6984
```

Example 38 (javascript):
```javascript
## [1] "Cutoff for HEK_A : 4 reads"
## [1] "Cutoff for HEK_B : 8 reads"
## [1] "Cutoff for HEK_C : 6 reads"
## [1] "Cutoff for THP1_A : 19 reads"
## [1] "Cutoff for THP1_B : 13 reads"
## [1] "Cutoff for THP1_C : 13 reads"
## [1] "Cutoff for K562_A : 4 reads"
## [1] "Cutoff for K562_B : 9 reads"
## [1] "Cutoff for K562_C : 5 reads"
## [1] "Cutoff for KG1_A : 26 reads"
## [1] "Cutoff for KG1_B : 46 reads"
## [1] "Cutoff for KG1_C : 41 reads"
## 
##  Doublet Negative  Singlet 
##      889      318     6984
```

Example 39 (r):
```r
hto_plot <- c("HEK_A","K562_B","KG1_A","THP1_C")
RidgePlot(hto12,features.plot = hto_plot,nCol = 2)
```

Example 40 (r):
```r
hto_plot <- c("HEK_A","K562_B","KG1_A","THP1_C")
RidgePlot(hto12,features.plot = hto_plot,nCol = 2)
```

Example 41 (r):
```r
HTOHeatmap(hto12,assay.type = "HTO",num.cells = length(hto12@cell.names))
```

Example 42 (r):
```r
HTOHeatmap(hto12,assay.type = "HTO",num.cells = length(hto12@cell.names))
```

Example 43 (r):
```r
# Remove the negative cells
hto12 <- SubsetData(hto12,ident.remove = "Negative")

# Run PCA on most variable genes
hto12 <- FindVariableGenes(hto12,do.plot = F)
hto12 <- ScaleData(hto12,genes.use = hto12@var.genes,display.progress = FALSE)
hto12 <- RunPCA(hto12,do.print = FALSE)

hto12 <- RunTSNE(hto12,dims.use = 1:5,perplexity = 100)
TSNEPlot(hto12)
```

Example 44 (r):
```r
# Remove the negative cells
hto12 <- SubsetData(hto12,ident.remove = "Negative")

# Run PCA on most variable genes
hto12 <- FindVariableGenes(hto12,do.plot = F)
hto12 <- ScaleData(hto12,genes.use = hto12@var.genes,display.progress = FALSE)
hto12 <- RunPCA(hto12,do.print = FALSE)

hto12 <- RunTSNE(hto12,dims.use = 1:5,perplexity = 100)
TSNEPlot(hto12)
```

---

## Mixscape Vignette • Seurat

**URL:** http://127.0.0.1:9173/seurat/archive/v4.3/mixscape_vignette/index.html

**Contents:**
- Mixscape Vignette
    - Compiled: March 27, 2023
- Overview
- Loading required packages
- Loading Seurat object containing ECCITE-seq dataset
- RNA-based clustering is driven by confounding sources of variation
- Calculating local perturbation signatures mitigates confounding effects
- Mixscape identifies cells with no detectable perturbation
- Inspecting mixscape results
- Visualizing perturbation responses with Linear Discriminant Analysis (LDA)
- Contents

This tutorial demonstrates how to use mixscape for the analyses of single-cell pooled CRSIPR screens. We introduce new Seurat functions for:Calculating the perturbation-specific signature of every cell.Identifying and removing cells that have ‘escaped’ CRISPR perturbation.Visualizing similarities/differences across different perturbations.

We use a 111 gRNA ECCITE-seq dataset generated from stimulated THP-1 cells that was recently published from our lab in bioRxiv Papalexi et al. 2020. This dataset can be easily downloaded from the SeuratData package. # Load object. eccite <- LoadData(ds = "thp1.eccite") # Normalize protein. eccite <- NormalizeData( object = eccite, assay = "ADT", normalization.method = "CLR", margin = 2)

Here, we follow the standard Seurat workflow to cluster cells based on their gene expression profiles. We expected to obtain perturbation-specific clusters however we saw that clustering is primarily driven by cell cycle phase and replicate ID. We only observed one perturbation-specific cluster containing cells expression IFNgamma pathway gRNAs. # Prepare RNA assay for dimensionality reduction: # Normalize data, find variable features and scale data. DefaultAssay(object = eccite) <- 'RNA' eccite <- NormalizeData(object = eccite) %>% FindVariableFeatures() %>% ScaleData() # Run Principle Component Analysis (PCA) to reduce the dimensionality of the data. eccite <- RunPCA(object = eccite) # Run Uniform Manifold Approximation and Projection (UMAP) to visualize clustering in 2-D. eccite <- RunUMAP(object = eccite, dims = 1:40) # Generate plots to check if clustering is driven by biological replicate ID, # cell cycle phase or target gene class. p1 <- DimPlot( object = eccite, group.by = 'replicate', label = F, pt.size = 0.2, reduction = "umap", cols = "Dark2", repel = T) + scale_color_brewer(palette = "Dark2") + ggtitle("Biological Replicate") + xlab("UMAP 1") + ylab("UMAP 2") + custom_theme p2 <- DimPlot( object = eccite, group.by = 'Phase', label = F, pt.size = 0.2, reduction = "umap", repel = T) + ggtitle("Cell Cycle Phase") + ylab("UMAP 2") + xlab("UMAP 1") + custom_theme p3 <- DimPlot( object = eccite, group.by = 'crispr', pt.size = 0.2, reduction = "umap", split.by = "crispr", ncol = 1, cols = c("grey39","goldenrod3")) + ggtitle("Perturbation Status") + ylab("UMAP 2") + xlab("UMAP 1") + custom_theme # Visualize plots. ((p1 / p2 + plot_layout(guides = 'auto')) | p3 )

To calculate local perturbation signatures we set the number of non-targeting Nearest Neighbors (NNs) equal to k=20 and we recommend that the user picks a k from the following range: 20 < k < 30. Intuitively, the user does not want to set k to a very small or large number as this will most likely not remove the technical variation from the dataset. Using the PRTB signature to cluster cells removes all technical variation and reveals one additional perturbation-specific cluster. # Calculate perturbation signature (PRTB). eccite<- CalcPerturbSig( object = eccite, assay = "RNA", slot = "data", gd.class ="gene", nt.cell.class = "NT", reduction = "pca", ndims = 40, num.neighbors = 20, split.by = "replicate", new.assay.name = "PRTB") # Prepare PRTB assay for dimensionality reduction: # Normalize data, find variable features and center data. DefaultAssay(object = eccite) <- 'PRTB' # Use variable features from RNA assay. VariableFeatures(object = eccite) <- VariableFeatures(object = eccite[["RNA"]]) eccite <- ScaleData(object = eccite, do.scale = F, do.center = T) # Run PCA to reduce the dimensionality of the data. eccite <- RunPCA(object = eccite, reduction.key = 'prtbpca', reduction.name = 'prtbpca') # Run UMAP to visualize clustering in 2-D. eccite <- RunUMAP( object = eccite, dims = 1:40, reduction = 'prtbpca', reduction.key = 'prtbumap', reduction.name = 'prtbumap') # Generate plots to check if clustering is driven by biological replicate ID, # cell cycle phase or target gene class. q1 <- DimPlot( object = eccite, group.by = 'replicate', reduction = 'prtbumap', pt.size = 0.2, cols = "Dark2", label = F, repel = T) + scale_color_brewer(palette = "Dark2") + ggtitle("Biological Replicate") + ylab("UMAP 2") + xlab("UMAP 1") + custom_theme q2 <- DimPlot( object = eccite, group.by = 'Phase', reduction = 'prtbumap', pt.size = 0.2, label = F, repel = T) + ggtitle("Cell Cycle Phase") + ylab("UMAP 2") + xlab("UMAP 1") + custom_theme q3 <- DimPlot( object = eccite, group.by = 'crispr', reduction = 'prtbumap', split.by = "crispr", ncol = 1, pt.size = 0.2, cols = c("grey39","goldenrod3")) + ggtitle("Perturbation Status") + ylab("UMAP 2") + xlab("UMAP 1") + custom_theme # Visualize plots. (q1 / q2 + plot_layout(guides = 'auto') | q3)

Here, we are assuming each target gene class is a mixture of two Gaussian distributions one representing the knockout (KO) and the other the non-perturbed (NP) cells. We further assume that the distribution of the NP cells is identical to that of cells expressing non-targeting gRNAs (NT) and we try to estimate the distribution of KO cells using the function normalmixEM() from the mixtools package. Next, we calculate the posterior probability that a cell belongs to the KO distribution and classify cells with a probability higher than 0.5 as KOs. Applying this method we identify KOs in 11 target gene classes and detect variation in gRNA targeting efficiency within each class. # Run mixscape. eccite <- RunMixscape( object = eccite, assay = "PRTB", slot = "scale.data", labels = "gene", nt.class.name = "NT", min.de.genes = 5, iter.num = 10, de.assay = "RNA", verbose = F, prtb.type = "KO") # Calculate percentage of KO cells for all target gene classes. df <- prop.table(table(eccite$mixscape_class.global, eccite$NT),2) df2 <- reshape2::melt(df) df2$Var2 <- as.character(df2$Var2) test <- df2[which(df2$Var1 == "KO"),] test <- test[order(test$value, decreasing = T),] new.levels <- test$Var2 df2$Var2 <- factor(df2$Var2, levels = new.levels ) df2$Var1 <- factor(df2$Var1, levels = c("NT", "NP", "KO")) df2$gene <- sapply(as.character(df2$Var2), function(x) strsplit(x, split = "g")[[1]][1]) df2$guide_number <- sapply(as.character(df2$Var2), function(x) strsplit(x, split = "g")[[1]][2]) df3 <- df2[-c(which(df2$gene == "NT")),] p1 <- ggplot(df3, aes(x = guide_number, y = value*100, fill= Var1)) + geom_bar(stat= "identity") + theme_classic()+ scale_fill_manual(values = c("grey49", "grey79","coral1")) + ylab("% of cells") + xlab("sgRNA") p1 + theme(axis.text.x = element_text(size = 18, hjust = 1), axis.text.y = element_text(size = 18), axis.title = element_text(size = 16), strip.text = element_text(size=16, face = "bold")) + facet_wrap(vars(gene),ncol = 5, scales = "free") + labs(fill = "mixscape class") +theme(legend.title = element_text(size = 14), legend.text = element_text(size = 12))

To ensure mixscape is assigning the correct perturbation status to cells we can use the functions below to look at the perturbation score distributions and the posterior probabilities of cells within a target gene class (for example IFNGR2) and compare it to those of the NT cells. In addition, we can perform differential expression (DE) analyses and show that only IFNGR2 KO cells have reduced expression of the IFNG-pathway genes. Finally, as an independent check, we can look at the PD-L1 protein expression values in NP and KO cells for target genes known to be PD-L1 regulators. # Explore the perturbation scores of cells. PlotPerturbScore(object = eccite, target.gene.ident = "IFNGR2", mixscape.class = "mixscape_class", col = "coral2") +labs(fill = "mixscape class") # Inspect the posterior probability values in NP and KO cells. VlnPlot(eccite, "mixscape_class_p_ko", idents = c("NT", "IFNGR2 KO", "IFNGR2 NP")) + theme(axis.text.x = element_text(angle = 0, hjust = 0.5),axis.text = element_text(size = 16) ,plot.title = element_text(size = 20)) + NoLegend() + ggtitle("mixscape posterior probabilities") # Run DE analysis and visualize results on a heatmap ordering cells by their posterior # probability values. Idents(object = eccite) <- "gene" MixscapeHeatmap(object = eccite, ident.1 = "NT", ident.2 = "IFNGR2", balanced = F, assay = "RNA", max.genes = 20, angle = 0, group.by = "mixscape_class", max.cells.group = 300, size=6.5) + NoLegend() +theme(axis.text.y = element_text(size = 16)) # Show that only IFNG pathway KO cells have a reduction in PD-L1 protein expression. VlnPlot( object = eccite, features = "adt_PDL1", idents = c("NT","JAK2","STAT1","IFNGR1","IFNGR2", "IRF1"), group.by = "gene", pt.size = 0.2, sort = T, split.by = "mixscape_class.global", cols = c("coral3","grey79","grey39")) + ggtitle("PD-L1 protein") + theme(axis.text.x = element_text(angle = 0, hjust = 0.5), plot.title = element_text(size = 20), axis.text = element_text(size = 16))

# Inspect the posterior probability values in NP and KO cells. VlnPlot(eccite, "mixscape_class_p_ko", idents = c("NT", "IFNGR2 KO", "IFNGR2 NP")) + theme(axis.text.x = element_text(angle = 0, hjust = 0.5),axis.text = element_text(size = 16) ,plot.title = element_text(size = 20)) + NoLegend() + ggtitle("mixscape posterior probabilities") # Run DE analysis and visualize results on a heatmap ordering cells by their posterior # probability values. Idents(object = eccite) <- "gene" MixscapeHeatmap(object = eccite, ident.1 = "NT", ident.2 = "IFNGR2", balanced = F, assay = "RNA", max.genes = 20, angle = 0, group.by = "mixscape_class", max.cells.group = 300, size=6.5) + NoLegend() +theme(axis.text.y = element_text(size = 16)) # Show that only IFNG pathway KO cells have a reduction in PD-L1 protein expression. VlnPlot( object = eccite, features = "adt_PDL1", idents = c("NT","JAK2","STAT1","IFNGR1","IFNGR2", "IRF1"), group.by = "gene", pt.size = 0.2, sort = T, split.by = "mixscape_class.global", cols = c("coral3","grey79","grey39")) + ggtitle("PD-L1 protein") + theme(axis.text.x = element_text(angle = 0, hjust = 0.5), plot.title = element_text(size = 20), axis.text = element_text(size = 16))

# Run DE analysis and visualize results on a heatmap ordering cells by their posterior # probability values. Idents(object = eccite) <- "gene" MixscapeHeatmap(object = eccite, ident.1 = "NT", ident.2 = "IFNGR2", balanced = F, assay = "RNA", max.genes = 20, angle = 0, group.by = "mixscape_class", max.cells.group = 300, size=6.5) + NoLegend() +theme(axis.text.y = element_text(size = 16)) # Show that only IFNG pathway KO cells have a reduction in PD-L1 protein expression. VlnPlot( object = eccite, features = "adt_PDL1", idents = c("NT","JAK2","STAT1","IFNGR1","IFNGR2", "IRF1"), group.by = "gene", pt.size = 0.2, sort = T, split.by = "mixscape_class.global", cols = c("coral3","grey79","grey39")) + ggtitle("PD-L1 protein") + theme(axis.text.x = element_text(angle = 0, hjust = 0.5), plot.title = element_text(size = 20), axis.text = element_text(size = 16))

# Show that only IFNG pathway KO cells have a reduction in PD-L1 protein expression. VlnPlot( object = eccite, features = "adt_PDL1", idents = c("NT","JAK2","STAT1","IFNGR1","IFNGR2", "IRF1"), group.by = "gene", pt.size = 0.2, sort = T, split.by = "mixscape_class.global", cols = c("coral3","grey79","grey39")) + ggtitle("PD-L1 protein") + theme(axis.text.x = element_text(angle = 0, hjust = 0.5), plot.title = element_text(size = 20), axis.text = element_text(size = 16))

We use LDA as a dimensionality reduction method to visualize perturbation-specific clusters. LDA is trying to maximize the separability of known labels (mixscape classes) using both gene expression and the labels as input. # Remove non-perturbed cells and run LDA to reduce the dimensionality of the data. Idents(eccite) <- "mixscape_class.global" sub <- subset(eccite, idents = c("KO", "NT")) # Run LDA. sub <- MixscapeLDA( object = sub, assay = "RNA", pc.assay = "PRTB", labels = "gene", nt.label = "NT", npcs = 10, logfc.threshold = 0.25, verbose = F) # Use LDA results to run UMAP and visualize cells on 2-D. # Here, we note that the number of the dimensions to be used is equal to the number of # labels minus one (to account for NT cells). sub <- RunUMAP( object = sub, dims = 1:11, reduction = 'lda', reduction.key = 'ldaumap', reduction.name = 'ldaumap') # Visualize UMAP clustering results. Idents(sub) <- "mixscape_class" sub$mixscape_class <- as.factor(sub$mixscape_class) # Set colors for each perturbation. col = setNames(object = hue_pal()(12),nm = levels(sub$mixscape_class)) names(col) <- c(names(col)[1:7], "NT", names(col)[9:12]) col[8] <- "grey39" p <- DimPlot(object = sub, reduction = "ldaumap", repel = T, label.size = 5, label = T, cols = col) + NoLegend() p2 <- p+ scale_color_manual(values=col, drop=FALSE) + ylab("UMAP 2") + xlab("UMAP 1") + custom_theme p2Session Info sessionInfo()## R version 4.2.0 (2022-04-22) ## Platform: x86_64-pc-linux-gnu (64-bit) ## Running under: Ubuntu 20.04.5 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/liblapack.so.3 ## ## locale: ## [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C ## [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8 ## [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 ## ## attached base packages: ## [1] stats graphics grDevices utils datasets methods base ## ## other attached packages: ## [1] reshape2_1.4.4 dplyr_1.1.0 ## [3] scales_1.2.1 patchwork_1.1.2 ## [5] ggplot2_3.4.1 thp1.eccite.SeuratData_3.1.5 ## [7] stxBrain.SeuratData_0.1.1 ssHippo.SeuratData_3.1.4 ## [9] pbmcsca.SeuratData_3.0.0 pbmcMultiome.SeuratData_0.1.2 ## [11] pbmc3k.SeuratData_3.1.4 panc8.SeuratData_3.0.2 ## [13] ifnb.SeuratData_3.1.0 hcabm40k.SeuratData_3.0.0 ## [15] bmcite.SeuratData_0.3.0 SeuratData_0.2.2 ## [17] SeuratObject_4.1.3 Seurat_4.3.0 ## ## loaded via a namespace (and not attached): ## [1] systemfonts_1.0.4 plyr_1.8.8 igraph_1.4.1 ## [4] lazyeval_0.2.2 sp_1.6-0 splines_4.2.0 ## [7] listenv_0.9.0 scattermore_0.8 digest_0.6.31 ## [10] htmltools_0.5.4 fansi_1.0.4 magrittr_2.0.3 ## [13] memoise_2.0.1 tensor_1.5 cluster_2.1.3 ## [16] mixtools_2.0.0 ROCR_1.0-11 limma_3.54.1 ## [19] globals_0.16.2 matrixStats_0.63.0 pkgdown_2.0.7 ## [22] spatstat.sparse_3.0-0 colorspace_2.1-0 rappdirs_0.3.3 ## [25] ggrepel_0.9.3 textshaping_0.3.6 xfun_0.37 ## [28] crayon_1.5.2 jsonlite_1.8.4 progressr_0.13.0 ## [31] spatstat.data_3.0-0 survival_3.3-1 zoo_1.8-11 ## [34] glue_1.6.2 polyclip_1.10-4 gtable_0.3.1 ## [37] leiden_0.4.3 kernlab_0.9-32 future.apply_1.10.0 ## [40] abind_1.4-5 spatstat.random_3.1-3 miniUI_0.1.1.1 ## [43] Rcpp_1.0.10 viridisLite_0.4.1 xtable_1.8-4 ## [46] reticulate_1.28 htmlwidgets_1.6.1 httr_1.4.5 ## [49] RColorBrewer_1.1-3 ellipsis_0.3.2 ica_1.0-3 ## [52] farver_2.1.1 pkgconfig_2.0.3 sass_0.4.5 ## [55] uwot_0.1.14 deldir_1.0-6 utf8_1.2.3 ## [58] tidyselect_1.2.0 labeling_0.4.2 rlang_1.0.6 ## [61] later_1.3.0 munsell_0.5.0 tools_4.2.0 ## [64] cachem_1.0.7 cli_3.6.0 generics_0.1.3 ## [67] ggridges_0.5.4 evaluate_0.20 stringr_1.5.0 ## [70] fastmap_1.1.1 yaml_2.3.7 ragg_1.2.5 ## [73] goftest_1.2-3 knitr_1.42 fs_1.6.1 ## [76] fitdistrplus_1.1-8 purrr_1.0.1 RANN_2.6.1 ## [79] pbapply_1.7-0 future_1.31.0 nlme_3.1-157 ## [82] mime_0.12 compiler_4.2.0 plotly_4.10.1 ## [85] png_0.1-8 spatstat.utils_3.0-1 tibble_3.1.8 ## [88] bslib_0.4.2 stringi_1.7.12 highr_0.10 ## [91] desc_1.4.2 lattice_0.20-45 Matrix_1.5-3 ## [94] vctrs_0.5.2 pillar_1.8.1 lifecycle_1.0.3 ## [97] spatstat.geom_3.0-6 lmtest_0.9-40 jquerylib_0.1.4 ## [100] RcppAnnoy_0.0.20 data.table_1.14.8 cowplot_1.1.1 ## [103] irlba_2.3.5.1 httpuv_1.6.9 R6_2.5.1 ## [106] promises_1.2.0.1 KernSmooth_2.23-20 gridExtra_2.3 ## [109] parallelly_1.34.0 codetools_0.2-18 MASS_7.3-56 ## [112] rprojroot_2.0.3 withr_2.5.0 sctransform_0.3.5 ## [115] parallel_4.2.0 grid_4.2.0 tidyr_1.3.0 ## [118] rmarkdown_2.20 segmented_1.6-2 Rtsne_0.16 ## [121] spatstat.explore_3.0-6 shiny_1.7.4

Session Info sessionInfo()## R version 4.2.0 (2022-04-22) ## Platform: x86_64-pc-linux-gnu (64-bit) ## Running under: Ubuntu 20.04.5 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/liblapack.so.3 ## ## locale: ## [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C ## [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8 ## [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 ## ## attached base packages: ## [1] stats graphics grDevices utils datasets methods base ## ## other attached packages: ## [1] reshape2_1.4.4 dplyr_1.1.0 ## [3] scales_1.2.1 patchwork_1.1.2 ## [5] ggplot2_3.4.1 thp1.eccite.SeuratData_3.1.5 ## [7] stxBrain.SeuratData_0.1.1 ssHippo.SeuratData_3.1.4 ## [9] pbmcsca.SeuratData_3.0.0 pbmcMultiome.SeuratData_0.1.2 ## [11] pbmc3k.SeuratData_3.1.4 panc8.SeuratData_3.0.2 ## [13] ifnb.SeuratData_3.1.0 hcabm40k.SeuratData_3.0.0 ## [15] bmcite.SeuratData_0.3.0 SeuratData_0.2.2 ## [17] SeuratObject_4.1.3 Seurat_4.3.0 ## ## loaded via a namespace (and not attached): ## [1] systemfonts_1.0.4 plyr_1.8.8 igraph_1.4.1 ## [4] lazyeval_0.2.2 sp_1.6-0 splines_4.2.0 ## [7] listenv_0.9.0 scattermore_0.8 digest_0.6.31 ## [10] htmltools_0.5.4 fansi_1.0.4 magrittr_2.0.3 ## [13] memoise_2.0.1 tensor_1.5 cluster_2.1.3 ## [16] mixtools_2.0.0 ROCR_1.0-11 limma_3.54.1 ## [19] globals_0.16.2 matrixStats_0.63.0 pkgdown_2.0.7 ## [22] spatstat.sparse_3.0-0 colorspace_2.1-0 rappdirs_0.3.3 ## [25] ggrepel_0.9.3 textshaping_0.3.6 xfun_0.37 ## [28] crayon_1.5.2 jsonlite_1.8.4 progressr_0.13.0 ## [31] spatstat.data_3.0-0 survival_3.3-1 zoo_1.8-11 ## [34] glue_1.6.2 polyclip_1.10-4 gtable_0.3.1 ## [37] leiden_0.4.3 kernlab_0.9-32 future.apply_1.10.0 ## [40] abind_1.4-5 spatstat.random_3.1-3 miniUI_0.1.1.1 ## [43] Rcpp_1.0.10 viridisLite_0.4.1 xtable_1.8-4 ## [46] reticulate_1.28 htmlwidgets_1.6.1 httr_1.4.5 ## [49] RColorBrewer_1.1-3 ellipsis_0.3.2 ica_1.0-3 ## [52] farver_2.1.1 pkgconfig_2.0.3 sass_0.4.5 ## [55] uwot_0.1.14 deldir_1.0-6 utf8_1.2.3 ## [58] tidyselect_1.2.0 labeling_0.4.2 rlang_1.0.6 ## [61] later_1.3.0 munsell_0.5.0 tools_4.2.0 ## [64] cachem_1.0.7 cli_3.6.0 generics_0.1.3 ## [67] ggridges_0.5.4 evaluate_0.20 stringr_1.5.0 ## [70] fastmap_1.1.1 yaml_2.3.7 ragg_1.2.5 ## [73] goftest_1.2-3 knitr_1.42 fs_1.6.1 ## [76] fitdistrplus_1.1-8 purrr_1.0.1 RANN_2.6.1 ## [79] pbapply_1.7-0 future_1.31.0 nlme_3.1-157 ## [82] mime_0.12 compiler_4.2.0 plotly_4.10.1 ## [85] png_0.1-8 spatstat.utils_3.0-1 tibble_3.1.8 ## [88] bslib_0.4.2 stringi_1.7.12 highr_0.10 ## [91] desc_1.4.2 lattice_0.20-45 Matrix_1.5-3 ## [94] vctrs_0.5.2 pillar_1.8.1 lifecycle_1.0.3 ## [97] spatstat.geom_3.0-6 lmtest_0.9-40 jquerylib_0.1.4 ## [100] RcppAnnoy_0.0.20 data.table_1.14.8 cowplot_1.1.1 ## [103] irlba_2.3.5.1 httpuv_1.6.9 R6_2.5.1 ## [106] promises_1.2.0.1 KernSmooth_2.23-20 gridExtra_2.3 ## [109] parallelly_1.34.0 codetools_0.2-18 MASS_7.3-56 ## [112] rprojroot_2.0.3 withr_2.5.0 sctransform_0.3.5 ## [115] parallel_4.2.0 grid_4.2.0 tidyr_1.3.0 ## [118] rmarkdown_2.20 segmented_1.6-2 Rtsne_0.16 ## [121] spatstat.explore_3.0-6 shiny_1.7.4

sessionInfo()## R version 4.2.0 (2022-04-22) ## Platform: x86_64-pc-linux-gnu (64-bit) ## Running under: Ubuntu 20.04.5 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/liblapack.so.3 ## ## locale: ## [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C ## [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8 ## [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 ## ## attached base packages: ## [1] stats graphics grDevices utils datasets methods base ## ## other attached packages: ## [1] reshape2_1.4.4 dplyr_1.1.0 ## [3] scales_1.2.1 patchwork_1.1.2 ## [5] ggplot2_3.4.1 thp1.eccite.SeuratData_3.1.5 ## [7] stxBrain.SeuratData_0.1.1 ssHippo.SeuratData_3.1.4 ## [9] pbmcsca.SeuratData_3.0.0 pbmcMultiome.SeuratData_0.1.2 ## [11] pbmc3k.SeuratData_3.1.4 panc8.SeuratData_3.0.2 ## [13] ifnb.SeuratData_3.1.0 hcabm40k.SeuratData_3.0.0 ## [15] bmcite.SeuratData_0.3.0 SeuratData_0.2.2 ## [17] SeuratObject_4.1.3 Seurat_4.3.0 ## ## loaded via a namespace (and not attached): ## [1] systemfonts_1.0.4 plyr_1.8.8 igraph_1.4.1 ## [4] lazyeval_0.2.2 sp_1.6-0 splines_4.2.0 ## [7] listenv_0.9.0 scattermore_0.8 digest_0.6.31 ## [10] htmltools_0.5.4 fansi_1.0.4 magrittr_2.0.3 ## [13] memoise_2.0.1 tensor_1.5 cluster_2.1.3 ## [16] mixtools_2.0.0 ROCR_1.0-11 limma_3.54.1 ## [19] globals_0.16.2 matrixStats_0.63.0 pkgdown_2.0.7 ## [22] spatstat.sparse_3.0-0 colorspace_2.1-0 rappdirs_0.3.3 ## [25] ggrepel_0.9.3 textshaping_0.3.6 xfun_0.37 ## [28] crayon_1.5.2 jsonlite_1.8.4 progressr_0.13.0 ## [31] spatstat.data_3.0-0 survival_3.3-1 zoo_1.8-11 ## [34] glue_1.6.2 polyclip_1.10-4 gtable_0.3.1 ## [37] leiden_0.4.3 kernlab_0.9-32 future.apply_1.10.0 ## [40] abind_1.4-5 spatstat.random_3.1-3 miniUI_0.1.1.1 ## [43] Rcpp_1.0.10 viridisLite_0.4.1 xtable_1.8-4 ## [46] reticulate_1.28 htmlwidgets_1.6.1 httr_1.4.5 ## [49] RColorBrewer_1.1-3 ellipsis_0.3.2 ica_1.0-3 ## [52] farver_2.1.1 pkgconfig_2.0.3 sass_0.4.5 ## [55] uwot_0.1.14 deldir_1.0-6 utf8_1.2.3 ## [58] tidyselect_1.2.0 labeling_0.4.2 rlang_1.0.6 ## [61] later_1.3.0 munsell_0.5.0 tools_4.2.0 ## [64] cachem_1.0.7 cli_3.6.0 generics_0.1.3 ## [67] ggridges_0.5.4 evaluate_0.20 stringr_1.5.0 ## [70] fastmap_1.1.1 yaml_2.3.7 ragg_1.2.5 ## [73] goftest_1.2-3 knitr_1.42 fs_1.6.1 ## [76] fitdistrplus_1.1-8 purrr_1.0.1 RANN_2.6.1 ## [79] pbapply_1.7-0 future_1.31.0 nlme_3.1-157 ## [82] mime_0.12 compiler_4.2.0 plotly_4.10.1 ## [85] png_0.1-8 spatstat.utils_3.0-1 tibble_3.1.8 ## [88] bslib_0.4.2 stringi_1.7.12 highr_0.10 ## [91] desc_1.4.2 lattice_0.20-45 Matrix_1.5-3 ## [94] vctrs_0.5.2 pillar_1.8.1 lifecycle_1.0.3 ## [97] spatstat.geom_3.0-6 lmtest_0.9-40 jquerylib_0.1.4 ## [100] RcppAnnoy_0.0.20 data.table_1.14.8 cowplot_1.1.1 ## [103] irlba_2.3.5.1 httpuv_1.6.9 R6_2.5.1 ## [106] promises_1.2.0.1 KernSmooth_2.23-20 gridExtra_2.3 ## [109] parallelly_1.34.0 codetools_0.2-18 MASS_7.3-56 ## [112] rprojroot_2.0.3 withr_2.5.0 sctransform_0.3.5 ## [115] parallel_4.2.0 grid_4.2.0 tidyr_1.3.0 ## [118] rmarkdown_2.20 segmented_1.6-2 Rtsne_0.16 ## [121] spatstat.explore_3.0-6 shiny_1.7.4

Developed by Paul Hoffman, Satija Lab and Collaborators.

Developed by Paul Hoffman, Satija Lab and Collaborators.

Site built with pkgdown 2.0.7.

Site built with pkgdown 2.0.7.

**Examples:**

Example 1 (unknown):
```unknown
vignettes/mixscape_vignette.Rmd
```

Example 2 (unknown):
```unknown
mixscape_vignette.Rmd
```

Example 3 (unknown):
```unknown
# Load packages.
library(Seurat)
library(SeuratData)
library(ggplot2)
library(patchwork)
library(scales)
library(dplyr)
library(reshape2)

# Download dataset using SeuratData.
InstallData(ds = "thp1.eccite")

# Setup custom theme for plotting.
custom_theme <- theme(
  plot.title = element_text(size=16, hjust = 0.5), 
  legend.key.size = unit(0.7, "cm"), 
  legend.text = element_text(size = 14))
```

Example 4 (r):
```r
# Load packages.
library(Seurat)
library(SeuratData)
library(ggplot2)
library(patchwork)
library(scales)
library(dplyr)
library(reshape2)

# Download dataset using SeuratData.
InstallData(ds = "thp1.eccite")

# Setup custom theme for plotting.
custom_theme <- theme(
  plot.title = element_text(size=16, hjust = 0.5), 
  legend.key.size = unit(0.7, "cm"), 
  legend.text = element_text(size = 14))
```

Example 5 (r):
```r
# Load packages.
library(Seurat)
library(SeuratData)
library(ggplot2)
library(patchwork)
library(scales)
library(dplyr)
library(reshape2)

# Download dataset using SeuratData.
InstallData(ds = "thp1.eccite")

# Setup custom theme for plotting.
custom_theme <- theme(
  plot.title = element_text(size=16, hjust = 0.5), 
  legend.key.size = unit(0.7, "cm"), 
  legend.text = element_text(size = 14))
```

Example 6 (unknown):
```unknown
# Load object.
eccite <- LoadData(ds = "thp1.eccite")

# Normalize protein.
eccite <- NormalizeData(
  object = eccite, 
  assay = "ADT", 
  normalization.method = "CLR", 
  margin = 2)
```

Example 7 (r):
```r
# Load object.
eccite <- LoadData(ds = "thp1.eccite")

# Normalize protein.
eccite <- NormalizeData(
  object = eccite, 
  assay = "ADT", 
  normalization.method = "CLR", 
  margin = 2)
```

Example 8 (r):
```r
# Load object.
eccite <- LoadData(ds = "thp1.eccite")

# Normalize protein.
eccite <- NormalizeData(
  object = eccite, 
  assay = "ADT", 
  normalization.method = "CLR", 
  margin = 2)
```

Example 9 (unknown):
```unknown
# Prepare RNA assay for dimensionality reduction: 
# Normalize data, find variable features and scale data.
DefaultAssay(object = eccite) <- 'RNA'
eccite <- NormalizeData(object = eccite) %>% FindVariableFeatures() %>% ScaleData()

# Run Principle Component Analysis (PCA) to reduce the dimensionality of the data.
eccite <- RunPCA(object = eccite)

# Run Uniform Manifold Approximation and Projection (UMAP) to visualize clustering in 2-D.
eccite <- RunUMAP(object = eccite, dims = 1:40)

# Generate plots to check if clustering is driven by biological replicate ID, 
# cell cycle phase or target gene class.
p1 <- DimPlot(
  object = eccite, 
  group.by = 'replicate', 
  label = F, 
  pt.size = 0.2, 
  reduction = "umap", cols = "Dark2", repel = T) +
  scale_color_brewer(palette = "Dark2") +
  ggtitle("Biological Replicate") +
  xlab("UMAP 1") +
  ylab("UMAP 2") +
  custom_theme

p2 <- DimPlot(
  object = eccite, 
  group.by = 'Phase', 
  label = F, pt.size = 0.2, 
  reduction = "umap", repel = T) + 
  ggtitle("Cell Cycle Phase") +
  ylab("UMAP 2") +
  xlab("UMAP 1") +
  custom_theme

p3 <- DimPlot(
  object = eccite, 
  group.by = 'crispr', 
  pt.size = 0.2, 
  reduction = "umap", 
  split.by = "crispr", 
  ncol = 1, 
  cols = c("grey39","goldenrod3")) + 
  ggtitle("Perturbation Status") +
  ylab("UMAP 2") +
  xlab("UMAP 1") +
  custom_theme

# Visualize plots.
((p1 / p2 + plot_layout(guides = 'auto')) | p3 )
```

Example 10 (r):
```r
# Prepare RNA assay for dimensionality reduction: 
# Normalize data, find variable features and scale data.
DefaultAssay(object = eccite) <- 'RNA'
eccite <- NormalizeData(object = eccite) %>% FindVariableFeatures() %>% ScaleData()

# Run Principle Component Analysis (PCA) to reduce the dimensionality of the data.
eccite <- RunPCA(object = eccite)

# Run Uniform Manifold Approximation and Projection (UMAP) to visualize clustering in 2-D.
eccite <- RunUMAP(object = eccite, dims = 1:40)

# Generate plots to check if clustering is driven by biological replicate ID, 
# cell cycle phase or target gene class.
p1 <- DimPlot(
  object = eccite, 
  group.by = 'replicate', 
  label = F, 
  pt.size = 0.2, 
  reduction = "umap", cols = "Dark2", repel = T) +
  scale_color_brewer(palette = "Dark2") +
  ggtitle("Biological Replicate") +
  xlab("UMAP 1") +
  ylab("UMAP 2") +
  custom_theme

p2 <- DimPlot(
  object = eccite, 
  group.by = 'Phase', 
  label = F, pt.size = 0.2, 
  reduction = "umap", repel = T) + 
  ggtitle("Cell Cycle Phase") +
  ylab("UMAP 2") +
  xlab("UMAP 1") +
  custom_theme

p3 <- DimPlot(
  object = eccite, 
  group.by = 'crispr', 
  pt.size = 0.2, 
  reduction = "umap", 
  split.by = "crispr", 
  ncol = 1, 
  cols = c("grey39","goldenrod3")) + 
  ggtitle("Perturbation Status") +
  ylab("UMAP 2") +
  xlab("UMAP 1") +
  custom_theme

# Visualize plots.
((p1 / p2 + plot_layout(guides = 'auto')) | p3 )
```

Example 11 (r):
```r
# Prepare RNA assay for dimensionality reduction: 
# Normalize data, find variable features and scale data.
DefaultAssay(object = eccite) <- 'RNA'
eccite <- NormalizeData(object = eccite) %>% FindVariableFeatures() %>% ScaleData()

# Run Principle Component Analysis (PCA) to reduce the dimensionality of the data.
eccite <- RunPCA(object = eccite)

# Run Uniform Manifold Approximation and Projection (UMAP) to visualize clustering in 2-D.
eccite <- RunUMAP(object = eccite, dims = 1:40)

# Generate plots to check if clustering is driven by biological replicate ID, 
# cell cycle phase or target gene class.
p1 <- DimPlot(
  object = eccite, 
  group.by = 'replicate', 
  label = F, 
  pt.size = 0.2, 
  reduction = "umap", cols = "Dark2", repel = T) +
  scale_color_brewer(palette = "Dark2") +
  ggtitle("Biological Replicate") +
  xlab("UMAP 1") +
  ylab("UMAP 2") +
  custom_theme

p2 <- DimPlot(
  object = eccite, 
  group.by = 'Phase', 
  label = F, pt.size = 0.2, 
  reduction = "umap", repel = T) + 
  ggtitle("Cell Cycle Phase") +
  ylab("UMAP 2") +
  xlab("UMAP 1") +
  custom_theme

p3 <- DimPlot(
  object = eccite, 
  group.by = 'crispr', 
  pt.size = 0.2, 
  reduction = "umap", 
  split.by = "crispr", 
  ncol = 1, 
  cols = c("grey39","goldenrod3")) + 
  ggtitle("Perturbation Status") +
  ylab("UMAP 2") +
  xlab("UMAP 1") +
  custom_theme

# Visualize plots.
((p1 / p2 + plot_layout(guides = 'auto')) | p3 )
```

Example 12 (python):
```python
# Calculate perturbation signature (PRTB).
eccite<- CalcPerturbSig(
  object = eccite, 
  assay = "RNA", 
  slot = "data", 
  gd.class ="gene", 
  nt.cell.class = "NT", 
  reduction = "pca", 
  ndims = 40, 
  num.neighbors = 20, 
  split.by = "replicate", 
  new.assay.name = "PRTB")

# Prepare PRTB assay for dimensionality reduction: 
# Normalize data, find variable features and center data.
DefaultAssay(object = eccite) <- 'PRTB'

# Use variable features from RNA assay.
VariableFeatures(object = eccite) <- VariableFeatures(object = eccite[["RNA"]])
eccite <- ScaleData(object = eccite, do.scale = F, do.center = T)

# Run PCA to reduce the dimensionality of the data.
eccite <- RunPCA(object = eccite, reduction.key = 'prtbpca', reduction.name = 'prtbpca')

# Run UMAP to visualize clustering in 2-D.
eccite <- RunUMAP(
  object = eccite, 
  dims = 1:40, 
  reduction = 'prtbpca', 
  reduction.key = 'prtbumap', 
  reduction.name = 'prtbumap')

# Generate plots to check if clustering is driven by biological replicate ID, 
# cell cycle phase or target gene class.
q1 <- DimPlot(
  object = eccite, 
  group.by = 'replicate', 
  reduction = 'prtbumap', 
  pt.size = 0.2, cols = "Dark2", label = F, repel = T) +
  scale_color_brewer(palette = "Dark2") +
  ggtitle("Biological Replicate") +
  ylab("UMAP 2") +
  xlab("UMAP 1") +
  custom_theme

q2 <- DimPlot(
  object = eccite, 
  group.by = 'Phase', 
  reduction = 'prtbumap', 
  pt.size = 0.2, label = F, repel = T) +
  ggtitle("Cell Cycle Phase") +
  ylab("UMAP 2") +
  xlab("UMAP 1") + 
  custom_theme

q3 <- DimPlot(
  object = eccite,
  group.by = 'crispr',
  reduction = 'prtbumap', 
  split.by = "crispr", 
  ncol = 1, 
  pt.size = 0.2, 
  cols = c("grey39","goldenrod3")) +
  ggtitle("Perturbation Status") +
  ylab("UMAP 2") +
  xlab("UMAP 1") +
  custom_theme

# Visualize plots.
(q1 / q2 + plot_layout(guides = 'auto') | q3)
```

Example 13 (r):
```r
# Calculate perturbation signature (PRTB).
eccite<- CalcPerturbSig(
  object = eccite, 
  assay = "RNA", 
  slot = "data", 
  gd.class ="gene", 
  nt.cell.class = "NT", 
  reduction = "pca", 
  ndims = 40, 
  num.neighbors = 20, 
  split.by = "replicate", 
  new.assay.name = "PRTB")

# Prepare PRTB assay for dimensionality reduction: 
# Normalize data, find variable features and center data.
DefaultAssay(object = eccite) <- 'PRTB'

# Use variable features from RNA assay.
VariableFeatures(object = eccite) <- VariableFeatures(object = eccite[["RNA"]])
eccite <- ScaleData(object = eccite, do.scale = F, do.center = T)

# Run PCA to reduce the dimensionality of the data.
eccite <- RunPCA(object = eccite, reduction.key = 'prtbpca', reduction.name = 'prtbpca')

# Run UMAP to visualize clustering in 2-D.
eccite <- RunUMAP(
  object = eccite, 
  dims = 1:40, 
  reduction = 'prtbpca', 
  reduction.key = 'prtbumap', 
  reduction.name = 'prtbumap')

# Generate plots to check if clustering is driven by biological replicate ID, 
# cell cycle phase or target gene class.
q1 <- DimPlot(
  object = eccite, 
  group.by = 'replicate', 
  reduction = 'prtbumap', 
  pt.size = 0.2, cols = "Dark2", label = F, repel = T) +
  scale_color_brewer(palette = "Dark2") +
  ggtitle("Biological Replicate") +
  ylab("UMAP 2") +
  xlab("UMAP 1") +
  custom_theme

q2 <- DimPlot(
  object = eccite, 
  group.by = 'Phase', 
  reduction = 'prtbumap', 
  pt.size = 0.2, label = F, repel = T) +
  ggtitle("Cell Cycle Phase") +
  ylab("UMAP 2") +
  xlab("UMAP 1") + 
  custom_theme

q3 <- DimPlot(
  object = eccite,
  group.by = 'crispr',
  reduction = 'prtbumap', 
  split.by = "crispr", 
  ncol = 1, 
  pt.size = 0.2, 
  cols = c("grey39","goldenrod3")) +
  ggtitle("Perturbation Status") +
  ylab("UMAP 2") +
  xlab("UMAP 1") +
  custom_theme

# Visualize plots.
(q1 / q2 + plot_layout(guides = 'auto') | q3)
```

Example 14 (r):
```r
# Calculate perturbation signature (PRTB).
eccite<- CalcPerturbSig(
  object = eccite, 
  assay = "RNA", 
  slot = "data", 
  gd.class ="gene", 
  nt.cell.class = "NT", 
  reduction = "pca", 
  ndims = 40, 
  num.neighbors = 20, 
  split.by = "replicate", 
  new.assay.name = "PRTB")

# Prepare PRTB assay for dimensionality reduction: 
# Normalize data, find variable features and center data.
DefaultAssay(object = eccite) <- 'PRTB'

# Use variable features from RNA assay.
VariableFeatures(object = eccite) <- VariableFeatures(object = eccite[["RNA"]])
eccite <- ScaleData(object = eccite, do.scale = F, do.center = T)

# Run PCA to reduce the dimensionality of the data.
eccite <- RunPCA(object = eccite, reduction.key = 'prtbpca', reduction.name = 'prtbpca')

# Run UMAP to visualize clustering in 2-D.
eccite <- RunUMAP(
  object = eccite, 
  dims = 1:40, 
  reduction = 'prtbpca', 
  reduction.key = 'prtbumap', 
  reduction.name = 'prtbumap')

# Generate plots to check if clustering is driven by biological replicate ID, 
# cell cycle phase or target gene class.
q1 <- DimPlot(
  object = eccite, 
  group.by = 'replicate', 
  reduction = 'prtbumap', 
  pt.size = 0.2, cols = "Dark2", label = F, repel = T) +
  scale_color_brewer(palette = "Dark2") +
  ggtitle("Biological Replicate") +
  ylab("UMAP 2") +
  xlab("UMAP 1") +
  custom_theme

q2 <- DimPlot(
  object = eccite, 
  group.by = 'Phase', 
  reduction = 'prtbumap', 
  pt.size = 0.2, label = F, repel = T) +
  ggtitle("Cell Cycle Phase") +
  ylab("UMAP 2") +
  xlab("UMAP 1") + 
  custom_theme

q3 <- DimPlot(
  object = eccite,
  group.by = 'crispr',
  reduction = 'prtbumap', 
  split.by = "crispr", 
  ncol = 1, 
  pt.size = 0.2, 
  cols = c("grey39","goldenrod3")) +
  ggtitle("Perturbation Status") +
  ylab("UMAP 2") +
  xlab("UMAP 1") +
  custom_theme

# Visualize plots.
(q1 / q2 + plot_layout(guides = 'auto') | q3)
```

Example 15 (unknown):
```unknown
normalmixEM()
```

Example 16 (javascript):
```javascript
# Run mixscape.
eccite <- RunMixscape(
  object = eccite, 
  assay = "PRTB", 
  slot = "scale.data", 
  labels = "gene", 
  nt.class.name = "NT", 
  min.de.genes = 5, 
  iter.num = 10, 
  de.assay = "RNA", 
  verbose = F,
  prtb.type = "KO")

# Calculate percentage of KO cells for all target gene classes.
df <- prop.table(table(eccite$mixscape_class.global, eccite$NT),2)

df2 <- reshape2::melt(df)
df2$Var2 <- as.character(df2$Var2)
test <- df2[which(df2$Var1 == "KO"),]
test <- test[order(test$value, decreasing = T),]
new.levels <- test$Var2
df2$Var2 <- factor(df2$Var2, levels = new.levels )
df2$Var1 <- factor(df2$Var1, levels = c("NT", "NP", "KO"))
df2$gene <- sapply(as.character(df2$Var2), function(x) strsplit(x, split = "g")[[1]][1])
df2$guide_number <- sapply(as.character(df2$Var2), 
                           function(x) strsplit(x, split = "g")[[1]][2])
df3 <- df2[-c(which(df2$gene == "NT")),]

p1 <- ggplot(df3, aes(x = guide_number, y = value*100, fill= Var1)) +
  geom_bar(stat= "identity") +
  theme_classic()+
  scale_fill_manual(values = c("grey49", "grey79","coral1")) + 
  ylab("% of cells") +
  xlab("sgRNA")

p1 + theme(axis.text.x = element_text(size = 18, hjust = 1), 
           axis.text.y = element_text(size = 18), 
           axis.title = element_text(size = 16), 
           strip.text = element_text(size=16, face = "bold")) + 
  facet_wrap(vars(gene),ncol = 5, scales = "free") +
  labs(fill = "mixscape class") +theme(legend.title = element_text(size = 14),
          legend.text = element_text(size = 12))
```

Example 17 (r):
```r
# Run mixscape.
eccite <- RunMixscape(
  object = eccite, 
  assay = "PRTB", 
  slot = "scale.data", 
  labels = "gene", 
  nt.class.name = "NT", 
  min.de.genes = 5, 
  iter.num = 10, 
  de.assay = "RNA", 
  verbose = F,
  prtb.type = "KO")

# Calculate percentage of KO cells for all target gene classes.
df <- prop.table(table(eccite$mixscape_class.global, eccite$NT),2)

df2 <- reshape2::melt(df)
df2$Var2 <- as.character(df2$Var2)
test <- df2[which(df2$Var1 == "KO"),]
test <- test[order(test$value, decreasing = T),]
new.levels <- test$Var2
df2$Var2 <- factor(df2$Var2, levels = new.levels )
df2$Var1 <- factor(df2$Var1, levels = c("NT", "NP", "KO"))
df2$gene <- sapply(as.character(df2$Var2), function(x) strsplit(x, split = "g")[[1]][1])
df2$guide_number <- sapply(as.character(df2$Var2), 
                           function(x) strsplit(x, split = "g")[[1]][2])
df3 <- df2[-c(which(df2$gene == "NT")),]

p1 <- ggplot(df3, aes(x = guide_number, y = value*100, fill= Var1)) +
  geom_bar(stat= "identity") +
  theme_classic()+
  scale_fill_manual(values = c("grey49", "grey79","coral1")) + 
  ylab("% of cells") +
  xlab("sgRNA")

p1 + theme(axis.text.x = element_text(size = 18, hjust = 1), 
           axis.text.y = element_text(size = 18), 
           axis.title = element_text(size = 16), 
           strip.text = element_text(size=16, face = "bold")) + 
  facet_wrap(vars(gene),ncol = 5, scales = "free") +
  labs(fill = "mixscape class") +theme(legend.title = element_text(size = 14),
          legend.text = element_text(size = 12))
```

Example 18 (r):
```r
# Run mixscape.
eccite <- RunMixscape(
  object = eccite, 
  assay = "PRTB", 
  slot = "scale.data", 
  labels = "gene", 
  nt.class.name = "NT", 
  min.de.genes = 5, 
  iter.num = 10, 
  de.assay = "RNA", 
  verbose = F,
  prtb.type = "KO")

# Calculate percentage of KO cells for all target gene classes.
df <- prop.table(table(eccite$mixscape_class.global, eccite$NT),2)

df2 <- reshape2::melt(df)
df2$Var2 <- as.character(df2$Var2)
test <- df2[which(df2$Var1 == "KO"),]
test <- test[order(test$value, decreasing = T),]
new.levels <- test$Var2
df2$Var2 <- factor(df2$Var2, levels = new.levels )
df2$Var1 <- factor(df2$Var1, levels = c("NT", "NP", "KO"))
df2$gene <- sapply(as.character(df2$Var2), function(x) strsplit(x, split = "g")[[1]][1])
df2$guide_number <- sapply(as.character(df2$Var2), 
                           function(x) strsplit(x, split = "g")[[1]][2])
df3 <- df2[-c(which(df2$gene == "NT")),]

p1 <- ggplot(df3, aes(x = guide_number, y = value*100, fill= Var1)) +
  geom_bar(stat= "identity") +
  theme_classic()+
  scale_fill_manual(values = c("grey49", "grey79","coral1")) + 
  ylab("% of cells") +
  xlab("sgRNA")

p1 + theme(axis.text.x = element_text(size = 18, hjust = 1), 
           axis.text.y = element_text(size = 18), 
           axis.title = element_text(size = 16), 
           strip.text = element_text(size=16, face = "bold")) + 
  facet_wrap(vars(gene),ncol = 5, scales = "free") +
  labs(fill = "mixscape class") +theme(legend.title = element_text(size = 14),
          legend.text = element_text(size = 12))
```

Example 19 (python):
```python
# Explore the perturbation scores of cells.
PlotPerturbScore(object = eccite, 
                 target.gene.ident = "IFNGR2", 
                 mixscape.class = "mixscape_class", 
                 col = "coral2") +labs(fill = "mixscape class")
```

Example 20 (r):
```r
# Explore the perturbation scores of cells.
PlotPerturbScore(object = eccite, 
                 target.gene.ident = "IFNGR2", 
                 mixscape.class = "mixscape_class", 
                 col = "coral2") +labs(fill = "mixscape class")
```

Example 21 (r):
```r
# Explore the perturbation scores of cells.
PlotPerturbScore(object = eccite, 
                 target.gene.ident = "IFNGR2", 
                 mixscape.class = "mixscape_class", 
                 col = "coral2") +labs(fill = "mixscape class")
```

Example 22 (unknown):
```unknown
# Inspect the posterior probability values in NP and KO cells.
VlnPlot(eccite, "mixscape_class_p_ko", idents = c("NT", "IFNGR2 KO", "IFNGR2 NP")) +
  theme(axis.text.x = element_text(angle = 0, hjust = 0.5),axis.text = element_text(size = 16) ,plot.title = element_text(size = 20)) + 
  NoLegend() +
  ggtitle("mixscape posterior probabilities")
```

Example 23 (r):
```r
# Inspect the posterior probability values in NP and KO cells.
VlnPlot(eccite, "mixscape_class_p_ko", idents = c("NT", "IFNGR2 KO", "IFNGR2 NP")) +
  theme(axis.text.x = element_text(angle = 0, hjust = 0.5),axis.text = element_text(size = 16) ,plot.title = element_text(size = 20)) + 
  NoLegend() +
  ggtitle("mixscape posterior probabilities")
```

Example 24 (r):
```r
# Inspect the posterior probability values in NP and KO cells.
VlnPlot(eccite, "mixscape_class_p_ko", idents = c("NT", "IFNGR2 KO", "IFNGR2 NP")) +
  theme(axis.text.x = element_text(angle = 0, hjust = 0.5),axis.text = element_text(size = 16) ,plot.title = element_text(size = 20)) + 
  NoLegend() +
  ggtitle("mixscape posterior probabilities")
```

Example 25 (unknown):
```unknown
# Run DE analysis and visualize results on a heatmap ordering cells by their posterior 
# probability values.
Idents(object = eccite) <- "gene"
MixscapeHeatmap(object = eccite, 
                ident.1 = "NT", 
                ident.2 = "IFNGR2", 
                balanced = F, 
                assay = "RNA", 
                max.genes = 20, angle = 0, 
                group.by = "mixscape_class", 
                max.cells.group = 300, 
                size=6.5) + NoLegend() +theme(axis.text.y = element_text(size = 16))
```

Example 26 (r):
```r
# Run DE analysis and visualize results on a heatmap ordering cells by their posterior 
# probability values.
Idents(object = eccite) <- "gene"
MixscapeHeatmap(object = eccite, 
                ident.1 = "NT", 
                ident.2 = "IFNGR2", 
                balanced = F, 
                assay = "RNA", 
                max.genes = 20, angle = 0, 
                group.by = "mixscape_class", 
                max.cells.group = 300, 
                size=6.5) + NoLegend() +theme(axis.text.y = element_text(size = 16))
```

Example 27 (r):
```r
# Run DE analysis and visualize results on a heatmap ordering cells by their posterior 
# probability values.
Idents(object = eccite) <- "gene"
MixscapeHeatmap(object = eccite, 
                ident.1 = "NT", 
                ident.2 = "IFNGR2", 
                balanced = F, 
                assay = "RNA", 
                max.genes = 20, angle = 0, 
                group.by = "mixscape_class", 
                max.cells.group = 300, 
                size=6.5) + NoLegend() +theme(axis.text.y = element_text(size = 16))
```

Example 28 (unknown):
```unknown
# Show that only IFNG pathway KO cells have a reduction in PD-L1 protein expression.
VlnPlot(
  object = eccite, 
  features = "adt_PDL1", 
  idents = c("NT","JAK2","STAT1","IFNGR1","IFNGR2", "IRF1"), 
  group.by = "gene", 
  pt.size = 0.2, 
  sort = T, 
  split.by = "mixscape_class.global", 
  cols = c("coral3","grey79","grey39")) +
  ggtitle("PD-L1 protein") +
  theme(axis.text.x = element_text(angle = 0, hjust = 0.5), plot.title = element_text(size = 20), axis.text = element_text(size = 16))
```

Example 29 (r):
```r
# Show that only IFNG pathway KO cells have a reduction in PD-L1 protein expression.
VlnPlot(
  object = eccite, 
  features = "adt_PDL1", 
  idents = c("NT","JAK2","STAT1","IFNGR1","IFNGR2", "IRF1"), 
  group.by = "gene", 
  pt.size = 0.2, 
  sort = T, 
  split.by = "mixscape_class.global", 
  cols = c("coral3","grey79","grey39")) +
  ggtitle("PD-L1 protein") +
  theme(axis.text.x = element_text(angle = 0, hjust = 0.5), plot.title = element_text(size = 20), axis.text = element_text(size = 16))
```

Example 30 (r):
```r
# Show that only IFNG pathway KO cells have a reduction in PD-L1 protein expression.
VlnPlot(
  object = eccite, 
  features = "adt_PDL1", 
  idents = c("NT","JAK2","STAT1","IFNGR1","IFNGR2", "IRF1"), 
  group.by = "gene", 
  pt.size = 0.2, 
  sort = T, 
  split.by = "mixscape_class.global", 
  cols = c("coral3","grey79","grey39")) +
  ggtitle("PD-L1 protein") +
  theme(axis.text.x = element_text(angle = 0, hjust = 0.5), plot.title = element_text(size = 20), axis.text = element_text(size = 16))
```

Example 31 (python):
```python
# Remove non-perturbed cells and run LDA to reduce the dimensionality of the data.
Idents(eccite) <- "mixscape_class.global"
sub <- subset(eccite, idents = c("KO", "NT"))

# Run LDA.
sub <- MixscapeLDA(
  object = sub, 
  assay = "RNA", 
  pc.assay = "PRTB", 
  labels = "gene", 
  nt.label = "NT", 
  npcs = 10, 
  logfc.threshold = 0.25, 
  verbose = F)

# Use LDA results to run UMAP and visualize cells on 2-D. 
# Here, we note that the number of the dimensions to be used is equal to the number of 
# labels minus one (to account for NT cells).
sub <- RunUMAP(
  object = sub,
  dims = 1:11,
  reduction = 'lda',
  reduction.key = 'ldaumap',
  reduction.name = 'ldaumap')

# Visualize UMAP clustering results.
Idents(sub) <- "mixscape_class"
sub$mixscape_class <- as.factor(sub$mixscape_class)

# Set colors for each perturbation.
col = setNames(object = hue_pal()(12),nm = levels(sub$mixscape_class))
names(col) <- c(names(col)[1:7], "NT", names(col)[9:12])
col[8] <- "grey39"

p <- DimPlot(object = sub, 
             reduction = "ldaumap", 
             repel = T, 
             label.size = 5, 
             label = T, 
             cols = col) + NoLegend()

p2 <- p+ 
  scale_color_manual(values=col, drop=FALSE) + 
  ylab("UMAP 2") +
  xlab("UMAP 1") +
  custom_theme
p2
```

Example 32 (r):
```r
# Remove non-perturbed cells and run LDA to reduce the dimensionality of the data.
Idents(eccite) <- "mixscape_class.global"
sub <- subset(eccite, idents = c("KO", "NT"))

# Run LDA.
sub <- MixscapeLDA(
  object = sub, 
  assay = "RNA", 
  pc.assay = "PRTB", 
  labels = "gene", 
  nt.label = "NT", 
  npcs = 10, 
  logfc.threshold = 0.25, 
  verbose = F)

# Use LDA results to run UMAP and visualize cells on 2-D. 
# Here, we note that the number of the dimensions to be used is equal to the number of 
# labels minus one (to account for NT cells).
sub <- RunUMAP(
  object = sub,
  dims = 1:11,
  reduction = 'lda',
  reduction.key = 'ldaumap',
  reduction.name = 'ldaumap')

# Visualize UMAP clustering results.
Idents(sub) <- "mixscape_class"
sub$mixscape_class <- as.factor(sub$mixscape_class)

# Set colors for each perturbation.
col = setNames(object = hue_pal()(12),nm = levels(sub$mixscape_class))
names(col) <- c(names(col)[1:7], "NT", names(col)[9:12])
col[8] <- "grey39"

p <- DimPlot(object = sub, 
             reduction = "ldaumap", 
             repel = T, 
             label.size = 5, 
             label = T, 
             cols = col) + NoLegend()

p2 <- p+ 
  scale_color_manual(values=col, drop=FALSE) + 
  ylab("UMAP 2") +
  xlab("UMAP 1") +
  custom_theme
p2
```

Example 33 (r):
```r
# Remove non-perturbed cells and run LDA to reduce the dimensionality of the data.
Idents(eccite) <- "mixscape_class.global"
sub <- subset(eccite, idents = c("KO", "NT"))

# Run LDA.
sub <- MixscapeLDA(
  object = sub, 
  assay = "RNA", 
  pc.assay = "PRTB", 
  labels = "gene", 
  nt.label = "NT", 
  npcs = 10, 
  logfc.threshold = 0.25, 
  verbose = F)

# Use LDA results to run UMAP and visualize cells on 2-D. 
# Here, we note that the number of the dimensions to be used is equal to the number of 
# labels minus one (to account for NT cells).
sub <- RunUMAP(
  object = sub,
  dims = 1:11,
  reduction = 'lda',
  reduction.key = 'ldaumap',
  reduction.name = 'ldaumap')

# Visualize UMAP clustering results.
Idents(sub) <- "mixscape_class"
sub$mixscape_class <- as.factor(sub$mixscape_class)

# Set colors for each perturbation.
col = setNames(object = hue_pal()(12),nm = levels(sub$mixscape_class))
names(col) <- c(names(col)[1:7], "NT", names(col)[9:12])
col[8] <- "grey39"

p <- DimPlot(object = sub, 
             reduction = "ldaumap", 
             repel = T, 
             label.size = 5, 
             label = T, 
             cols = col) + NoLegend()

p2 <- p+ 
  scale_color_manual(values=col, drop=FALSE) + 
  ylab("UMAP 2") +
  xlab("UMAP 1") +
  custom_theme
p2
```

Example 34 (unknown):
```unknown
sessionInfo()
```

Example 35 (r):
```r
sessionInfo()
```

Example 36 (r):
```r
sessionInfo()
```

Example 37 (unknown):
```unknown
## R version 4.2.0 (2022-04-22)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.5 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/liblapack.so.3
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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       
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
##  [1] reshape2_1.4.4                dplyr_1.1.0                  
##  [3] scales_1.2.1                  patchwork_1.1.2              
##  [5] ggplot2_3.4.1                 thp1.eccite.SeuratData_3.1.5 
##  [7] stxBrain.SeuratData_0.1.1     ssHippo.SeuratData_3.1.4     
##  [9] pbmcsca.SeuratData_3.0.0      pbmcMultiome.SeuratData_0.1.2
## [11] pbmc3k.SeuratData_3.1.4       panc8.SeuratData_3.0.2       
## [13] ifnb.SeuratData_3.1.0         hcabm40k.SeuratData_3.0.0    
## [15] bmcite.SeuratData_0.3.0       SeuratData_0.2.2             
## [17] SeuratObject_4.1.3            Seurat_4.3.0                 
## 
## loaded via a namespace (and not attached):
##   [1] systemfonts_1.0.4      plyr_1.8.8             igraph_1.4.1          
##   [4] lazyeval_0.2.2         sp_1.6-0               splines_4.2.0         
##   [7] listenv_0.9.0          scattermore_0.8        digest_0.6.31         
##  [10] htmltools_0.5.4        fansi_1.0.4            magrittr_2.0.3        
##  [13] memoise_2.0.1          tensor_1.5             cluster_2.1.3         
##  [16] mixtools_2.0.0         ROCR_1.0-11            limma_3.54.1          
##  [19] globals_0.16.2         matrixStats_0.63.0     pkgdown_2.0.7         
##  [22] spatstat.sparse_3.0-0  colorspace_2.1-0       rappdirs_0.3.3        
##  [25] ggrepel_0.9.3          textshaping_0.3.6      xfun_0.37             
##  [28] crayon_1.5.2           jsonlite_1.8.4         progressr_0.13.0      
##  [31] spatstat.data_3.0-0    survival_3.3-1         zoo_1.8-11            
##  [34] glue_1.6.2             polyclip_1.10-4        gtable_0.3.1          
##  [37] leiden_0.4.3           kernlab_0.9-32         future.apply_1.10.0   
##  [40] abind_1.4-5            spatstat.random_3.1-3  miniUI_0.1.1.1        
##  [43] Rcpp_1.0.10            viridisLite_0.4.1      xtable_1.8-4          
##  [46] reticulate_1.28        htmlwidgets_1.6.1      httr_1.4.5            
##  [49] RColorBrewer_1.1-3     ellipsis_0.3.2         ica_1.0-3             
##  [52] farver_2.1.1           pkgconfig_2.0.3        sass_0.4.5            
##  [55] uwot_0.1.14            deldir_1.0-6           utf8_1.2.3            
##  [58] tidyselect_1.2.0       labeling_0.4.2         rlang_1.0.6           
##  [61] later_1.3.0            munsell_0.5.0          tools_4.2.0           
##  [64] cachem_1.0.7           cli_3.6.0              generics_0.1.3        
##  [67] ggridges_0.5.4         evaluate_0.20          stringr_1.5.0         
##  [70] fastmap_1.1.1          yaml_2.3.7             ragg_1.2.5            
##  [73] goftest_1.2-3          knitr_1.42             fs_1.6.1              
##  [76] fitdistrplus_1.1-8     purrr_1.0.1            RANN_2.6.1            
##  [79] pbapply_1.7-0          future_1.31.0          nlme_3.1-157          
##  [82] mime_0.12              compiler_4.2.0         plotly_4.10.1         
##  [85] png_0.1-8              spatstat.utils_3.0-1   tibble_3.1.8          
##  [88] bslib_0.4.2            stringi_1.7.12         highr_0.10            
##  [91] desc_1.4.2             lattice_0.20-45        Matrix_1.5-3          
##  [94] vctrs_0.5.2            pillar_1.8.1           lifecycle_1.0.3       
##  [97] spatstat.geom_3.0-6    lmtest_0.9-40          jquerylib_0.1.4       
## [100] RcppAnnoy_0.0.20       data.table_1.14.8      cowplot_1.1.1         
## [103] irlba_2.3.5.1          httpuv_1.6.9           R6_2.5.1              
## [106] promises_1.2.0.1       KernSmooth_2.23-20     gridExtra_2.3         
## [109] parallelly_1.34.0      codetools_0.2-18       MASS_7.3-56           
## [112] rprojroot_2.0.3        withr_2.5.0            sctransform_0.3.5     
## [115] parallel_4.2.0         grid_4.2.0             tidyr_1.3.0           
## [118] rmarkdown_2.20         segmented_1.6-2        Rtsne_0.16            
## [121] spatstat.explore_3.0-6 shiny_1.7.4
```

Example 38 (unknown):
```unknown
## R version 4.2.0 (2022-04-22)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.5 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/liblapack.so.3
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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       
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
##  [1] reshape2_1.4.4                dplyr_1.1.0                  
##  [3] scales_1.2.1                  patchwork_1.1.2              
##  [5] ggplot2_3.4.1                 thp1.eccite.SeuratData_3.1.5 
##  [7] stxBrain.SeuratData_0.1.1     ssHippo.SeuratData_3.1.4     
##  [9] pbmcsca.SeuratData_3.0.0      pbmcMultiome.SeuratData_0.1.2
## [11] pbmc3k.SeuratData_3.1.4       panc8.SeuratData_3.0.2       
## [13] ifnb.SeuratData_3.1.0         hcabm40k.SeuratData_3.0.0    
## [15] bmcite.SeuratData_0.3.0       SeuratData_0.2.2             
## [17] SeuratObject_4.1.3            Seurat_4.3.0                 
## 
## loaded via a namespace (and not attached):
##   [1] systemfonts_1.0.4      plyr_1.8.8             igraph_1.4.1          
##   [4] lazyeval_0.2.2         sp_1.6-0               splines_4.2.0         
##   [7] listenv_0.9.0          scattermore_0.8        digest_0.6.31         
##  [10] htmltools_0.5.4        fansi_1.0.4            magrittr_2.0.3        
##  [13] memoise_2.0.1          tensor_1.5             cluster_2.1.3         
##  [16] mixtools_2.0.0         ROCR_1.0-11            limma_3.54.1          
##  [19] globals_0.16.2         matrixStats_0.63.0     pkgdown_2.0.7         
##  [22] spatstat.sparse_3.0-0  colorspace_2.1-0       rappdirs_0.3.3        
##  [25] ggrepel_0.9.3          textshaping_0.3.6      xfun_0.37             
##  [28] crayon_1.5.2           jsonlite_1.8.4         progressr_0.13.0      
##  [31] spatstat.data_3.0-0    survival_3.3-1         zoo_1.8-11            
##  [34] glue_1.6.2             polyclip_1.10-4        gtable_0.3.1          
##  [37] leiden_0.4.3           kernlab_0.9-32         future.apply_1.10.0   
##  [40] abind_1.4-5            spatstat.random_3.1-3  miniUI_0.1.1.1        
##  [43] Rcpp_1.0.10            viridisLite_0.4.1      xtable_1.8-4          
##  [46] reticulate_1.28        htmlwidgets_1.6.1      httr_1.4.5            
##  [49] RColorBrewer_1.1-3     ellipsis_0.3.2         ica_1.0-3             
##  [52] farver_2.1.1           pkgconfig_2.0.3        sass_0.4.5            
##  [55] uwot_0.1.14            deldir_1.0-6           utf8_1.2.3            
##  [58] tidyselect_1.2.0       labeling_0.4.2         rlang_1.0.6           
##  [61] later_1.3.0            munsell_0.5.0          tools_4.2.0           
##  [64] cachem_1.0.7           cli_3.6.0              generics_0.1.3        
##  [67] ggridges_0.5.4         evaluate_0.20          stringr_1.5.0         
##  [70] fastmap_1.1.1          yaml_2.3.7             ragg_1.2.5            
##  [73] goftest_1.2-3          knitr_1.42             fs_1.6.1              
##  [76] fitdistrplus_1.1-8     purrr_1.0.1            RANN_2.6.1            
##  [79] pbapply_1.7-0          future_1.31.0          nlme_3.1-157          
##  [82] mime_0.12              compiler_4.2.0         plotly_4.10.1         
##  [85] png_0.1-8              spatstat.utils_3.0-1   tibble_3.1.8          
##  [88] bslib_0.4.2            stringi_1.7.12         highr_0.10            
##  [91] desc_1.4.2             lattice_0.20-45        Matrix_1.5-3          
##  [94] vctrs_0.5.2            pillar_1.8.1           lifecycle_1.0.3       
##  [97] spatstat.geom_3.0-6    lmtest_0.9-40          jquerylib_0.1.4       
## [100] RcppAnnoy_0.0.20       data.table_1.14.8      cowplot_1.1.1         
## [103] irlba_2.3.5.1          httpuv_1.6.9           R6_2.5.1              
## [106] promises_1.2.0.1       KernSmooth_2.23-20     gridExtra_2.3         
## [109] parallelly_1.34.0      codetools_0.2-18       MASS_7.3-56           
## [112] rprojroot_2.0.3        withr_2.5.0            sctransform_0.3.5     
## [115] parallel_4.2.0         grid_4.2.0             tidyr_1.3.0           
## [118] rmarkdown_2.20         segmented_1.6-2        Rtsne_0.16            
## [121] spatstat.explore_3.0-6 shiny_1.7.4
```

---

## Analysis, visualization, and integration of Visium HD spatial datasets with Seurat • Seurat

**URL:** http://127.0.0.1:9173/seurat/articles/mixscape_vignette/index.html

**Contents:**
- Mixscape Vignette
    - Compiled: October 31, 2023
- Overview
- Loading required packages
- Loading Seurat object containing ECCITE-seq dataset
- RNA-based clustering is driven by confounding sources of variation
- Calculating local perturbation signatures mitigates confounding effects
- Mixscape identifies cells with no detectable perturbation
- Inspecting mixscape results
- Visualizing perturbation responses with Linear Discriminant Analysis (LDA)
- Contents

This tutorial demonstrates how to use mixscape for the analyses of single-cell pooled CRISPR screens. We introduce new Seurat functions for:

We use a 111 gRNA ECCITE-seq dataset generated from stimulated THP-1 cells that was recently published from our lab in bioRxiv Papalexi et al. 2020. This dataset can be easily downloaded from the SeuratData package.

Here, we follow the standard Seurat workflow to cluster cells based on their gene expression profiles. We expected to obtain perturbation-specific clusters however we saw that clustering is primarily driven by cell cycle phase and replicate ID. We only observed one perturbation-specific cluster containing cells expression IFNgamma pathway gRNAs.

To calculate local perturbation signatures we set the number of non-targeting Nearest Neighbors (NNs) equal to k=20 and we recommend that the user picks a k from the following range: 20 < k < 30. Intuitively, the user does not want to set k to a very small or large number as this will most likely not remove the technical variation from the dataset. Using the PRTB signature to cluster cells removes all technical variation and reveals one additional perturbation-specific cluster.

Here, we are assuming each target gene class is a mixture of two Gaussian distributions one representing the knockout (KO) and the other the non-perturbed (NP) cells. We further assume that the distribution of the NP cells is identical to that of cells expressing non-targeting gRNAs (NT) and we try to estimate the distribution of KO cells using the function normalmixEM() from the mixtools package. Next, we calculate the posterior probability that a cell belongs to the KO distribution and classify cells with a probability higher than 0.5 as KOs. Applying this method we identify KOs in 11 target gene classes and detect variation in gRNA targeting efficiency within each class.

To ensure mixscape is assigning the correct perturbation status to cells we can use the functions below to look at the perturbation score distributions and the posterior probabilities of cells within a target gene class (for example IFNGR2) and compare it to those of the NT cells. In addition, we can perform differential expression (DE) analyses and show that only IFNGR2 KO cells have reduced expression of the IFNG-pathway genes. Finally, as an independent check, we can look at the PD-L1 protein expression values in NP and KO cells for target genes known to be PD-L1 regulators.

We use LDA as a dimensionality reduction method to visualize perturbation-specific clusters. LDA is trying to maximize the separability of known labels (mixscape classes) using both gene expression and the labels as input.

Developed by Rahul Satija, Satija Lab and Collaborators.

Site built with pkgdown 2.0.7.

**Examples:**

Example 1 (unknown):
```unknown
vignettes/mixscape_vignette.Rmd
```

Example 2 (unknown):
```unknown
mixscape_vignette.Rmd
```

Example 3 (unknown):
```unknown
# Load packages.
library(Seurat)
library(SeuratData)
library(ggplot2)
library(patchwork)
library(scales)
library(dplyr)
library(reshape2)

# Download dataset using SeuratData.
InstallData(ds = "thp1.eccite")

# Setup custom theme for plotting.
custom_theme <- theme(
  plot.title = element_text(size=16, hjust = 0.5), 
  legend.key.size = unit(0.7, "cm"), 
  legend.text = element_text(size = 14))
```

Example 4 (r):
```r
# Load packages.
library(Seurat)
library(SeuratData)
library(ggplot2)
library(patchwork)
library(scales)
library(dplyr)
library(reshape2)

# Download dataset using SeuratData.
InstallData(ds = "thp1.eccite")

# Setup custom theme for plotting.
custom_theme <- theme(
  plot.title = element_text(size=16, hjust = 0.5), 
  legend.key.size = unit(0.7, "cm"), 
  legend.text = element_text(size = 14))
```

Example 5 (r):
```r
# Load packages.
library(Seurat)
library(SeuratData)
library(ggplot2)
library(patchwork)
library(scales)
library(dplyr)
library(reshape2)

# Download dataset using SeuratData.
InstallData(ds = "thp1.eccite")

# Setup custom theme for plotting.
custom_theme <- theme(
  plot.title = element_text(size=16, hjust = 0.5), 
  legend.key.size = unit(0.7, "cm"), 
  legend.text = element_text(size = 14))
```

Example 6 (unknown):
```unknown
# Load object.
eccite <- LoadData(ds = "thp1.eccite")

# Normalize protein.
eccite <- NormalizeData(
  object = eccite, 
  assay = "ADT", 
  normalization.method = "CLR", 
  margin = 2)
```

Example 7 (r):
```r
# Load object.
eccite <- LoadData(ds = "thp1.eccite")

# Normalize protein.
eccite <- NormalizeData(
  object = eccite, 
  assay = "ADT", 
  normalization.method = "CLR", 
  margin = 2)
```

Example 8 (r):
```r
# Load object.
eccite <- LoadData(ds = "thp1.eccite")

# Normalize protein.
eccite <- NormalizeData(
  object = eccite, 
  assay = "ADT", 
  normalization.method = "CLR", 
  margin = 2)
```

Example 9 (unknown):
```unknown
# Prepare RNA assay for dimensionality reduction: 
# Normalize data, find variable features and scale data.
DefaultAssay(object = eccite) <- 'RNA'
eccite <- NormalizeData(object = eccite) %>% FindVariableFeatures() %>% ScaleData()

# Run Principle Component Analysis (PCA) to reduce the dimensionality of the data.
eccite <- RunPCA(object = eccite)

# Run Uniform Manifold Approximation and Projection (UMAP) to visualize clustering in 2-D.
eccite <- RunUMAP(object = eccite, dims = 1:40)

# Generate plots to check if clustering is driven by biological replicate ID, 
# cell cycle phase or target gene class.
p1 <- DimPlot(
  object = eccite, 
  group.by = 'replicate', 
  label = F, 
  pt.size = 0.2, 
  reduction = "umap", cols = "Dark2", repel = T) +
  scale_color_brewer(palette = "Dark2") +
  ggtitle("Biological Replicate") +
  xlab("UMAP 1") +
  ylab("UMAP 2") +
  custom_theme

p2 <- DimPlot(
  object = eccite, 
  group.by = 'Phase', 
  label = F, pt.size = 0.2, 
  reduction = "umap", repel = T) + 
  ggtitle("Cell Cycle Phase") +
  ylab("UMAP 2") +
  xlab("UMAP 1") +
  custom_theme

p3 <- DimPlot(
  object = eccite, 
  group.by = 'crispr', 
  pt.size = 0.2, 
  reduction = "umap", 
  split.by = "crispr", 
  ncol = 1, 
  cols = c("grey39","goldenrod3")) + 
  ggtitle("Perturbation Status") +
  ylab("UMAP 2") +
  xlab("UMAP 1") +
  custom_theme

# Visualize plots.
((p1 / p2 + plot_layout(guides = 'auto')) | p3 )
```

Example 10 (r):
```r
# Prepare RNA assay for dimensionality reduction: 
# Normalize data, find variable features and scale data.
DefaultAssay(object = eccite) <- 'RNA'
eccite <- NormalizeData(object = eccite) %>% FindVariableFeatures() %>% ScaleData()

# Run Principle Component Analysis (PCA) to reduce the dimensionality of the data.
eccite <- RunPCA(object = eccite)

# Run Uniform Manifold Approximation and Projection (UMAP) to visualize clustering in 2-D.
eccite <- RunUMAP(object = eccite, dims = 1:40)

# Generate plots to check if clustering is driven by biological replicate ID, 
# cell cycle phase or target gene class.
p1 <- DimPlot(
  object = eccite, 
  group.by = 'replicate', 
  label = F, 
  pt.size = 0.2, 
  reduction = "umap", cols = "Dark2", repel = T) +
  scale_color_brewer(palette = "Dark2") +
  ggtitle("Biological Replicate") +
  xlab("UMAP 1") +
  ylab("UMAP 2") +
  custom_theme

p2 <- DimPlot(
  object = eccite, 
  group.by = 'Phase', 
  label = F, pt.size = 0.2, 
  reduction = "umap", repel = T) + 
  ggtitle("Cell Cycle Phase") +
  ylab("UMAP 2") +
  xlab("UMAP 1") +
  custom_theme

p3 <- DimPlot(
  object = eccite, 
  group.by = 'crispr', 
  pt.size = 0.2, 
  reduction = "umap", 
  split.by = "crispr", 
  ncol = 1, 
  cols = c("grey39","goldenrod3")) + 
  ggtitle("Perturbation Status") +
  ylab("UMAP 2") +
  xlab("UMAP 1") +
  custom_theme

# Visualize plots.
((p1 / p2 + plot_layout(guides = 'auto')) | p3 )
```

Example 11 (r):
```r
# Prepare RNA assay for dimensionality reduction: 
# Normalize data, find variable features and scale data.
DefaultAssay(object = eccite) <- 'RNA'
eccite <- NormalizeData(object = eccite) %>% FindVariableFeatures() %>% ScaleData()

# Run Principle Component Analysis (PCA) to reduce the dimensionality of the data.
eccite <- RunPCA(object = eccite)

# Run Uniform Manifold Approximation and Projection (UMAP) to visualize clustering in 2-D.
eccite <- RunUMAP(object = eccite, dims = 1:40)

# Generate plots to check if clustering is driven by biological replicate ID, 
# cell cycle phase or target gene class.
p1 <- DimPlot(
  object = eccite, 
  group.by = 'replicate', 
  label = F, 
  pt.size = 0.2, 
  reduction = "umap", cols = "Dark2", repel = T) +
  scale_color_brewer(palette = "Dark2") +
  ggtitle("Biological Replicate") +
  xlab("UMAP 1") +
  ylab("UMAP 2") +
  custom_theme

p2 <- DimPlot(
  object = eccite, 
  group.by = 'Phase', 
  label = F, pt.size = 0.2, 
  reduction = "umap", repel = T) + 
  ggtitle("Cell Cycle Phase") +
  ylab("UMAP 2") +
  xlab("UMAP 1") +
  custom_theme

p3 <- DimPlot(
  object = eccite, 
  group.by = 'crispr', 
  pt.size = 0.2, 
  reduction = "umap", 
  split.by = "crispr", 
  ncol = 1, 
  cols = c("grey39","goldenrod3")) + 
  ggtitle("Perturbation Status") +
  ylab("UMAP 2") +
  xlab("UMAP 1") +
  custom_theme

# Visualize plots.
((p1 / p2 + plot_layout(guides = 'auto')) | p3 )
```

Example 12 (python):
```python
# Calculate perturbation signature (PRTB).
eccite<- CalcPerturbSig(
  object = eccite, 
  assay = "RNA", 
  slot = "data", 
  gd.class ="gene", 
  nt.cell.class = "NT", 
  reduction = "pca", 
  ndims = 40, 
  num.neighbors = 20, 
  split.by = "replicate", 
  new.assay.name = "PRTB")

# Prepare PRTB assay for dimensionality reduction: 
# Normalize data, find variable features and center data.
DefaultAssay(object = eccite) <- 'PRTB'

# Use variable features from RNA assay.
VariableFeatures(object = eccite) <- VariableFeatures(object = eccite[["RNA"]])
eccite <- ScaleData(object = eccite, do.scale = F, do.center = T)

# Run PCA to reduce the dimensionality of the data.
eccite <- RunPCA(object = eccite, reduction.key = 'prtbpca', reduction.name = 'prtbpca')

# Run UMAP to visualize clustering in 2-D.
eccite <- RunUMAP(
  object = eccite, 
  dims = 1:40, 
  reduction = 'prtbpca', 
  reduction.key = 'prtbumap', 
  reduction.name = 'prtbumap')

# Generate plots to check if clustering is driven by biological replicate ID, 
# cell cycle phase or target gene class.
q1 <- DimPlot(
  object = eccite, 
  group.by = 'replicate', 
  reduction = 'prtbumap', 
  pt.size = 0.2, cols = "Dark2", label = F, repel = T) +
  scale_color_brewer(palette = "Dark2") +
  ggtitle("Biological Replicate") +
  ylab("UMAP 2") +
  xlab("UMAP 1") +
  custom_theme

q2 <- DimPlot(
  object = eccite, 
  group.by = 'Phase', 
  reduction = 'prtbumap', 
  pt.size = 0.2, label = F, repel = T) +
  ggtitle("Cell Cycle Phase") +
  ylab("UMAP 2") +
  xlab("UMAP 1") + 
  custom_theme

q3 <- DimPlot(
  object = eccite,
  group.by = 'crispr',
  reduction = 'prtbumap', 
  split.by = "crispr", 
  ncol = 1, 
  pt.size = 0.2, 
  cols = c("grey39","goldenrod3")) +
  ggtitle("Perturbation Status") +
  ylab("UMAP 2") +
  xlab("UMAP 1") +
  custom_theme

# Visualize plots.
(q1 / q2 + plot_layout(guides = 'auto') | q3)
```

Example 13 (r):
```r
# Calculate perturbation signature (PRTB).
eccite<- CalcPerturbSig(
  object = eccite, 
  assay = "RNA", 
  slot = "data", 
  gd.class ="gene", 
  nt.cell.class = "NT", 
  reduction = "pca", 
  ndims = 40, 
  num.neighbors = 20, 
  split.by = "replicate", 
  new.assay.name = "PRTB")

# Prepare PRTB assay for dimensionality reduction: 
# Normalize data, find variable features and center data.
DefaultAssay(object = eccite) <- 'PRTB'

# Use variable features from RNA assay.
VariableFeatures(object = eccite) <- VariableFeatures(object = eccite[["RNA"]])
eccite <- ScaleData(object = eccite, do.scale = F, do.center = T)

# Run PCA to reduce the dimensionality of the data.
eccite <- RunPCA(object = eccite, reduction.key = 'prtbpca', reduction.name = 'prtbpca')

# Run UMAP to visualize clustering in 2-D.
eccite <- RunUMAP(
  object = eccite, 
  dims = 1:40, 
  reduction = 'prtbpca', 
  reduction.key = 'prtbumap', 
  reduction.name = 'prtbumap')

# Generate plots to check if clustering is driven by biological replicate ID, 
# cell cycle phase or target gene class.
q1 <- DimPlot(
  object = eccite, 
  group.by = 'replicate', 
  reduction = 'prtbumap', 
  pt.size = 0.2, cols = "Dark2", label = F, repel = T) +
  scale_color_brewer(palette = "Dark2") +
  ggtitle("Biological Replicate") +
  ylab("UMAP 2") +
  xlab("UMAP 1") +
  custom_theme

q2 <- DimPlot(
  object = eccite, 
  group.by = 'Phase', 
  reduction = 'prtbumap', 
  pt.size = 0.2, label = F, repel = T) +
  ggtitle("Cell Cycle Phase") +
  ylab("UMAP 2") +
  xlab("UMAP 1") + 
  custom_theme

q3 <- DimPlot(
  object = eccite,
  group.by = 'crispr',
  reduction = 'prtbumap', 
  split.by = "crispr", 
  ncol = 1, 
  pt.size = 0.2, 
  cols = c("grey39","goldenrod3")) +
  ggtitle("Perturbation Status") +
  ylab("UMAP 2") +
  xlab("UMAP 1") +
  custom_theme

# Visualize plots.
(q1 / q2 + plot_layout(guides = 'auto') | q3)
```

Example 14 (r):
```r
# Calculate perturbation signature (PRTB).
eccite<- CalcPerturbSig(
  object = eccite, 
  assay = "RNA", 
  slot = "data", 
  gd.class ="gene", 
  nt.cell.class = "NT", 
  reduction = "pca", 
  ndims = 40, 
  num.neighbors = 20, 
  split.by = "replicate", 
  new.assay.name = "PRTB")

# Prepare PRTB assay for dimensionality reduction: 
# Normalize data, find variable features and center data.
DefaultAssay(object = eccite) <- 'PRTB'

# Use variable features from RNA assay.
VariableFeatures(object = eccite) <- VariableFeatures(object = eccite[["RNA"]])
eccite <- ScaleData(object = eccite, do.scale = F, do.center = T)

# Run PCA to reduce the dimensionality of the data.
eccite <- RunPCA(object = eccite, reduction.key = 'prtbpca', reduction.name = 'prtbpca')

# Run UMAP to visualize clustering in 2-D.
eccite <- RunUMAP(
  object = eccite, 
  dims = 1:40, 
  reduction = 'prtbpca', 
  reduction.key = 'prtbumap', 
  reduction.name = 'prtbumap')

# Generate plots to check if clustering is driven by biological replicate ID, 
# cell cycle phase or target gene class.
q1 <- DimPlot(
  object = eccite, 
  group.by = 'replicate', 
  reduction = 'prtbumap', 
  pt.size = 0.2, cols = "Dark2", label = F, repel = T) +
  scale_color_brewer(palette = "Dark2") +
  ggtitle("Biological Replicate") +
  ylab("UMAP 2") +
  xlab("UMAP 1") +
  custom_theme

q2 <- DimPlot(
  object = eccite, 
  group.by = 'Phase', 
  reduction = 'prtbumap', 
  pt.size = 0.2, label = F, repel = T) +
  ggtitle("Cell Cycle Phase") +
  ylab("UMAP 2") +
  xlab("UMAP 1") + 
  custom_theme

q3 <- DimPlot(
  object = eccite,
  group.by = 'crispr',
  reduction = 'prtbumap', 
  split.by = "crispr", 
  ncol = 1, 
  pt.size = 0.2, 
  cols = c("grey39","goldenrod3")) +
  ggtitle("Perturbation Status") +
  ylab("UMAP 2") +
  xlab("UMAP 1") +
  custom_theme

# Visualize plots.
(q1 / q2 + plot_layout(guides = 'auto') | q3)
```

Example 15 (unknown):
```unknown
normalmixEM()
```

Example 16 (javascript):
```javascript
# Run mixscape.
eccite <- RunMixscape(
  object = eccite, 
  assay = "PRTB", 
  slot = "scale.data", 
  labels = "gene", 
  nt.class.name = "NT", 
  min.de.genes = 5, 
  iter.num = 10, 
  de.assay = "RNA", 
  verbose = F,
  prtb.type = "KO")

# Calculate percentage of KO cells for all target gene classes.
df <- prop.table(table(eccite$mixscape_class.global, eccite$NT),2)

df2 <- reshape2::melt(df)
df2$Var2 <- as.character(df2$Var2)
test <- df2[which(df2$Var1 == "KO"),]
test <- test[order(test$value, decreasing = T),]
new.levels <- test$Var2
df2$Var2 <- factor(df2$Var2, levels = new.levels )
df2$Var1 <- factor(df2$Var1, levels = c("NT", "NP", "KO"))
df2$gene <- sapply(as.character(df2$Var2), function(x) strsplit(x, split = "g")[[1]][1])
df2$guide_number <- sapply(as.character(df2$Var2), 
                           function(x) strsplit(x, split = "g")[[1]][2])
df3 <- df2[-c(which(df2$gene == "NT")),]

p1 <- ggplot(df3, aes(x = guide_number, y = value*100, fill= Var1)) +
  geom_bar(stat= "identity") +
  theme_classic()+
  scale_fill_manual(values = c("grey49", "grey79","coral1")) + 
  ylab("% of cells") +
  xlab("sgRNA")

p1 + theme(axis.text.x = element_text(size = 18, hjust = 1), 
           axis.text.y = element_text(size = 18), 
           axis.title = element_text(size = 16), 
           strip.text = element_text(size=16, face = "bold")) + 
  facet_wrap(vars(gene),ncol = 5, scales = "free") +
  labs(fill = "mixscape class") +theme(legend.title = element_text(size = 14),
          legend.text = element_text(size = 12))
```

Example 17 (r):
```r
# Run mixscape.
eccite <- RunMixscape(
  object = eccite, 
  assay = "PRTB", 
  slot = "scale.data", 
  labels = "gene", 
  nt.class.name = "NT", 
  min.de.genes = 5, 
  iter.num = 10, 
  de.assay = "RNA", 
  verbose = F,
  prtb.type = "KO")

# Calculate percentage of KO cells for all target gene classes.
df <- prop.table(table(eccite$mixscape_class.global, eccite$NT),2)

df2 <- reshape2::melt(df)
df2$Var2 <- as.character(df2$Var2)
test <- df2[which(df2$Var1 == "KO"),]
test <- test[order(test$value, decreasing = T),]
new.levels <- test$Var2
df2$Var2 <- factor(df2$Var2, levels = new.levels )
df2$Var1 <- factor(df2$Var1, levels = c("NT", "NP", "KO"))
df2$gene <- sapply(as.character(df2$Var2), function(x) strsplit(x, split = "g")[[1]][1])
df2$guide_number <- sapply(as.character(df2$Var2), 
                           function(x) strsplit(x, split = "g")[[1]][2])
df3 <- df2[-c(which(df2$gene == "NT")),]

p1 <- ggplot(df3, aes(x = guide_number, y = value*100, fill= Var1)) +
  geom_bar(stat= "identity") +
  theme_classic()+
  scale_fill_manual(values = c("grey49", "grey79","coral1")) + 
  ylab("% of cells") +
  xlab("sgRNA")

p1 + theme(axis.text.x = element_text(size = 18, hjust = 1), 
           axis.text.y = element_text(size = 18), 
           axis.title = element_text(size = 16), 
           strip.text = element_text(size=16, face = "bold")) + 
  facet_wrap(vars(gene),ncol = 5, scales = "free") +
  labs(fill = "mixscape class") +theme(legend.title = element_text(size = 14),
          legend.text = element_text(size = 12))
```

Example 18 (r):
```r
# Run mixscape.
eccite <- RunMixscape(
  object = eccite, 
  assay = "PRTB", 
  slot = "scale.data", 
  labels = "gene", 
  nt.class.name = "NT", 
  min.de.genes = 5, 
  iter.num = 10, 
  de.assay = "RNA", 
  verbose = F,
  prtb.type = "KO")

# Calculate percentage of KO cells for all target gene classes.
df <- prop.table(table(eccite$mixscape_class.global, eccite$NT),2)

df2 <- reshape2::melt(df)
df2$Var2 <- as.character(df2$Var2)
test <- df2[which(df2$Var1 == "KO"),]
test <- test[order(test$value, decreasing = T),]
new.levels <- test$Var2
df2$Var2 <- factor(df2$Var2, levels = new.levels )
df2$Var1 <- factor(df2$Var1, levels = c("NT", "NP", "KO"))
df2$gene <- sapply(as.character(df2$Var2), function(x) strsplit(x, split = "g")[[1]][1])
df2$guide_number <- sapply(as.character(df2$Var2), 
                           function(x) strsplit(x, split = "g")[[1]][2])
df3 <- df2[-c(which(df2$gene == "NT")),]

p1 <- ggplot(df3, aes(x = guide_number, y = value*100, fill= Var1)) +
  geom_bar(stat= "identity") +
  theme_classic()+
  scale_fill_manual(values = c("grey49", "grey79","coral1")) + 
  ylab("% of cells") +
  xlab("sgRNA")

p1 + theme(axis.text.x = element_text(size = 18, hjust = 1), 
           axis.text.y = element_text(size = 18), 
           axis.title = element_text(size = 16), 
           strip.text = element_text(size=16, face = "bold")) + 
  facet_wrap(vars(gene),ncol = 5, scales = "free") +
  labs(fill = "mixscape class") +theme(legend.title = element_text(size = 14),
          legend.text = element_text(size = 12))
```

Example 19 (python):
```python
# Explore the perturbation scores of cells.
PlotPerturbScore(object = eccite, 
                 target.gene.ident = "IFNGR2", 
                 mixscape.class = "mixscape_class", 
                 col = "coral2") +labs(fill = "mixscape class")
```

Example 20 (r):
```r
# Explore the perturbation scores of cells.
PlotPerturbScore(object = eccite, 
                 target.gene.ident = "IFNGR2", 
                 mixscape.class = "mixscape_class", 
                 col = "coral2") +labs(fill = "mixscape class")
```

Example 21 (r):
```r
# Explore the perturbation scores of cells.
PlotPerturbScore(object = eccite, 
                 target.gene.ident = "IFNGR2", 
                 mixscape.class = "mixscape_class", 
                 col = "coral2") +labs(fill = "mixscape class")
```

Example 22 (unknown):
```unknown
# Inspect the posterior probability values in NP and KO cells.
VlnPlot(eccite, "mixscape_class_p_ko", idents = c("NT", "IFNGR2 KO", "IFNGR2 NP")) +
  theme(axis.text.x = element_text(angle = 0, hjust = 0.5),axis.text = element_text(size = 16) ,plot.title = element_text(size = 20)) + 
  NoLegend() +
  ggtitle("mixscape posterior probabilities")
```

Example 23 (r):
```r
# Inspect the posterior probability values in NP and KO cells.
VlnPlot(eccite, "mixscape_class_p_ko", idents = c("NT", "IFNGR2 KO", "IFNGR2 NP")) +
  theme(axis.text.x = element_text(angle = 0, hjust = 0.5),axis.text = element_text(size = 16) ,plot.title = element_text(size = 20)) + 
  NoLegend() +
  ggtitle("mixscape posterior probabilities")
```

Example 24 (r):
```r
# Inspect the posterior probability values in NP and KO cells.
VlnPlot(eccite, "mixscape_class_p_ko", idents = c("NT", "IFNGR2 KO", "IFNGR2 NP")) +
  theme(axis.text.x = element_text(angle = 0, hjust = 0.5),axis.text = element_text(size = 16) ,plot.title = element_text(size = 20)) + 
  NoLegend() +
  ggtitle("mixscape posterior probabilities")
```

Example 25 (unknown):
```unknown
# Run DE analysis and visualize results on a heatmap ordering cells by their posterior 
# probability values.
Idents(object = eccite) <- "gene"
MixscapeHeatmap(object = eccite, 
                ident.1 = "NT", 
                ident.2 = "IFNGR2", 
                balanced = F, 
                assay = "RNA", 
                max.genes = 20, angle = 0, 
                group.by = "mixscape_class", 
                max.cells.group = 300, 
                size=6.5) + NoLegend() +theme(axis.text.y = element_text(size = 16))
```

Example 26 (r):
```r
# Run DE analysis and visualize results on a heatmap ordering cells by their posterior 
# probability values.
Idents(object = eccite) <- "gene"
MixscapeHeatmap(object = eccite, 
                ident.1 = "NT", 
                ident.2 = "IFNGR2", 
                balanced = F, 
                assay = "RNA", 
                max.genes = 20, angle = 0, 
                group.by = "mixscape_class", 
                max.cells.group = 300, 
                size=6.5) + NoLegend() +theme(axis.text.y = element_text(size = 16))
```

Example 27 (r):
```r
# Run DE analysis and visualize results on a heatmap ordering cells by their posterior 
# probability values.
Idents(object = eccite) <- "gene"
MixscapeHeatmap(object = eccite, 
                ident.1 = "NT", 
                ident.2 = "IFNGR2", 
                balanced = F, 
                assay = "RNA", 
                max.genes = 20, angle = 0, 
                group.by = "mixscape_class", 
                max.cells.group = 300, 
                size=6.5) + NoLegend() +theme(axis.text.y = element_text(size = 16))
```

Example 28 (unknown):
```unknown
# Show that only IFNG pathway KO cells have a reduction in PD-L1 protein expression.
VlnPlot(
  object = eccite, 
  features = "adt_PDL1", 
  idents = c("NT","JAK2","STAT1","IFNGR1","IFNGR2", "IRF1"), 
  group.by = "gene", 
  pt.size = 0.2, 
  sort = T, 
  split.by = "mixscape_class.global", 
  cols = c("coral3","grey79","grey39")) +
  ggtitle("PD-L1 protein") +
  theme(axis.text.x = element_text(angle = 0, hjust = 0.5), plot.title = element_text(size = 20), axis.text = element_text(size = 16))
```

Example 29 (r):
```r
# Show that only IFNG pathway KO cells have a reduction in PD-L1 protein expression.
VlnPlot(
  object = eccite, 
  features = "adt_PDL1", 
  idents = c("NT","JAK2","STAT1","IFNGR1","IFNGR2", "IRF1"), 
  group.by = "gene", 
  pt.size = 0.2, 
  sort = T, 
  split.by = "mixscape_class.global", 
  cols = c("coral3","grey79","grey39")) +
  ggtitle("PD-L1 protein") +
  theme(axis.text.x = element_text(angle = 0, hjust = 0.5), plot.title = element_text(size = 20), axis.text = element_text(size = 16))
```

Example 30 (r):
```r
# Show that only IFNG pathway KO cells have a reduction in PD-L1 protein expression.
VlnPlot(
  object = eccite, 
  features = "adt_PDL1", 
  idents = c("NT","JAK2","STAT1","IFNGR1","IFNGR2", "IRF1"), 
  group.by = "gene", 
  pt.size = 0.2, 
  sort = T, 
  split.by = "mixscape_class.global", 
  cols = c("coral3","grey79","grey39")) +
  ggtitle("PD-L1 protein") +
  theme(axis.text.x = element_text(angle = 0, hjust = 0.5), plot.title = element_text(size = 20), axis.text = element_text(size = 16))
```

Example 31 (unknown):
```unknown
p <- VlnPlot(object = eccite, features = "adt_PDL1", idents = c("NT","JAK2","STAT1","IFNGR1","IFNGR2", "IRF1"), group.by = "gene", pt.size = 0.2, sort = T, split.by = "mixscape_class.global", cols = c("coral3","grey79","grey39")) +ggtitle("PD-L1 protein") +theme(axis.text.x = element_text(angle = 0, hjust = 0.5))
```

Example 32 (r):
```r
p <- VlnPlot(object = eccite, features = "adt_PDL1", idents = c("NT","JAK2","STAT1","IFNGR1","IFNGR2", "IRF1"), group.by = "gene", pt.size = 0.2, sort = T, split.by = "mixscape_class.global", cols = c("coral3","grey79","grey39")) +ggtitle("PD-L1 protein") +theme(axis.text.x = element_text(angle = 0, hjust = 0.5))
```

Example 33 (r):
```r
p <- VlnPlot(object = eccite, features = "adt_PDL1", idents = c("NT","JAK2","STAT1","IFNGR1","IFNGR2", "IRF1"), group.by = "gene", pt.size = 0.2, sort = T, split.by = "mixscape_class.global", cols = c("coral3","grey79","grey39")) +ggtitle("PD-L1 protein") +theme(axis.text.x = element_text(angle = 0, hjust = 0.5))
```

Example 34 (python):
```python
# Remove non-perturbed cells and run LDA to reduce the dimensionality of the data.
Idents(eccite) <- "mixscape_class.global"
sub <- subset(eccite, idents = c("KO", "NT"))

# Run LDA.
sub <- MixscapeLDA(
  object = sub, 
  assay = "RNA", 
  pc.assay = "PRTB", 
  labels = "gene", 
  nt.label = "NT", 
  npcs = 10, 
  logfc.threshold = 0.25, 
  verbose = F)

# Use LDA results to run UMAP and visualize cells on 2-D. 
# Here, we note that the number of the dimensions to be used is equal to the number of 
# labels minus one (to account for NT cells).
sub <- RunUMAP(
  object = sub,
  dims = 1:11,
  reduction = 'lda',
  reduction.key = 'ldaumap',
  reduction.name = 'ldaumap')

# Visualize UMAP clustering results.
Idents(sub) <- "mixscape_class"
sub$mixscape_class <- as.factor(sub$mixscape_class)

# Set colors for each perturbation.
col = setNames(object = hue_pal()(12),nm = levels(sub$mixscape_class))
names(col) <- c(names(col)[1:7], "NT", names(col)[9:12])
col[8] <- "grey39"

p <- DimPlot(object = sub, 
             reduction = "ldaumap", 
             repel = T, 
             label.size = 5, 
             label = T, 
             cols = col) + NoLegend()

p2 <- p+ 
  scale_color_manual(values=col, drop=FALSE) + 
  ylab("UMAP 2") +
  xlab("UMAP 1") +
  custom_theme
p2
```

Example 35 (r):
```r
# Remove non-perturbed cells and run LDA to reduce the dimensionality of the data.
Idents(eccite) <- "mixscape_class.global"
sub <- subset(eccite, idents = c("KO", "NT"))

# Run LDA.
sub <- MixscapeLDA(
  object = sub, 
  assay = "RNA", 
  pc.assay = "PRTB", 
  labels = "gene", 
  nt.label = "NT", 
  npcs = 10, 
  logfc.threshold = 0.25, 
  verbose = F)

# Use LDA results to run UMAP and visualize cells on 2-D. 
# Here, we note that the number of the dimensions to be used is equal to the number of 
# labels minus one (to account for NT cells).
sub <- RunUMAP(
  object = sub,
  dims = 1:11,
  reduction = 'lda',
  reduction.key = 'ldaumap',
  reduction.name = 'ldaumap')

# Visualize UMAP clustering results.
Idents(sub) <- "mixscape_class"
sub$mixscape_class <- as.factor(sub$mixscape_class)

# Set colors for each perturbation.
col = setNames(object = hue_pal()(12),nm = levels(sub$mixscape_class))
names(col) <- c(names(col)[1:7], "NT", names(col)[9:12])
col[8] <- "grey39"

p <- DimPlot(object = sub, 
             reduction = "ldaumap", 
             repel = T, 
             label.size = 5, 
             label = T, 
             cols = col) + NoLegend()

p2 <- p+ 
  scale_color_manual(values=col, drop=FALSE) + 
  ylab("UMAP 2") +
  xlab("UMAP 1") +
  custom_theme
p2
```

Example 36 (r):
```r
# Remove non-perturbed cells and run LDA to reduce the dimensionality of the data.
Idents(eccite) <- "mixscape_class.global"
sub <- subset(eccite, idents = c("KO", "NT"))

# Run LDA.
sub <- MixscapeLDA(
  object = sub, 
  assay = "RNA", 
  pc.assay = "PRTB", 
  labels = "gene", 
  nt.label = "NT", 
  npcs = 10, 
  logfc.threshold = 0.25, 
  verbose = F)

# Use LDA results to run UMAP and visualize cells on 2-D. 
# Here, we note that the number of the dimensions to be used is equal to the number of 
# labels minus one (to account for NT cells).
sub <- RunUMAP(
  object = sub,
  dims = 1:11,
  reduction = 'lda',
  reduction.key = 'ldaumap',
  reduction.name = 'ldaumap')

# Visualize UMAP clustering results.
Idents(sub) <- "mixscape_class"
sub$mixscape_class <- as.factor(sub$mixscape_class)

# Set colors for each perturbation.
col = setNames(object = hue_pal()(12),nm = levels(sub$mixscape_class))
names(col) <- c(names(col)[1:7], "NT", names(col)[9:12])
col[8] <- "grey39"

p <- DimPlot(object = sub, 
             reduction = "ldaumap", 
             repel = T, 
             label.size = 5, 
             label = T, 
             cols = col) + NoLegend()

p2 <- p+ 
  scale_color_manual(values=col, drop=FALSE) + 
  ylab("UMAP 2") +
  xlab("UMAP 1") +
  custom_theme
p2
```

Example 37 (unknown):
```unknown
sessionInfo()
```

Example 38 (r):
```r
sessionInfo()
```

Example 39 (r):
```r
sessionInfo()
```

Example 40 (unknown):
```unknown
## R version 4.2.2 Patched (2022-11-10 r83330)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.6 LTS
## 
## Matrix products: default
## BLAS:   /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.9.0
## LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.9.0
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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       
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
##  [1] reshape2_1.4.4                dplyr_1.1.3                  
##  [3] scales_1.2.1                  patchwork_1.1.3              
##  [5] ggplot2_3.4.4                 thp1.eccite.SeuratData_3.1.5 
##  [7] stxBrain.SeuratData_0.1.1     ssHippo.SeuratData_3.1.4     
##  [9] pbmcsca.SeuratData_3.0.0      pbmcref.SeuratData_1.0.0     
## [11] pbmcMultiome.SeuratData_0.1.4 pbmc3k.SeuratData_3.1.4      
## [13] panc8.SeuratData_3.0.2        ifnb.SeuratData_3.0.0        
## [15] hcabm40k.SeuratData_3.0.0     cbmc.SeuratData_3.1.4        
## [17] bmcite.SeuratData_0.3.0       SeuratData_0.2.2.9001        
## [19] Seurat_5.0.0                  SeuratObject_5.0.0           
## [21] sp_2.1-1                     
## 
## loaded via a namespace (and not attached):
##   [1] spam_2.10-0            systemfonts_1.0.4      plyr_1.8.9            
##   [4] igraph_1.5.1           lazyeval_0.2.2         splines_4.2.2         
##   [7] RcppHNSW_0.5.0         listenv_0.9.0          scattermore_1.2       
##  [10] digest_0.6.33          htmltools_0.5.6.1      fansi_1.0.5           
##  [13] magrittr_2.0.3         memoise_2.0.1          tensor_1.5            
##  [16] cluster_2.1.4          mixtools_2.0.0         ROCR_1.0-11           
##  [19] limma_3.54.1           globals_0.16.2         matrixStats_1.0.0     
##  [22] pkgdown_2.0.7          spatstat.sparse_3.0-3  colorspace_2.1-0      
##  [25] rappdirs_0.3.3         ggrepel_0.9.4          textshaping_0.3.6     
##  [28] xfun_0.40              crayon_1.5.2           jsonlite_1.8.7        
##  [31] progressr_0.14.0       spatstat.data_3.0-3    survival_3.5-7        
##  [34] zoo_1.8-12             glue_1.6.2             polyclip_1.10-6       
##  [37] gtable_0.3.4           leiden_0.4.3           kernlab_0.9-32        
##  [40] future.apply_1.11.0    abind_1.4-5            spatstat.random_3.2-1 
##  [43] miniUI_0.1.1.1         Rcpp_1.0.11            viridisLite_0.4.2     
##  [46] xtable_1.8-4           reticulate_1.34.0      dotCall64_1.1-0       
##  [49] htmlwidgets_1.6.2      httr_1.4.7             RColorBrewer_1.1-3    
##  [52] ellipsis_0.3.2         ica_1.0-3              farver_2.1.1          
##  [55] pkgconfig_2.0.3        sass_0.4.7             uwot_0.1.16           
##  [58] deldir_1.0-9           utf8_1.2.4             labeling_0.4.3        
##  [61] tidyselect_1.2.0       rlang_1.1.1            later_1.3.1           
##  [64] munsell_0.5.0          tools_4.2.2            cachem_1.0.8          
##  [67] cli_3.6.1              generics_0.1.3         ggridges_0.5.4        
##  [70] evaluate_0.22          stringr_1.5.0          fastmap_1.1.1         
##  [73] yaml_2.3.7             ragg_1.2.5             goftest_1.2-3         
##  [76] knitr_1.45             fs_1.6.3               fitdistrplus_1.1-11   
##  [79] purrr_1.0.2            RANN_2.6.1             pbapply_1.7-2         
##  [82] future_1.33.0          nlme_3.1-162           mime_0.12             
##  [85] ggrastr_1.0.1          compiler_4.2.2         beeswarm_0.4.0        
##  [88] plotly_4.10.3          png_0.1-8              spatstat.utils_3.0-4  
##  [91] tibble_3.2.1           bslib_0.5.1            stringi_1.7.12        
##  [94] highr_0.10             desc_1.4.2             RSpectra_0.16-1       
##  [97] lattice_0.21-9         Matrix_1.6-1.1         vctrs_0.6.4           
## [100] pillar_1.9.0           lifecycle_1.0.3        spatstat.geom_3.2-7   
## [103] lmtest_0.9-40          jquerylib_0.1.4        RcppAnnoy_0.0.21      
## [106] data.table_1.14.8      cowplot_1.1.1          irlba_2.3.5.1         
## [109] httpuv_1.6.12          R6_2.5.1               promises_1.2.1        
## [112] KernSmooth_2.23-22     gridExtra_2.3          vipor_0.4.5           
## [115] parallelly_1.36.0      codetools_0.2-19       fastDummies_1.7.3     
## [118] MASS_7.3-58.2          rprojroot_2.0.3        withr_2.5.2           
## [121] presto_1.0.0           sctransform_0.4.1      parallel_4.2.2        
## [124] grid_4.2.2             tidyr_1.3.0            rmarkdown_2.25        
## [127] segmented_1.6-4        Rtsne_0.16             spatstat.explore_3.2-5
## [130] shiny_1.7.5.1          ggbeeswarm_0.7.1
```

Example 41 (unknown):
```unknown
## R version 4.2.2 Patched (2022-11-10 r83330)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.6 LTS
## 
## Matrix products: default
## BLAS:   /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.9.0
## LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.9.0
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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       
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
##  [1] reshape2_1.4.4                dplyr_1.1.3                  
##  [3] scales_1.2.1                  patchwork_1.1.3              
##  [5] ggplot2_3.4.4                 thp1.eccite.SeuratData_3.1.5 
##  [7] stxBrain.SeuratData_0.1.1     ssHippo.SeuratData_3.1.4     
##  [9] pbmcsca.SeuratData_3.0.0      pbmcref.SeuratData_1.0.0     
## [11] pbmcMultiome.SeuratData_0.1.4 pbmc3k.SeuratData_3.1.4      
## [13] panc8.SeuratData_3.0.2        ifnb.SeuratData_3.0.0        
## [15] hcabm40k.SeuratData_3.0.0     cbmc.SeuratData_3.1.4        
## [17] bmcite.SeuratData_0.3.0       SeuratData_0.2.2.9001        
## [19] Seurat_5.0.0                  SeuratObject_5.0.0           
## [21] sp_2.1-1                     
## 
## loaded via a namespace (and not attached):
##   [1] spam_2.10-0            systemfonts_1.0.4      plyr_1.8.9            
##   [4] igraph_1.5.1           lazyeval_0.2.2         splines_4.2.2         
##   [7] RcppHNSW_0.5.0         listenv_0.9.0          scattermore_1.2       
##  [10] digest_0.6.33          htmltools_0.5.6.1      fansi_1.0.5           
##  [13] magrittr_2.0.3         memoise_2.0.1          tensor_1.5            
##  [16] cluster_2.1.4          mixtools_2.0.0         ROCR_1.0-11           
##  [19] limma_3.54.1           globals_0.16.2         matrixStats_1.0.0     
##  [22] pkgdown_2.0.7          spatstat.sparse_3.0-3  colorspace_2.1-0      
##  [25] rappdirs_0.3.3         ggrepel_0.9.4          textshaping_0.3.6     
##  [28] xfun_0.40              crayon_1.5.2           jsonlite_1.8.7        
##  [31] progressr_0.14.0       spatstat.data_3.0-3    survival_3.5-7        
##  [34] zoo_1.8-12             glue_1.6.2             polyclip_1.10-6       
##  [37] gtable_0.3.4           leiden_0.4.3           kernlab_0.9-32        
##  [40] future.apply_1.11.0    abind_1.4-5            spatstat.random_3.2-1 
##  [43] miniUI_0.1.1.1         Rcpp_1.0.11            viridisLite_0.4.2     
##  [46] xtable_1.8-4           reticulate_1.34.0      dotCall64_1.1-0       
##  [49] htmlwidgets_1.6.2      httr_1.4.7             RColorBrewer_1.1-3    
##  [52] ellipsis_0.3.2         ica_1.0-3              farver_2.1.1          
##  [55] pkgconfig_2.0.3        sass_0.4.7             uwot_0.1.16           
##  [58] deldir_1.0-9           utf8_1.2.4             labeling_0.4.3        
##  [61] tidyselect_1.2.0       rlang_1.1.1            later_1.3.1           
##  [64] munsell_0.5.0          tools_4.2.2            cachem_1.0.8          
##  [67] cli_3.6.1              generics_0.1.3         ggridges_0.5.4        
##  [70] evaluate_0.22          stringr_1.5.0          fastmap_1.1.1         
##  [73] yaml_2.3.7             ragg_1.2.5             goftest_1.2-3         
##  [76] knitr_1.45             fs_1.6.3               fitdistrplus_1.1-11   
##  [79] purrr_1.0.2            RANN_2.6.1             pbapply_1.7-2         
##  [82] future_1.33.0          nlme_3.1-162           mime_0.12             
##  [85] ggrastr_1.0.1          compiler_4.2.2         beeswarm_0.4.0        
##  [88] plotly_4.10.3          png_0.1-8              spatstat.utils_3.0-4  
##  [91] tibble_3.2.1           bslib_0.5.1            stringi_1.7.12        
##  [94] highr_0.10             desc_1.4.2             RSpectra_0.16-1       
##  [97] lattice_0.21-9         Matrix_1.6-1.1         vctrs_0.6.4           
## [100] pillar_1.9.0           lifecycle_1.0.3        spatstat.geom_3.2-7   
## [103] lmtest_0.9-40          jquerylib_0.1.4        RcppAnnoy_0.0.21      
## [106] data.table_1.14.8      cowplot_1.1.1          irlba_2.3.5.1         
## [109] httpuv_1.6.12          R6_2.5.1               promises_1.2.1        
## [112] KernSmooth_2.23-22     gridExtra_2.3          vipor_0.4.5           
## [115] parallelly_1.36.0      codetools_0.2-19       fastDummies_1.7.3     
## [118] MASS_7.3-58.2          rprojroot_2.0.3        withr_2.5.2           
## [121] presto_1.0.0           sctransform_0.4.1      parallel_4.2.2        
## [124] grid_4.2.2             tidyr_1.3.0            rmarkdown_2.25        
## [127] segmented_1.6-4        Rtsne_0.16             spatstat.explore_3.2-5
## [130] shiny_1.7.5.1          ggbeeswarm_0.7.1
```

---

## Analysis, visualization, and integration of Visium HD spatial datasets with Seurat • Seurat

**URL:** http://127.0.0.1:9173/articles_visualization_vignette.html

**Contents:**
- Data visualization methods in Seurat
    - Compiled: 2023-10-31
- Five visualizations of marker feature expression
- New additions to FeaturePlot
- Updated and expanded visualization functions
- Applying themes to plots
- Interactive plotting features
- Plotting Accessories
- Contents

We’ll demonstrate visualization techniques in Seurat using our previously computed Seurat object from the 2,700 PBMC tutorial. You can download this dataset from SeuratData

In addition to changes to FeaturePlot(), several other plotting functions have been updated and expanded with new features and taking over the role of now-deprecated functions

With Seurat, all plotting functions return ggplot2-based plots by default, allowing one to easily capture and manipulate plots just like any other ggplot2-based plot.

Seurat utilizes R’s plotly graphing library to create interactive plots. This interactive plotting feature works with any ggplot2-based scatter plots (requires a geom_point layer). To use, simply make a ggplot2-based scatter plot (such as DimPlot() or FeaturePlot()) and pass the resulting plot to HoverLocator()

Another interactive feature provided by Seurat is being able to manually select cells for further investigation. We have found this particularly useful for small clusters that do not always separate using unbiased clustering, but which look tantalizingly distinct. You can now select these cells by creating a ggplot2-based scatter plot (such as with DimPlot() or FeaturePlot(), and passing the returned plot to CellSelector(). CellSelector() will return a vector with the names of the points selected, so that you can then set them to a new identity class and perform differential expression.

For example, let’s pretend that DCs had merged with monocytes in the clustering, but we wanted to see what was unique about them based on their position in the tSNE plot.

We can then change the identity of these cells to turn them into their own mini-cluster.

Using CellSelector to Automatically Assign Cell Identities

In addition to returning a vector of cell names, CellSelector() can also take the selected cells and assign a new identity to them, returning a Seurat object with the identity classes already set. This is done by passing the Seurat object used to make the plot into CellSelector(), as well as an identity class. As an example, we’re going to select the same set of cells as before, and set their identity class to “selected”

Along with new functions add interactive functionality to plots, Seurat provides new accessory functions for manipulating and combining plots.

Plotting multiple plots was previously achieved with the CombinePlot() function. We are deprecating this functionality in favor of the patchwork system. Below is a brief demonstration but please see the patchwork package website here for more details and examples.

Developed by Rahul Satija, Satija Lab and Collaborators.

Site built with pkgdown 2.0.7.

**Examples:**

Example 1 (unknown):
```unknown
vignettes/visualization_vignette.Rmd
```

Example 2 (unknown):
```unknown
visualization_vignette.Rmd
```

Example 3 (unknown):
```unknown
SeuratData::InstallData("pbmc3k")
```

Example 4 (r):
```r
SeuratData::InstallData("pbmc3k")
```

Example 5 (r):
```r
SeuratData::InstallData("pbmc3k")
```

Example 6 (unknown):
```unknown
library(Seurat)
library(SeuratData)
library(ggplot2)
library(patchwork)
pbmc3k.final <- LoadData("pbmc3k", type = "pbmc3k.final")
pbmc3k.final$groups <- sample(c("group1", "group2"), size = ncol(pbmc3k.final), replace = TRUE)
features <- c("LYZ", "CCL5", "IL32", "PTPRCAP", "FCGR3A", "PF4")
pbmc3k.final
```

Example 7 (r):
```r
library(Seurat)
library(SeuratData)
library(ggplot2)
library(patchwork)
pbmc3k.final <- LoadData("pbmc3k", type = "pbmc3k.final")
pbmc3k.final$groups <- sample(c("group1", "group2"), size = ncol(pbmc3k.final), replace = TRUE)
features <- c("LYZ", "CCL5", "IL32", "PTPRCAP", "FCGR3A", "PF4")
pbmc3k.final
```

Example 8 (r):
```r
library(Seurat)
library(SeuratData)
library(ggplot2)
library(patchwork)
pbmc3k.final <- LoadData("pbmc3k", type = "pbmc3k.final")
pbmc3k.final$groups <- sample(c("group1", "group2"), size = ncol(pbmc3k.final), replace = TRUE)
features <- c("LYZ", "CCL5", "IL32", "PTPRCAP", "FCGR3A", "PF4")
pbmc3k.final
```

Example 9 (python):
```python
## An object of class Seurat 
## 13714 features across 2638 samples within 1 assay 
## Active assay: RNA (13714 features, 2000 variable features)
##  3 layers present: data, counts, scale.data
##  2 dimensional reductions calculated: pca, umap
```

Example 10 (python):
```python
## An object of class Seurat 
## 13714 features across 2638 samples within 1 assay 
## Active assay: RNA (13714 features, 2000 variable features)
##  3 layers present: data, counts, scale.data
##  2 dimensional reductions calculated: pca, umap
```

Example 11 (python):
```python
# Ridge plots - from ggridges. Visualize single cell expression distributions in each cluster
RidgePlot(pbmc3k.final, features = features, ncol = 2)
```

Example 12 (r):
```r
# Ridge plots - from ggridges. Visualize single cell expression distributions in each cluster
RidgePlot(pbmc3k.final, features = features, ncol = 2)
```

Example 13 (r):
```r
# Ridge plots - from ggridges. Visualize single cell expression distributions in each cluster
RidgePlot(pbmc3k.final, features = features, ncol = 2)
```

Example 14 (unknown):
```unknown
# Violin plot - Visualize single cell expression distributions in each cluster
VlnPlot(pbmc3k.final, features = features)
```

Example 15 (r):
```r
# Violin plot - Visualize single cell expression distributions in each cluster
VlnPlot(pbmc3k.final, features = features)
```

Example 16 (r):
```r
# Violin plot - Visualize single cell expression distributions in each cluster
VlnPlot(pbmc3k.final, features = features)
```

Example 17 (unknown):
```unknown
# Feature plot - visualize feature expression in low-dimensional space
FeaturePlot(pbmc3k.final, features = features)
```

Example 18 (r):
```r
# Feature plot - visualize feature expression in low-dimensional space
FeaturePlot(pbmc3k.final, features = features)
```

Example 19 (r):
```r
# Feature plot - visualize feature expression in low-dimensional space
FeaturePlot(pbmc3k.final, features = features)
```

Example 20 (unknown):
```unknown
# Dot plots - the size of the dot corresponds to the percentage of cells expressing the
# feature in each cluster. The color represents the average expression level
DotPlot(pbmc3k.final, features = features) + RotatedAxis()
```

Example 21 (r):
```r
# Dot plots - the size of the dot corresponds to the percentage of cells expressing the
# feature in each cluster. The color represents the average expression level
DotPlot(pbmc3k.final, features = features) + RotatedAxis()
```

Example 22 (r):
```r
# Dot plots - the size of the dot corresponds to the percentage of cells expressing the
# feature in each cluster. The color represents the average expression level
DotPlot(pbmc3k.final, features = features) + RotatedAxis()
```

Example 23 (unknown):
```unknown
# Single cell heatmap of feature expression
DoHeatmap(subset(pbmc3k.final, downsample = 100), features = features, size = 3)
```

Example 24 (r):
```r
# Single cell heatmap of feature expression
DoHeatmap(subset(pbmc3k.final, downsample = 100), features = features, size = 3)
```

Example 25 (r):
```r
# Single cell heatmap of feature expression
DoHeatmap(subset(pbmc3k.final, downsample = 100), features = features, size = 3)
```

Example 26 (unknown):
```unknown
FeaturePlot
```

Example 27 (unknown):
```unknown
# Plot a legend to map colors to expression levels
FeaturePlot(pbmc3k.final, features = "MS4A1")
```

Example 28 (r):
```r
# Plot a legend to map colors to expression levels
FeaturePlot(pbmc3k.final, features = "MS4A1")
```

Example 29 (r):
```r
# Plot a legend to map colors to expression levels
FeaturePlot(pbmc3k.final, features = "MS4A1")
```

Example 30 (unknown):
```unknown
# Adjust the contrast in the plot
FeaturePlot(pbmc3k.final, features = "MS4A1", min.cutoff = 1, max.cutoff = 3)
```

Example 31 (r):
```r
# Adjust the contrast in the plot
FeaturePlot(pbmc3k.final, features = "MS4A1", min.cutoff = 1, max.cutoff = 3)
```

Example 32 (r):
```r
# Adjust the contrast in the plot
FeaturePlot(pbmc3k.final, features = "MS4A1", min.cutoff = 1, max.cutoff = 3)
```

Example 33 (unknown):
```unknown
# Calculate feature-specific contrast levels based on quantiles of non-zero expression.
# Particularly useful when plotting multiple markers
FeaturePlot(pbmc3k.final, features = c("MS4A1", "PTPRCAP"), min.cutoff = "q10", max.cutoff = "q90")
```

Example 34 (r):
```r
# Calculate feature-specific contrast levels based on quantiles of non-zero expression.
# Particularly useful when plotting multiple markers
FeaturePlot(pbmc3k.final, features = c("MS4A1", "PTPRCAP"), min.cutoff = "q10", max.cutoff = "q90")
```

Example 35 (r):
```r
# Calculate feature-specific contrast levels based on quantiles of non-zero expression.
# Particularly useful when plotting multiple markers
FeaturePlot(pbmc3k.final, features = c("MS4A1", "PTPRCAP"), min.cutoff = "q10", max.cutoff = "q90")
```

Example 36 (unknown):
```unknown
# Visualize co-expression of two features simultaneously
FeaturePlot(pbmc3k.final, features = c("MS4A1", "CD79A"), blend = TRUE)
```

Example 37 (r):
```r
# Visualize co-expression of two features simultaneously
FeaturePlot(pbmc3k.final, features = c("MS4A1", "CD79A"), blend = TRUE)
```

Example 38 (r):
```r
# Visualize co-expression of two features simultaneously
FeaturePlot(pbmc3k.final, features = c("MS4A1", "CD79A"), blend = TRUE)
```

Example 39 (unknown):
```unknown
# Split visualization to view expression by groups (replaces FeatureHeatmap)
FeaturePlot(pbmc3k.final, features = c("MS4A1", "CD79A"), split.by = "groups")
```

Example 40 (r):
```r
# Split visualization to view expression by groups (replaces FeatureHeatmap)
FeaturePlot(pbmc3k.final, features = c("MS4A1", "CD79A"), split.by = "groups")
```

Example 41 (r):
```r
# Split visualization to view expression by groups (replaces FeatureHeatmap)
FeaturePlot(pbmc3k.final, features = c("MS4A1", "CD79A"), split.by = "groups")
```

Example 42 (unknown):
```unknown
FeaturePlot()
```

Example 43 (python):
```python
# Violin plots can also be split on some variable. Simply add the splitting variable to object
# metadata and pass it to the split.by argument
VlnPlot(pbmc3k.final, features = "percent.mt", split.by = "groups")
```

Example 44 (r):
```r
# Violin plots can also be split on some variable. Simply add the splitting variable to object
# metadata and pass it to the split.by argument
VlnPlot(pbmc3k.final, features = "percent.mt", split.by = "groups")
```

Example 45 (r):
```r
# Violin plots can also be split on some variable. Simply add the splitting variable to object
# metadata and pass it to the split.by argument
VlnPlot(pbmc3k.final, features = "percent.mt", split.by = "groups")
```

Example 46 (unknown):
```unknown
# SplitDotPlotGG has been replaced with the `split.by` parameter for DotPlot
DotPlot(pbmc3k.final, features = features, split.by = "groups") + RotatedAxis()
```

Example 47 (r):
```r
# SplitDotPlotGG has been replaced with the `split.by` parameter for DotPlot
DotPlot(pbmc3k.final, features = features, split.by = "groups") + RotatedAxis()
```

Example 48 (r):
```r
# SplitDotPlotGG has been replaced with the `split.by` parameter for DotPlot
DotPlot(pbmc3k.final, features = features, split.by = "groups") + RotatedAxis()
```

Example 49 (unknown):
```unknown
# DimPlot replaces TSNEPlot, PCAPlot, etc. In addition, it will plot either 'umap', 'tsne', or
# 'pca' by default, in that order
DimPlot(pbmc3k.final)
```

Example 50 (r):
```r
# DimPlot replaces TSNEPlot, PCAPlot, etc. In addition, it will plot either 'umap', 'tsne', or
# 'pca' by default, in that order
DimPlot(pbmc3k.final)
```

Example 51 (r):
```r
# DimPlot replaces TSNEPlot, PCAPlot, etc. In addition, it will plot either 'umap', 'tsne', or
# 'pca' by default, in that order
DimPlot(pbmc3k.final)
```

Example 52 (unknown):
```unknown
pbmc3k.final.no.umap <- pbmc3k.final
pbmc3k.final.no.umap[["umap"]] <- NULL
DimPlot(pbmc3k.final.no.umap) + RotatedAxis()
```

Example 53 (r):
```r
pbmc3k.final.no.umap <- pbmc3k.final
pbmc3k.final.no.umap[["umap"]] <- NULL
DimPlot(pbmc3k.final.no.umap) + RotatedAxis()
```

Example 54 (r):
```r
pbmc3k.final.no.umap <- pbmc3k.final
pbmc3k.final.no.umap[["umap"]] <- NULL
DimPlot(pbmc3k.final.no.umap) + RotatedAxis()
```

Example 55 (unknown):
```unknown
# DoHeatmap now shows a grouping bar, splitting the heatmap into groups or clusters. This can
# be changed with the `group.by` parameter
DoHeatmap(pbmc3k.final, features = VariableFeatures(pbmc3k.final)[1:100], cells = 1:500, size = 4,
    angle = 90) + NoLegend()
```

Example 56 (r):
```r
# DoHeatmap now shows a grouping bar, splitting the heatmap into groups or clusters. This can
# be changed with the `group.by` parameter
DoHeatmap(pbmc3k.final, features = VariableFeatures(pbmc3k.final)[1:100], cells = 1:500, size = 4,
    angle = 90) + NoLegend()
```

Example 57 (r):
```r
# DoHeatmap now shows a grouping bar, splitting the heatmap into groups or clusters. This can
# be changed with the `group.by` parameter
DoHeatmap(pbmc3k.final, features = VariableFeatures(pbmc3k.final)[1:100], cells = 1:500, size = 4,
    angle = 90) + NoLegend()
```

Example 58 (unknown):
```unknown
baseplot <- DimPlot(pbmc3k.final, reduction = "umap")
# Add custom labels and titles
baseplot + labs(title = "Clustering of 2,700 PBMCs")
```

Example 59 (r):
```r
baseplot <- DimPlot(pbmc3k.final, reduction = "umap")
# Add custom labels and titles
baseplot + labs(title = "Clustering of 2,700 PBMCs")
```

Example 60 (r):
```r
baseplot <- DimPlot(pbmc3k.final, reduction = "umap")
# Add custom labels and titles
baseplot + labs(title = "Clustering of 2,700 PBMCs")
```

Example 61 (unknown):
```unknown
# Use community-created themes, overwriting the default Seurat-applied theme Install ggmin
# with remotes::install_github('sjessa/ggmin')
baseplot + ggmin::theme_powerpoint()
```

Example 62 (r):
```r
# Use community-created themes, overwriting the default Seurat-applied theme Install ggmin
# with remotes::install_github('sjessa/ggmin')
baseplot + ggmin::theme_powerpoint()
```

Example 63 (r):
```r
# Use community-created themes, overwriting the default Seurat-applied theme Install ggmin
# with remotes::install_github('sjessa/ggmin')
baseplot + ggmin::theme_powerpoint()
```

Example 64 (unknown):
```unknown
# Seurat also provides several built-in themes, such as DarkTheme; for more details see
# ?SeuratTheme
baseplot + DarkTheme()
```

Example 65 (r):
```r
# Seurat also provides several built-in themes, such as DarkTheme; for more details see
# ?SeuratTheme
baseplot + DarkTheme()
```

Example 66 (r):
```r
# Seurat also provides several built-in themes, such as DarkTheme; for more details see
# ?SeuratTheme
baseplot + DarkTheme()
```

Example 67 (unknown):
```unknown
# Chain themes together
baseplot + FontSize(x.title = 20, y.title = 20) + NoLegend()
```

Example 68 (r):
```r
# Chain themes together
baseplot + FontSize(x.title = 20, y.title = 20) + NoLegend()
```

Example 69 (r):
```r
# Chain themes together
baseplot + FontSize(x.title = 20, y.title = 20) + NoLegend()
```

Example 70 (unknown):
```unknown
FeaturePlot()
```

Example 71 (unknown):
```unknown
HoverLocator()
```

Example 72 (unknown):
```unknown
# Include additional data to display alongside cell names by passing in a data frame of
# information.  Works well when using FetchData
plot <- FeaturePlot(pbmc3k.final, features = "MS4A1")
HoverLocator(plot = plot, information = FetchData(pbmc3k.final, vars = c("ident", "PC_1", "nFeature_RNA")))
```

Example 73 (r):
```r
# Include additional data to display alongside cell names by passing in a data frame of
# information.  Works well when using FetchData
plot <- FeaturePlot(pbmc3k.final, features = "MS4A1")
HoverLocator(plot = plot, information = FetchData(pbmc3k.final, vars = c("ident", "PC_1", "nFeature_RNA")))
```

Example 74 (r):
```r
# Include additional data to display alongside cell names by passing in a data frame of
# information.  Works well when using FetchData
plot <- FeaturePlot(pbmc3k.final, features = "MS4A1")
HoverLocator(plot = plot, information = FetchData(pbmc3k.final, vars = c("ident", "PC_1", "nFeature_RNA")))
```

Example 75 (unknown):
```unknown
FeaturePlot()
```

Example 76 (unknown):
```unknown
CellSelector()
```

Example 77 (unknown):
```unknown
CellSelector()
```

Example 78 (unknown):
```unknown
pbmc3k.final <- RenameIdents(pbmc3k.final, DC = "CD14+ Mono")
plot <- DimPlot(pbmc3k.final, reduction = "umap")
select.cells <- CellSelector(plot = plot)
```

Example 79 (r):
```r
pbmc3k.final <- RenameIdents(pbmc3k.final, DC = "CD14+ Mono")
plot <- DimPlot(pbmc3k.final, reduction = "umap")
select.cells <- CellSelector(plot = plot)
```

Example 80 (r):
```r
pbmc3k.final <- RenameIdents(pbmc3k.final, DC = "CD14+ Mono")
plot <- DimPlot(pbmc3k.final, reduction = "umap")
select.cells <- CellSelector(plot = plot)
```

Example 81 (unknown):
```unknown
head(select.cells)
```

Example 82 (r):
```r
head(select.cells)
```

Example 83 (r):
```r
head(select.cells)
```

Example 84 (unknown):
```unknown
## [1] "AAGATTACCGCCTT" "AAGCCATGAACTGC" "AATTACGAATTCCT" "ACCCGTTGCTTCTA"
## [5] "ACGAGGGACAGGAG" "ACGTGATGCCATGA"
```

Example 85 (unknown):
```unknown
## [1] "AAGATTACCGCCTT" "AAGCCATGAACTGC" "AATTACGAATTCCT" "ACCCGTTGCTTCTA"
## [5] "ACGAGGGACAGGAG" "ACGTGATGCCATGA"
```

Example 86 (unknown):
```unknown
Idents(pbmc3k.final, cells = select.cells) <- "NewCells"

# Now, we find markers that are specific to the new cells, and find clear DC markers
newcells.markers <- FindMarkers(pbmc3k.final, ident.1 = "NewCells", ident.2 = "CD14+ Mono", min.diff.pct = 0.3,
    only.pos = TRUE)
head(newcells.markers)
```

Example 87 (r):
```r
Idents(pbmc3k.final, cells = select.cells) <- "NewCells"

# Now, we find markers that are specific to the new cells, and find clear DC markers
newcells.markers <- FindMarkers(pbmc3k.final, ident.1 = "NewCells", ident.2 = "CD14+ Mono", min.diff.pct = 0.3,
    only.pos = TRUE)
head(newcells.markers)
```

Example 88 (r):
```r
Idents(pbmc3k.final, cells = select.cells) <- "NewCells"

# Now, we find markers that are specific to the new cells, and find clear DC markers
newcells.markers <- FindMarkers(pbmc3k.final, ident.1 = "NewCells", ident.2 = "CD14+ Mono", min.diff.pct = 0.3,
    only.pos = TRUE)
head(newcells.markers)
```

Example 89 (unknown):
```unknown
##                 p_val avg_log2FC pct.1 pct.2    p_val_adj
## FCER1A   3.239004e-69   6.504163 0.800 0.017 4.441970e-65
## SERPINF1 7.761413e-36   5.456560 0.457 0.013 1.064400e-31
## HLA-DQB2 1.721094e-34   4.752397 0.429 0.010 2.360309e-30
## CD1C     2.304106e-33   4.929607 0.514 0.025 3.159851e-29
## ENHO     5.099765e-32   5.076634 0.400 0.010 6.993818e-28
## ITM2C    4.299994e-29   5.660234 0.371 0.010 5.897012e-25
```

Example 90 (unknown):
```unknown
##                 p_val avg_log2FC pct.1 pct.2    p_val_adj
## FCER1A   3.239004e-69   6.504163 0.800 0.017 4.441970e-65
## SERPINF1 7.761413e-36   5.456560 0.457 0.013 1.064400e-31
## HLA-DQB2 1.721094e-34   4.752397 0.429 0.010 2.360309e-30
## CD1C     2.304106e-33   4.929607 0.514 0.025 3.159851e-29
## ENHO     5.099765e-32   5.076634 0.400 0.010 6.993818e-28
## ITM2C    4.299994e-29   5.660234 0.371 0.010 5.897012e-25
```

Example 91 (unknown):
```unknown
CellSelector
```

Example 92 (unknown):
```unknown
CellSelector()
```

Example 93 (unknown):
```unknown
CellSelector()
```

Example 94 (unknown):
```unknown
pbmc3k.final <- CellSelector(plot = plot, object = pbmc3k.final, ident = "selected")
```

Example 95 (r):
```r
pbmc3k.final <- CellSelector(plot = plot, object = pbmc3k.final, ident = "selected")
```

Example 96 (r):
```r
pbmc3k.final <- CellSelector(plot = plot, object = pbmc3k.final, ident = "selected")
```

Example 97 (unknown):
```unknown
levels(pbmc3k.final)
```

Example 98 (r):
```r
levels(pbmc3k.final)
```

Example 99 (r):
```r
levels(pbmc3k.final)
```

Example 100 (unknown):
```unknown
## [1] "selected"     "Naive CD4 T"  "Memory CD4 T" "CD14+ Mono"   "B"           
## [6] "CD8 T"        "FCGR3A+ Mono" "NK"           "Platelet"
```

Example 101 (unknown):
```unknown
## [1] "selected"     "Naive CD4 T"  "Memory CD4 T" "CD14+ Mono"   "B"           
## [6] "CD8 T"        "FCGR3A+ Mono" "NK"           "Platelet"
```

Example 102 (unknown):
```unknown
# LabelClusters and LabelPoints will label clusters (a coloring variable) or individual points
# on a ggplot2-based scatter plot
plot <- DimPlot(pbmc3k.final, reduction = "pca") + NoLegend()
LabelClusters(plot = plot, id = "ident")
```

Example 103 (r):
```r
# LabelClusters and LabelPoints will label clusters (a coloring variable) or individual points
# on a ggplot2-based scatter plot
plot <- DimPlot(pbmc3k.final, reduction = "pca") + NoLegend()
LabelClusters(plot = plot, id = "ident")
```

Example 104 (r):
```r
# LabelClusters and LabelPoints will label clusters (a coloring variable) or individual points
# on a ggplot2-based scatter plot
plot <- DimPlot(pbmc3k.final, reduction = "pca") + NoLegend()
LabelClusters(plot = plot, id = "ident")
```

Example 105 (python):
```python
# Both functions support `repel`, which will intelligently stagger labels and draw connecting
# lines from the labels to the points or clusters
LabelPoints(plot = plot, points = TopCells(object = pbmc3k.final[["pca"]]), repel = TRUE)
```

Example 106 (r):
```r
# Both functions support `repel`, which will intelligently stagger labels and draw connecting
# lines from the labels to the points or clusters
LabelPoints(plot = plot, points = TopCells(object = pbmc3k.final[["pca"]]), repel = TRUE)
```

Example 107 (r):
```r
# Both functions support `repel`, which will intelligently stagger labels and draw connecting
# lines from the labels to the points or clusters
LabelPoints(plot = plot, points = TopCells(object = pbmc3k.final[["pca"]]), repel = TRUE)
```

Example 108 (unknown):
```unknown
CombinePlot()
```

Example 109 (unknown):
```unknown
plot1 <- DimPlot(pbmc3k.final)
# Create scatter plot with the Pearson correlation value as the title
plot2 <- FeatureScatter(pbmc3k.final, feature1 = "LYZ", feature2 = "CCL5")
# Combine two plots
plot1 + plot2
```

Example 110 (r):
```r
plot1 <- DimPlot(pbmc3k.final)
# Create scatter plot with the Pearson correlation value as the title
plot2 <- FeatureScatter(pbmc3k.final, feature1 = "LYZ", feature2 = "CCL5")
# Combine two plots
plot1 + plot2
```

Example 111 (r):
```r
plot1 <- DimPlot(pbmc3k.final)
# Create scatter plot with the Pearson correlation value as the title
plot2 <- FeatureScatter(pbmc3k.final, feature1 = "LYZ", feature2 = "CCL5")
# Combine two plots
plot1 + plot2
```

Example 112 (python):
```python
# Remove the legend from all plots
(plot1 + plot2) & NoLegend()
```

Example 113 (r):
```r
# Remove the legend from all plots
(plot1 + plot2) & NoLegend()
```

Example 114 (r):
```r
# Remove the legend from all plots
(plot1 + plot2) & NoLegend()
```

Example 115 (unknown):
```unknown
sessionInfo()
```

Example 116 (r):
```r
sessionInfo()
```

Example 117 (r):
```r
sessionInfo()
```

Example 118 (unknown):
```unknown
## R version 4.2.2 Patched (2022-11-10 r83330)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.6 LTS
## 
## Matrix products: default
## BLAS:   /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.9.0
## LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.9.0
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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       
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
##  [1] patchwork_1.1.3               ggplot2_3.4.4                
##  [3] thp1.eccite.SeuratData_3.1.5  stxBrain.SeuratData_0.1.1    
##  [5] ssHippo.SeuratData_3.1.4      pbmcsca.SeuratData_3.0.0     
##  [7] pbmcref.SeuratData_1.0.0      pbmcMultiome.SeuratData_0.1.4
##  [9] pbmc3k.SeuratData_3.1.4       panc8.SeuratData_3.0.2       
## [11] ifnb.SeuratData_3.0.0         hcabm40k.SeuratData_3.0.0    
## [13] cbmc.SeuratData_3.1.4         bmcite.SeuratData_0.3.0      
## [15] SeuratData_0.2.2.9001         Seurat_5.0.0                 
## [17] SeuratObject_5.0.0            sp_2.1-1                     
## 
## loaded via a namespace (and not attached):
##   [1] spam_2.10-0            systemfonts_1.0.4      plyr_1.8.9            
##   [4] igraph_1.5.1           lazyeval_0.2.2         splines_4.2.2         
##   [7] RcppHNSW_0.5.0         crosstalk_1.2.0        listenv_0.9.0         
##  [10] scattermore_1.2        digest_0.6.33          htmltools_0.5.6.1     
##  [13] fansi_1.0.5            magrittr_2.0.3         memoise_2.0.1         
##  [16] tensor_1.5             cluster_2.1.4          ROCR_1.0-11           
##  [19] limma_3.54.1           globals_0.16.2         matrixStats_1.0.0     
##  [22] pkgdown_2.0.7          spatstat.sparse_3.0-3  colorspace_2.1-0      
##  [25] rappdirs_0.3.3         ggrepel_0.9.4          textshaping_0.3.6     
##  [28] xfun_0.40              dplyr_1.1.3            crayon_1.5.2          
##  [31] jsonlite_1.8.7         progressr_0.14.0       spatstat.data_3.0-3   
##  [34] survival_3.5-7         zoo_1.8-12             glue_1.6.2            
##  [37] polyclip_1.10-6        gtable_0.3.4           leiden_0.4.3          
##  [40] future.apply_1.11.0    abind_1.4-5            scales_1.2.1          
##  [43] spatstat.random_3.2-1  miniUI_0.1.1.1         Rcpp_1.0.11           
##  [46] viridisLite_0.4.2      xtable_1.8-4           reticulate_1.34.0     
##  [49] dotCall64_1.1-0        ggmin_0.0.0.9000       htmlwidgets_1.6.2     
##  [52] httr_1.4.7             RColorBrewer_1.1-3     ellipsis_0.3.2        
##  [55] ica_1.0-3              farver_2.1.1           pkgconfig_2.0.3       
##  [58] sass_0.4.7             uwot_0.1.16            deldir_1.0-9          
##  [61] utf8_1.2.4             labeling_0.4.3         tidyselect_1.2.0      
##  [64] rlang_1.1.1            reshape2_1.4.4         later_1.3.1           
##  [67] munsell_0.5.0          tools_4.2.2            cachem_1.0.8          
##  [70] cli_3.6.1              generics_0.1.3         ggridges_0.5.4        
##  [73] evaluate_0.22          stringr_1.5.0          fastmap_1.1.1         
##  [76] yaml_2.3.7             ragg_1.2.5             goftest_1.2-3         
##  [79] knitr_1.45             fs_1.6.3               fitdistrplus_1.1-11   
##  [82] purrr_1.0.2            RANN_2.6.1             pbapply_1.7-2         
##  [85] future_1.33.0          nlme_3.1-162           mime_0.12             
##  [88] formatR_1.14           ggrastr_1.0.1          compiler_4.2.2        
##  [91] beeswarm_0.4.0         plotly_4.10.3          png_0.1-8             
##  [94] spatstat.utils_3.0-4   tibble_3.2.1           bslib_0.5.1           
##  [97] stringi_1.7.12         highr_0.10             desc_1.4.2            
## [100] RSpectra_0.16-1        lattice_0.21-9         Matrix_1.6-1.1        
## [103] vctrs_0.6.4            pillar_1.9.0           lifecycle_1.0.3       
## [106] spatstat.geom_3.2-7    lmtest_0.9-40          jquerylib_0.1.4       
## [109] RcppAnnoy_0.0.21       data.table_1.14.8      cowplot_1.1.1         
## [112] irlba_2.3.5.1          httpuv_1.6.12          R6_2.5.1              
## [115] promises_1.2.1         KernSmooth_2.23-22     gridExtra_2.3         
## [118] vipor_0.4.5            parallelly_1.36.0      codetools_0.2-19      
## [121] fastDummies_1.7.3      MASS_7.3-58.2          rprojroot_2.0.3       
## [124] withr_2.5.2            presto_1.0.0           sctransform_0.4.1     
## [127] parallel_4.2.2         grid_4.2.2             tidyr_1.3.0           
## [130] rmarkdown_2.25         Rtsne_0.16             spatstat.explore_3.2-5
## [133] shiny_1.7.5.1          ggbeeswarm_0.7.1
```

Example 119 (unknown):
```unknown
## R version 4.2.2 Patched (2022-11-10 r83330)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.6 LTS
## 
## Matrix products: default
## BLAS:   /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.9.0
## LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.9.0
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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       
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
##  [1] patchwork_1.1.3               ggplot2_3.4.4                
##  [3] thp1.eccite.SeuratData_3.1.5  stxBrain.SeuratData_0.1.1    
##  [5] ssHippo.SeuratData_3.1.4      pbmcsca.SeuratData_3.0.0     
##  [7] pbmcref.SeuratData_1.0.0      pbmcMultiome.SeuratData_0.1.4
##  [9] pbmc3k.SeuratData_3.1.4       panc8.SeuratData_3.0.2       
## [11] ifnb.SeuratData_3.0.0         hcabm40k.SeuratData_3.0.0    
## [13] cbmc.SeuratData_3.1.4         bmcite.SeuratData_0.3.0      
## [15] SeuratData_0.2.2.9001         Seurat_5.0.0                 
## [17] SeuratObject_5.0.0            sp_2.1-1                     
## 
## loaded via a namespace (and not attached):
##   [1] spam_2.10-0            systemfonts_1.0.4      plyr_1.8.9            
##   [4] igraph_1.5.1           lazyeval_0.2.2         splines_4.2.2         
##   [7] RcppHNSW_0.5.0         crosstalk_1.2.0        listenv_0.9.0         
##  [10] scattermore_1.2        digest_0.6.33          htmltools_0.5.6.1     
##  [13] fansi_1.0.5            magrittr_2.0.3         memoise_2.0.1         
##  [16] tensor_1.5             cluster_2.1.4          ROCR_1.0-11           
##  [19] limma_3.54.1           globals_0.16.2         matrixStats_1.0.0     
##  [22] pkgdown_2.0.7          spatstat.sparse_3.0-3  colorspace_2.1-0      
##  [25] rappdirs_0.3.3         ggrepel_0.9.4          textshaping_0.3.6     
##  [28] xfun_0.40              dplyr_1.1.3            crayon_1.5.2          
##  [31] jsonlite_1.8.7         progressr_0.14.0       spatstat.data_3.0-3   
##  [34] survival_3.5-7         zoo_1.8-12             glue_1.6.2            
##  [37] polyclip_1.10-6        gtable_0.3.4           leiden_0.4.3          
##  [40] future.apply_1.11.0    abind_1.4-5            scales_1.2.1          
##  [43] spatstat.random_3.2-1  miniUI_0.1.1.1         Rcpp_1.0.11           
##  [46] viridisLite_0.4.2      xtable_1.8-4           reticulate_1.34.0     
##  [49] dotCall64_1.1-0        ggmin_0.0.0.9000       htmlwidgets_1.6.2     
##  [52] httr_1.4.7             RColorBrewer_1.1-3     ellipsis_0.3.2        
##  [55] ica_1.0-3              farver_2.1.1           pkgconfig_2.0.3       
##  [58] sass_0.4.7             uwot_0.1.16            deldir_1.0-9          
##  [61] utf8_1.2.4             labeling_0.4.3         tidyselect_1.2.0      
##  [64] rlang_1.1.1            reshape2_1.4.4         later_1.3.1           
##  [67] munsell_0.5.0          tools_4.2.2            cachem_1.0.8          
##  [70] cli_3.6.1              generics_0.1.3         ggridges_0.5.4        
##  [73] evaluate_0.22          stringr_1.5.0          fastmap_1.1.1         
##  [76] yaml_2.3.7             ragg_1.2.5             goftest_1.2-3         
##  [79] knitr_1.45             fs_1.6.3               fitdistrplus_1.1-11   
##  [82] purrr_1.0.2            RANN_2.6.1             pbapply_1.7-2         
##  [85] future_1.33.0          nlme_3.1-162           mime_0.12             
##  [88] formatR_1.14           ggrastr_1.0.1          compiler_4.2.2        
##  [91] beeswarm_0.4.0         plotly_4.10.3          png_0.1-8             
##  [94] spatstat.utils_3.0-4   tibble_3.2.1           bslib_0.5.1           
##  [97] stringi_1.7.12         highr_0.10             desc_1.4.2            
## [100] RSpectra_0.16-1        lattice_0.21-9         Matrix_1.6-1.1        
## [103] vctrs_0.6.4            pillar_1.9.0           lifecycle_1.0.3       
## [106] spatstat.geom_3.2-7    lmtest_0.9-40          jquerylib_0.1.4       
## [109] RcppAnnoy_0.0.21       data.table_1.14.8      cowplot_1.1.1         
## [112] irlba_2.3.5.1          httpuv_1.6.12          R6_2.5.1              
## [115] promises_1.2.1         KernSmooth_2.23-22     gridExtra_2.3         
## [118] vipor_0.4.5            parallelly_1.36.0      codetools_0.2-19      
## [121] fastDummies_1.7.3      MASS_7.3-58.2          rprojroot_2.0.3       
## [124] withr_2.5.2            presto_1.0.0           sctransform_0.4.1     
## [127] parallel_4.2.2         grid_4.2.2             tidyr_1.3.0           
## [130] rmarkdown_2.25         Rtsne_0.16             spatstat.explore_3.2-5
## [133] shiny_1.7.5.1          ggbeeswarm_0.7.1
```

---

## Analysis, visualization, and integration of spatial datasets with Seurat

**URL:** http://127.0.0.1:9173/seurat/archive/v3.2/spatial_vignette/index.html

**Contents:**
- Analysis, visualization, and integration of spatial datasets with Seurat
    - Compiled: 2020-10-02
  - Overview
- 10x Visium
  - Dataset
  - Data preprocessing
  - Gene expression visualization
  - Dimensionality reduction, clustering, and visualization
  - Interactive plotting
  - Identification of Spatially Variable Features
  - Subset out anatomical regions
  - Integration with single-cell data
  - Working with multiple slices in Seurat
  - Acknowledgments
- Slide-seq
  - Dataset
  - Data preprocessing
  - Integration with a scRNA-seq reference
  - Identification of Spatially Variable Features

This tutorial demonstrates how to use Seurat (>=3.2) to analyze spatially-resolved RNA-seq data. While the analytical pipelines are similar to the Seurat workflow for single-cell RNA-seq analysis, we introduce updated interaction and visualization tools, with a particular emphasis on the integration of spatial and molecular information. This tutorial will cover the following tasks, which we believe will be common for many spatial analyses:

For our first vignette, we analyze a dataset generated with the Visium technology from 10x Genomics. We will be extending Seurat to work with additional data types in the near-future, including SLIDE-Seq, STARmap, and MERFISH.

First, we load Seurat and the other packages necessary for this vignette.

Here, we will be using a recently released dataset of sagital mouse brain slices generated using the Visium v1 chemistry. There are two serial anterior sections, and two (matched) serial posterior sections.

You can download the data here, and load it into Seurat using the Load10X_Spatial function. This reads in the output of the spaceranger pipeline, and returns a Seurat object that contains both the spot-level expression data along with the associated image of the tissue slice. You can also use our SeuratData package for easy data access, as demonstrated below. After installing the dataset, you can type ?stxBrain to learn more.

How is the spatial data stored within Seurat? The visium data from 10x consists of the following data types:

In the Seurat object, the spot by gene expression matrix is similar to a typical "RNA" Assay but contains spot level, not single-cell level data. The image itself is stored in a new images slot in the Seurat object. The images slot also stores the information necessary to associate spots with their physical position on the tissue image.

The initial preprocessing steps that we perform on the spot by gene expression data are similar to a typical scRNA-seq experiment. We first need to normalize the data in order to account for variance in sequencing depth across data points. We note that the variance in molecular counts / spot can be substantial for spatial datasets, particularly if there are differences in cell density across the tissue. We see substantial heterogeneity here, which requires effective normalization.

These plots demonstrate that the variance in molecular counts across spots is not just technical in nature, but also is dependent on the tissue anatomy. For example, regions of the tissue that are depleted for neurons (such as the cortical white matter), reproducibly exhibit lower molecular counts. As a result, standard approaches (such as the LogNormalize function), which force each data point to have the same underlying 'size' after normalization, can be problematic.

As an alternative, we recommend using sctransform (Hafemeister and Satija, Genome Biology 2019), which which builds regularized negative binomial models of gene expression in order to account for technical artifacts while preserving biological variance. For more details on sctransform, please see the paper here and the Seurat vignette here. sctransform normalizes the data, detects high-variance features, and stores the data in the SCT assay.

How do results compare to log-normalization? To explore the differences in normalization methods, we examine how both the sctransform and log normalization results correlate with the number of UMIs. For this comparison, we first rerun sctransform to store values for all genes and run a log-normalization procedure via NormalizeData.

For the boxplots above, we calculate the correlation of each feature (gene) with the number of UMIs (the nCount_Spatial variable here). We then place genes into groups based on their mean expression, and generate boxplots of these correlations. You can see that log-normalization fails to adequately normalize genes in the first three groups, suggesting that technical factors continue to influence normalized expression estimates for highly expressed genes. In contrast, sctransform normalization substantially mitigates this effect.

In Seurat v3.2, we have included new functionality to explore and interact with the inherently visual nature of spatial data. The SpatialFeaturePlot function in Seurat extends FeaturePlot, and can overlay molecular data on top of tissue histology. For example, in this data set of the mouse brain, the gene Hpca is a strong hippocampal marker and Ttr is a marker of the choroid plexus.

The default parameters in Seurat emphasize the visualization of molecular data. However, you can also adjust the size of the spots (and their transparency) to improve the visualization of the histology image, by changing the following parameters:

We can then proceed to run dimensionality reduction and clustering on the RNA expression data, using the same workflow as we use for scRNA-seq analysis.

We can then visualize the results of the clustering either in UMAP space (with DimPlot) or overlayed on the image with SpatialDimPlot.

As there are many colors, it can be challenging to visualize which voxel belongs to which cluster. We have a few strategies to help with this. Setting the label parameter places a colored box at the median of each cluster (see the plot above).

You can also use the cells.highlight parameter to demarcate particular cells of interest on a SpatialDimPlot. This can be very useful for distinguishing the spatial localization of individual clusters, as we show below:

We have also built in a number of interactive plotting capabilities. Both SpatialDimPlot and SpatialFeaturePlot now have an interactive parameter, that when set to TRUE, will open up the Rstudio viewer pane with an interactive Shiny plot. The example below demonstrates an interactive SpatialDimPlot in which you can hover over spots and view the cell name and current identity class (analagous to the previous do.hover behavior).

For SpatialFeaturePlot, setting interactive to TRUE brings up an interactive pane in which you can adjust the transparency of the spots, the point size, as well as the Assay and feature being plotted. After exploring the data, selecting the done button will return the last active plot as a ggplot object.

The LinkedDimPlot function links the UMAP representation to the tissue image representation and allows for interactive selection. For example, you can select a region in the UMAP plot and the corresponding spots in the image representation will be highlighted.

Seurat offers two workflows to identify molecular features that correlate with spatial location within a tissue. The first is to perform differential expression based on pre-annotated anatomical regions within the tissue, which may be determined either from unsupervised clustering or prior knowledge. This strategy works will in this case, as the clusters above exhibit clear spatial restriction.

An alternative approach, implemented in FindSpatiallyVariables, is to search for features exhibiting spatial patterning in the absence of pre-annotation. The default method (method = 'markvariogram), is inspired by the Trendsceek, which models spatial transcriptomics data as a mark point process and computes a 'variogram', which identifies genes whose expression level is dependent on their spatial location. More specifically, this process calculates gamma(r) values measuring the dependence between two spots a certain "r" distance apart. By default, we use an r-value of '5' in these analyes, and only compute these values for variable genes (where variation is calculated independently of spatial location) to save time.

We note that there are mulitple methods in the literature to accomplish this task, including SpatialDE, and Splotch. We encourage interested users to explore these methods, and hope to add support for them in the near future.

Now we visualize the expression of the top 6 features identified by this measure.

As with single-cell objects, you can subset the object to focus on a subset of data. Here, we approximately subset the frontal cortex. This process also facilitates the integration of these data with a cortical scRNA-seq dataset in the next section. First, we take a subset of clusters, and then further segment based on exact positions. After subsetting, we can visualize the cortical cells either on the full image, or a cropped image.

At ~50um, spots from the visium assay will encompass the expression profiles of multiple cells. For the growing list of systems where scRNA-seq data is available, users may be interested to 'deconvolute' each of the spatial voxels to predict the underlying composition of cell types. In preparing this vignette, we tested a wide variety of decovonlution and integration methods, using a reference scRNA-seq dataset of ~14,000 adult mouse cortical cell taxonomy from the Allen Institute, generated with the SMART-Seq2 protocol. We consistently found superior performance using integration methods (as opposed to deconvolution methods), likely because of substantially different noise models that characterize spatial and single-cell datasets, and integration methods are specifiically designed to be robust to these differences. We therefore apply the 'anchor'-based integration workflow recently introduced in Seurat v3, that enables the probabilistic transfer of annotations from a reference to a query set. We therefore follow the label transfer workflow introduced here, taking advantage of sctransform normalization, but anticipate new methods to be developed to accomplish this task.

We first load the data (download available here), pre-process the scRNA-seq reference, and then perform label transfer. The procedure outputs, for each spot, a probabilistic classification for each of the scRNA-seq derived classes. We add these predictions as a new assay in the Seurat object.

Now we get prediction scores for each spot for each class. Of particular interest in the frontal cortex region are the laminar excitatory neurons. Here we can distinguish between distinct sequential layers of these neuronal subtypes, for example:

Based on these prediction scores, we can also predict cell types whose location is spatially restricted. We use the same methods based on marked point processes to define spatially variable features, but use the cell type prediction scores as the "marks" rather than gene expression.

Finally, we show that our integrative procedure is capable of recovering the known spatial localization patterns of both neuronal and non-neuronal subsets, including laminar excitatory, layer-1 astrocytes, and the cortical grey matter.

This dataset of the mouse brain contains another slice corresponding to the other half of the brain. Here we read it in and perform the same initial normalization.

In order to work with multiple slices in the same Seurat object, we provide the merge function.

This then enables joint dimensional reduction and clustering on the underlying RNA expression data.

Finally, the data can be jointly visualized in a single UMAP plot. SpatialDimPlot and SpatialFeaturePlot will by default plot all slices as columns and groupings/features as rows.

We would like to thank Nigel Delaney and Stephen Williams for their helpful feedback and contributions to the new spatial Seurat code.

Here, we will be analyzing a dataset generated using Slide-seq v2 of the mouse hippocampus. This tutorial will follow much of the same structure as the spatial vignette for 10x Visium data but is tailored to give a demonstration specific to Slide-seq data.

You can use our SeuratData package for easy data access, as demonstrated below. After installing the dataset, you can type ?ssHippo to see the commands used to create the Seurat object.

The initial preprocessing steps for the bead by gene expression data are similar to other spatial Seurat analyses and to typical scRNA-seq experiments. Here, we note that many beads contain particularly low UMI counts but choose to keep all detected beads for downstream analysis.

We then normalize the data using sctransform and perform a standard scRNA-seq dimensionality reduction and clustering workflow.

We can then visualize the results of the clustering either in UMAP space (with DimPlot) or in the bead coordinate space with SpatialDimPlot.

To facilitate cell-type annotation of the Slide-seq dataset, we are leveraging an existing mouse single-cell RNA-seq hippocampus dataset, produced in Saunders*, Macosko*, et al. 2018. The data is available for download as a processed Seurat object here, with the raw count matrices available on the DropViz website.

The original annotations from the paper are provided in the cell metadata of the Seurat object. These annotations are provided at several "resolutions", from broad classes (ref$class) to subclusters within celltypes (ref$subcluster). For the purposes of this vignette, we'll work off of a modification of the celltype annotations (ref$celltype) which we felt struck a good balance.

We'll start by running the Seurat label transfer method to predict the major celltype for each bead.

We can then visualize the prediction scores for some of the major expected classes.

As mentioned in the Visium vignette, we can identify spatially variable features in two general ways: differential expression testing between pre-annotated anatomical regions or statistics that measure the dependence of a feature on spatial location.

Here, we demonstrate the latter with an implementation of Moran's I available via FindSpatiallyVariableFeatures by setting method = 'moransi'. Moran's I computes an overall spatial autocorrelation and gives a statistic (similar to a correlation coefficient) that measures the dependence of a feature on spatial location. This allows us to rank features based on how spatially variable their expression is. In order to facilitate quick estimation of this statistic, we implemented a basic binning strategy that will draw a rectangular grid over Slide-seq puck and average the feature and location within each bin. The number of bins in the x and y direction are controlled by the x.cuts and y.cuts parameters respectively. Additionally, while not required, installing the optional Rfast2 package(install.packages('Rfast2')), will significantly decrease the runtime via a more efficient implementation.

Now we visualize the expression of the top 6 features identified by Moran's I.

**Examples:**

Example 1 (r):
```r
library(Seurat)
library(SeuratData)
library(ggplot2)
library(patchwork)
library(dplyr)
```

Example 2 (r):
```r
library(Seurat)
library(SeuratData)
library(ggplot2)
library(patchwork)
library(dplyr)
```

Example 3 (unknown):
```unknown
Load10X_Spatial
```

Example 4 (r):
```r
InstallData("stxBrain")
```

Example 5 (r):
```r
InstallData("stxBrain")
```

Example 6 (r):
```r
brain <- LoadData("stxBrain", type = "anterior1")
```

Example 7 (r):
```r
brain <- LoadData("stxBrain", type = "anterior1")
```

Example 8 (r):
```r
plot1 <- VlnPlot(brain, features = "nCount_Spatial", pt.size = 0.1) + NoLegend()
plot2 <- SpatialFeaturePlot(brain, features = "nCount_Spatial") + theme(legend.position = "right")
wrap_plots(plot1, plot2)
```

Example 9 (r):
```r
plot1 <- VlnPlot(brain, features = "nCount_Spatial", pt.size = 0.1) + NoLegend()
plot2 <- SpatialFeaturePlot(brain, features = "nCount_Spatial") + theme(legend.position = "right")
wrap_plots(plot1, plot2)
```

Example 10 (unknown):
```unknown
LogNormalize
```

Example 11 (r):
```r
brain <- SCTransform(brain, assay = "Spatial", verbose = FALSE)
```

Example 12 (r):
```r
brain <- SCTransform(brain, assay = "Spatial", verbose = FALSE)
```

Example 13 (unknown):
```unknown
NormalizeData
```

Example 14 (r):
```r
# rerun normalization to store sctransform residuals for all genes
brain <- SCTransform(brain, assay = "Spatial", return.only.var.genes = FALSE, verbose = FALSE)
# also run standard log normalization for comparison
brain <- NormalizeData(brain, verbose = FALSE, assay = "Spatial")
```

Example 15 (r):
```r
# rerun normalization to store sctransform residuals for all genes
brain <- SCTransform(brain, assay = "Spatial", return.only.var.genes = FALSE, verbose = FALSE)
# also run standard log normalization for comparison
brain <- NormalizeData(brain, verbose = FALSE, assay = "Spatial")
```

Example 16 (r):
```r
# Computes the correlation of the log normalized data and sctransform residuals with the number
# of UMIs
brain <- GroupCorrelation(brain, group.assay = "Spatial", assay = "Spatial", slot = "data", do.plot = FALSE)
brain <- GroupCorrelation(brain, group.assay = "Spatial", assay = "SCT", slot = "scale.data", do.plot = FALSE)
```

Example 17 (r):
```r
# Computes the correlation of the log normalized data and sctransform residuals with the number
# of UMIs
brain <- GroupCorrelation(brain, group.assay = "Spatial", assay = "Spatial", slot = "data", do.plot = FALSE)
brain <- GroupCorrelation(brain, group.assay = "Spatial", assay = "SCT", slot = "scale.data", do.plot = FALSE)
```

Example 18 (r):
```r
p1 <- GroupCorrelationPlot(brain, assay = "Spatial", cor = "nCount_Spatial_cor") + ggtitle("Log Normalization") + 
    theme(plot.title = element_text(hjust = 0.5))
p2 <- GroupCorrelationPlot(brain, assay = "SCT", cor = "nCount_Spatial_cor") + ggtitle("SCTransform Normalization") + 
    theme(plot.title = element_text(hjust = 0.5))
p1 + p2
```

Example 19 (r):
```r
p1 <- GroupCorrelationPlot(brain, assay = "Spatial", cor = "nCount_Spatial_cor") + ggtitle("Log Normalization") + 
    theme(plot.title = element_text(hjust = 0.5))
p2 <- GroupCorrelationPlot(brain, assay = "SCT", cor = "nCount_Spatial_cor") + ggtitle("SCTransform Normalization") + 
    theme(plot.title = element_text(hjust = 0.5))
p1 + p2
```

Example 20 (unknown):
```unknown
nCount_Spatial
```

Example 21 (unknown):
```unknown
SpatialFeaturePlot
```

Example 22 (unknown):
```unknown
FeaturePlot
```

Example 23 (r):
```r
SpatialFeaturePlot(brain, features = c("Hpca", "Ttr"))
```

Example 24 (r):
```r
SpatialFeaturePlot(brain, features = c("Hpca", "Ttr"))
```

Example 25 (unknown):
```unknown
pt.size.factor
```

Example 26 (r):
```r
p1 <- SpatialFeaturePlot(brain, features = "Ttr", pt.size.factor = 1)
p2 <- SpatialFeaturePlot(brain, features = "Ttr", alpha = c(0.1, 1))
p1 + p2
```

Example 27 (r):
```r
p1 <- SpatialFeaturePlot(brain, features = "Ttr", pt.size.factor = 1)
p2 <- SpatialFeaturePlot(brain, features = "Ttr", alpha = c(0.1, 1))
p1 + p2
```

Example 28 (r):
```r
brain <- RunPCA(brain, assay = "SCT", verbose = FALSE)
brain <- FindNeighbors(brain, reduction = "pca", dims = 1:30)
brain <- FindClusters(brain, verbose = FALSE)
brain <- RunUMAP(brain, reduction = "pca", dims = 1:30)
```

Example 29 (r):
```r
brain <- RunPCA(brain, assay = "SCT", verbose = FALSE)
brain <- FindNeighbors(brain, reduction = "pca", dims = 1:30)
brain <- FindClusters(brain, verbose = FALSE)
brain <- RunUMAP(brain, reduction = "pca", dims = 1:30)
```

Example 30 (unknown):
```unknown
SpatialDimPlot
```

Example 31 (r):
```r
p1 <- DimPlot(brain, reduction = "umap", label = TRUE)
p2 <- SpatialDimPlot(brain, label = TRUE, label.size = 3)
p1 + p2
```

Example 32 (r):
```r
p1 <- DimPlot(brain, reduction = "umap", label = TRUE)
p2 <- SpatialDimPlot(brain, label = TRUE, label.size = 3)
p1 + p2
```

Example 33 (unknown):
```unknown
cells.highlight
```

Example 34 (unknown):
```unknown
SpatialDimPlot
```

Example 35 (r):
```r
SpatialDimPlot(brain, cells.highlight = CellsByIdentities(object = brain, idents = c(2, 1, 4, 3, 
    5, 8)), facet.highlight = TRUE, ncol = 3)
```

Example 36 (r):
```r
SpatialDimPlot(brain, cells.highlight = CellsByIdentities(object = brain, idents = c(2, 1, 4, 3, 
    5, 8)), facet.highlight = TRUE, ncol = 3)
```

Example 37 (unknown):
```unknown
SpatialDimPlot
```

Example 38 (unknown):
```unknown
SpatialFeaturePlot
```

Example 39 (unknown):
```unknown
interactive
```

Example 40 (unknown):
```unknown
SpatialDimPlot
```

Example 41 (r):
```r
SpatialDimPlot(brain, interactive = TRUE)
```

Example 42 (r):
```r
SpatialDimPlot(brain, interactive = TRUE)
```

Example 43 (unknown):
```unknown
SpatialFeaturePlot
```

Example 44 (r):
```r
SpatialFeaturePlot(brain, features = "Ttr", interactive = TRUE)
```

Example 45 (r):
```r
SpatialFeaturePlot(brain, features = "Ttr", interactive = TRUE)
```

Example 46 (unknown):
```unknown
LinkedDimPlot
```

Example 47 (r):
```r
LinkedDimPlot(brain)
```

Example 48 (r):
```r
LinkedDimPlot(brain)
```

Example 49 (r):
```r
de_markers <- FindMarkers(brain, ident.1 = 5, ident.2 = 6)
SpatialFeaturePlot(object = brain, features = rownames(de_markers)[1:3], alpha = c(0.1, 1), ncol = 3)
```

Example 50 (r):
```r
de_markers <- FindMarkers(brain, ident.1 = 5, ident.2 = 6)
SpatialFeaturePlot(object = brain, features = rownames(de_markers)[1:3], alpha = c(0.1, 1), ncol = 3)
```

Example 51 (unknown):
```unknown
FindSpatiallyVariables
```

Example 52 (unknown):
```unknown
method = 'markvariogram
```

Example 53 (r):
```r
brain <- FindSpatiallyVariableFeatures(brain, assay = "SCT", features = VariableFeatures(brain)[1:1000], 
    selection.method = "markvariogram")
```

Example 54 (r):
```r
brain <- FindSpatiallyVariableFeatures(brain, assay = "SCT", features = VariableFeatures(brain)[1:1000], 
    selection.method = "markvariogram")
```

Example 55 (r):
```r
top.features <- head(SpatiallyVariableFeatures(brain, selection.method = "markvariogram"), 6)
SpatialFeaturePlot(brain, features = top.features, ncol = 3, alpha = c(0.1, 1))
```

Example 56 (r):
```r
top.features <- head(SpatiallyVariableFeatures(brain, selection.method = "markvariogram"), 6)
SpatialFeaturePlot(brain, features = top.features, ncol = 3, alpha = c(0.1, 1))
```

Example 57 (r):
```r
cortex <- subset(brain, idents = c(1, 2, 3, 4, 6, 7))
# now remove additional cells, use SpatialDimPlots to visualize what to remove
# SpatialDimPlot(cortex,cells.highlight = WhichCells(cortex, expression = image_imagerow > 400 |
# image_imagecol < 150))
cortex <- subset(cortex, anterior1_imagerow > 400 | anterior1_imagecol < 150, invert = TRUE)
cortex <- subset(cortex, anterior1_imagerow > 275 & anterior1_imagecol > 370, invert = TRUE)
cortex <- subset(cortex, anterior1_imagerow > 250 & anterior1_imagecol > 440, invert = TRUE)
```

Example 58 (r):
```r
cortex <- subset(brain, idents = c(1, 2, 3, 4, 6, 7))
# now remove additional cells, use SpatialDimPlots to visualize what to remove
# SpatialDimPlot(cortex,cells.highlight = WhichCells(cortex, expression = image_imagerow > 400 |
# image_imagecol < 150))
cortex <- subset(cortex, anterior1_imagerow > 400 | anterior1_imagecol < 150, invert = TRUE)
cortex <- subset(cortex, anterior1_imagerow > 275 & anterior1_imagecol > 370, invert = TRUE)
cortex <- subset(cortex, anterior1_imagerow > 250 & anterior1_imagecol > 440, invert = TRUE)
```

Example 59 (r):
```r
p1 <- SpatialDimPlot(cortex, crop = TRUE, label = TRUE)
p2 <- SpatialDimPlot(cortex, crop = FALSE, label = TRUE, pt.size.factor = 1, label.size = 3)
p1 + p2
```

Example 60 (r):
```r
p1 <- SpatialDimPlot(cortex, crop = TRUE, label = TRUE)
p2 <- SpatialDimPlot(cortex, crop = FALSE, label = TRUE, pt.size.factor = 1, label.size = 3)
p1 + p2
```

Example 61 (r):
```r
allen_reference <- readRDS("../data/allen_cortex.rds")
```

Example 62 (r):
```r
allen_reference <- readRDS("../data/allen_cortex.rds")
```

Example 63 (r):
```r
# note that setting ncells=3000 normalizes the full dataset but learns noise models on 3k cells
# this speeds up SCTransform dramatically with no loss in performance
library(dplyr)
allen_reference <- SCTransform(allen_reference, ncells = 3000, verbose = FALSE) %>% RunPCA(verbose = FALSE) %>% 
    RunUMAP(dims = 1:30)
```

Example 64 (r):
```r
# note that setting ncells=3000 normalizes the full dataset but learns noise models on 3k cells
# this speeds up SCTransform dramatically with no loss in performance
library(dplyr)
allen_reference <- SCTransform(allen_reference, ncells = 3000, verbose = FALSE) %>% RunPCA(verbose = FALSE) %>% 
    RunUMAP(dims = 1:30)
```

Example 65 (r):
```r
# After subsetting, we renormalize cortex
cortex <- SCTransform(cortex, assay = "Spatial", verbose = FALSE) %>% RunPCA(verbose = FALSE)
# the annotation is stored in the 'subclass' column of object metadata
DimPlot(allen_reference, group.by = "subclass", label = TRUE)
```

Example 66 (r):
```r
# After subsetting, we renormalize cortex
cortex <- SCTransform(cortex, assay = "Spatial", verbose = FALSE) %>% RunPCA(verbose = FALSE)
# the annotation is stored in the 'subclass' column of object metadata
DimPlot(allen_reference, group.by = "subclass", label = TRUE)
```

Example 67 (r):
```r
anchors <- FindTransferAnchors(reference = allen_reference, query = cortex, normalization.method = "SCT")
predictions.assay <- TransferData(anchorset = anchors, refdata = allen_reference$subclass, prediction.assay = TRUE, 
    weight.reduction = cortex[["pca"]])
cortex[["predictions"]] <- predictions.assay
```

Example 68 (r):
```r
anchors <- FindTransferAnchors(reference = allen_reference, query = cortex, normalization.method = "SCT")
predictions.assay <- TransferData(anchorset = anchors, refdata = allen_reference$subclass, prediction.assay = TRUE, 
    weight.reduction = cortex[["pca"]])
cortex[["predictions"]] <- predictions.assay
```

Example 69 (r):
```r
DefaultAssay(cortex) <- "predictions"
SpatialFeaturePlot(cortex, features = c("L2/3 IT", "L4"), pt.size.factor = 1.6, ncol = 2, crop = TRUE)
```

Example 70 (r):
```r
DefaultAssay(cortex) <- "predictions"
SpatialFeaturePlot(cortex, features = c("L2/3 IT", "L4"), pt.size.factor = 1.6, ncol = 2, crop = TRUE)
```

Example 71 (r):
```r
cortex <- FindSpatiallyVariableFeatures(cortex, assay = "predictions", selection.method = "markvariogram", 
    features = rownames(cortex), r.metric = 5, slot = "data")
top.clusters <- head(SpatiallyVariableFeatures(cortex), 4)
SpatialPlot(object = cortex, features = top.clusters, ncol = 2)
```

Example 72 (r):
```r
cortex <- FindSpatiallyVariableFeatures(cortex, assay = "predictions", selection.method = "markvariogram", 
    features = rownames(cortex), r.metric = 5, slot = "data")
top.clusters <- head(SpatiallyVariableFeatures(cortex), 4)
SpatialPlot(object = cortex, features = top.clusters, ncol = 2)
```

Example 73 (r):
```r
SpatialFeaturePlot(cortex, features = c("Astro", "L2/3 IT", "L4", "L5 PT", "L5 IT", "L6 CT", "L6 IT", 
    "L6b", "Oligo"), pt.size.factor = 1, ncol = 2, crop = FALSE, alpha = c(0.1, 1))
```

Example 74 (r):
```r
SpatialFeaturePlot(cortex, features = c("Astro", "L2/3 IT", "L4", "L5 PT", "L5 IT", "L6 CT", "L6 IT", 
    "L6b", "Oligo"), pt.size.factor = 1, ncol = 2, crop = FALSE, alpha = c(0.1, 1))
```

Example 75 (r):
```r
brain2 <- LoadData("stxBrain", type = "posterior1")
brain2 <- SCTransform(brain2, assay = "Spatial", verbose = FALSE)
```

Example 76 (r):
```r
brain2 <- LoadData("stxBrain", type = "posterior1")
brain2 <- SCTransform(brain2, assay = "Spatial", verbose = FALSE)
```

Example 77 (r):
```r
brain.merge <- merge(brain, brain2)
```

Example 78 (r):
```r
brain.merge <- merge(brain, brain2)
```

Example 79 (r):
```r
DefaultAssay(brain.merge) <- "SCT"
VariableFeatures(brain.merge) <- c(VariableFeatures(brain), VariableFeatures(brain2))
brain.merge <- RunPCA(brain.merge, verbose = FALSE)
brain.merge <- FindNeighbors(brain.merge, dims = 1:30)
brain.merge <- FindClusters(brain.merge, verbose = FALSE)
brain.merge <- RunUMAP(brain.merge, dims = 1:30)
```

Example 80 (r):
```r
DefaultAssay(brain.merge) <- "SCT"
VariableFeatures(brain.merge) <- c(VariableFeatures(brain), VariableFeatures(brain2))
brain.merge <- RunPCA(brain.merge, verbose = FALSE)
brain.merge <- FindNeighbors(brain.merge, dims = 1:30)
brain.merge <- FindClusters(brain.merge, verbose = FALSE)
brain.merge <- RunUMAP(brain.merge, dims = 1:30)
```

Example 81 (unknown):
```unknown
SpatialDimPlot
```

Example 82 (unknown):
```unknown
SpatialFeaturePlot
```

Example 83 (r):
```r
DimPlot(brain.merge, reduction = "umap", group.by = c("ident", "orig.ident"))
```

Example 84 (r):
```r
DimPlot(brain.merge, reduction = "umap", group.by = c("ident", "orig.ident"))
```

Example 85 (r):
```r
SpatialDimPlot(brain.merge)
```

Example 86 (r):
```r
SpatialDimPlot(brain.merge)
```

Example 87 (r):
```r
SpatialFeaturePlot(brain.merge, features = c("Hpca", "Plp1"))
```

Example 88 (r):
```r
SpatialFeaturePlot(brain.merge, features = c("Hpca", "Plp1"))
```

Example 89 (r):
```r
InstallData("ssHippo")
```

Example 90 (r):
```r
InstallData("ssHippo")
```

Example 91 (r):
```r
slide.seq <- LoadData("ssHippo")
```

Example 92 (r):
```r
slide.seq <- LoadData("ssHippo")
```

Example 93 (r):
```r
plot1 <- VlnPlot(slide.seq, features = "nCount_Spatial", pt.size = 0, log = TRUE) + NoLegend()
slide.seq$log_nCount_Spatial <- log(slide.seq$nCount_Spatial)
plot2 <- SpatialFeaturePlot(slide.seq, features = "log_nCount_Spatial") + theme(legend.position = "right")
wrap_plots(plot1, plot2)
```

Example 94 (r):
```r
plot1 <- VlnPlot(slide.seq, features = "nCount_Spatial", pt.size = 0, log = TRUE) + NoLegend()
slide.seq$log_nCount_Spatial <- log(slide.seq$nCount_Spatial)
plot2 <- SpatialFeaturePlot(slide.seq, features = "log_nCount_Spatial") + theme(legend.position = "right")
wrap_plots(plot1, plot2)
```

Example 95 (r):
```r
slide.seq <- SCTransform(slide.seq, assay = "Spatial", ncells = 3000, verbose = FALSE)
slide.seq <- RunPCA(slide.seq)
slide.seq <- RunUMAP(slide.seq, dims = 1:30)
slide.seq <- FindNeighbors(slide.seq, dims = 1:30)
slide.seq <- FindClusters(slide.seq, resolution = 0.3, verbose = FALSE)
```

Example 96 (r):
```r
slide.seq <- SCTransform(slide.seq, assay = "Spatial", ncells = 3000, verbose = FALSE)
slide.seq <- RunPCA(slide.seq)
slide.seq <- RunUMAP(slide.seq, dims = 1:30)
slide.seq <- FindNeighbors(slide.seq, dims = 1:30)
slide.seq <- FindClusters(slide.seq, resolution = 0.3, verbose = FALSE)
```

Example 97 (unknown):
```unknown
SpatialDimPlot
```

Example 98 (r):
```r
plot1 <- DimPlot(slide.seq, reduction = "umap", label = TRUE)
plot2 <- SpatialDimPlot(slide.seq, stroke = 0)
plot1 + plot2
```

Example 99 (r):
```r
plot1 <- DimPlot(slide.seq, reduction = "umap", label = TRUE)
plot2 <- SpatialDimPlot(slide.seq, stroke = 0)
plot1 + plot2
```

Example 100 (r):
```r
SpatialDimPlot(slide.seq, cells.highlight = CellsByIdentities(object = slide.seq, idents = c(1, 
    6, 13)), facet.highlight = TRUE)
```

Example 101 (r):
```r
SpatialDimPlot(slide.seq, cells.highlight = CellsByIdentities(object = slide.seq, idents = c(1, 
    6, 13)), facet.highlight = TRUE)
```

Example 102 (r):
```r
ref <- readRDS("../data/mouse_hippocampus_reference.rds")
```

Example 103 (r):
```r
ref <- readRDS("../data/mouse_hippocampus_reference.rds")
```

Example 104 (unknown):
```unknown
ref$subcluster
```

Example 105 (unknown):
```unknown
ref$celltype
```

Example 106 (r):
```r
anchors <- FindTransferAnchors(reference = ref, query = slide.seq, normalization.method = "SCT", 
    npcs = 50)
predictions.assay <- TransferData(anchorset = anchors, refdata = ref$celltype, prediction.assay = TRUE, 
    weight.reduction = slide.seq[["pca"]], dims = 1:50)
slide.seq[["predictions"]] <- predictions.assay
```

Example 107 (r):
```r
anchors <- FindTransferAnchors(reference = ref, query = slide.seq, normalization.method = "SCT", 
    npcs = 50)
predictions.assay <- TransferData(anchorset = anchors, refdata = ref$celltype, prediction.assay = TRUE, 
    weight.reduction = slide.seq[["pca"]], dims = 1:50)
slide.seq[["predictions"]] <- predictions.assay
```

Example 108 (r):
```r
DefaultAssay(slide.seq) <- "predictions"
SpatialFeaturePlot(slide.seq, features = c("Dentate Principal cells", "CA3 Principal cells", "Entorhinal cortex", 
    "Endothelial tip", "Ependymal", "Oligodendrocyte"), alpha = c(0.1, 1))
```

Example 109 (r):
```r
DefaultAssay(slide.seq) <- "predictions"
SpatialFeaturePlot(slide.seq, features = c("Dentate Principal cells", "CA3 Principal cells", "Entorhinal cortex", 
    "Endothelial tip", "Ependymal", "Oligodendrocyte"), alpha = c(0.1, 1))
```

Example 110 (r):
```r
slide.seq$predicted.id <- GetTransferPredictions(slide.seq)
Idents(slide.seq) <- "predicted.id"
SpatialDimPlot(slide.seq, cells.highlight = CellsByIdentities(object = slide.seq, idents = c("CA3 Principal cells", 
    "Dentate Principal cells", "Endothelial tip")), facet.highlight = TRUE)
```

Example 111 (r):
```r
slide.seq$predicted.id <- GetTransferPredictions(slide.seq)
Idents(slide.seq) <- "predicted.id"
SpatialDimPlot(slide.seq, cells.highlight = CellsByIdentities(object = slide.seq, idents = c("CA3 Principal cells", 
    "Dentate Principal cells", "Endothelial tip")), facet.highlight = TRUE)
```

Example 112 (unknown):
```unknown
FindSpatiallyVariableFeatures
```

Example 113 (unknown):
```unknown
method = 'moransi'
```

Example 114 (unknown):
```unknown
install.packages('Rfast2')
```

Example 115 (r):
```r
DefaultAssay(slide.seq) <- "SCT"
slide.seq <- FindSpatiallyVariableFeatures(slide.seq, assay = "SCT", slot = "scale.data", features = VariableFeatures(slide.seq)[1:1000], 
    selection.method = "moransi", x.cuts = 100, y.cuts = 100)
```

Example 116 (r):
```r
DefaultAssay(slide.seq) <- "SCT"
slide.seq <- FindSpatiallyVariableFeatures(slide.seq, assay = "SCT", slot = "scale.data", features = VariableFeatures(slide.seq)[1:1000], 
    selection.method = "moransi", x.cuts = 100, y.cuts = 100)
```

Example 117 (r):
```r
SpatialFeaturePlot(slide.seq, features = head(SpatiallyVariableFeatures(slide.seq, selection.method = "moransi"), 
    6), ncol = 3, alpha = c(0.1, 1), max.cutoff = "q95")
```

Example 118 (r):
```r
SpatialFeaturePlot(slide.seq, features = head(SpatiallyVariableFeatures(slide.seq, selection.method = "moransi"), 
    6), ncol = 3, alpha = c(0.1, 1), max.cutoff = "q95")
```

---

## Analysis, visualization, and integration of Visium HD spatial datasets with Seurat • Seurat

**URL:** http://127.0.0.1:9173/seurat/articles/essential_commands/index.html

**Contents:**
- Seurat Command List
    - Compiled: 2023-10-31
- Standard Seurat workflow
  - SCtransform version
- Seurat Object Data Access
  - Cell, feature, and layer names
  - Identity class labels
  - Cell metadata
  - Expression data (stored as layers in Seurat v5)
  - Dimensional reductions
  - FetchData
- Subsetting and merging
  - Subset Seurat objects
  - Split layers
  - Split objects
  - Merge objects (without integration)
  - Merge objects (with integration)
- Pseudobulk analysis
  - Group cells together, based on multiple categories
- Visualization in Seurat
- Multi-Assay Features
- Additional resources
- Contents

In Seurat v5, merging creates a single object, but keeps the expression information split into different layers for integration. If not proceeding with integration, rejoin the layers after merging.

See introduction to integration for more information.

See DE vignette for information on how to add the donor_id column to meta data.

Seurat has a vast, ggplot2-based plotting library. All plotting functions will return a ggplot2 plot by default, allowing easy customization with ggplot2.

Seurat provides many prebuilt themes that can be added to ggplot2 plots for quick customization

With Seurat, you can easily switch between different assays at the single cell level (such as ADT counts from CITE-seq, or integrated/batch-corrected data). Most functions now take an assay parameter, but you can set a Default Assay to avoid repetitive statements.

Users who are particularly interested in some of the technical changes to data storage in Seurat v5 can explore the following resources:

Developed by Rahul Satija, Satija Lab and Collaborators.

Site built with pkgdown 2.0.7.

**Examples:**

Example 1 (unknown):
```unknown
vignettes/essential_commands.Rmd
```

Example 2 (unknown):
```unknown
essential_commands.Rmd
```

Example 3 (unknown):
```unknown
pbmc <- NormalizeData(object = pbmc)
pbmc <- FindVariableFeatures(object = pbmc)
pbmc <- ScaleData(object = pbmc)
pbmc <- RunPCA(object = pbmc)
pbmc <- FindNeighbors(object = pbmc, dims = 1:30)
pbmc <- FindClusters(object = pbmc)
pbmc <- RunUMAP(object = pbmc, dims = 1:30)
DimPlot(object = pbmc, reduction = "umap")
```

Example 4 (r):
```r
pbmc <- NormalizeData(object = pbmc)
pbmc <- FindVariableFeatures(object = pbmc)
pbmc <- ScaleData(object = pbmc)
pbmc <- RunPCA(object = pbmc)
pbmc <- FindNeighbors(object = pbmc, dims = 1:30)
pbmc <- FindClusters(object = pbmc)
pbmc <- RunUMAP(object = pbmc, dims = 1:30)
DimPlot(object = pbmc, reduction = "umap")
```

Example 5 (r):
```r
pbmc <- NormalizeData(object = pbmc)
pbmc <- FindVariableFeatures(object = pbmc)
pbmc <- ScaleData(object = pbmc)
pbmc <- RunPCA(object = pbmc)
pbmc <- FindNeighbors(object = pbmc, dims = 1:30)
pbmc <- FindClusters(object = pbmc)
pbmc <- RunUMAP(object = pbmc, dims = 1:30)
DimPlot(object = pbmc, reduction = "umap")
```

Example 6 (unknown):
```unknown
pbmc <- SCTransform(object = pbmc)
pbmc <- RunPCA(object = pbmc)
pbmc <- FindNeighbors(object = pbmc, dims = 1:30)
pbmc <- FindClusters(object = pbmc)
pbmc <- RunUMAP(object = pbmc, dims = 1:30)
DimPlot(object = pbmc, reduction = "umap")
```

Example 7 (r):
```r
pbmc <- SCTransform(object = pbmc)
pbmc <- RunPCA(object = pbmc)
pbmc <- FindNeighbors(object = pbmc, dims = 1:30)
pbmc <- FindClusters(object = pbmc)
pbmc <- RunUMAP(object = pbmc, dims = 1:30)
DimPlot(object = pbmc, reduction = "umap")
```

Example 8 (r):
```r
pbmc <- SCTransform(object = pbmc)
pbmc <- RunPCA(object = pbmc)
pbmc <- FindNeighbors(object = pbmc, dims = 1:30)
pbmc <- FindClusters(object = pbmc)
pbmc <- RunUMAP(object = pbmc, dims = 1:30)
DimPlot(object = pbmc, reduction = "umap")
```

Example 9 (unknown):
```unknown
# note that you can chain multiple commands together with %>%
pbmc <- SCTransform(pbmc) %>%
    RunPCA() %>%
    FindNeighbors(dims = 1:30) %>%
    FindClusters() %>%
    RunUMAP(dims = 1:30)
```

Example 10 (r):
```r
# note that you can chain multiple commands together with %>%
pbmc <- SCTransform(pbmc) %>%
    RunPCA() %>%
    FindNeighbors(dims = 1:30) %>%
    FindClusters() %>%
    RunUMAP(dims = 1:30)
```

Example 11 (r):
```r
# note that you can chain multiple commands together with %>%
pbmc <- SCTransform(pbmc) %>%
    RunPCA() %>%
    FindNeighbors(dims = 1:30) %>%
    FindClusters() %>%
    RunUMAP(dims = 1:30)
```

Example 12 (unknown):
```unknown
# Get cell and feature names, and total numbers We show multiple ways to get the same output cell names
colnames(pbmc)
Cells(pbmc)

# feature names
Features(pbmc)
rownames(pbmc)

# number of cells/features
num_cells <- ncol(pbmc)
num_features <- nrow(pbmc)

# List of object layers
Layers(pbmc)

# working with multimodal objects list assays
Assays(cbmc)

# Assay-specific features (genes/ADT)
Features(cbmc[["RNA"]])
Features(cbmc[["ADT"]])

# Variable feature names
VariableFeatures(pbmc)
```

Example 13 (r):
```r
# Get cell and feature names, and total numbers We show multiple ways to get the same output cell names
colnames(pbmc)
Cells(pbmc)

# feature names
Features(pbmc)
rownames(pbmc)

# number of cells/features
num_cells <- ncol(pbmc)
num_features <- nrow(pbmc)

# List of object layers
Layers(pbmc)

# working with multimodal objects list assays
Assays(cbmc)

# Assay-specific features (genes/ADT)
Features(cbmc[["RNA"]])
Features(cbmc[["ADT"]])

# Variable feature names
VariableFeatures(pbmc)
```

Example 14 (r):
```r
# Get cell and feature names, and total numbers We show multiple ways to get the same output cell names
colnames(pbmc)
Cells(pbmc)

# feature names
Features(pbmc)
rownames(pbmc)

# number of cells/features
num_cells <- ncol(pbmc)
num_features <- nrow(pbmc)

# List of object layers
Layers(pbmc)

# working with multimodal objects list assays
Assays(cbmc)

# Assay-specific features (genes/ADT)
Features(cbmc[["RNA"]])
Features(cbmc[["ADT"]])

# Variable feature names
VariableFeatures(pbmc)
```

Example 15 (unknown):
```unknown
# Set variable features
VariableFeatures(cbmc) <- var.gene.names

# set for a specific assay
VariableFeatures(cbmc[["ADT"]]) <- var.gene.names
```

Example 16 (r):
```r
# Set variable features
VariableFeatures(cbmc) <- var.gene.names

# set for a specific assay
VariableFeatures(cbmc[["ADT"]]) <- var.gene.names
```

Example 17 (r):
```r
# Set variable features
VariableFeatures(cbmc) <- var.gene.names

# set for a specific assay
VariableFeatures(cbmc[["ADT"]]) <- var.gene.names
```

Example 18 (python):
```python
# Setting and retrieving cell identities

# Set identity classes to an existing column in meta data
Idents(object = pbmc) <- "seurat_annotations"

# View cell identities, get summary table
Idents(pbmc)
table(Idents(pbmc))

# Set identity to CD4 T cells for all cells
Idents(pbmc) <- "CD4 T cells"

# Set for a selected group of cells
pbmc.cells <- Cells(pbmc)
Idents(object = pbmc, cells = pbmc.cells[1:10]) <- "CD4 T cells"

# Get cell identity classes
Idents(object = pbmc)
levels(x = pbmc)

# Stash cell identity classes in metadata
pbmc[["old.ident"]] <- Idents(object = pbmc)
pbmc <- StashIdent(object = pbmc, save.name = "old.ident")

# Rename identity classes
pbmc <- RenameIdents(object = pbmc, `CD4 T cells` = "T Helper cells")
```

Example 19 (r):
```r
# Setting and retrieving cell identities

# Set identity classes to an existing column in meta data
Idents(object = pbmc) <- "seurat_annotations"

# View cell identities, get summary table
Idents(pbmc)
table(Idents(pbmc))

# Set identity to CD4 T cells for all cells
Idents(pbmc) <- "CD4 T cells"

# Set for a selected group of cells
pbmc.cells <- Cells(pbmc)
Idents(object = pbmc, cells = pbmc.cells[1:10]) <- "CD4 T cells"

# Get cell identity classes
Idents(object = pbmc)
levels(x = pbmc)

# Stash cell identity classes in metadata
pbmc[["old.ident"]] <- Idents(object = pbmc)
pbmc <- StashIdent(object = pbmc, save.name = "old.ident")

# Rename identity classes
pbmc <- RenameIdents(object = pbmc, `CD4 T cells` = "T Helper cells")
```

Example 20 (r):
```r
# Setting and retrieving cell identities

# Set identity classes to an existing column in meta data
Idents(object = pbmc) <- "seurat_annotations"

# View cell identities, get summary table
Idents(pbmc)
table(Idents(pbmc))

# Set identity to CD4 T cells for all cells
Idents(pbmc) <- "CD4 T cells"

# Set for a selected group of cells
pbmc.cells <- Cells(pbmc)
Idents(object = pbmc, cells = pbmc.cells[1:10]) <- "CD4 T cells"

# Get cell identity classes
Idents(object = pbmc)
levels(x = pbmc)

# Stash cell identity classes in metadata
pbmc[["old.ident"]] <- Idents(object = pbmc)
pbmc <- StashIdent(object = pbmc, save.name = "old.ident")

# Rename identity classes
pbmc <- RenameIdents(object = pbmc, `CD4 T cells` = "T Helper cells")
```

Example 21 (python):
```python
# View metadata data frame, stored in object@meta.data
pbmc[[]]

# Retrieve specific values from the metadata
pbmc$nCount_RNA
pbmc[[c("percent.mito", "nFeature_RNA")]]

# Add metadata, see ?AddMetaData
random_group_labels <- sample(x = c("g1", "g2"), size = ncol(x = pbmc), replace = TRUE)
pbmc$groups <- random_group_labels
```

Example 22 (r):
```r
# View metadata data frame, stored in object@meta.data
pbmc[[]]

# Retrieve specific values from the metadata
pbmc$nCount_RNA
pbmc[[c("percent.mito", "nFeature_RNA")]]

# Add metadata, see ?AddMetaData
random_group_labels <- sample(x = c("g1", "g2"), size = ncol(x = pbmc), replace = TRUE)
pbmc$groups <- random_group_labels
```

Example 23 (r):
```r
# View metadata data frame, stored in object@meta.data
pbmc[[]]

# Retrieve specific values from the metadata
pbmc$nCount_RNA
pbmc[[c("percent.mito", "nFeature_RNA")]]

# Add metadata, see ?AddMetaData
random_group_labels <- sample(x = c("g1", "g2"), size = ncol(x = pbmc), replace = TRUE)
pbmc$groups <- random_group_labels
```

Example 24 (python):
```python
# Retrieve data in an expression matrix RNA counts matrix
pbmc[["RNA"]]$counts

# Alternate accessor function with the same result
LayerData(pbmc, assay = "RNA", layer = "counts")

# GetAssayData from Seurat v4 is still supported
GetAssayData(object = pbmc, assay = "RNA", slot = "counts")

# ADT counts matrix (multimodal object)
cbmc[["ADT"]]$counts
```

Example 25 (r):
```r
# Retrieve data in an expression matrix RNA counts matrix
pbmc[["RNA"]]$counts

# Alternate accessor function with the same result
LayerData(pbmc, assay = "RNA", layer = "counts")

# GetAssayData from Seurat v4 is still supported
GetAssayData(object = pbmc, assay = "RNA", slot = "counts")

# ADT counts matrix (multimodal object)
cbmc[["ADT"]]$counts
```

Example 26 (r):
```r
# Retrieve data in an expression matrix RNA counts matrix
pbmc[["RNA"]]$counts

# Alternate accessor function with the same result
LayerData(pbmc, assay = "RNA", layer = "counts")

# GetAssayData from Seurat v4 is still supported
GetAssayData(object = pbmc, assay = "RNA", slot = "counts")

# ADT counts matrix (multimodal object)
cbmc[["ADT"]]$counts
```

Example 27 (python):
```python
# Set expression data assume new.data is a new expression matrix
pbmc[["RNA"]]$counts <- new.data

# Alternate setter function with the same result
LayerData(pbmc, assay = "RNA", layer = "counts") <- new.data

# SetAssayData from Seurat v4 is still supported
pbmc <- SetAssayData(object = pbmc, slot = "counts", new.data = new.data)
```

Example 28 (r):
```r
# Set expression data assume new.data is a new expression matrix
pbmc[["RNA"]]$counts <- new.data

# Alternate setter function with the same result
LayerData(pbmc, assay = "RNA", layer = "counts") <- new.data

# SetAssayData from Seurat v4 is still supported
pbmc <- SetAssayData(object = pbmc, slot = "counts", new.data = new.data)
```

Example 29 (r):
```r
# Set expression data assume new.data is a new expression matrix
pbmc[["RNA"]]$counts <- new.data

# Alternate setter function with the same result
LayerData(pbmc, assay = "RNA", layer = "counts") <- new.data

# SetAssayData from Seurat v4 is still supported
pbmc <- SetAssayData(object = pbmc, slot = "counts", new.data = new.data)
```

Example 30 (unknown):
```unknown
# Get cell embeddings and feature loadings stored on pbmc[['pca']]@cell.embeddings
Embeddings(pbmc, reduction = "pca")

# stored in pbmc[['pca]]@feature.loadings
Loadings(pbmc, reduction = "pca")
```

Example 31 (r):
```r
# Get cell embeddings and feature loadings stored on pbmc[['pca']]@cell.embeddings
Embeddings(pbmc, reduction = "pca")

# stored in pbmc[['pca]]@feature.loadings
Loadings(pbmc, reduction = "pca")
```

Example 32 (r):
```r
# Get cell embeddings and feature loadings stored on pbmc[['pca']]@cell.embeddings
Embeddings(pbmc, reduction = "pca")

# stored in pbmc[['pca]]@feature.loadings
Loadings(pbmc, reduction = "pca")
```

Example 33 (unknown):
```unknown
# Create custom dimensional reduction loadings matrix is optional
new_reduction <- CreateDimReducObject(embeddings = new.embeddings, loadings = new.loadings, key = "custom_pca")
pbmc[["custom_pca"]] <- new_reduction
```

Example 34 (r):
```r
# Create custom dimensional reduction loadings matrix is optional
new_reduction <- CreateDimReducObject(embeddings = new.embeddings, loadings = new.loadings, key = "custom_pca")
pbmc[["custom_pca"]] <- new_reduction
```

Example 35 (r):
```r
# Create custom dimensional reduction loadings matrix is optional
new_reduction <- CreateDimReducObject(embeddings = new.embeddings, loadings = new.loadings, key = "custom_pca")
pbmc[["custom_pca"]] <- new_reduction
```

Example 36 (python):
```python
# FetchData can access anything from expression matrices, cell embeddings, or metadata Use the previously listed
# commands to access entire matrices Use FetchData to access individual/small groups of variables
FetchData(object = pbmc, vars = c("PC_1", "nFeature_RNA", "MS4A1"), layer = "counts")
```

Example 37 (r):
```r
# FetchData can access anything from expression matrices, cell embeddings, or metadata Use the previously listed
# commands to access entire matrices Use FetchData to access individual/small groups of variables
FetchData(object = pbmc, vars = c("PC_1", "nFeature_RNA", "MS4A1"), layer = "counts")
```

Example 38 (r):
```r
# FetchData can access anything from expression matrices, cell embeddings, or metadata Use the previously listed
# commands to access entire matrices Use FetchData to access individual/small groups of variables
FetchData(object = pbmc, vars = c("PC_1", "nFeature_RNA", "MS4A1"), layer = "counts")
```

Example 39 (unknown):
```unknown
# Subset Seurat object based on identity class, also see ?SubsetData
subset(x = pbmc, idents = "B")
subset(x = pbmc, idents = c("Naive CD4 T", "CD8 T"), invert = TRUE)

# Subset on the expression level of a gene/feature
subset(x = pbmc, subset = MS4A1 > 2.5)

# Subset on a combination of criteria
subset(x = pbmc, subset = MS4A1 > 2.5 & PC_1 > 5)
subset(x = pbmc, subset = MS4A1 > 2.5, idents = "B")

# Subset on a value in the object meta data
subset(x = pbmc, subset = groups == "g1")

# Downsample the number of cells per identity class
subset(x = pbmc, downsample = 100)
```

Example 40 (r):
```r
# Subset Seurat object based on identity class, also see ?SubsetData
subset(x = pbmc, idents = "B")
subset(x = pbmc, idents = c("Naive CD4 T", "CD8 T"), invert = TRUE)

# Subset on the expression level of a gene/feature
subset(x = pbmc, subset = MS4A1 > 2.5)

# Subset on a combination of criteria
subset(x = pbmc, subset = MS4A1 > 2.5 & PC_1 > 5)
subset(x = pbmc, subset = MS4A1 > 2.5, idents = "B")

# Subset on a value in the object meta data
subset(x = pbmc, subset = groups == "g1")

# Downsample the number of cells per identity class
subset(x = pbmc, downsample = 100)
```

Example 41 (r):
```r
# Subset Seurat object based on identity class, also see ?SubsetData
subset(x = pbmc, idents = "B")
subset(x = pbmc, idents = c("Naive CD4 T", "CD8 T"), invert = TRUE)

# Subset on the expression level of a gene/feature
subset(x = pbmc, subset = MS4A1 > 2.5)

# Subset on a combination of criteria
subset(x = pbmc, subset = MS4A1 > 2.5 & PC_1 > 5)
subset(x = pbmc, subset = MS4A1 > 2.5, idents = "B")

# Subset on a value in the object meta data
subset(x = pbmc, subset = groups == "g1")

# Downsample the number of cells per identity class
subset(x = pbmc, downsample = 100)
```

Example 42 (unknown):
```unknown
# In Seurat v5, users can now split in object directly into different layers keeps expression data in one object, but
# splits multiple samples into layers can proceed directly to integration workflow after splitting layers
ifnb[["RNA"]] <- split(ifnb[["RNA"]], f = ifnb$stim)
Layers(ifnb)

# If desired, for example after intergation, the layers can be joined together again
ifnb <- JoinLayers(ifnb)
```

Example 43 (r):
```r
# In Seurat v5, users can now split in object directly into different layers keeps expression data in one object, but
# splits multiple samples into layers can proceed directly to integration workflow after splitting layers
ifnb[["RNA"]] <- split(ifnb[["RNA"]], f = ifnb$stim)
Layers(ifnb)

# If desired, for example after intergation, the layers can be joined together again
ifnb <- JoinLayers(ifnb)
```

Example 44 (r):
```r
# In Seurat v5, users can now split in object directly into different layers keeps expression data in one object, but
# splits multiple samples into layers can proceed directly to integration workflow after splitting layers
ifnb[["RNA"]] <- split(ifnb[["RNA"]], f = ifnb$stim)
Layers(ifnb)

# If desired, for example after intergation, the layers can be joined together again
ifnb <- JoinLayers(ifnb)
```

Example 45 (python):
```python
# In line with prior workflows, you can also into split your object into a list of multiple objects based on a metadata
# column creates a list of two objects
ifnb_list <- SplitObject(ifnb, split.by = "stim")
ifnb_list$CTRL
ifnb_list$STIM
```

Example 46 (r):
```r
# In line with prior workflows, you can also into split your object into a list of multiple objects based on a metadata
# column creates a list of two objects
ifnb_list <- SplitObject(ifnb, split.by = "stim")
ifnb_list$CTRL
ifnb_list$STIM
```

Example 47 (r):
```r
# In line with prior workflows, you can also into split your object into a list of multiple objects based on a metadata
# column creates a list of two objects
ifnb_list <- SplitObject(ifnb, split.by = "stim")
ifnb_list$CTRL
ifnb_list$STIM
```

Example 48 (unknown):
```unknown
# Merge two Seurat objects
merged_obj <- merge(x = ifnb_list$CTRL, y = ifnb_list$STIM)
merged_obj[["RNA"]] <- JoinLayers(merged_obj)

# Example to merge more than two Seurat objects
merge(x = pbmc1, y = list(pbmc2, pbmc3))
```

Example 49 (r):
```r
# Merge two Seurat objects
merged_obj <- merge(x = ifnb_list$CTRL, y = ifnb_list$STIM)
merged_obj[["RNA"]] <- JoinLayers(merged_obj)

# Example to merge more than two Seurat objects
merge(x = pbmc1, y = list(pbmc2, pbmc3))
```

Example 50 (r):
```r
# Merge two Seurat objects
merged_obj <- merge(x = ifnb_list$CTRL, y = ifnb_list$STIM)
merged_obj[["RNA"]] <- JoinLayers(merged_obj)

# Example to merge more than two Seurat objects
merge(x = pbmc1, y = list(pbmc2, pbmc3))
```

Example 51 (unknown):
```unknown
merged_obj <- merge(x = ifnb_list$CTRL, y = ifnb_list$STIM)
merged_obj <- NormalizeData(merged_obj)
merged_obj <- FindVariableFeatures(merged_obj)
merged_obj <- ScaleData(merged_obj)
merged_obj <- RunPCA(merged_obj)
merged_obj <- IntegrateLayers(object = obj, method = RPCAIntegration, orig.reduction = "pca", new.reduction = "integrated.rpca",
    verbose = FALSE)

# now that integration is complete, rejoin layers
merged_obj[["RNA"]] <- JoinLayers(merged_obj)
```

Example 52 (r):
```r
merged_obj <- merge(x = ifnb_list$CTRL, y = ifnb_list$STIM)
merged_obj <- NormalizeData(merged_obj)
merged_obj <- FindVariableFeatures(merged_obj)
merged_obj <- ScaleData(merged_obj)
merged_obj <- RunPCA(merged_obj)
merged_obj <- IntegrateLayers(object = obj, method = RPCAIntegration, orig.reduction = "pca", new.reduction = "integrated.rpca",
    verbose = FALSE)

# now that integration is complete, rejoin layers
merged_obj[["RNA"]] <- JoinLayers(merged_obj)
```

Example 53 (r):
```r
merged_obj <- merge(x = ifnb_list$CTRL, y = ifnb_list$STIM)
merged_obj <- NormalizeData(merged_obj)
merged_obj <- FindVariableFeatures(merged_obj)
merged_obj <- ScaleData(merged_obj)
merged_obj <- RunPCA(merged_obj)
merged_obj <- IntegrateLayers(object = obj, method = RPCAIntegration, orig.reduction = "pca", new.reduction = "integrated.rpca",
    verbose = FALSE)

# now that integration is complete, rejoin layers
merged_obj[["RNA"]] <- JoinLayers(merged_obj)
```

Example 54 (unknown):
```unknown
# pseudobulk cells only by cell type
bulk <- AggregateExpression(ifnb, group.by = "seurat_annotations", return.seurat = TRUE)
Cells(bulk)

# pseudobulk cells by stimulation condition AND cell type
bulk <- AggregateExpression(ifnb, group.by = c("stim", "seurat_annotations"), return.seurat = TRUE)
Cells(bulk)

# pseudobulk cells by stimulation condition AND cell type AND donor
bulk <- AggregateExpression(ifnb, group.by = c("stim", "seurat_annotations", "donor_id"), return.seurat = TRUE)
Cells(bulk)
```

Example 55 (r):
```r
# pseudobulk cells only by cell type
bulk <- AggregateExpression(ifnb, group.by = "seurat_annotations", return.seurat = TRUE)
Cells(bulk)

# pseudobulk cells by stimulation condition AND cell type
bulk <- AggregateExpression(ifnb, group.by = c("stim", "seurat_annotations"), return.seurat = TRUE)
Cells(bulk)

# pseudobulk cells by stimulation condition AND cell type AND donor
bulk <- AggregateExpression(ifnb, group.by = c("stim", "seurat_annotations", "donor_id"), return.seurat = TRUE)
Cells(bulk)
```

Example 56 (r):
```r
# pseudobulk cells only by cell type
bulk <- AggregateExpression(ifnb, group.by = "seurat_annotations", return.seurat = TRUE)
Cells(bulk)

# pseudobulk cells by stimulation condition AND cell type
bulk <- AggregateExpression(ifnb, group.by = c("stim", "seurat_annotations"), return.seurat = TRUE)
Cells(bulk)

# pseudobulk cells by stimulation condition AND cell type AND donor
bulk <- AggregateExpression(ifnb, group.by = c("stim", "seurat_annotations", "donor_id"), return.seurat = TRUE)
Cells(bulk)
```

Example 57 (unknown):
```unknown
# Dimensional reduction plot
DimPlot(object = pbmc, reduction = "pca")

# Dimensional reduction plot, with cells colored by a quantitative feature Defaults to UMAP if available
FeaturePlot(object = pbmc, features = "MS4A1")

# Scatter plot across single cells
FeatureScatter(object = pbmc, feature1 = "MS4A1", feature2 = "PC_1")
FeatureScatter(object = pbmc, feature1 = "MS4A1", feature2 = "CD3D")

# Scatter plot across individual features, repleaces CellPlot
CellScatter(object = pbmc, cell1 = "AGTCTACTAGGGTG", cell2 = "CACAGATGGTTTCT")

VariableFeaturePlot(object = pbmc)

# Violin and Ridge plots
VlnPlot(object = pbmc, features = c("LYZ", "CCL5", "IL32"))
RidgePlot(object = pbmc, feature = c("LYZ", "CCL5", "IL32"))
```

Example 58 (r):
```r
# Dimensional reduction plot
DimPlot(object = pbmc, reduction = "pca")

# Dimensional reduction plot, with cells colored by a quantitative feature Defaults to UMAP if available
FeaturePlot(object = pbmc, features = "MS4A1")

# Scatter plot across single cells
FeatureScatter(object = pbmc, feature1 = "MS4A1", feature2 = "PC_1")
FeatureScatter(object = pbmc, feature1 = "MS4A1", feature2 = "CD3D")

# Scatter plot across individual features, repleaces CellPlot
CellScatter(object = pbmc, cell1 = "AGTCTACTAGGGTG", cell2 = "CACAGATGGTTTCT")

VariableFeaturePlot(object = pbmc)

# Violin and Ridge plots
VlnPlot(object = pbmc, features = c("LYZ", "CCL5", "IL32"))
RidgePlot(object = pbmc, feature = c("LYZ", "CCL5", "IL32"))
```

Example 59 (r):
```r
# Dimensional reduction plot
DimPlot(object = pbmc, reduction = "pca")

# Dimensional reduction plot, with cells colored by a quantitative feature Defaults to UMAP if available
FeaturePlot(object = pbmc, features = "MS4A1")

# Scatter plot across single cells
FeatureScatter(object = pbmc, feature1 = "MS4A1", feature2 = "PC_1")
FeatureScatter(object = pbmc, feature1 = "MS4A1", feature2 = "CD3D")

# Scatter plot across individual features, repleaces CellPlot
CellScatter(object = pbmc, cell1 = "AGTCTACTAGGGTG", cell2 = "CACAGATGGTTTCT")

VariableFeaturePlot(object = pbmc)

# Violin and Ridge plots
VlnPlot(object = pbmc, features = c("LYZ", "CCL5", "IL32"))
RidgePlot(object = pbmc, feature = c("LYZ", "CCL5", "IL32"))
```

Example 60 (unknown):
```unknown
# Heatmaps (visualize scale.data slot)
DimHeatmap(object = pbmc, reduction = "pca", cells = 200)

# standard workflow
pbmc <- ScaleData(pbmc, features = heatmap_markers)
DoHeatmap(object = pbmc, features = heatmap_markers)

# sctransform workflow
pbmc <- GetResidual(pbmc, features = heatmap_markers)
DoHeatmap(object = pbmc, features = heatmap_markers)

# heatmap with maximum of 100 cells per group
DoHeatmap(pbmc, heatmap_markers, cells = subset(pbmc, downsample = 100))
```

Example 61 (r):
```r
# Heatmaps (visualize scale.data slot)
DimHeatmap(object = pbmc, reduction = "pca", cells = 200)

# standard workflow
pbmc <- ScaleData(pbmc, features = heatmap_markers)
DoHeatmap(object = pbmc, features = heatmap_markers)

# sctransform workflow
pbmc <- GetResidual(pbmc, features = heatmap_markers)
DoHeatmap(object = pbmc, features = heatmap_markers)

# heatmap with maximum of 100 cells per group
DoHeatmap(pbmc, heatmap_markers, cells = subset(pbmc, downsample = 100))
```

Example 62 (r):
```r
# Heatmaps (visualize scale.data slot)
DimHeatmap(object = pbmc, reduction = "pca", cells = 200)

# standard workflow
pbmc <- ScaleData(pbmc, features = heatmap_markers)
DoHeatmap(object = pbmc, features = heatmap_markers)

# sctransform workflow
pbmc <- GetResidual(pbmc, features = heatmap_markers)
DoHeatmap(object = pbmc, features = heatmap_markers)

# heatmap with maximum of 100 cells per group
DoHeatmap(pbmc, heatmap_markers, cells = subset(pbmc, downsample = 100))
```

Example 63 (unknown):
```unknown
# New things to try!  Note that plotting functions now return ggplot2 objects, so you can add themes, titles, and
# options onto them
VlnPlot(object = pbmc, features = "MS4A1", split.by = "groups")
DotPlot(object = pbmc, features = c("LYZ", "CCL5", "IL32"), split.by = "groups")
FeaturePlot(object = pbmc, features = c("MS4A1", "CD79A"), blend = TRUE)
DimPlot(object = pbmc) + DarkTheme()
DimPlot(object = pbmc) + labs(title = "2,700 PBMCs clustered using Seurat and viewed\non a two-dimensional UMAP")
```

Example 64 (r):
```r
# New things to try!  Note that plotting functions now return ggplot2 objects, so you can add themes, titles, and
# options onto them
VlnPlot(object = pbmc, features = "MS4A1", split.by = "groups")
DotPlot(object = pbmc, features = c("LYZ", "CCL5", "IL32"), split.by = "groups")
FeaturePlot(object = pbmc, features = c("MS4A1", "CD79A"), blend = TRUE)
DimPlot(object = pbmc) + DarkTheme()
DimPlot(object = pbmc) + labs(title = "2,700 PBMCs clustered using Seurat and viewed\non a two-dimensional UMAP")
```

Example 65 (r):
```r
# New things to try!  Note that plotting functions now return ggplot2 objects, so you can add themes, titles, and
# options onto them
VlnPlot(object = pbmc, features = "MS4A1", split.by = "groups")
DotPlot(object = pbmc, features = c("LYZ", "CCL5", "IL32"), split.by = "groups")
FeaturePlot(object = pbmc, features = c("MS4A1", "CD79A"), blend = TRUE)
DimPlot(object = pbmc) + DarkTheme()
DimPlot(object = pbmc) + labs(title = "2,700 PBMCs clustered using Seurat and viewed\non a two-dimensional UMAP")
```

Example 66 (unknown):
```unknown
RestoreLegend
```

Example 67 (unknown):
```unknown
RotatedAxis
```

Example 68 (unknown):
```unknown
# Plotting helper functions work with ggplot2-based scatter plots, such as DimPlot, FeaturePlot, CellScatter, and
# FeatureScatter
plot <- DimPlot(object = pbmc) + NoLegend()

# HoverLocator replaces the former `do.hover` argument It can also show extra data throught the `information` argument,
# designed to work smoothly with FetchData
HoverLocator(plot = plot, information = FetchData(object = pbmc, vars = c("ident", "PC_1", "nFeature_RNA")))

# FeatureLocator replaces the former `do.identify`
select.cells <- FeatureLocator(plot = plot)

# Label points on a ggplot object
LabelPoints(plot = plot, points = TopCells(object = pbmc[["pca"]]), repel = TRUE)
```

Example 69 (r):
```r
# Plotting helper functions work with ggplot2-based scatter plots, such as DimPlot, FeaturePlot, CellScatter, and
# FeatureScatter
plot <- DimPlot(object = pbmc) + NoLegend()

# HoverLocator replaces the former `do.hover` argument It can also show extra data throught the `information` argument,
# designed to work smoothly with FetchData
HoverLocator(plot = plot, information = FetchData(object = pbmc, vars = c("ident", "PC_1", "nFeature_RNA")))

# FeatureLocator replaces the former `do.identify`
select.cells <- FeatureLocator(plot = plot)

# Label points on a ggplot object
LabelPoints(plot = plot, points = TopCells(object = pbmc[["pca"]]), repel = TRUE)
```

Example 70 (r):
```r
# Plotting helper functions work with ggplot2-based scatter plots, such as DimPlot, FeaturePlot, CellScatter, and
# FeatureScatter
plot <- DimPlot(object = pbmc) + NoLegend()

# HoverLocator replaces the former `do.hover` argument It can also show extra data throught the `information` argument,
# designed to work smoothly with FetchData
HoverLocator(plot = plot, information = FetchData(object = pbmc, vars = c("ident", "PC_1", "nFeature_RNA")))

# FeatureLocator replaces the former `do.identify`
select.cells <- FeatureLocator(plot = plot)

# Label points on a ggplot object
LabelPoints(plot = plot, points = TopCells(object = pbmc[["pca"]]), repel = TRUE)
```

Example 71 (python):
```python
cbmc <- CreateSeuratObject(counts = cbmc.rna)
# Add ADT data
cbmc[["ADT"]] <- CreateAssayObject(counts = cbmc.adt)
# Run analyses by specifying the assay to use
NormalizeData(object = cbmc, assay = "RNA")
NormalizeData(object = cbmc, assay = "ADT", method = "CLR")

# Retrieve and set the default assay
DefaultAssay(object = cbmc)
DefaultAssay(object = cbmc) <- "ADT"
DefaultAssay(object = cbmc)

# Pull feature expression from both assays by using keys
FetchData(object = cbmc, vars = c("rna_CD3E", "adt_CD3"))

# Plot data from multiple assays using keys
FeatureScatter(object = cbmc, feature1 = "rna_CD3E", feature2 = "adt_CD3")
```

Example 72 (r):
```r
cbmc <- CreateSeuratObject(counts = cbmc.rna)
# Add ADT data
cbmc[["ADT"]] <- CreateAssayObject(counts = cbmc.adt)
# Run analyses by specifying the assay to use
NormalizeData(object = cbmc, assay = "RNA")
NormalizeData(object = cbmc, assay = "ADT", method = "CLR")

# Retrieve and set the default assay
DefaultAssay(object = cbmc)
DefaultAssay(object = cbmc) <- "ADT"
DefaultAssay(object = cbmc)

# Pull feature expression from both assays by using keys
FetchData(object = cbmc, vars = c("rna_CD3E", "adt_CD3"))

# Plot data from multiple assays using keys
FeatureScatter(object = cbmc, feature1 = "rna_CD3E", feature2 = "adt_CD3")
```

Example 73 (r):
```r
cbmc <- CreateSeuratObject(counts = cbmc.rna)
# Add ADT data
cbmc[["ADT"]] <- CreateAssayObject(counts = cbmc.adt)
# Run analyses by specifying the assay to use
NormalizeData(object = cbmc, assay = "RNA")
NormalizeData(object = cbmc, assay = "ADT", method = "CLR")

# Retrieve and set the default assay
DefaultAssay(object = cbmc)
DefaultAssay(object = cbmc) <- "ADT"
DefaultAssay(object = cbmc)

# Pull feature expression from both assays by using keys
FetchData(object = cbmc, vars = c("rna_CD3E", "adt_CD3"))

# Plot data from multiple assays using keys
FeatureScatter(object = cbmc, feature1 = "rna_CD3E", feature2 = "adt_CD3")
```

Example 74 (unknown):
```unknown
sessionInfo()
```

Example 75 (r):
```r
sessionInfo()
```

Example 76 (r):
```r
sessionInfo()
```

---

## Analysis, visualization, and integration of Visium HD spatial datasets with Seurat • Seurat

**URL:** http://127.0.0.1:9173/seurat/de_vignette.html

**Contents:**
- Differential expression testing
    - Compiled: 2024-03-04
  - Load in the data
  - Perform default differential expression tests
  - Perform DE analysis within the same cell type across conditions
    - Perform DE analysis after pseudobulking
  - Perform DE analysis using alternative tests

This vignette highlights some example workflows for performing differential expression in Seurat. For demonstration purposes, we will be using the interferon-beta stimulated human PBMCs dataset (ifnb) that is available via the SeuratData package.

The bulk of Seurat’s differential expression features can be accessed through the FindMarkers() function. By default, Seurat performs differential expression (DE) testing based on the non-parametric Wilcoxon rank sum test. To test for DE genes between two specific groups of cells, specify the ident.1 and ident.2 parameters.

The results data frame has the following columns :

If the ident.2 parameter is omitted or set to NULL, FindMarkers() will test for differentially expressed features between the group specified by ident.1 and all other cells. Additionally, the parameter only.pos can be set to TRUE to only search for positive markers, i.e. features that are more highly expressed in the ident.1 group.

Since this dataset contains treatment information (control versus stimulated with interferon-beta), we can also ask what genes change in different conditions for cells of the same type. First, we create a column in the meta.data slot to hold both the cell type and treatment information and switch the current Idents to that column. Then we use FindMarkers() to find the genes that are different between control and stimulated CD14 monocytes.

However, the p-values obtained from this analysis should be interpreted with caution, because these tests treat each cell as an independent replicate and ignore inherent correlations between cells originating from the same sample. Such analyses have been shown to find a large number of false positive associations, as has been demonstrated by Squair et al., 2021, Zimmerman et al., 2021, Junttila et al., 2022, and others. Below, we show how pseudobulking can be used to account for such within-sample correlation.

To pseudobulk, we will use AggregateExpression() to sum together gene counts of all the cells from the same sample for each cell type. This results in one gene expression profile per sample and cell type. We can then perform DE analysis using DESeq2 on the sample level. This treats the samples, rather than the individual cells, as independent observations.

First, we need to retrieve the sample information for each cell. This is not loaded in the metadata, so we will load it from the Github repo of the source data for the original paper.

Add sample information to the dataset

We can now perform pseudobulking (AggregateExpression()) based on the donor IDs.

Next, we perform DE testing on the pseudobulk level for CD14 monocytes, and compare it against the previous single-cell-level DE results.

We can see that while the p-values are correlated between the single-cell and pseudobulk data, the single-cell p-values are often smaller and suggest higher levels of significance. In particular, there are 3,519 genes with evidence of differential expression (prior to multiple hypothesis testing) in both analyses, 1,649 genes that only appear to be differentially expressed in the single-cell analysis, and just 204 genes that only appear to be differentially expressed in the bulk analysis. We can investigate these discrepancies using VlnPlot.

First, we can examine the top genes that are differentially expressed in both analyses.

In both the pseudobulk and single-cell analyses, the p-values for these two genes are astronomically small. For both of these genes, when just comparing all stimulated CD4 monocytes to all control CD4 monocytes across samples, we see much higher expression in the stimulated cells. When breaking down these cells by sample, we continue to see consistently higher expression levels in the stimulated samples compared to the control samples; in other words, this finding is not driven by just one or two samples. Because of this consistency, we find this signal in both analyses.

By contrast, we can examine examples of genes that are only DE under the single-cell analysis.

Here, SRGN and HLA-DRA both have very small p-values in the single-cell analysis (on the orders of \(10^{-21}\) and \(10^{-9}\)), but much larger p-values around 0.18 in the pseudobulk analysis. While there appears to be a difference between control and simulated cells when ignoring sample information, the signal is much weaker on the sample level, and we can see notable variability from sample to sample.

Finally, we also support many other DE tests using other methods. For completeness, the following tests are currently supported:

Developed by Rahul Satija, Satija Lab and Collaborators.

Site built with pkgdown 2.0.7.

**Examples:**

Example 1 (unknown):
```unknown
vignettes/de_vignette.Rmd
```

Example 2 (unknown):
```unknown
de_vignette.Rmd
```

Example 3 (unknown):
```unknown
library(Seurat)
library(SeuratData)
library(ggplot2)
ifnb <- LoadData("ifnb")
```

Example 4 (r):
```r
library(Seurat)
library(SeuratData)
library(ggplot2)
ifnb <- LoadData("ifnb")
```

Example 5 (r):
```r
library(Seurat)
library(SeuratData)
library(ggplot2)
ifnb <- LoadData("ifnb")
```

Example 6 (unknown):
```unknown
FindMarkers()
```

Example 7 (unknown):
```unknown
# Normalize the data
ifnb <- NormalizeData(ifnb)

# Find DE features between CD16 Mono and CD1 Mono
Idents(ifnb) <- "seurat_annotations"
monocyte.de.markers <- FindMarkers(ifnb, ident.1 = "CD16 Mono", ident.2 = "CD14 Mono")
# view results
head(monocyte.de.markers)
```

Example 8 (r):
```r
# Normalize the data
ifnb <- NormalizeData(ifnb)

# Find DE features between CD16 Mono and CD1 Mono
Idents(ifnb) <- "seurat_annotations"
monocyte.de.markers <- FindMarkers(ifnb, ident.1 = "CD16 Mono", ident.2 = "CD14 Mono")
# view results
head(monocyte.de.markers)
```

Example 9 (r):
```r
# Normalize the data
ifnb <- NormalizeData(ifnb)

# Find DE features between CD16 Mono and CD1 Mono
Idents(ifnb) <- "seurat_annotations"
monocyte.de.markers <- FindMarkers(ifnb, ident.1 = "CD16 Mono", ident.2 = "CD14 Mono")
# view results
head(monocyte.de.markers)
```

Example 10 (unknown):
```unknown
##        p_val avg_log2FC pct.1 pct.2 p_val_adj
## VMO1       0   5.700274 0.778 0.084         0
## MS4A4A     0   3.349751 0.748 0.143         0
## FCGR3A     0   3.281942 0.982 0.418         0
## PLAC8      0   3.268470 0.636 0.124         0
## CXCL16     0   2.014758 0.938 0.475         0
## MS4A7      0   2.386436 0.978 0.558         0
```

Example 11 (unknown):
```unknown
##        p_val avg_log2FC pct.1 pct.2 p_val_adj
## VMO1       0   5.700274 0.778 0.084         0
## MS4A4A     0   3.349751 0.748 0.143         0
## FCGR3A     0   3.281942 0.982 0.418         0
## PLAC8      0   3.268470 0.636 0.124         0
## CXCL16     0   2.014758 0.938 0.475         0
## MS4A7      0   2.386436 0.978 0.558         0
```

Example 12 (unknown):
```unknown
FindMarkers()
```

Example 13 (unknown):
```unknown
# Find differentially expressed features between CD14+ Monocytes and all other cells, only
# search for positive markers
monocyte.de.markers <- FindMarkers(ifnb, ident.1 = "CD16 Mono", ident.2 = NULL, only.pos = TRUE)
# view results
head(monocyte.de.markers)
```

Example 14 (r):
```r
# Find differentially expressed features between CD14+ Monocytes and all other cells, only
# search for positive markers
monocyte.de.markers <- FindMarkers(ifnb, ident.1 = "CD16 Mono", ident.2 = NULL, only.pos = TRUE)
# view results
head(monocyte.de.markers)
```

Example 15 (r):
```r
# Find differentially expressed features between CD14+ Monocytes and all other cells, only
# search for positive markers
monocyte.de.markers <- FindMarkers(ifnb, ident.1 = "CD16 Mono", ident.2 = NULL, only.pos = TRUE)
# view results
head(monocyte.de.markers)
```

Example 16 (unknown):
```unknown
##        p_val avg_log2FC pct.1 pct.2 p_val_adj
## FCGR3A     0   4.532656 0.982 0.168         0
## MS4A7      0   3.806350 0.978 0.216         0
## CXCL16     0   3.274267 0.938 0.196         0
## VMO1       0   6.254651 0.778 0.044         0
## MS4A4A     0   4.747731 0.748 0.055         0
## LST1       0   2.927351 0.912 0.228         0
```

Example 17 (unknown):
```unknown
##        p_val avg_log2FC pct.1 pct.2 p_val_adj
## FCGR3A     0   4.532656 0.982 0.168         0
## MS4A7      0   3.806350 0.978 0.216         0
## CXCL16     0   3.274267 0.938 0.196         0
## VMO1       0   6.254651 0.778 0.044         0
## MS4A4A     0   4.747731 0.748 0.055         0
## LST1       0   2.927351 0.912 0.228         0
```

Example 18 (unknown):
```unknown
FindMarkers()
```

Example 19 (unknown):
```unknown
ifnb$celltype.stim <- paste(ifnb$seurat_annotations, ifnb$stim, sep = "_")
Idents(ifnb) <- "celltype.stim"
mono.de <- FindMarkers(ifnb, ident.1 = "CD14 Mono_STIM", ident.2 = "CD14 Mono_CTRL", verbose = FALSE)
head(mono.de, n = 10)
```

Example 20 (r):
```r
ifnb$celltype.stim <- paste(ifnb$seurat_annotations, ifnb$stim, sep = "_")
Idents(ifnb) <- "celltype.stim"
mono.de <- FindMarkers(ifnb, ident.1 = "CD14 Mono_STIM", ident.2 = "CD14 Mono_CTRL", verbose = FALSE)
head(mono.de, n = 10)
```

Example 21 (r):
```r
ifnb$celltype.stim <- paste(ifnb$seurat_annotations, ifnb$stim, sep = "_")
Idents(ifnb) <- "celltype.stim"
mono.de <- FindMarkers(ifnb, ident.1 = "CD14 Mono_STIM", ident.2 = "CD14 Mono_CTRL", verbose = FALSE)
head(mono.de, n = 10)
```

Example 22 (unknown):
```unknown
##         p_val avg_log2FC pct.1 pct.2 p_val_adj
## IFIT1       0   7.319139 0.985 0.033         0
## CXCL10      0   8.036564 0.984 0.035         0
## RSAD2       0   6.741673 0.988 0.045         0
## TNFSF10     0   6.991279 0.989 0.047         0
## IFIT3       0   6.883785 0.992 0.056         0
## IFIT2       0   7.179929 0.961 0.039         0
## CXCL11      0   8.624208 0.932 0.012         0
## CCL8        0   9.134191 0.918 0.017         0
## IDO1        0   5.455898 0.965 0.089         0
## MX1         0   5.059052 0.960 0.093         0
```

Example 23 (unknown):
```unknown
##         p_val avg_log2FC pct.1 pct.2 p_val_adj
## IFIT1       0   7.319139 0.985 0.033         0
## CXCL10      0   8.036564 0.984 0.035         0
## RSAD2       0   6.741673 0.988 0.045         0
## TNFSF10     0   6.991279 0.989 0.047         0
## IFIT3       0   6.883785 0.992 0.056         0
## IFIT2       0   7.179929 0.961 0.039         0
## CXCL11      0   8.624208 0.932 0.012         0
## CCL8        0   9.134191 0.918 0.017         0
## IDO1        0   5.455898 0.965 0.089         0
## MX1         0   5.059052 0.960 0.093         0
```

Example 24 (python):
```python
# load the inferred sample IDs of each cell
ctrl <- read.table(url("https://raw.githubusercontent.com/yelabucsf/demuxlet_paper_code/master/fig3/ye1.ctrl.8.10.sm.best"), head = T, stringsAsFactors = F)
stim <- read.table(url("https://raw.githubusercontent.com/yelabucsf/demuxlet_paper_code/master/fig3/ye2.stim.8.10.sm.best"), head = T, stringsAsFactors = F)
info <- rbind(ctrl, stim)

# rename the cell IDs by substituting the '-' into '.'
info$BARCODE <- gsub(pattern = "\\-", replacement = "\\.", info$BARCODE)

# only keep the cells with high-confidence sample ID
info <- info[grep(pattern = "SNG", x = info$BEST), ]

# remove cells with duplicated IDs in both ctrl and stim groups
info <- info[!duplicated(info$BARCODE) & !duplicated(info$BARCODE, fromLast = T), ]

# now add the sample IDs to ifnb 
rownames(info) <- info$BARCODE
info <- info[, c("BEST"), drop = F]
names(info) <- c("donor_id")
ifnb <- AddMetaData(ifnb, metadata = info)

# remove cells without donor IDs
ifnb$donor_id[is.na(ifnb$donor_id)] <- "unknown"
ifnb <- subset(ifnb, subset = donor_id != "unknown")
```

Example 25 (r):
```r
# load the inferred sample IDs of each cell
ctrl <- read.table(url("https://raw.githubusercontent.com/yelabucsf/demuxlet_paper_code/master/fig3/ye1.ctrl.8.10.sm.best"), head = T, stringsAsFactors = F)
stim <- read.table(url("https://raw.githubusercontent.com/yelabucsf/demuxlet_paper_code/master/fig3/ye2.stim.8.10.sm.best"), head = T, stringsAsFactors = F)
info <- rbind(ctrl, stim)

# rename the cell IDs by substituting the '-' into '.'
info$BARCODE <- gsub(pattern = "\\-", replacement = "\\.", info$BARCODE)

# only keep the cells with high-confidence sample ID
info <- info[grep(pattern = "SNG", x = info$BEST), ]

# remove cells with duplicated IDs in both ctrl and stim groups
info <- info[!duplicated(info$BARCODE) & !duplicated(info$BARCODE, fromLast = T), ]

# now add the sample IDs to ifnb 
rownames(info) <- info$BARCODE
info <- info[, c("BEST"), drop = F]
names(info) <- c("donor_id")
ifnb <- AddMetaData(ifnb, metadata = info)

# remove cells without donor IDs
ifnb$donor_id[is.na(ifnb$donor_id)] <- "unknown"
ifnb <- subset(ifnb, subset = donor_id != "unknown")
```

Example 26 (r):
```r
# load the inferred sample IDs of each cell
ctrl <- read.table(url("https://raw.githubusercontent.com/yelabucsf/demuxlet_paper_code/master/fig3/ye1.ctrl.8.10.sm.best"), head = T, stringsAsFactors = F)
stim <- read.table(url("https://raw.githubusercontent.com/yelabucsf/demuxlet_paper_code/master/fig3/ye2.stim.8.10.sm.best"), head = T, stringsAsFactors = F)
info <- rbind(ctrl, stim)

# rename the cell IDs by substituting the '-' into '.'
info$BARCODE <- gsub(pattern = "\\-", replacement = "\\.", info$BARCODE)

# only keep the cells with high-confidence sample ID
info <- info[grep(pattern = "SNG", x = info$BEST), ]

# remove cells with duplicated IDs in both ctrl and stim groups
info <- info[!duplicated(info$BARCODE) & !duplicated(info$BARCODE, fromLast = T), ]

# now add the sample IDs to ifnb 
rownames(info) <- info$BARCODE
info <- info[, c("BEST"), drop = F]
names(info) <- c("donor_id")
ifnb <- AddMetaData(ifnb, metadata = info)

# remove cells without donor IDs
ifnb$donor_id[is.na(ifnb$donor_id)] <- "unknown"
ifnb <- subset(ifnb, subset = donor_id != "unknown")
```

Example 27 (unknown):
```unknown
AggregateExpression()
```

Example 28 (unknown):
```unknown
# pseudobulk the counts based on donor-condition-celltype
pseudo_ifnb <- AggregateExpression(ifnb, assays = "RNA", return.seurat = T, group.by = c("stim", "donor_id", "seurat_annotations"))

# each 'cell' is a donor-condition-celltype pseudobulk profile
tail(Cells(pseudo_ifnb))
```

Example 29 (r):
```r
# pseudobulk the counts based on donor-condition-celltype
pseudo_ifnb <- AggregateExpression(ifnb, assays = "RNA", return.seurat = T, group.by = c("stim", "donor_id", "seurat_annotations"))

# each 'cell' is a donor-condition-celltype pseudobulk profile
tail(Cells(pseudo_ifnb))
```

Example 30 (r):
```r
# pseudobulk the counts based on donor-condition-celltype
pseudo_ifnb <- AggregateExpression(ifnb, assays = "RNA", return.seurat = T, group.by = c("stim", "donor_id", "seurat_annotations"))

# each 'cell' is a donor-condition-celltype pseudobulk profile
tail(Cells(pseudo_ifnb))
```

Example 31 (unknown):
```unknown
## [1] "STIM_SNG-1488_NK"          "STIM_SNG-1488_DC"         
## [3] "STIM_SNG-1488_B Activated" "STIM_SNG-1488_Mk"         
## [5] "STIM_SNG-1488_pDC"         "STIM_SNG-1488_Eryth"
```

Example 32 (unknown):
```unknown
## [1] "STIM_SNG-1488_NK"          "STIM_SNG-1488_DC"         
## [3] "STIM_SNG-1488_B Activated" "STIM_SNG-1488_Mk"         
## [5] "STIM_SNG-1488_pDC"         "STIM_SNG-1488_Eryth"
```

Example 33 (unknown):
```unknown
pseudo_ifnb$celltype.stim <- paste(pseudo_ifnb$seurat_annotations, pseudo_ifnb$stim, sep = "_")
```

Example 34 (r):
```r
pseudo_ifnb$celltype.stim <- paste(pseudo_ifnb$seurat_annotations, pseudo_ifnb$stim, sep = "_")
```

Example 35 (r):
```r
pseudo_ifnb$celltype.stim <- paste(pseudo_ifnb$seurat_annotations, pseudo_ifnb$stim, sep = "_")
```

Example 36 (unknown):
```unknown
Idents(pseudo_ifnb) <- "celltype.stim"

bulk.mono.de <- FindMarkers(object = pseudo_ifnb, 
                         ident.1 = "CD14 Mono_STIM", 
                         ident.2 = "CD14 Mono_CTRL",
                         test.use = "DESeq2")
head(bulk.mono.de, n = 15)
```

Example 37 (r):
```r
Idents(pseudo_ifnb) <- "celltype.stim"

bulk.mono.de <- FindMarkers(object = pseudo_ifnb, 
                         ident.1 = "CD14 Mono_STIM", 
                         ident.2 = "CD14 Mono_CTRL",
                         test.use = "DESeq2")
head(bulk.mono.de, n = 15)
```

Example 38 (r):
```r
Idents(pseudo_ifnb) <- "celltype.stim"

bulk.mono.de <- FindMarkers(object = pseudo_ifnb, 
                         ident.1 = "CD14 Mono_STIM", 
                         ident.2 = "CD14 Mono_CTRL",
                         test.use = "DESeq2")
head(bulk.mono.de, n = 15)
```

Example 39 (unknown):
```unknown
##                  p_val avg_log2FC pct.1 pct.2     p_val_adj
## IL1RN    3.701542e-275   6.160156     1     1 5.201777e-271
## IFITM2   1.955626e-250   4.318976     1     1 2.748242e-246
## SSB      2.699554e-203   3.066647     1     1 3.793684e-199
## NT5C3A   2.239898e-198   5.412972     1     1 3.147729e-194
## RTCB     5.700554e-162   3.133362     1     1 8.010989e-158
## RABGAP1L 4.743010e-161   5.562364     1     1 6.665352e-157
## DYNLT1   9.735640e-159   2.402726     1     1 1.368150e-154
## PLSCR1   3.191691e-146   2.676047     1     1 4.485284e-142
## ISG20    9.664488e-145   5.443114     1     1 1.358150e-140
## NAPA     2.858013e-144   1.977719     1     1 4.016365e-140
## DDX58    5.957026e-142   4.640111     1     1 8.371409e-138
## HERC5    6.333722e-133   5.266515     1     1 8.900780e-129
## OASL     3.892853e-130   3.946745     1     1 5.470627e-126
## EIF2AK2  6.636434e-128   3.940167     1     1 9.326180e-124
## TMEM50A  6.731955e-117   1.355947     1     1 9.460417e-113
```

Example 40 (unknown):
```unknown
##                  p_val avg_log2FC pct.1 pct.2     p_val_adj
## IL1RN    3.701542e-275   6.160156     1     1 5.201777e-271
## IFITM2   1.955626e-250   4.318976     1     1 2.748242e-246
## SSB      2.699554e-203   3.066647     1     1 3.793684e-199
## NT5C3A   2.239898e-198   5.412972     1     1 3.147729e-194
## RTCB     5.700554e-162   3.133362     1     1 8.010989e-158
## RABGAP1L 4.743010e-161   5.562364     1     1 6.665352e-157
## DYNLT1   9.735640e-159   2.402726     1     1 1.368150e-154
## PLSCR1   3.191691e-146   2.676047     1     1 4.485284e-142
## ISG20    9.664488e-145   5.443114     1     1 1.358150e-140
## NAPA     2.858013e-144   1.977719     1     1 4.016365e-140
## DDX58    5.957026e-142   4.640111     1     1 8.371409e-138
## HERC5    6.333722e-133   5.266515     1     1 8.900780e-129
## OASL     3.892853e-130   3.946745     1     1 5.470627e-126
## EIF2AK2  6.636434e-128   3.940167     1     1 9.326180e-124
## TMEM50A  6.731955e-117   1.355947     1     1 9.460417e-113
```

Example 41 (python):
```python
# compare the DE P-values between the single-cell level and the pseudobulk level results
names(bulk.mono.de) <- paste0(names(bulk.mono.de), ".bulk")
bulk.mono.de$gene <- rownames(bulk.mono.de)

names(mono.de) <- paste0(names(mono.de), ".sc")
mono.de$gene <- rownames(mono.de)

merge_dat <- merge(mono.de, bulk.mono.de, by = "gene")
merge_dat <- merge_dat[order(merge_dat$p_val.bulk), ]

# Number of genes that are marginally significant in both; marginally significant only in bulk; and marginally significant only in single-cell
common <- merge_dat$gene[which(merge_dat$p_val.bulk < 0.05 & 
                                merge_dat$p_val.sc < 0.05)]
only_sc <- merge_dat$gene[which(merge_dat$p_val.bulk > 0.05 & 
                                  merge_dat$p_val.sc < 0.05)]
only_bulk <- merge_dat$gene[which(merge_dat$p_val.bulk < 0.05 & 
                                    merge_dat$p_val.sc > 0.05)]
print(paste0('# Common: ',length(common)))
```

Example 42 (r):
```r
# compare the DE P-values between the single-cell level and the pseudobulk level results
names(bulk.mono.de) <- paste0(names(bulk.mono.de), ".bulk")
bulk.mono.de$gene <- rownames(bulk.mono.de)

names(mono.de) <- paste0(names(mono.de), ".sc")
mono.de$gene <- rownames(mono.de)

merge_dat <- merge(mono.de, bulk.mono.de, by = "gene")
merge_dat <- merge_dat[order(merge_dat$p_val.bulk), ]

# Number of genes that are marginally significant in both; marginally significant only in bulk; and marginally significant only in single-cell
common <- merge_dat$gene[which(merge_dat$p_val.bulk < 0.05 & 
                                merge_dat$p_val.sc < 0.05)]
only_sc <- merge_dat$gene[which(merge_dat$p_val.bulk > 0.05 & 
                                  merge_dat$p_val.sc < 0.05)]
only_bulk <- merge_dat$gene[which(merge_dat$p_val.bulk < 0.05 & 
                                    merge_dat$p_val.sc > 0.05)]
print(paste0('# Common: ',length(common)))
```

Example 43 (r):
```r
# compare the DE P-values between the single-cell level and the pseudobulk level results
names(bulk.mono.de) <- paste0(names(bulk.mono.de), ".bulk")
bulk.mono.de$gene <- rownames(bulk.mono.de)

names(mono.de) <- paste0(names(mono.de), ".sc")
mono.de$gene <- rownames(mono.de)

merge_dat <- merge(mono.de, bulk.mono.de, by = "gene")
merge_dat <- merge_dat[order(merge_dat$p_val.bulk), ]

# Number of genes that are marginally significant in both; marginally significant only in bulk; and marginally significant only in single-cell
common <- merge_dat$gene[which(merge_dat$p_val.bulk < 0.05 & 
                                merge_dat$p_val.sc < 0.05)]
only_sc <- merge_dat$gene[which(merge_dat$p_val.bulk > 0.05 & 
                                  merge_dat$p_val.sc < 0.05)]
only_bulk <- merge_dat$gene[which(merge_dat$p_val.bulk < 0.05 & 
                                    merge_dat$p_val.sc > 0.05)]
print(paste0('# Common: ',length(common)))
```

Example 44 (unknown):
```unknown
## [1] "# Common: 3519"
```

Example 45 (unknown):
```unknown
## [1] "# Common: 3519"
```

Example 46 (python):
```python
print(paste0('# Only in single-cell: ',length(only_sc)))
```

Example 47 (r):
```r
print(paste0('# Only in single-cell: ',length(only_sc)))
```

Example 48 (r):
```r
print(paste0('# Only in single-cell: ',length(only_sc)))
```

Example 49 (unknown):
```unknown
## [1] "# Only in single-cell: 1649"
```

Example 50 (unknown):
```unknown
## [1] "# Only in single-cell: 1649"
```

Example 51 (python):
```python
print(paste0('# Only in bulk: ',length(only_bulk)))
```

Example 52 (r):
```r
print(paste0('# Only in bulk: ',length(only_bulk)))
```

Example 53 (r):
```r
print(paste0('# Only in bulk: ',length(only_bulk)))
```

Example 54 (unknown):
```unknown
## [1] "# Only in bulk: 204"
```

Example 55 (unknown):
```unknown
## [1] "# Only in bulk: 204"
```

Example 56 (python):
```python
# create a new column to annotate sample-condition-celltype in the single-cell dataset
ifnb$donor_id.stim <- paste0(ifnb$stim, "-", ifnb$donor_id)

# generate violin plot 
Idents(ifnb) <- "celltype.stim"
print(merge_dat[merge_dat$gene%in%common[1:2],c('gene','p_val.sc','p_val.bulk')])
```

Example 57 (r):
```r
# create a new column to annotate sample-condition-celltype in the single-cell dataset
ifnb$donor_id.stim <- paste0(ifnb$stim, "-", ifnb$donor_id)

# generate violin plot 
Idents(ifnb) <- "celltype.stim"
print(merge_dat[merge_dat$gene%in%common[1:2],c('gene','p_val.sc','p_val.bulk')])
```

Example 58 (r):
```r
# create a new column to annotate sample-condition-celltype in the single-cell dataset
ifnb$donor_id.stim <- paste0(ifnb$stim, "-", ifnb$donor_id)

# generate violin plot 
Idents(ifnb) <- "celltype.stim"
print(merge_dat[merge_dat$gene%in%common[1:2],c('gene','p_val.sc','p_val.bulk')])
```

Example 59 (unknown):
```unknown
##        gene p_val.sc    p_val.bulk
## 2785  IL1RN        0 3.701542e-275
## 2739 IFITM2        0 1.955626e-250
```

Example 60 (unknown):
```unknown
##        gene p_val.sc    p_val.bulk
## 2785  IL1RN        0 3.701542e-275
## 2739 IFITM2        0 1.955626e-250
```

Example 61 (unknown):
```unknown
VlnPlot(ifnb, features = common[1:2], idents = c("CD14 Mono_CTRL", "CD14 Mono_STIM"), group.by = "stim")
```

Example 62 (r):
```r
VlnPlot(ifnb, features = common[1:2], idents = c("CD14 Mono_CTRL", "CD14 Mono_STIM"), group.by = "stim")
```

Example 63 (r):
```r
VlnPlot(ifnb, features = common[1:2], idents = c("CD14 Mono_CTRL", "CD14 Mono_STIM"), group.by = "stim")
```

Example 64 (unknown):
```unknown
VlnPlot(ifnb, features = common[1:2], idents = c("CD14 Mono_CTRL", "CD14 Mono_STIM"), group.by = "donor_id.stim", ncol = 1)
```

Example 65 (r):
```r
VlnPlot(ifnb, features = common[1:2], idents = c("CD14 Mono_CTRL", "CD14 Mono_STIM"), group.by = "donor_id.stim", ncol = 1)
```

Example 66 (r):
```r
VlnPlot(ifnb, features = common[1:2], idents = c("CD14 Mono_CTRL", "CD14 Mono_STIM"), group.by = "donor_id.stim", ncol = 1)
```

Example 67 (python):
```python
print(merge_dat[merge_dat$gene%in%c('SRGN','HLA-DRA'),c('gene','p_val.sc','p_val.bulk')])
```

Example 68 (r):
```r
print(merge_dat[merge_dat$gene%in%c('SRGN','HLA-DRA'),c('gene','p_val.sc','p_val.bulk')])
```

Example 69 (r):
```r
print(merge_dat[merge_dat$gene%in%c('SRGN','HLA-DRA'),c('gene','p_val.sc','p_val.bulk')])
```

Example 70 (unknown):
```unknown
##         gene     p_val.sc p_val.bulk
## 5710    SRGN 4.025076e-21  0.1823188
## 2603 HLA-DRA 4.989863e-09  0.1851302
```

Example 71 (unknown):
```unknown
##         gene     p_val.sc p_val.bulk
## 5710    SRGN 4.025076e-21  0.1823188
## 2603 HLA-DRA 4.989863e-09  0.1851302
```

Example 72 (unknown):
```unknown
VlnPlot(ifnb, features <- c('SRGN','HLA-DRA'), idents = c("CD14 Mono_CTRL", "CD14 Mono_STIM"), group.by = "stim")
```

Example 73 (r):
```r
VlnPlot(ifnb, features <- c('SRGN','HLA-DRA'), idents = c("CD14 Mono_CTRL", "CD14 Mono_STIM"), group.by = "stim")
```

Example 74 (r):
```r
VlnPlot(ifnb, features <- c('SRGN','HLA-DRA'), idents = c("CD14 Mono_CTRL", "CD14 Mono_STIM"), group.by = "stim")
```

Example 75 (unknown):
```unknown
VlnPlot(ifnb, features <- c('SRGN','HLA-DRA'), idents = c("CD14 Mono_CTRL", "CD14 Mono_STIM"), group.by = "donor_id.stim", ncol = 1)
```

Example 76 (r):
```r
VlnPlot(ifnb, features <- c('SRGN','HLA-DRA'), idents = c("CD14 Mono_CTRL", "CD14 Mono_STIM"), group.by = "donor_id.stim", ncol = 1)
```

Example 77 (r):
```r
VlnPlot(ifnb, features <- c('SRGN','HLA-DRA'), idents = c("CD14 Mono_CTRL", "CD14 Mono_STIM"), group.by = "donor_id.stim", ncol = 1)
```

Example 78 (unknown):
```unknown
# Test for DE features using the MAST package
Idents(ifnb) <- "seurat_annotations"
head(FindMarkers(ifnb, ident.1 = "CD14 Mono", ident.2 = "CD16 Mono", test.use = "MAST"))
```

Example 79 (r):
```r
# Test for DE features using the MAST package
Idents(ifnb) <- "seurat_annotations"
head(FindMarkers(ifnb, ident.1 = "CD14 Mono", ident.2 = "CD16 Mono", test.use = "MAST"))
```

Example 80 (r):
```r
# Test for DE features using the MAST package
Idents(ifnb) <- "seurat_annotations"
head(FindMarkers(ifnb, ident.1 = "CD14 Mono", ident.2 = "CD16 Mono", test.use = "MAST"))
```

---

## Analysis, visualization, and integration of Visium HD spatial datasets with Seurat • Seurat

**URL:** http://127.0.0.1:9173/seurat/articles/seurat5_essential_commands/index.html

**Contents:**
- Seurat v5 Command Cheat Sheet
    - Compiled: October 31, 2023
- Load datasets
- Access and store expression data
- Access cell names and metadata
- Create Seurat or Assay objects
- Working with layers
- Accessing additional data
- Contents

Here, we describe important commands and functions to store, access, and process data using Seurat v5. To demonstrate commamnds, we use a dataset of 3,000 PBMC (stored in-memory), and a dataset of 1.3M E18 mouse neurons (stored on-disk), which we constructed as described in the BPCells vignette.

The $ and double-bracket [[]] symbols can be used as efficient accessor functions for Seurat5 assays.

Despite the drastic difference in dataset size, the 1.3M cell dataset occupies a small memory footprint thanks to on-disk storage.

Get cell names. Since Seurat v5 object doesn’t require all assays have the same cells, Cells() is designed to get cell names of the default assay and colnames() is deigned to get cell names of the entire object

Access object metadata

By setting a global option (Seurat.object.assay.version), you can default to creating either Seurat v3 assays, or Seurat v5 assays. The use of v5 assays is set by default upon package loading, which ensures backwards compatibiltiy with existing workflows.

CreateAssayObject() and CreateAssay5Object() can be used to create v3 and v5 assay regardless of the setting in Seurat.object.assay.version

Assay5 objects are more flexible, and can be used to store only a data layer, with no counts data. This can be used to create Seurat objects that require less space

We can also convert (cast) between Assay and Assay5 objects with as().

Seurat v5 assays store data in layers. These layers can store raw, un-normalized counts (layer='counts'), normalized data (layer='data'), or z-scored/variance-stabilized data (layer='scale.data').

Prior to performing integration analysis in Seurat v5, we can split the layers into groups. The IntegrateLayers function, described in our vignette, will then align shared cell types across these layers. After performing integration, you can rejoin the layers.

If you have multiple counts matrices, you can also create a Seurat object that is initialized with multiple layers.

Developed by Rahul Satija, Satija Lab and Collaborators.

Site built with pkgdown 2.0.7.

**Examples:**

Example 1 (unknown):
```unknown
vignettes/seurat5_essential_commands.Rmd
```

Example 2 (unknown):
```unknown
seurat5_essential_commands.Rmd
```

Example 3 (unknown):
```unknown
library(Seurat)
library(SeuratData)
library(BPCells)
library(dplyr)
options(Seurat.object.assay.version = "v5")
```

Example 4 (r):
```r
library(Seurat)
library(SeuratData)
library(BPCells)
library(dplyr)
options(Seurat.object.assay.version = "v5")
```

Example 5 (r):
```r
library(Seurat)
library(SeuratData)
library(BPCells)
library(dplyr)
options(Seurat.object.assay.version = "v5")
```

Example 6 (unknown):
```unknown
pbmc3k <- LoadData("pbmc3k")
mousebrain1m <- readRDS("/brahms/hartmana/vignette_data/1p3_million_mouse_brain.rds")

#  RNA assay is of the Assay5 class
class(pbmc3k[["RNA"]])
class(mousebrain1m[["RNA"]])
```

Example 7 (r):
```r
pbmc3k <- LoadData("pbmc3k")
mousebrain1m <- readRDS("/brahms/hartmana/vignette_data/1p3_million_mouse_brain.rds")

#  RNA assay is of the Assay5 class
class(pbmc3k[["RNA"]])
class(mousebrain1m[["RNA"]])
```

Example 8 (r):
```r
pbmc3k <- LoadData("pbmc3k")
mousebrain1m <- readRDS("/brahms/hartmana/vignette_data/1p3_million_mouse_brain.rds")

#  RNA assay is of the Assay5 class
class(pbmc3k[["RNA"]])
class(mousebrain1m[["RNA"]])
```

Example 9 (python):
```python
# access the counts matrix from the RNA assay
counts_matrix <- pbmc3k[["RNA"]]$counts

# Add a layer
# Equivalent to running pbmc3k <-NormalizeData(pbmc3k)
pbmc3k[["RNA"]]$data <- NormalizeData(pbmc3k[["RNA"]]$counts)

# Delete a layer
pbmc3k[["RNA"]]$data <- NULL

# pbmc3k counts matrix is stored in-memory
class(pbmc3k[["RNA"]]$counts)

# 1.3M cell dataset counts matrix is stored on-disk
class(mousebrain1m[["RNA"]]$counts)
```

Example 10 (r):
```r
# access the counts matrix from the RNA assay
counts_matrix <- pbmc3k[["RNA"]]$counts

# Add a layer
# Equivalent to running pbmc3k <-NormalizeData(pbmc3k)
pbmc3k[["RNA"]]$data <- NormalizeData(pbmc3k[["RNA"]]$counts)

# Delete a layer
pbmc3k[["RNA"]]$data <- NULL

# pbmc3k counts matrix is stored in-memory
class(pbmc3k[["RNA"]]$counts)

# 1.3M cell dataset counts matrix is stored on-disk
class(mousebrain1m[["RNA"]]$counts)
```

Example 11 (r):
```r
# access the counts matrix from the RNA assay
counts_matrix <- pbmc3k[["RNA"]]$counts

# Add a layer
# Equivalent to running pbmc3k <-NormalizeData(pbmc3k)
pbmc3k[["RNA"]]$data <- NormalizeData(pbmc3k[["RNA"]]$counts)

# Delete a layer
pbmc3k[["RNA"]]$data <- NULL

# pbmc3k counts matrix is stored in-memory
class(pbmc3k[["RNA"]]$counts)

# 1.3M cell dataset counts matrix is stored on-disk
class(mousebrain1m[["RNA"]]$counts)
```

Example 12 (unknown):
```unknown
paste("PBMC 3k contains", length(colnames(pbmc3k)), "cells")
paste("Mouse brain 1.3M contains", length(colnames(mousebrain1m)), "cells")

# Despite the mouse brain dataset containing 1.3 million cells, the assay is under 350Mbs in size due to on-disk storage
paste("PBMC 3k assay size:", format(object.size(pbmc3k[["RNA"]]), units = "Mb"))
paste("Mouse brain 1.3M assay size:", format(object.size(mousebrain1m[["RNA"]]), units = "Mb"))
```

Example 13 (r):
```r
paste("PBMC 3k contains", length(colnames(pbmc3k)), "cells")
paste("Mouse brain 1.3M contains", length(colnames(mousebrain1m)), "cells")

# Despite the mouse brain dataset containing 1.3 million cells, the assay is under 350Mbs in size due to on-disk storage
paste("PBMC 3k assay size:", format(object.size(pbmc3k[["RNA"]]), units = "Mb"))
paste("Mouse brain 1.3M assay size:", format(object.size(mousebrain1m[["RNA"]]), units = "Mb"))
```

Example 14 (r):
```r
paste("PBMC 3k contains", length(colnames(pbmc3k)), "cells")
paste("Mouse brain 1.3M contains", length(colnames(mousebrain1m)), "cells")

# Despite the mouse brain dataset containing 1.3 million cells, the assay is under 350Mbs in size due to on-disk storage
paste("PBMC 3k assay size:", format(object.size(pbmc3k[["RNA"]]), units = "Mb"))
paste("Mouse brain 1.3M assay size:", format(object.size(mousebrain1m[["RNA"]]), units = "Mb"))
```

Example 15 (unknown):
```unknown
pbmc3k[["RNAsub"]] <- subset(pbmc3k[["RNA"]], cells = colnames(pbmc3k)[1:100])
DefaultAssay(pbmc3k) <- "RNAsub"
length(Cells(pbmc3k))
length(colnames(pbmc3k))
```

Example 16 (r):
```r
pbmc3k[["RNAsub"]] <- subset(pbmc3k[["RNA"]], cells = colnames(pbmc3k)[1:100])
DefaultAssay(pbmc3k) <- "RNAsub"
length(Cells(pbmc3k))
length(colnames(pbmc3k))
```

Example 17 (r):
```r
pbmc3k[["RNAsub"]] <- subset(pbmc3k[["RNA"]], cells = colnames(pbmc3k)[1:100])
DefaultAssay(pbmc3k) <- "RNAsub"
length(Cells(pbmc3k))
length(colnames(pbmc3k))
```

Example 18 (python):
```python
# get all object metadata
pbmc_metadata <- pbmc3k[[]]

# get list of metadata columns
colnames(pbmc_metadata)

# get annotations stored in metadata
annotations <- pbmc3k$seurat_annotations
```

Example 19 (r):
```r
# get all object metadata
pbmc_metadata <- pbmc3k[[]]

# get list of metadata columns
colnames(pbmc_metadata)

# get annotations stored in metadata
annotations <- pbmc3k$seurat_annotations
```

Example 20 (r):
```r
# get all object metadata
pbmc_metadata <- pbmc3k[[]]

# get list of metadata columns
colnames(pbmc_metadata)

# get annotations stored in metadata
annotations <- pbmc3k$seurat_annotations
```

Example 21 (unknown):
```unknown
Seurat.object.assay.version
```

Example 22 (unknown):
```unknown
# create v3 assays
options(Seurat.object.assay.version = "v3")
pbmc.counts <- Read10X(data.dir = "/brahms/hartmana/vignette_data/pbmc3k/filtered_gene_bc_matrices/hg19/")
pbmc <- CreateSeuratObject(counts = pbmc.counts)
class(pbmc[["RNA"]])

# create v5 assays
options(Seurat.object.assay.version = "v5")
pbmc.counts <- Read10X(data.dir = "/brahms/hartmana/vignette_data/pbmc3k/filtered_gene_bc_matrices/hg19/")
pbmc <- CreateSeuratObject(counts = pbmc.counts)
class(pbmc[["RNA"]])
```

Example 23 (r):
```r
# create v3 assays
options(Seurat.object.assay.version = "v3")
pbmc.counts <- Read10X(data.dir = "/brahms/hartmana/vignette_data/pbmc3k/filtered_gene_bc_matrices/hg19/")
pbmc <- CreateSeuratObject(counts = pbmc.counts)
class(pbmc[["RNA"]])

# create v5 assays
options(Seurat.object.assay.version = "v5")
pbmc.counts <- Read10X(data.dir = "/brahms/hartmana/vignette_data/pbmc3k/filtered_gene_bc_matrices/hg19/")
pbmc <- CreateSeuratObject(counts = pbmc.counts)
class(pbmc[["RNA"]])
```

Example 24 (r):
```r
# create v3 assays
options(Seurat.object.assay.version = "v3")
pbmc.counts <- Read10X(data.dir = "/brahms/hartmana/vignette_data/pbmc3k/filtered_gene_bc_matrices/hg19/")
pbmc <- CreateSeuratObject(counts = pbmc.counts)
class(pbmc[["RNA"]])

# create v5 assays
options(Seurat.object.assay.version = "v5")
pbmc.counts <- Read10X(data.dir = "/brahms/hartmana/vignette_data/pbmc3k/filtered_gene_bc_matrices/hg19/")
pbmc <- CreateSeuratObject(counts = pbmc.counts)
class(pbmc[["RNA"]])
```

Example 25 (unknown):
```unknown
CreateAssayObject()
```

Example 26 (unknown):
```unknown
CreateAssay5Object()
```

Example 27 (unknown):
```unknown
Seurat.object.assay.version
```

Example 28 (unknown):
```unknown
# create a v3 assay
assay.v3 <- CreateAssayObject(counts = pbmc.counts)

# create a v5 assay
assay.v5 <- CreateAssay5Object(counts = pbmc.counts)

class(assay.v3)
class(assay.v5)
```

Example 29 (r):
```r
# create a v3 assay
assay.v3 <- CreateAssayObject(counts = pbmc.counts)

# create a v5 assay
assay.v5 <- CreateAssay5Object(counts = pbmc.counts)

class(assay.v3)
class(assay.v5)
```

Example 30 (r):
```r
# create a v3 assay
assay.v3 <- CreateAssayObject(counts = pbmc.counts)

# create a v5 assay
assay.v5 <- CreateAssay5Object(counts = pbmc.counts)

class(assay.v3)
class(assay.v5)
```

Example 31 (unknown):
```unknown
# create an assay using only normalized data
assay.v5 <- CreateAssay5Object(data = log1p(pbmc.counts))

# create a Seurat object based on this assay
pbmc3k_slim <- CreateSeuratObject(assay.v5)
pbmc3k_slim
```

Example 32 (r):
```r
# create an assay using only normalized data
assay.v5 <- CreateAssay5Object(data = log1p(pbmc.counts))

# create a Seurat object based on this assay
pbmc3k_slim <- CreateSeuratObject(assay.v5)
pbmc3k_slim
```

Example 33 (r):
```r
# create an assay using only normalized data
assay.v5 <- CreateAssay5Object(data = log1p(pbmc.counts))

# create a Seurat object based on this assay
pbmc3k_slim <- CreateSeuratObject(assay.v5)
pbmc3k_slim
```

Example 34 (unknown):
```unknown
# convert a v5 assay to a v3 assay
pbmc3k[["RNA3"]] <- as(object = pbmc3k[["RNA"]], Class = "Assay")

# convert a v3 assay to a v5 assay
pbmc3k[["RNA5"]] <- as(object = pbmc3k[["RNA3"]], Class = "Assay5")
```

Example 35 (r):
```r
# convert a v5 assay to a v3 assay
pbmc3k[["RNA3"]] <- as(object = pbmc3k[["RNA"]], Class = "Assay")

# convert a v3 assay to a v5 assay
pbmc3k[["RNA5"]] <- as(object = pbmc3k[["RNA3"]], Class = "Assay5")
```

Example 36 (r):
```r
# convert a v5 assay to a v3 assay
pbmc3k[["RNA3"]] <- as(object = pbmc3k[["RNA"]], Class = "Assay")

# convert a v3 assay to a v5 assay
pbmc3k[["RNA5"]] <- as(object = pbmc3k[["RNA3"]], Class = "Assay5")
```

Example 37 (unknown):
```unknown
layer='counts'
```

Example 38 (unknown):
```unknown
layer='data'
```

Example 39 (unknown):
```unknown
layer='scale.data'
```

Example 40 (python):
```python
# by default, creates an RNA assay with a counts layer
obj <- CreateSeuratObject(counts = pbmc.counts)
obj

# creates a normalized data layer
obj <- NormalizeData(obj, verbose = FALSE)
obj

# extract only the layer names from an assay
Layers(obj[["RNA"]])
```

Example 41 (r):
```r
# by default, creates an RNA assay with a counts layer
obj <- CreateSeuratObject(counts = pbmc.counts)
obj

# creates a normalized data layer
obj <- NormalizeData(obj, verbose = FALSE)
obj

# extract only the layer names from an assay
Layers(obj[["RNA"]])
```

Example 42 (r):
```r
# by default, creates an RNA assay with a counts layer
obj <- CreateSeuratObject(counts = pbmc.counts)
obj

# creates a normalized data layer
obj <- NormalizeData(obj, verbose = FALSE)
obj

# extract only the layer names from an assay
Layers(obj[["RNA"]])
```

Example 43 (unknown):
```unknown
IntegrateLayers
```

Example 44 (unknown):
```unknown
# create random batches
pbmc3k$batch <- sample(c("batchA", "batchB", "batchC"), ncol(pbmc3k), replace = TRUE)

# split layers
pbmc3k[["RNA"]] <- split(pbmc3k[["RNA"]], f = pbmc3k$batch)
Layers(pbmc3k[["RNA"]])

# rejoin layers
pbmc3k[["RNA"]] <- JoinLayers(pbmc3k[["RNA"]])
Layers(pbmc3k[["RNA"]])
```

Example 45 (r):
```r
# create random batches
pbmc3k$batch <- sample(c("batchA", "batchB", "batchC"), ncol(pbmc3k), replace = TRUE)

# split layers
pbmc3k[["RNA"]] <- split(pbmc3k[["RNA"]], f = pbmc3k$batch)
Layers(pbmc3k[["RNA"]])

# rejoin layers
pbmc3k[["RNA"]] <- JoinLayers(pbmc3k[["RNA"]])
Layers(pbmc3k[["RNA"]])
```

Example 46 (r):
```r
# create random batches
pbmc3k$batch <- sample(c("batchA", "batchB", "batchC"), ncol(pbmc3k), replace = TRUE)

# split layers
pbmc3k[["RNA"]] <- split(pbmc3k[["RNA"]], f = pbmc3k$batch)
Layers(pbmc3k[["RNA"]])

# rejoin layers
pbmc3k[["RNA"]] <- JoinLayers(pbmc3k[["RNA"]])
Layers(pbmc3k[["RNA"]])
```

Example 47 (unknown):
```unknown
batchA_counts <- pbmc.counts[, 1:200]
batchB_counts <- pbmc.counts[, 201:400]
batchC_counts <- pbmc.counts[, 401:600]
count_list <- list(batchA_counts, batchB_counts, batchC_counts)
names(count_list) <- c("batchA", "batchB", "batchC")

# create a Seurat object initialized with multiple layers
obj <- CreateSeuratObject(counts = count_list)
Layers(obj[["RNA"]])
```

Example 48 (r):
```r
batchA_counts <- pbmc.counts[, 1:200]
batchB_counts <- pbmc.counts[, 201:400]
batchC_counts <- pbmc.counts[, 401:600]
count_list <- list(batchA_counts, batchB_counts, batchC_counts)
names(count_list) <- c("batchA", "batchB", "batchC")

# create a Seurat object initialized with multiple layers
obj <- CreateSeuratObject(counts = count_list)
Layers(obj[["RNA"]])
```

Example 49 (r):
```r
batchA_counts <- pbmc.counts[, 1:200]
batchB_counts <- pbmc.counts[, 201:400]
batchC_counts <- pbmc.counts[, 401:600]
count_list <- list(batchA_counts, batchB_counts, batchC_counts)
names(count_list) <- c("batchA", "batchB", "batchC")

# create a Seurat object initialized with multiple layers
obj <- CreateSeuratObject(counts = count_list)
Layers(obj[["RNA"]])
```

Example 50 (python):
```python
pbmc3k <- FindVariableFeatures(pbmc3k, verbose = FALSE)
pbmc3k <- ScaleData(pbmc3k, verbose = FALSE)
pbmc3k <- RunPCA(pbmc3k, verbose = FALSE)

# return variable features

# returns information from both assay, cell embeddings and meta.data as a data.frame
fetch_df <- FetchData(object = pbmc3k, layer = "counts", vars = c("rna_MS4A1", "PC_1", "nCount_RNA"))
head(fetch_df)

# get cell embeddings
head(Embeddings(object = pbmc3k[["pca"]])[, 1:5])

# get feature loadings
head(Loadings(object = pbmc3k[["pca"]])[, 1:5])
```

Example 51 (r):
```r
pbmc3k <- FindVariableFeatures(pbmc3k, verbose = FALSE)
pbmc3k <- ScaleData(pbmc3k, verbose = FALSE)
pbmc3k <- RunPCA(pbmc3k, verbose = FALSE)

# return variable features

# returns information from both assay, cell embeddings and meta.data as a data.frame
fetch_df <- FetchData(object = pbmc3k, layer = "counts", vars = c("rna_MS4A1", "PC_1", "nCount_RNA"))
head(fetch_df)

# get cell embeddings
head(Embeddings(object = pbmc3k[["pca"]])[, 1:5])

# get feature loadings
head(Loadings(object = pbmc3k[["pca"]])[, 1:5])
```

Example 52 (r):
```r
pbmc3k <- FindVariableFeatures(pbmc3k, verbose = FALSE)
pbmc3k <- ScaleData(pbmc3k, verbose = FALSE)
pbmc3k <- RunPCA(pbmc3k, verbose = FALSE)

# return variable features

# returns information from both assay, cell embeddings and meta.data as a data.frame
fetch_df <- FetchData(object = pbmc3k, layer = "counts", vars = c("rna_MS4A1", "PC_1", "nCount_RNA"))
head(fetch_df)

# get cell embeddings
head(Embeddings(object = pbmc3k[["pca"]])[, 1:5])

# get feature loadings
head(Loadings(object = pbmc3k[["pca"]])[, 1:5])
```

Example 53 (unknown):
```unknown
sessionInfo()
```

Example 54 (r):
```r
sessionInfo()
```

Example 55 (r):
```r
sessionInfo()
```

---

## Analysis, visualization, and integration of Visium HD spatial datasets with Seurat • Seurat

**URL:** http://127.0.0.1:9173/articles_covid_sctmapping.html

**Contents:**
- Map COVID PBMC datasets to a healthy reference
    - Compiled: 2023-11-15
- Introduction: Reference mapping analysis in Seurat v5
- Load the PBMC Reference Dataset and Query Datasets
- Mapping
- Explore the mapping results
- Differential composition analysis
- Differential expression analysis
- Contents

In Seurat v5, we introduce a scalable approach for reference mapping datasets from separate studies or individuals. Reference mapping is a powerful approach to identify consistent labels across studies and perform cross-dataset analysis. We emphasize that while individual datasets are manageable in size, the aggregate of many datasets often amounts to millions of cell which do not fit in-memory. Furthermore, cross-dataset analysis is often challenged by disparate or unique cell type labels. Through reference mapping, we annotate all cells with a common reference for consistent cell type labels. Importantly, we never simultaneously load all of the cells in-memory to maintain low memory usage.

In this vignette, we reference map three publicly available datasets totaling 1,498,064 cells and 277 donors which are available through CZI cellxgene collections: Ahern, et al., Nature 2022, Jin, et al., Science 2021, and Yoshida, et al., Nature 2022. Each dataset consists of PBMCs from both healthy donors and donors diagnosed with COVID-19. Using the harmonized annotations, we demonstrate how to prepare a pseudobulk object to perform differential expression analysis across disease within cell types.

Prior to running this vignette, please install Seurat v5 and see the BPCells vignette to construct the on-disk object used in this vignette. Additionally, we map to our annotated CITE-seq reference containing 162,000 cells and 228 antibodies (Hao, Hao, et al., Cell 2021) which is available for download here.

We first load the reference (available here) and normalize the query Seurat object prepared in the BPCells interaction vignette. The query object consists of datasets from three different studies constructed using the CreateSeuratObject function, which accepts a list of BPCells matrices as input. Within the Seurat object, the three datasets reside in the RNA assay in three separate layers on-disk.

Using the same code from the v4 reference mapping vignette, we find anchors between the reference and query in the precomputed supervised PCA. We recommend the use of supervised PCA for CITE-seq reference datasets, and demonstrate how to compute this transformation in v4 reference mapping vignette. In Seurat v5, we only need to call FindTransferAnchors and MapQuery once to map all three datasets as they are all contained within the query object. Furthermore, utilizing the on-disk capabilities of BPCells, we map 1.5 million cells without ever loading them all into memory.

Next, we visualize all cells from the three studies which have been projected into a UMAP-space defined by the reference. Each cell is annotated at two levels of granularity (predicted.celltype.l1 and predicted.celltype.l2). We can compare the differing ontologies used in the original annotations (cell_type) to the now harmonized annotations (predicted.celltype.l2, for example) that were predicted from reference-mapping. Previously, the lack of standardization prevented us from directly performing integrative analysis across studies, but now we can easily compare.

We utilize our harmonized annotations to identify differences in the proportion of different cell types between healthy individuals and COVID-19 patients. For example, we noticed a reduction in MAIT cells as well as an increase in plasmablasts among COVID-19 patients.

In addition to composition analysis, we use an aggregation-based (pseudobulk) workflow to explore differential genes between healthy individuals and COVID-19 donors. We aggregate all cells within the same cell type and donor using the AggregateExpression function. This returns a Seurat object where each ‘cell’ represents the pseudobulk profile of one cell type in one individual.

Once a pseudobulk object is created, we can perform cell type-specific differential expression analysis between healthy individuals and COVID-19 donors. Here, we only visualize certain interferon-stimulated genes which are often upregulated during viral infection.

Developed by Rahul Satija, Satija Lab and Collaborators.

Site built with pkgdown 2.0.7.

**Examples:**

Example 1 (unknown):
```unknown
vignettes/COVID_SCTMapping.Rmd
```

Example 2 (unknown):
```unknown
COVID_SCTMapping.Rmd
```

Example 3 (unknown):
```unknown
library(Seurat)
library(BPCells)
library(dplyr)
library(patchwork)
library(ggplot2)
options(future.globals.maxSize = 1e9)
```

Example 4 (r):
```r
library(Seurat)
library(BPCells)
library(dplyr)
library(patchwork)
library(ggplot2)
options(future.globals.maxSize = 1e9)
```

Example 5 (unknown):
```unknown
CreateSeuratObject
```

Example 6 (unknown):
```unknown
reference <- readRDS("/brahms/hartmana/vignette_data/pbmc_multimodal_2023.rds")
object <- readRDS("/brahms/mollag/seurat_v5/vignette_data/merged_covid_object.rds")
object <- NormalizeData(object, verbose = FALSE)
```

Example 7 (r):
```r
reference <- readRDS("/brahms/hartmana/vignette_data/pbmc_multimodal_2023.rds")
object <- readRDS("/brahms/mollag/seurat_v5/vignette_data/merged_covid_object.rds")
object <- NormalizeData(object, verbose = FALSE)
```

Example 8 (r):
```r
reference <- readRDS("/brahms/hartmana/vignette_data/pbmc_multimodal_2023.rds")
object <- readRDS("/brahms/mollag/seurat_v5/vignette_data/merged_covid_object.rds")
object <- NormalizeData(object, verbose = FALSE)
```

Example 9 (unknown):
```unknown
FindTransferAnchors
```

Example 10 (unknown):
```unknown
anchor <- FindTransferAnchors(
  reference = reference,
  query = object,
  reference.reduction = "spca",
  normalization.method = "SCT",
  dims = 1:50
)
object <- MapQuery(
  anchorset = anchor,
  query = object,
  reference = reference,
  refdata = list(
    celltype.l1 = "celltype.l1",
    celltype.l2 = "celltype.l2"
  ),
  reduction.model = "wnn.umap"
)
```

Example 11 (r):
```r
anchor <- FindTransferAnchors(
  reference = reference,
  query = object,
  reference.reduction = "spca",
  normalization.method = "SCT",
  dims = 1:50
)
object <- MapQuery(
  anchorset = anchor,
  query = object,
  reference = reference,
  refdata = list(
    celltype.l1 = "celltype.l1",
    celltype.l2 = "celltype.l2"
  ),
  reduction.model = "wnn.umap"
)
```

Example 12 (r):
```r
anchor <- FindTransferAnchors(
  reference = reference,
  query = object,
  reference.reduction = "spca",
  normalization.method = "SCT",
  dims = 1:50
)
object <- MapQuery(
  anchorset = anchor,
  query = object,
  reference = reference,
  refdata = list(
    celltype.l1 = "celltype.l1",
    celltype.l2 = "celltype.l2"
  ),
  reduction.model = "wnn.umap"
)
```

Example 13 (unknown):
```unknown
predicted.celltype.l1
```

Example 14 (unknown):
```unknown
predicted.celltype.l2
```

Example 15 (unknown):
```unknown
predicted.celltype.l2
```

Example 16 (unknown):
```unknown
DimPlot(object, reduction = "ref.umap", group.by = "cell_type", alpha = 0.1, label = TRUE, split.by = "publication", ncol = 3, label.size = 3) + NoLegend()
```

Example 17 (r):
```r
DimPlot(object, reduction = "ref.umap", group.by = "cell_type", alpha = 0.1, label = TRUE, split.by = "publication", ncol = 3, label.size = 3) + NoLegend()
```

Example 18 (r):
```r
DimPlot(object, reduction = "ref.umap", group.by = "cell_type", alpha = 0.1, label = TRUE, split.by = "publication", ncol = 3, label.size = 3) + NoLegend()
```

Example 19 (unknown):
```unknown
DimPlot(object, reduction = "ref.umap", group.by = "predicted.celltype.l2", alpha = 0.1, label = TRUE, split.by = "publication", ncol = 3, label.size = 3) + NoLegend()
```

Example 20 (r):
```r
DimPlot(object, reduction = "ref.umap", group.by = "predicted.celltype.l2", alpha = 0.1, label = TRUE, split.by = "publication", ncol = 3, label.size = 3) + NoLegend()
```

Example 21 (r):
```r
DimPlot(object, reduction = "ref.umap", group.by = "predicted.celltype.l2", alpha = 0.1, label = TRUE, split.by = "publication", ncol = 3, label.size = 3) + NoLegend()
```

Example 22 (unknown):
```unknown
df_comp <- as.data.frame.matrix(table(object$donor_id, object$predicted.celltype.l2))
select.donors <- rownames(df_comp)[rowSums(df_comp) > 50]
df_comp <- df_comp[select.donors, ]
df_comp_relative <- sweep(x = df_comp, MARGIN = 1, STATS = rowSums(df_comp), FUN = "/")

df_disease <- as.data.frame.matrix(table(object$donor_id, object$disease))[select.donors, ]

df_comp_relative$disease <- "other"
df_comp_relative$disease[df_disease$normal != 0] <- "normal"
df_comp_relative$disease[df_disease$`COVID-19` != 0] <- "COVID-19"
df_comp_relative$disease <- factor(df_comp_relative$disease, levels = c("normal", "COVID-19", "other"))
df_comp_relative <- df_comp_relative[df_comp_relative$disease %in% c("normal", "COVID-19"), ]
```

Example 23 (r):
```r
df_comp <- as.data.frame.matrix(table(object$donor_id, object$predicted.celltype.l2))
select.donors <- rownames(df_comp)[rowSums(df_comp) > 50]
df_comp <- df_comp[select.donors, ]
df_comp_relative <- sweep(x = df_comp, MARGIN = 1, STATS = rowSums(df_comp), FUN = "/")

df_disease <- as.data.frame.matrix(table(object$donor_id, object$disease))[select.donors, ]

df_comp_relative$disease <- "other"
df_comp_relative$disease[df_disease$normal != 0] <- "normal"
df_comp_relative$disease[df_disease$`COVID-19` != 0] <- "COVID-19"
df_comp_relative$disease <- factor(df_comp_relative$disease, levels = c("normal", "COVID-19", "other"))
df_comp_relative <- df_comp_relative[df_comp_relative$disease %in% c("normal", "COVID-19"), ]
```

Example 24 (r):
```r
df_comp <- as.data.frame.matrix(table(object$donor_id, object$predicted.celltype.l2))
select.donors <- rownames(df_comp)[rowSums(df_comp) > 50]
df_comp <- df_comp[select.donors, ]
df_comp_relative <- sweep(x = df_comp, MARGIN = 1, STATS = rowSums(df_comp), FUN = "/")

df_disease <- as.data.frame.matrix(table(object$donor_id, object$disease))[select.donors, ]

df_comp_relative$disease <- "other"
df_comp_relative$disease[df_disease$normal != 0] <- "normal"
df_comp_relative$disease[df_disease$`COVID-19` != 0] <- "COVID-19"
df_comp_relative$disease <- factor(df_comp_relative$disease, levels = c("normal", "COVID-19", "other"))
df_comp_relative <- df_comp_relative[df_comp_relative$disease %in% c("normal", "COVID-19"), ]
```

Example 25 (python):
```python
p1 <- ggplot(data = df_comp_relative, mapping = aes(x = disease, y = MAIT, fill = disease)) +
  geom_boxplot(outlier.shape = NA) +
  scale_fill_manual(values = c("#377eb8", "#e41a1c")) +
  xlab("") +
  ylab("relative abundance") +
  ggtitle("MAIT") +
  geom_jitter(color = "black", size = 0.4, alpha = 0.9) +
  theme_bw() +
  theme(
    axis.title = element_text(size = 12),
    axis.text = element_text(size = 12),
    plot.title = element_text(size = 15, hjust = 0.5, face = "bold")
  )

p2 <- ggplot(data = df_comp_relative, mapping = aes(x = disease, y = Plasmablast, fill = disease)) +
  geom_boxplot(outlier.shape = NA) +
  scale_fill_manual(values = c("#377eb8", "#e41a1c")) +
  xlab("") +
  ylab("relative abundance") +
  ggtitle("Plasmablast") +
  geom_jitter(color = "black", size = 0.4, alpha = 0.9) +
  theme_bw() +
  theme(
    axis.title = element_text(size = 12),
    axis.text = element_text(size = 12),
    plot.title = element_text(size = 15, hjust = 0.5, face = "bold")
  )

p1 + p2 + plot_layout(ncol = 2)
```

Example 26 (r):
```r
p1 <- ggplot(data = df_comp_relative, mapping = aes(x = disease, y = MAIT, fill = disease)) +
  geom_boxplot(outlier.shape = NA) +
  scale_fill_manual(values = c("#377eb8", "#e41a1c")) +
  xlab("") +
  ylab("relative abundance") +
  ggtitle("MAIT") +
  geom_jitter(color = "black", size = 0.4, alpha = 0.9) +
  theme_bw() +
  theme(
    axis.title = element_text(size = 12),
    axis.text = element_text(size = 12),
    plot.title = element_text(size = 15, hjust = 0.5, face = "bold")
  )

p2 <- ggplot(data = df_comp_relative, mapping = aes(x = disease, y = Plasmablast, fill = disease)) +
  geom_boxplot(outlier.shape = NA) +
  scale_fill_manual(values = c("#377eb8", "#e41a1c")) +
  xlab("") +
  ylab("relative abundance") +
  ggtitle("Plasmablast") +
  geom_jitter(color = "black", size = 0.4, alpha = 0.9) +
  theme_bw() +
  theme(
    axis.title = element_text(size = 12),
    axis.text = element_text(size = 12),
    plot.title = element_text(size = 15, hjust = 0.5, face = "bold")
  )

p1 + p2 + plot_layout(ncol = 2)
```

Example 27 (r):
```r
p1 <- ggplot(data = df_comp_relative, mapping = aes(x = disease, y = MAIT, fill = disease)) +
  geom_boxplot(outlier.shape = NA) +
  scale_fill_manual(values = c("#377eb8", "#e41a1c")) +
  xlab("") +
  ylab("relative abundance") +
  ggtitle("MAIT") +
  geom_jitter(color = "black", size = 0.4, alpha = 0.9) +
  theme_bw() +
  theme(
    axis.title = element_text(size = 12),
    axis.text = element_text(size = 12),
    plot.title = element_text(size = 15, hjust = 0.5, face = "bold")
  )

p2 <- ggplot(data = df_comp_relative, mapping = aes(x = disease, y = Plasmablast, fill = disease)) +
  geom_boxplot(outlier.shape = NA) +
  scale_fill_manual(values = c("#377eb8", "#e41a1c")) +
  xlab("") +
  ylab("relative abundance") +
  ggtitle("Plasmablast") +
  geom_jitter(color = "black", size = 0.4, alpha = 0.9) +
  theme_bw() +
  theme(
    axis.title = element_text(size = 12),
    axis.text = element_text(size = 12),
    plot.title = element_text(size = 15, hjust = 0.5, face = "bold")
  )

p1 + p2 + plot_layout(ncol = 2)
```

Example 28 (unknown):
```unknown
AggregateExpression
```

Example 29 (unknown):
```unknown
bulk <- AggregateExpression(object,
  return.seurat = TRUE,
  assays = "RNA",
  group.by = c("predicted.celltype.l2", "donor_id", "disease")
)
```

Example 30 (r):
```r
bulk <- AggregateExpression(object,
  return.seurat = TRUE,
  assays = "RNA",
  group.by = c("predicted.celltype.l2", "donor_id", "disease")
)
```

Example 31 (r):
```r
bulk <- AggregateExpression(object,
  return.seurat = TRUE,
  assays = "RNA",
  group.by = c("predicted.celltype.l2", "donor_id", "disease")
)
```

Example 32 (unknown):
```unknown
bulk <- subset(bulk, subset = disease %in% c("normal", "COVID-19"))
bulk <- subset(bulk, subset = predicted.celltype.l2 != "Doublet")
bulk$disease <- factor(bulk$disease, levels = c("normal", "COVID-19"))
```

Example 33 (r):
```r
bulk <- subset(bulk, subset = disease %in% c("normal", "COVID-19"))
bulk <- subset(bulk, subset = predicted.celltype.l2 != "Doublet")
bulk$disease <- factor(bulk$disease, levels = c("normal", "COVID-19"))
```

Example 34 (r):
```r
bulk <- subset(bulk, subset = disease %in% c("normal", "COVID-19"))
bulk <- subset(bulk, subset = predicted.celltype.l2 != "Doublet")
bulk$disease <- factor(bulk$disease, levels = c("normal", "COVID-19"))
```

Example 35 (unknown):
```unknown
p1 <- VlnPlot(
  object = bulk, features = "IFI6", group.by = "predicted.celltype.l2",
  split.by = "disease", cols = c("#377eb8", "#e41a1c")
)
p2 <- VlnPlot(
  object = bulk, features = c("ISG15"), group.by = "predicted.celltype.l2",
  split.by = "disease", cols = c("#377eb8", "#e41a1c")
)
p3 <- VlnPlot(
  object = bulk, features = c("IFIT5"), group.by = "predicted.celltype.l2",
  split.by = "disease", cols = c("#377eb8", "#e41a1c")
)
p1 + p2 + p3 + plot_layout(ncol = 1)
```

Example 36 (r):
```r
p1 <- VlnPlot(
  object = bulk, features = "IFI6", group.by = "predicted.celltype.l2",
  split.by = "disease", cols = c("#377eb8", "#e41a1c")
)
p2 <- VlnPlot(
  object = bulk, features = c("ISG15"), group.by = "predicted.celltype.l2",
  split.by = "disease", cols = c("#377eb8", "#e41a1c")
)
p3 <- VlnPlot(
  object = bulk, features = c("IFIT5"), group.by = "predicted.celltype.l2",
  split.by = "disease", cols = c("#377eb8", "#e41a1c")
)
p1 + p2 + p3 + plot_layout(ncol = 1)
```

Example 37 (r):
```r
p1 <- VlnPlot(
  object = bulk, features = "IFI6", group.by = "predicted.celltype.l2",
  split.by = "disease", cols = c("#377eb8", "#e41a1c")
)
p2 <- VlnPlot(
  object = bulk, features = c("ISG15"), group.by = "predicted.celltype.l2",
  split.by = "disease", cols = c("#377eb8", "#e41a1c")
)
p3 <- VlnPlot(
  object = bulk, features = c("IFIT5"), group.by = "predicted.celltype.l2",
  split.by = "disease", cols = c("#377eb8", "#e41a1c")
)
p1 + p2 + p3 + plot_layout(ncol = 1)
```

Example 38 (unknown):
```unknown
sessionInfo()
```

Example 39 (r):
```r
sessionInfo()
```

Example 40 (r):
```r
sessionInfo()
```

Example 41 (unknown):
```unknown
## R version 4.2.2 Patched (2022-11-10 r83330)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.6 LTS
## 
## Matrix products: default
## BLAS:   /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.9.0
## LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.9.0
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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       
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
## [1] ggplot2_3.4.4      patchwork_1.1.3    dplyr_1.1.3        BPCells_0.1.0     
## [5] Seurat_5.0.1  testthat_3.2.0     SeuratObject_5.0.1 sp_2.1-1          
## 
## loaded via a namespace (and not attached):
##   [1] utf8_1.2.4             spatstat.explore_3.2-5 reticulate_1.34.0     
##   [4] R.utils_2.12.2         tidyselect_1.2.0       htmlwidgets_1.6.2     
##   [7] grid_4.2.2             Rtsne_0.16             devtools_2.4.5        
##  [10] munsell_0.5.0          codetools_0.2-19       ragg_1.2.5            
##  [13] ica_1.0-3              future_1.33.0          miniUI_0.1.1.1        
##  [16] withr_2.5.2            spatstat.random_3.2-1  colorspace_2.1-0      
##  [19] progressr_0.14.0       highr_0.10             knitr_1.45            
##  [22] rstudioapi_0.14        stats4_4.2.2           ROCR_1.0-11           
##  [25] tensor_1.5             listenv_0.9.0          labeling_0.4.3        
##  [28] GenomeInfoDbData_1.2.9 polyclip_1.10-6        farver_2.1.1          
##  [31] rprojroot_2.0.4        parallelly_1.36.0      vctrs_0.6.4           
##  [34] generics_0.1.3         xfun_0.40              R6_2.5.1              
##  [37] GenomeInfoDb_1.34.9    ggbeeswarm_0.7.1       bitops_1.0-7          
##  [40] spatstat.utils_3.0-4   cachem_1.0.8           promises_1.2.1        
##  [43] scales_1.2.1           beeswarm_0.4.0         gtable_0.3.4          
##  [46] globals_0.16.2         processx_3.8.2         goftest_1.2-3         
##  [49] spam_2.10-0            rlang_1.1.1            systemfonts_1.0.4     
##  [52] splines_4.2.2          lazyeval_0.2.2         spatstat.geom_3.2-7   
##  [55] yaml_2.3.7             reshape2_1.4.4         abind_1.4-5           
##  [58] httpuv_1.6.12          tools_4.2.2            usethis_2.1.6         
##  [61] ellipsis_0.3.2         jquerylib_0.1.4        RColorBrewer_1.1-3    
##  [64] BiocGenerics_0.44.0    sessioninfo_1.2.2      ggridges_0.5.4        
##  [67] Rcpp_1.0.11            plyr_1.8.9             zlibbioc_1.44.0       
##  [70] purrr_1.0.2            RCurl_1.98-1.12        ps_1.7.5              
##  [73] prettyunits_1.2.0      deldir_1.0-9           pbapply_1.7-2         
##  [76] cowplot_1.1.1          urlchecker_1.0.1       S4Vectors_0.36.2      
##  [79] zoo_1.8-12             ggrepel_0.9.4          cluster_2.1.4         
##  [82] fs_1.6.3               magrittr_2.0.3         data.table_1.14.8     
##  [85] RSpectra_0.16-1        scattermore_1.2        lmtest_0.9-40         
##  [88] RANN_2.6.1             fitdistrplus_1.1-11    R.cache_0.16.0        
##  [91] matrixStats_1.0.0      pkgload_1.3.3          mime_0.12             
##  [94] evaluate_0.22          xtable_1.8-4           fastDummies_1.7.3     
##  [97] IRanges_2.32.0         gridExtra_2.3          compiler_4.2.2        
## [100] tibble_3.2.1           KernSmooth_2.23-22     crayon_1.5.2          
## [103] R.oo_1.25.0            htmltools_0.5.6.1      later_1.3.1           
## [106] tidyr_1.3.0            MASS_7.3-58.2          Matrix_1.6-1.1        
## [109] brio_1.1.3             cli_3.6.1              R.methodsS3_1.8.2     
## [112] parallel_4.2.2         dotCall64_1.1-0        igraph_1.5.1          
## [115] GenomicRanges_1.50.2   pkgconfig_2.0.3        pkgdown_2.0.7         
## [118] plotly_4.10.3          spatstat.sparse_3.0-3  vipor_0.4.5           
## [121] bslib_0.5.1            XVector_0.38.0         stringr_1.5.0         
## [124] callr_3.7.3            digest_0.6.33          sctransform_0.4.1     
## [127] RcppAnnoy_0.0.21       spatstat.data_3.0-3    rmarkdown_2.25        
## [130] leiden_0.4.3           uwot_0.1.16            shiny_1.7.5.1         
## [133] lifecycle_1.0.4        nlme_3.1-162           jsonlite_1.8.7        
## [136] desc_1.4.2             viridisLite_0.4.2      fansi_1.0.5           
## [139] pillar_1.9.0           lattice_0.21-9         ggrastr_1.0.1         
## [142] fastmap_1.1.1          httr_1.4.7             pkgbuild_1.4.2        
## [145] survival_3.5-7         glue_1.6.2             remotes_2.4.2.1       
## [148] png_0.1-8              stringi_1.7.12         sass_0.4.7            
## [151] profvis_0.3.7          textshaping_0.3.6      RcppHNSW_0.5.0        
## [154] memoise_2.0.1          styler_1.10.2          irlba_2.3.5.1         
## [157] future.apply_1.11.0
```

Example 42 (unknown):
```unknown
## R version 4.2.2 Patched (2022-11-10 r83330)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.6 LTS
## 
## Matrix products: default
## BLAS:   /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.9.0
## LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.9.0
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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       
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
## [1] ggplot2_3.4.4      patchwork_1.1.3    dplyr_1.1.3        BPCells_0.1.0     
## [5] Seurat_5.0.1  testthat_3.2.0     SeuratObject_5.0.1 sp_2.1-1          
## 
## loaded via a namespace (and not attached):
##   [1] utf8_1.2.4             spatstat.explore_3.2-5 reticulate_1.34.0     
##   [4] R.utils_2.12.2         tidyselect_1.2.0       htmlwidgets_1.6.2     
##   [7] grid_4.2.2             Rtsne_0.16             devtools_2.4.5        
##  [10] munsell_0.5.0          codetools_0.2-19       ragg_1.2.5            
##  [13] ica_1.0-3              future_1.33.0          miniUI_0.1.1.1        
##  [16] withr_2.5.2            spatstat.random_3.2-1  colorspace_2.1-0      
##  [19] progressr_0.14.0       highr_0.10             knitr_1.45            
##  [22] rstudioapi_0.14        stats4_4.2.2           ROCR_1.0-11           
##  [25] tensor_1.5             listenv_0.9.0          labeling_0.4.3        
##  [28] GenomeInfoDbData_1.2.9 polyclip_1.10-6        farver_2.1.1          
##  [31] rprojroot_2.0.4        parallelly_1.36.0      vctrs_0.6.4           
##  [34] generics_0.1.3         xfun_0.40              R6_2.5.1              
##  [37] GenomeInfoDb_1.34.9    ggbeeswarm_0.7.1       bitops_1.0-7          
##  [40] spatstat.utils_3.0-4   cachem_1.0.8           promises_1.2.1        
##  [43] scales_1.2.1           beeswarm_0.4.0         gtable_0.3.4          
##  [46] globals_0.16.2         processx_3.8.2         goftest_1.2-3         
##  [49] spam_2.10-0            rlang_1.1.1            systemfonts_1.0.4     
##  [52] splines_4.2.2          lazyeval_0.2.2         spatstat.geom_3.2-7   
##  [55] yaml_2.3.7             reshape2_1.4.4         abind_1.4-5           
##  [58] httpuv_1.6.12          tools_4.2.2            usethis_2.1.6         
##  [61] ellipsis_0.3.2         jquerylib_0.1.4        RColorBrewer_1.1-3    
##  [64] BiocGenerics_0.44.0    sessioninfo_1.2.2      ggridges_0.5.4        
##  [67] Rcpp_1.0.11            plyr_1.8.9             zlibbioc_1.44.0       
##  [70] purrr_1.0.2            RCurl_1.98-1.12        ps_1.7.5              
##  [73] prettyunits_1.2.0      deldir_1.0-9           pbapply_1.7-2         
##  [76] cowplot_1.1.1          urlchecker_1.0.1       S4Vectors_0.36.2      
##  [79] zoo_1.8-12             ggrepel_0.9.4          cluster_2.1.4         
##  [82] fs_1.6.3               magrittr_2.0.3         data.table_1.14.8     
##  [85] RSpectra_0.16-1        scattermore_1.2        lmtest_0.9-40         
##  [88] RANN_2.6.1             fitdistrplus_1.1-11    R.cache_0.16.0        
##  [91] matrixStats_1.0.0      pkgload_1.3.3          mime_0.12             
##  [94] evaluate_0.22          xtable_1.8-4           fastDummies_1.7.3     
##  [97] IRanges_2.32.0         gridExtra_2.3          compiler_4.2.2        
## [100] tibble_3.2.1           KernSmooth_2.23-22     crayon_1.5.2          
## [103] R.oo_1.25.0            htmltools_0.5.6.1      later_1.3.1           
## [106] tidyr_1.3.0            MASS_7.3-58.2          Matrix_1.6-1.1        
## [109] brio_1.1.3             cli_3.6.1              R.methodsS3_1.8.2     
## [112] parallel_4.2.2         dotCall64_1.1-0        igraph_1.5.1          
## [115] GenomicRanges_1.50.2   pkgconfig_2.0.3        pkgdown_2.0.7         
## [118] plotly_4.10.3          spatstat.sparse_3.0-3  vipor_0.4.5           
## [121] bslib_0.5.1            XVector_0.38.0         stringr_1.5.0         
## [124] callr_3.7.3            digest_0.6.33          sctransform_0.4.1     
## [127] RcppAnnoy_0.0.21       spatstat.data_3.0-3    rmarkdown_2.25        
## [130] leiden_0.4.3           uwot_0.1.16            shiny_1.7.5.1         
## [133] lifecycle_1.0.4        nlme_3.1-162           jsonlite_1.8.7        
## [136] desc_1.4.2             viridisLite_0.4.2      fansi_1.0.5           
## [139] pillar_1.9.0           lattice_0.21-9         ggrastr_1.0.1         
## [142] fastmap_1.1.1          httr_1.4.7             pkgbuild_1.4.2        
## [145] survival_3.5-7         glue_1.6.2             remotes_2.4.2.1       
## [148] png_0.1-8              stringi_1.7.12         sass_0.4.7            
## [151] profvis_0.3.7          textshaping_0.3.6      RcppHNSW_0.5.0        
## [154] memoise_2.0.1          styler_1.10.2          irlba_2.3.5.1         
## [157] future.apply_1.11.0
```

---

## Analysis, visualization, and integration of Visium HD spatial datasets with Seurat • Seurat

**URL:** http://127.0.0.1:9173/seurat/essential_commands.html

**Contents:**
- Seurat Command List
    - Compiled: 2023-10-31
- Standard Seurat workflow
  - SCtransform version
- Seurat Object Data Access
  - Cell, feature, and layer names
  - Identity class labels
  - Cell metadata
  - Expression data (stored as layers in Seurat v5)
  - Dimensional reductions
  - FetchData
- Subsetting and merging
  - Subset Seurat objects
  - Split layers
  - Split objects
  - Merge objects (without integration)
  - Merge objects (with integration)
- Pseudobulk analysis
  - Group cells together, based on multiple categories
- Visualization in Seurat
- Multi-Assay Features
- Additional resources
- Contents

In Seurat v5, merging creates a single object, but keeps the expression information split into different layers for integration. If not proceeding with integration, rejoin the layers after merging.

See introduction to integration for more information.

See DE vignette for information on how to add the donor_id column to meta data.

Seurat has a vast, ggplot2-based plotting library. All plotting functions will return a ggplot2 plot by default, allowing easy customization with ggplot2.

Seurat provides many prebuilt themes that can be added to ggplot2 plots for quick customization

With Seurat, you can easily switch between different assays at the single cell level (such as ADT counts from CITE-seq, or integrated/batch-corrected data). Most functions now take an assay parameter, but you can set a Default Assay to avoid repetitive statements.

Users who are particularly interested in some of the technical changes to data storage in Seurat v5 can explore the following resources:

Developed by Rahul Satija, Satija Lab and Collaborators.

Site built with pkgdown 2.0.7.

**Examples:**

Example 1 (unknown):
```unknown
vignettes/essential_commands.Rmd
```

Example 2 (unknown):
```unknown
essential_commands.Rmd
```

Example 3 (unknown):
```unknown
pbmc <- NormalizeData(object = pbmc)
pbmc <- FindVariableFeatures(object = pbmc)
pbmc <- ScaleData(object = pbmc)
pbmc <- RunPCA(object = pbmc)
pbmc <- FindNeighbors(object = pbmc, dims = 1:30)
pbmc <- FindClusters(object = pbmc)
pbmc <- RunUMAP(object = pbmc, dims = 1:30)
DimPlot(object = pbmc, reduction = "umap")
```

Example 4 (r):
```r
pbmc <- NormalizeData(object = pbmc)
pbmc <- FindVariableFeatures(object = pbmc)
pbmc <- ScaleData(object = pbmc)
pbmc <- RunPCA(object = pbmc)
pbmc <- FindNeighbors(object = pbmc, dims = 1:30)
pbmc <- FindClusters(object = pbmc)
pbmc <- RunUMAP(object = pbmc, dims = 1:30)
DimPlot(object = pbmc, reduction = "umap")
```

Example 5 (r):
```r
pbmc <- NormalizeData(object = pbmc)
pbmc <- FindVariableFeatures(object = pbmc)
pbmc <- ScaleData(object = pbmc)
pbmc <- RunPCA(object = pbmc)
pbmc <- FindNeighbors(object = pbmc, dims = 1:30)
pbmc <- FindClusters(object = pbmc)
pbmc <- RunUMAP(object = pbmc, dims = 1:30)
DimPlot(object = pbmc, reduction = "umap")
```

Example 6 (unknown):
```unknown
pbmc <- SCTransform(object = pbmc)
pbmc <- RunPCA(object = pbmc)
pbmc <- FindNeighbors(object = pbmc, dims = 1:30)
pbmc <- FindClusters(object = pbmc)
pbmc <- RunUMAP(object = pbmc, dims = 1:30)
DimPlot(object = pbmc, reduction = "umap")
```

Example 7 (r):
```r
pbmc <- SCTransform(object = pbmc)
pbmc <- RunPCA(object = pbmc)
pbmc <- FindNeighbors(object = pbmc, dims = 1:30)
pbmc <- FindClusters(object = pbmc)
pbmc <- RunUMAP(object = pbmc, dims = 1:30)
DimPlot(object = pbmc, reduction = "umap")
```

Example 8 (r):
```r
pbmc <- SCTransform(object = pbmc)
pbmc <- RunPCA(object = pbmc)
pbmc <- FindNeighbors(object = pbmc, dims = 1:30)
pbmc <- FindClusters(object = pbmc)
pbmc <- RunUMAP(object = pbmc, dims = 1:30)
DimPlot(object = pbmc, reduction = "umap")
```

Example 9 (unknown):
```unknown
# note that you can chain multiple commands together with %>%
pbmc <- SCTransform(pbmc) %>%
    RunPCA() %>%
    FindNeighbors(dims = 1:30) %>%
    FindClusters() %>%
    RunUMAP(dims = 1:30)
```

Example 10 (r):
```r
# note that you can chain multiple commands together with %>%
pbmc <- SCTransform(pbmc) %>%
    RunPCA() %>%
    FindNeighbors(dims = 1:30) %>%
    FindClusters() %>%
    RunUMAP(dims = 1:30)
```

Example 11 (r):
```r
# note that you can chain multiple commands together with %>%
pbmc <- SCTransform(pbmc) %>%
    RunPCA() %>%
    FindNeighbors(dims = 1:30) %>%
    FindClusters() %>%
    RunUMAP(dims = 1:30)
```

Example 12 (unknown):
```unknown
# Get cell and feature names, and total numbers We show multiple ways to get the same output cell names
colnames(pbmc)
Cells(pbmc)

# feature names
Features(pbmc)
rownames(pbmc)

# number of cells/features
num_cells <- ncol(pbmc)
num_features <- nrow(pbmc)

# List of object layers
Layers(pbmc)

# working with multimodal objects list assays
Assays(cbmc)

# Assay-specific features (genes/ADT)
Features(cbmc[["RNA"]])
Features(cbmc[["ADT"]])

# Variable feature names
VariableFeatures(pbmc)
```

Example 13 (r):
```r
# Get cell and feature names, and total numbers We show multiple ways to get the same output cell names
colnames(pbmc)
Cells(pbmc)

# feature names
Features(pbmc)
rownames(pbmc)

# number of cells/features
num_cells <- ncol(pbmc)
num_features <- nrow(pbmc)

# List of object layers
Layers(pbmc)

# working with multimodal objects list assays
Assays(cbmc)

# Assay-specific features (genes/ADT)
Features(cbmc[["RNA"]])
Features(cbmc[["ADT"]])

# Variable feature names
VariableFeatures(pbmc)
```

Example 14 (r):
```r
# Get cell and feature names, and total numbers We show multiple ways to get the same output cell names
colnames(pbmc)
Cells(pbmc)

# feature names
Features(pbmc)
rownames(pbmc)

# number of cells/features
num_cells <- ncol(pbmc)
num_features <- nrow(pbmc)

# List of object layers
Layers(pbmc)

# working with multimodal objects list assays
Assays(cbmc)

# Assay-specific features (genes/ADT)
Features(cbmc[["RNA"]])
Features(cbmc[["ADT"]])

# Variable feature names
VariableFeatures(pbmc)
```

Example 15 (unknown):
```unknown
# Set variable features
VariableFeatures(cbmc) <- var.gene.names

# set for a specific assay
VariableFeatures(cbmc[["ADT"]]) <- var.gene.names
```

Example 16 (r):
```r
# Set variable features
VariableFeatures(cbmc) <- var.gene.names

# set for a specific assay
VariableFeatures(cbmc[["ADT"]]) <- var.gene.names
```

Example 17 (r):
```r
# Set variable features
VariableFeatures(cbmc) <- var.gene.names

# set for a specific assay
VariableFeatures(cbmc[["ADT"]]) <- var.gene.names
```

Example 18 (python):
```python
# Setting and retrieving cell identities

# Set identity classes to an existing column in meta data
Idents(object = pbmc) <- "seurat_annotations"

# View cell identities, get summary table
Idents(pbmc)
table(Idents(pbmc))

# Set identity to CD4 T cells for all cells
Idents(pbmc) <- "CD4 T cells"

# Set for a selected group of cells
pbmc.cells <- Cells(pbmc)
Idents(object = pbmc, cells = pbmc.cells[1:10]) <- "CD4 T cells"

# Get cell identity classes
Idents(object = pbmc)
levels(x = pbmc)

# Stash cell identity classes in metadata
pbmc[["old.ident"]] <- Idents(object = pbmc)
pbmc <- StashIdent(object = pbmc, save.name = "old.ident")

# Rename identity classes
pbmc <- RenameIdents(object = pbmc, `CD4 T cells` = "T Helper cells")
```

Example 19 (r):
```r
# Setting and retrieving cell identities

# Set identity classes to an existing column in meta data
Idents(object = pbmc) <- "seurat_annotations"

# View cell identities, get summary table
Idents(pbmc)
table(Idents(pbmc))

# Set identity to CD4 T cells for all cells
Idents(pbmc) <- "CD4 T cells"

# Set for a selected group of cells
pbmc.cells <- Cells(pbmc)
Idents(object = pbmc, cells = pbmc.cells[1:10]) <- "CD4 T cells"

# Get cell identity classes
Idents(object = pbmc)
levels(x = pbmc)

# Stash cell identity classes in metadata
pbmc[["old.ident"]] <- Idents(object = pbmc)
pbmc <- StashIdent(object = pbmc, save.name = "old.ident")

# Rename identity classes
pbmc <- RenameIdents(object = pbmc, `CD4 T cells` = "T Helper cells")
```

Example 20 (r):
```r
# Setting and retrieving cell identities

# Set identity classes to an existing column in meta data
Idents(object = pbmc) <- "seurat_annotations"

# View cell identities, get summary table
Idents(pbmc)
table(Idents(pbmc))

# Set identity to CD4 T cells for all cells
Idents(pbmc) <- "CD4 T cells"

# Set for a selected group of cells
pbmc.cells <- Cells(pbmc)
Idents(object = pbmc, cells = pbmc.cells[1:10]) <- "CD4 T cells"

# Get cell identity classes
Idents(object = pbmc)
levels(x = pbmc)

# Stash cell identity classes in metadata
pbmc[["old.ident"]] <- Idents(object = pbmc)
pbmc <- StashIdent(object = pbmc, save.name = "old.ident")

# Rename identity classes
pbmc <- RenameIdents(object = pbmc, `CD4 T cells` = "T Helper cells")
```

Example 21 (python):
```python
# View metadata data frame, stored in object@meta.data
pbmc[[]]

# Retrieve specific values from the metadata
pbmc$nCount_RNA
pbmc[[c("percent.mito", "nFeature_RNA")]]

# Add metadata, see ?AddMetaData
random_group_labels <- sample(x = c("g1", "g2"), size = ncol(x = pbmc), replace = TRUE)
pbmc$groups <- random_group_labels
```

Example 22 (r):
```r
# View metadata data frame, stored in object@meta.data
pbmc[[]]

# Retrieve specific values from the metadata
pbmc$nCount_RNA
pbmc[[c("percent.mito", "nFeature_RNA")]]

# Add metadata, see ?AddMetaData
random_group_labels <- sample(x = c("g1", "g2"), size = ncol(x = pbmc), replace = TRUE)
pbmc$groups <- random_group_labels
```

Example 23 (r):
```r
# View metadata data frame, stored in object@meta.data
pbmc[[]]

# Retrieve specific values from the metadata
pbmc$nCount_RNA
pbmc[[c("percent.mito", "nFeature_RNA")]]

# Add metadata, see ?AddMetaData
random_group_labels <- sample(x = c("g1", "g2"), size = ncol(x = pbmc), replace = TRUE)
pbmc$groups <- random_group_labels
```

Example 24 (python):
```python
# Retrieve data in an expression matrix RNA counts matrix
pbmc[["RNA"]]$counts

# Alternate accessor function with the same result
LayerData(pbmc, assay = "RNA", layer = "counts")

# GetAssayData from Seurat v4 is still supported
GetAssayData(object = pbmc, assay = "RNA", slot = "counts")

# ADT counts matrix (multimodal object)
cbmc[["ADT"]]$counts
```

Example 25 (r):
```r
# Retrieve data in an expression matrix RNA counts matrix
pbmc[["RNA"]]$counts

# Alternate accessor function with the same result
LayerData(pbmc, assay = "RNA", layer = "counts")

# GetAssayData from Seurat v4 is still supported
GetAssayData(object = pbmc, assay = "RNA", slot = "counts")

# ADT counts matrix (multimodal object)
cbmc[["ADT"]]$counts
```

Example 26 (r):
```r
# Retrieve data in an expression matrix RNA counts matrix
pbmc[["RNA"]]$counts

# Alternate accessor function with the same result
LayerData(pbmc, assay = "RNA", layer = "counts")

# GetAssayData from Seurat v4 is still supported
GetAssayData(object = pbmc, assay = "RNA", slot = "counts")

# ADT counts matrix (multimodal object)
cbmc[["ADT"]]$counts
```

Example 27 (python):
```python
# Set expression data assume new.data is a new expression matrix
pbmc[["RNA"]]$counts <- new.data

# Alternate setter function with the same result
LayerData(pbmc, assay = "RNA", layer = "counts") <- new.data

# SetAssayData from Seurat v4 is still supported
pbmc <- SetAssayData(object = pbmc, slot = "counts", new.data = new.data)
```

Example 28 (r):
```r
# Set expression data assume new.data is a new expression matrix
pbmc[["RNA"]]$counts <- new.data

# Alternate setter function with the same result
LayerData(pbmc, assay = "RNA", layer = "counts") <- new.data

# SetAssayData from Seurat v4 is still supported
pbmc <- SetAssayData(object = pbmc, slot = "counts", new.data = new.data)
```

Example 29 (r):
```r
# Set expression data assume new.data is a new expression matrix
pbmc[["RNA"]]$counts <- new.data

# Alternate setter function with the same result
LayerData(pbmc, assay = "RNA", layer = "counts") <- new.data

# SetAssayData from Seurat v4 is still supported
pbmc <- SetAssayData(object = pbmc, slot = "counts", new.data = new.data)
```

Example 30 (unknown):
```unknown
# Get cell embeddings and feature loadings stored on pbmc[['pca']]@cell.embeddings
Embeddings(pbmc, reduction = "pca")

# stored in pbmc[['pca]]@feature.loadings
Loadings(pbmc, reduction = "pca")
```

Example 31 (r):
```r
# Get cell embeddings and feature loadings stored on pbmc[['pca']]@cell.embeddings
Embeddings(pbmc, reduction = "pca")

# stored in pbmc[['pca]]@feature.loadings
Loadings(pbmc, reduction = "pca")
```

Example 32 (r):
```r
# Get cell embeddings and feature loadings stored on pbmc[['pca']]@cell.embeddings
Embeddings(pbmc, reduction = "pca")

# stored in pbmc[['pca]]@feature.loadings
Loadings(pbmc, reduction = "pca")
```

Example 33 (unknown):
```unknown
# Create custom dimensional reduction loadings matrix is optional
new_reduction <- CreateDimReducObject(embeddings = new.embeddings, loadings = new.loadings, key = "custom_pca")
pbmc[["custom_pca"]] <- new_reduction
```

Example 34 (r):
```r
# Create custom dimensional reduction loadings matrix is optional
new_reduction <- CreateDimReducObject(embeddings = new.embeddings, loadings = new.loadings, key = "custom_pca")
pbmc[["custom_pca"]] <- new_reduction
```

Example 35 (r):
```r
# Create custom dimensional reduction loadings matrix is optional
new_reduction <- CreateDimReducObject(embeddings = new.embeddings, loadings = new.loadings, key = "custom_pca")
pbmc[["custom_pca"]] <- new_reduction
```

Example 36 (python):
```python
# FetchData can access anything from expression matrices, cell embeddings, or metadata Use the previously listed
# commands to access entire matrices Use FetchData to access individual/small groups of variables
FetchData(object = pbmc, vars = c("PC_1", "nFeature_RNA", "MS4A1"), layer = "counts")
```

Example 37 (r):
```r
# FetchData can access anything from expression matrices, cell embeddings, or metadata Use the previously listed
# commands to access entire matrices Use FetchData to access individual/small groups of variables
FetchData(object = pbmc, vars = c("PC_1", "nFeature_RNA", "MS4A1"), layer = "counts")
```

Example 38 (r):
```r
# FetchData can access anything from expression matrices, cell embeddings, or metadata Use the previously listed
# commands to access entire matrices Use FetchData to access individual/small groups of variables
FetchData(object = pbmc, vars = c("PC_1", "nFeature_RNA", "MS4A1"), layer = "counts")
```

Example 39 (unknown):
```unknown
# Subset Seurat object based on identity class, also see ?SubsetData
subset(x = pbmc, idents = "B")
subset(x = pbmc, idents = c("Naive CD4 T", "CD8 T"), invert = TRUE)

# Subset on the expression level of a gene/feature
subset(x = pbmc, subset = MS4A1 > 2.5)

# Subset on a combination of criteria
subset(x = pbmc, subset = MS4A1 > 2.5 & PC_1 > 5)
subset(x = pbmc, subset = MS4A1 > 2.5, idents = "B")

# Subset on a value in the object meta data
subset(x = pbmc, subset = groups == "g1")

# Downsample the number of cells per identity class
subset(x = pbmc, downsample = 100)
```

Example 40 (r):
```r
# Subset Seurat object based on identity class, also see ?SubsetData
subset(x = pbmc, idents = "B")
subset(x = pbmc, idents = c("Naive CD4 T", "CD8 T"), invert = TRUE)

# Subset on the expression level of a gene/feature
subset(x = pbmc, subset = MS4A1 > 2.5)

# Subset on a combination of criteria
subset(x = pbmc, subset = MS4A1 > 2.5 & PC_1 > 5)
subset(x = pbmc, subset = MS4A1 > 2.5, idents = "B")

# Subset on a value in the object meta data
subset(x = pbmc, subset = groups == "g1")

# Downsample the number of cells per identity class
subset(x = pbmc, downsample = 100)
```

Example 41 (r):
```r
# Subset Seurat object based on identity class, also see ?SubsetData
subset(x = pbmc, idents = "B")
subset(x = pbmc, idents = c("Naive CD4 T", "CD8 T"), invert = TRUE)

# Subset on the expression level of a gene/feature
subset(x = pbmc, subset = MS4A1 > 2.5)

# Subset on a combination of criteria
subset(x = pbmc, subset = MS4A1 > 2.5 & PC_1 > 5)
subset(x = pbmc, subset = MS4A1 > 2.5, idents = "B")

# Subset on a value in the object meta data
subset(x = pbmc, subset = groups == "g1")

# Downsample the number of cells per identity class
subset(x = pbmc, downsample = 100)
```

Example 42 (unknown):
```unknown
# In Seurat v5, users can now split in object directly into different layers keeps expression data in one object, but
# splits multiple samples into layers can proceed directly to integration workflow after splitting layers
ifnb[["RNA"]] <- split(ifnb[["RNA"]], f = ifnb$stim)
Layers(ifnb)

# If desired, for example after intergation, the layers can be joined together again
ifnb <- JoinLayers(ifnb)
```

Example 43 (r):
```r
# In Seurat v5, users can now split in object directly into different layers keeps expression data in one object, but
# splits multiple samples into layers can proceed directly to integration workflow after splitting layers
ifnb[["RNA"]] <- split(ifnb[["RNA"]], f = ifnb$stim)
Layers(ifnb)

# If desired, for example after intergation, the layers can be joined together again
ifnb <- JoinLayers(ifnb)
```

Example 44 (r):
```r
# In Seurat v5, users can now split in object directly into different layers keeps expression data in one object, but
# splits multiple samples into layers can proceed directly to integration workflow after splitting layers
ifnb[["RNA"]] <- split(ifnb[["RNA"]], f = ifnb$stim)
Layers(ifnb)

# If desired, for example after intergation, the layers can be joined together again
ifnb <- JoinLayers(ifnb)
```

Example 45 (python):
```python
# In line with prior workflows, you can also into split your object into a list of multiple objects based on a metadata
# column creates a list of two objects
ifnb_list <- SplitObject(ifnb, split.by = "stim")
ifnb_list$CTRL
ifnb_list$STIM
```

Example 46 (r):
```r
# In line with prior workflows, you can also into split your object into a list of multiple objects based on a metadata
# column creates a list of two objects
ifnb_list <- SplitObject(ifnb, split.by = "stim")
ifnb_list$CTRL
ifnb_list$STIM
```

Example 47 (r):
```r
# In line with prior workflows, you can also into split your object into a list of multiple objects based on a metadata
# column creates a list of two objects
ifnb_list <- SplitObject(ifnb, split.by = "stim")
ifnb_list$CTRL
ifnb_list$STIM
```

Example 48 (unknown):
```unknown
# Merge two Seurat objects
merged_obj <- merge(x = ifnb_list$CTRL, y = ifnb_list$STIM)
merged_obj[["RNA"]] <- JoinLayers(merged_obj)

# Example to merge more than two Seurat objects
merge(x = pbmc1, y = list(pbmc2, pbmc3))
```

Example 49 (r):
```r
# Merge two Seurat objects
merged_obj <- merge(x = ifnb_list$CTRL, y = ifnb_list$STIM)
merged_obj[["RNA"]] <- JoinLayers(merged_obj)

# Example to merge more than two Seurat objects
merge(x = pbmc1, y = list(pbmc2, pbmc3))
```

Example 50 (r):
```r
# Merge two Seurat objects
merged_obj <- merge(x = ifnb_list$CTRL, y = ifnb_list$STIM)
merged_obj[["RNA"]] <- JoinLayers(merged_obj)

# Example to merge more than two Seurat objects
merge(x = pbmc1, y = list(pbmc2, pbmc3))
```

Example 51 (unknown):
```unknown
merged_obj <- merge(x = ifnb_list$CTRL, y = ifnb_list$STIM)
merged_obj <- NormalizeData(merged_obj)
merged_obj <- FindVariableFeatures(merged_obj)
merged_obj <- ScaleData(merged_obj)
merged_obj <- RunPCA(merged_obj)
merged_obj <- IntegrateLayers(object = obj, method = RPCAIntegration, orig.reduction = "pca", new.reduction = "integrated.rpca",
    verbose = FALSE)

# now that integration is complete, rejoin layers
merged_obj[["RNA"]] <- JoinLayers(merged_obj)
```

Example 52 (r):
```r
merged_obj <- merge(x = ifnb_list$CTRL, y = ifnb_list$STIM)
merged_obj <- NormalizeData(merged_obj)
merged_obj <- FindVariableFeatures(merged_obj)
merged_obj <- ScaleData(merged_obj)
merged_obj <- RunPCA(merged_obj)
merged_obj <- IntegrateLayers(object = obj, method = RPCAIntegration, orig.reduction = "pca", new.reduction = "integrated.rpca",
    verbose = FALSE)

# now that integration is complete, rejoin layers
merged_obj[["RNA"]] <- JoinLayers(merged_obj)
```

Example 53 (r):
```r
merged_obj <- merge(x = ifnb_list$CTRL, y = ifnb_list$STIM)
merged_obj <- NormalizeData(merged_obj)
merged_obj <- FindVariableFeatures(merged_obj)
merged_obj <- ScaleData(merged_obj)
merged_obj <- RunPCA(merged_obj)
merged_obj <- IntegrateLayers(object = obj, method = RPCAIntegration, orig.reduction = "pca", new.reduction = "integrated.rpca",
    verbose = FALSE)

# now that integration is complete, rejoin layers
merged_obj[["RNA"]] <- JoinLayers(merged_obj)
```

Example 54 (unknown):
```unknown
# pseudobulk cells only by cell type
bulk <- AggregateExpression(ifnb, group.by = "seurat_annotations", return.seurat = TRUE)
Cells(bulk)

# pseudobulk cells by stimulation condition AND cell type
bulk <- AggregateExpression(ifnb, group.by = c("stim", "seurat_annotations"), return.seurat = TRUE)
Cells(bulk)

# pseudobulk cells by stimulation condition AND cell type AND donor
bulk <- AggregateExpression(ifnb, group.by = c("stim", "seurat_annotations", "donor_id"), return.seurat = TRUE)
Cells(bulk)
```

Example 55 (r):
```r
# pseudobulk cells only by cell type
bulk <- AggregateExpression(ifnb, group.by = "seurat_annotations", return.seurat = TRUE)
Cells(bulk)

# pseudobulk cells by stimulation condition AND cell type
bulk <- AggregateExpression(ifnb, group.by = c("stim", "seurat_annotations"), return.seurat = TRUE)
Cells(bulk)

# pseudobulk cells by stimulation condition AND cell type AND donor
bulk <- AggregateExpression(ifnb, group.by = c("stim", "seurat_annotations", "donor_id"), return.seurat = TRUE)
Cells(bulk)
```

Example 56 (r):
```r
# pseudobulk cells only by cell type
bulk <- AggregateExpression(ifnb, group.by = "seurat_annotations", return.seurat = TRUE)
Cells(bulk)

# pseudobulk cells by stimulation condition AND cell type
bulk <- AggregateExpression(ifnb, group.by = c("stim", "seurat_annotations"), return.seurat = TRUE)
Cells(bulk)

# pseudobulk cells by stimulation condition AND cell type AND donor
bulk <- AggregateExpression(ifnb, group.by = c("stim", "seurat_annotations", "donor_id"), return.seurat = TRUE)
Cells(bulk)
```

Example 57 (unknown):
```unknown
# Dimensional reduction plot
DimPlot(object = pbmc, reduction = "pca")

# Dimensional reduction plot, with cells colored by a quantitative feature Defaults to UMAP if available
FeaturePlot(object = pbmc, features = "MS4A1")

# Scatter plot across single cells
FeatureScatter(object = pbmc, feature1 = "MS4A1", feature2 = "PC_1")
FeatureScatter(object = pbmc, feature1 = "MS4A1", feature2 = "CD3D")

# Scatter plot across individual features, repleaces CellPlot
CellScatter(object = pbmc, cell1 = "AGTCTACTAGGGTG", cell2 = "CACAGATGGTTTCT")

VariableFeaturePlot(object = pbmc)

# Violin and Ridge plots
VlnPlot(object = pbmc, features = c("LYZ", "CCL5", "IL32"))
RidgePlot(object = pbmc, feature = c("LYZ", "CCL5", "IL32"))
```

Example 58 (r):
```r
# Dimensional reduction plot
DimPlot(object = pbmc, reduction = "pca")

# Dimensional reduction plot, with cells colored by a quantitative feature Defaults to UMAP if available
FeaturePlot(object = pbmc, features = "MS4A1")

# Scatter plot across single cells
FeatureScatter(object = pbmc, feature1 = "MS4A1", feature2 = "PC_1")
FeatureScatter(object = pbmc, feature1 = "MS4A1", feature2 = "CD3D")

# Scatter plot across individual features, repleaces CellPlot
CellScatter(object = pbmc, cell1 = "AGTCTACTAGGGTG", cell2 = "CACAGATGGTTTCT")

VariableFeaturePlot(object = pbmc)

# Violin and Ridge plots
VlnPlot(object = pbmc, features = c("LYZ", "CCL5", "IL32"))
RidgePlot(object = pbmc, feature = c("LYZ", "CCL5", "IL32"))
```

Example 59 (r):
```r
# Dimensional reduction plot
DimPlot(object = pbmc, reduction = "pca")

# Dimensional reduction plot, with cells colored by a quantitative feature Defaults to UMAP if available
FeaturePlot(object = pbmc, features = "MS4A1")

# Scatter plot across single cells
FeatureScatter(object = pbmc, feature1 = "MS4A1", feature2 = "PC_1")
FeatureScatter(object = pbmc, feature1 = "MS4A1", feature2 = "CD3D")

# Scatter plot across individual features, repleaces CellPlot
CellScatter(object = pbmc, cell1 = "AGTCTACTAGGGTG", cell2 = "CACAGATGGTTTCT")

VariableFeaturePlot(object = pbmc)

# Violin and Ridge plots
VlnPlot(object = pbmc, features = c("LYZ", "CCL5", "IL32"))
RidgePlot(object = pbmc, feature = c("LYZ", "CCL5", "IL32"))
```

Example 60 (unknown):
```unknown
# Heatmaps (visualize scale.data slot)
DimHeatmap(object = pbmc, reduction = "pca", cells = 200)

# standard workflow
pbmc <- ScaleData(pbmc, features = heatmap_markers)
DoHeatmap(object = pbmc, features = heatmap_markers)

# sctransform workflow
pbmc <- GetResidual(pbmc, features = heatmap_markers)
DoHeatmap(object = pbmc, features = heatmap_markers)

# heatmap with maximum of 100 cells per group
DoHeatmap(pbmc, heatmap_markers, cells = subset(pbmc, downsample = 100))
```

Example 61 (r):
```r
# Heatmaps (visualize scale.data slot)
DimHeatmap(object = pbmc, reduction = "pca", cells = 200)

# standard workflow
pbmc <- ScaleData(pbmc, features = heatmap_markers)
DoHeatmap(object = pbmc, features = heatmap_markers)

# sctransform workflow
pbmc <- GetResidual(pbmc, features = heatmap_markers)
DoHeatmap(object = pbmc, features = heatmap_markers)

# heatmap with maximum of 100 cells per group
DoHeatmap(pbmc, heatmap_markers, cells = subset(pbmc, downsample = 100))
```

Example 62 (r):
```r
# Heatmaps (visualize scale.data slot)
DimHeatmap(object = pbmc, reduction = "pca", cells = 200)

# standard workflow
pbmc <- ScaleData(pbmc, features = heatmap_markers)
DoHeatmap(object = pbmc, features = heatmap_markers)

# sctransform workflow
pbmc <- GetResidual(pbmc, features = heatmap_markers)
DoHeatmap(object = pbmc, features = heatmap_markers)

# heatmap with maximum of 100 cells per group
DoHeatmap(pbmc, heatmap_markers, cells = subset(pbmc, downsample = 100))
```

Example 63 (unknown):
```unknown
# New things to try!  Note that plotting functions now return ggplot2 objects, so you can add themes, titles, and
# options onto them
VlnPlot(object = pbmc, features = "MS4A1", split.by = "groups")
DotPlot(object = pbmc, features = c("LYZ", "CCL5", "IL32"), split.by = "groups")
FeaturePlot(object = pbmc, features = c("MS4A1", "CD79A"), blend = TRUE)
DimPlot(object = pbmc) + DarkTheme()
DimPlot(object = pbmc) + labs(title = "2,700 PBMCs clustered using Seurat and viewed\non a two-dimensional UMAP")
```

Example 64 (r):
```r
# New things to try!  Note that plotting functions now return ggplot2 objects, so you can add themes, titles, and
# options onto them
VlnPlot(object = pbmc, features = "MS4A1", split.by = "groups")
DotPlot(object = pbmc, features = c("LYZ", "CCL5", "IL32"), split.by = "groups")
FeaturePlot(object = pbmc, features = c("MS4A1", "CD79A"), blend = TRUE)
DimPlot(object = pbmc) + DarkTheme()
DimPlot(object = pbmc) + labs(title = "2,700 PBMCs clustered using Seurat and viewed\non a two-dimensional UMAP")
```

Example 65 (r):
```r
# New things to try!  Note that plotting functions now return ggplot2 objects, so you can add themes, titles, and
# options onto them
VlnPlot(object = pbmc, features = "MS4A1", split.by = "groups")
DotPlot(object = pbmc, features = c("LYZ", "CCL5", "IL32"), split.by = "groups")
FeaturePlot(object = pbmc, features = c("MS4A1", "CD79A"), blend = TRUE)
DimPlot(object = pbmc) + DarkTheme()
DimPlot(object = pbmc) + labs(title = "2,700 PBMCs clustered using Seurat and viewed\non a two-dimensional UMAP")
```

Example 66 (unknown):
```unknown
RestoreLegend
```

Example 67 (unknown):
```unknown
RotatedAxis
```

Example 68 (unknown):
```unknown
# Plotting helper functions work with ggplot2-based scatter plots, such as DimPlot, FeaturePlot, CellScatter, and
# FeatureScatter
plot <- DimPlot(object = pbmc) + NoLegend()

# HoverLocator replaces the former `do.hover` argument It can also show extra data throught the `information` argument,
# designed to work smoothly with FetchData
HoverLocator(plot = plot, information = FetchData(object = pbmc, vars = c("ident", "PC_1", "nFeature_RNA")))

# FeatureLocator replaces the former `do.identify`
select.cells <- FeatureLocator(plot = plot)

# Label points on a ggplot object
LabelPoints(plot = plot, points = TopCells(object = pbmc[["pca"]]), repel = TRUE)
```

Example 69 (r):
```r
# Plotting helper functions work with ggplot2-based scatter plots, such as DimPlot, FeaturePlot, CellScatter, and
# FeatureScatter
plot <- DimPlot(object = pbmc) + NoLegend()

# HoverLocator replaces the former `do.hover` argument It can also show extra data throught the `information` argument,
# designed to work smoothly with FetchData
HoverLocator(plot = plot, information = FetchData(object = pbmc, vars = c("ident", "PC_1", "nFeature_RNA")))

# FeatureLocator replaces the former `do.identify`
select.cells <- FeatureLocator(plot = plot)

# Label points on a ggplot object
LabelPoints(plot = plot, points = TopCells(object = pbmc[["pca"]]), repel = TRUE)
```

Example 70 (r):
```r
# Plotting helper functions work with ggplot2-based scatter plots, such as DimPlot, FeaturePlot, CellScatter, and
# FeatureScatter
plot <- DimPlot(object = pbmc) + NoLegend()

# HoverLocator replaces the former `do.hover` argument It can also show extra data throught the `information` argument,
# designed to work smoothly with FetchData
HoverLocator(plot = plot, information = FetchData(object = pbmc, vars = c("ident", "PC_1", "nFeature_RNA")))

# FeatureLocator replaces the former `do.identify`
select.cells <- FeatureLocator(plot = plot)

# Label points on a ggplot object
LabelPoints(plot = plot, points = TopCells(object = pbmc[["pca"]]), repel = TRUE)
```

Example 71 (python):
```python
cbmc <- CreateSeuratObject(counts = cbmc.rna)
# Add ADT data
cbmc[["ADT"]] <- CreateAssayObject(counts = cbmc.adt)
# Run analyses by specifying the assay to use
NormalizeData(object = cbmc, assay = "RNA")
NormalizeData(object = cbmc, assay = "ADT", method = "CLR")

# Retrieve and set the default assay
DefaultAssay(object = cbmc)
DefaultAssay(object = cbmc) <- "ADT"
DefaultAssay(object = cbmc)

# Pull feature expression from both assays by using keys
FetchData(object = cbmc, vars = c("rna_CD3E", "adt_CD3"))

# Plot data from multiple assays using keys
FeatureScatter(object = cbmc, feature1 = "rna_CD3E", feature2 = "adt_CD3")
```

Example 72 (r):
```r
cbmc <- CreateSeuratObject(counts = cbmc.rna)
# Add ADT data
cbmc[["ADT"]] <- CreateAssayObject(counts = cbmc.adt)
# Run analyses by specifying the assay to use
NormalizeData(object = cbmc, assay = "RNA")
NormalizeData(object = cbmc, assay = "ADT", method = "CLR")

# Retrieve and set the default assay
DefaultAssay(object = cbmc)
DefaultAssay(object = cbmc) <- "ADT"
DefaultAssay(object = cbmc)

# Pull feature expression from both assays by using keys
FetchData(object = cbmc, vars = c("rna_CD3E", "adt_CD3"))

# Plot data from multiple assays using keys
FeatureScatter(object = cbmc, feature1 = "rna_CD3E", feature2 = "adt_CD3")
```

Example 73 (r):
```r
cbmc <- CreateSeuratObject(counts = cbmc.rna)
# Add ADT data
cbmc[["ADT"]] <- CreateAssayObject(counts = cbmc.adt)
# Run analyses by specifying the assay to use
NormalizeData(object = cbmc, assay = "RNA")
NormalizeData(object = cbmc, assay = "ADT", method = "CLR")

# Retrieve and set the default assay
DefaultAssay(object = cbmc)
DefaultAssay(object = cbmc) <- "ADT"
DefaultAssay(object = cbmc)

# Pull feature expression from both assays by using keys
FetchData(object = cbmc, vars = c("rna_CD3E", "adt_CD3"))

# Plot data from multiple assays using keys
FeatureScatter(object = cbmc, feature1 = "rna_CD3E", feature2 = "adt_CD3")
```

Example 74 (unknown):
```unknown
sessionInfo()
```

Example 75 (r):
```r
sessionInfo()
```

Example 76 (r):
```r
sessionInfo()
```

---

## Analysis, visualization, and integration of Visium HD spatial datasets with Seurat • Seurat

**URL:** http://127.0.0.1:9173/articles_de_vignette.html

**Contents:**
- Differential expression testing
    - Compiled: 2024-03-04
  - Load in the data
  - Perform default differential expression tests
  - Perform DE analysis within the same cell type across conditions
    - Perform DE analysis after pseudobulking
  - Perform DE analysis using alternative tests

This vignette highlights some example workflows for performing differential expression in Seurat. For demonstration purposes, we will be using the interferon-beta stimulated human PBMCs dataset (ifnb) that is available via the SeuratData package.

The bulk of Seurat’s differential expression features can be accessed through the FindMarkers() function. By default, Seurat performs differential expression (DE) testing based on the non-parametric Wilcoxon rank sum test. To test for DE genes between two specific groups of cells, specify the ident.1 and ident.2 parameters.

The results data frame has the following columns :

If the ident.2 parameter is omitted or set to NULL, FindMarkers() will test for differentially expressed features between the group specified by ident.1 and all other cells. Additionally, the parameter only.pos can be set to TRUE to only search for positive markers, i.e. features that are more highly expressed in the ident.1 group.

Since this dataset contains treatment information (control versus stimulated with interferon-beta), we can also ask what genes change in different conditions for cells of the same type. First, we create a column in the meta.data slot to hold both the cell type and treatment information and switch the current Idents to that column. Then we use FindMarkers() to find the genes that are different between control and stimulated CD14 monocytes.

However, the p-values obtained from this analysis should be interpreted with caution, because these tests treat each cell as an independent replicate and ignore inherent correlations between cells originating from the same sample. Such analyses have been shown to find a large number of false positive associations, as has been demonstrated by Squair et al., 2021, Zimmerman et al., 2021, Junttila et al., 2022, and others. Below, we show how pseudobulking can be used to account for such within-sample correlation.

To pseudobulk, we will use AggregateExpression() to sum together gene counts of all the cells from the same sample for each cell type. This results in one gene expression profile per sample and cell type. We can then perform DE analysis using DESeq2 on the sample level. This treats the samples, rather than the individual cells, as independent observations.

First, we need to retrieve the sample information for each cell. This is not loaded in the metadata, so we will load it from the Github repo of the source data for the original paper.

Add sample information to the dataset

We can now perform pseudobulking (AggregateExpression()) based on the donor IDs.

Next, we perform DE testing on the pseudobulk level for CD14 monocytes, and compare it against the previous single-cell-level DE results.

We can see that while the p-values are correlated between the single-cell and pseudobulk data, the single-cell p-values are often smaller and suggest higher levels of significance. In particular, there are 3,519 genes with evidence of differential expression (prior to multiple hypothesis testing) in both analyses, 1,649 genes that only appear to be differentially expressed in the single-cell analysis, and just 204 genes that only appear to be differentially expressed in the bulk analysis. We can investigate these discrepancies using VlnPlot.

First, we can examine the top genes that are differentially expressed in both analyses.

In both the pseudobulk and single-cell analyses, the p-values for these two genes are astronomically small. For both of these genes, when just comparing all stimulated CD4 monocytes to all control CD4 monocytes across samples, we see much higher expression in the stimulated cells. When breaking down these cells by sample, we continue to see consistently higher expression levels in the stimulated samples compared to the control samples; in other words, this finding is not driven by just one or two samples. Because of this consistency, we find this signal in both analyses.

By contrast, we can examine examples of genes that are only DE under the single-cell analysis.

Here, SRGN and HLA-DRA both have very small p-values in the single-cell analysis (on the orders of \(10^{-21}\) and \(10^{-9}\)), but much larger p-values around 0.18 in the pseudobulk analysis. While there appears to be a difference between control and simulated cells when ignoring sample information, the signal is much weaker on the sample level, and we can see notable variability from sample to sample.

Finally, we also support many other DE tests using other methods. For completeness, the following tests are currently supported:

Developed by Rahul Satija, Satija Lab and Collaborators.

Site built with pkgdown 2.0.7.

**Examples:**

Example 1 (unknown):
```unknown
vignettes/de_vignette.Rmd
```

Example 2 (unknown):
```unknown
de_vignette.Rmd
```

Example 3 (unknown):
```unknown
library(Seurat)
library(SeuratData)
library(ggplot2)
ifnb <- LoadData("ifnb")
```

Example 4 (r):
```r
library(Seurat)
library(SeuratData)
library(ggplot2)
ifnb <- LoadData("ifnb")
```

Example 5 (r):
```r
library(Seurat)
library(SeuratData)
library(ggplot2)
ifnb <- LoadData("ifnb")
```

Example 6 (unknown):
```unknown
FindMarkers()
```

Example 7 (unknown):
```unknown
# Normalize the data
ifnb <- NormalizeData(ifnb)

# Find DE features between CD16 Mono and CD1 Mono
Idents(ifnb) <- "seurat_annotations"
monocyte.de.markers <- FindMarkers(ifnb, ident.1 = "CD16 Mono", ident.2 = "CD14 Mono")
# view results
head(monocyte.de.markers)
```

Example 8 (r):
```r
# Normalize the data
ifnb <- NormalizeData(ifnb)

# Find DE features between CD16 Mono and CD1 Mono
Idents(ifnb) <- "seurat_annotations"
monocyte.de.markers <- FindMarkers(ifnb, ident.1 = "CD16 Mono", ident.2 = "CD14 Mono")
# view results
head(monocyte.de.markers)
```

Example 9 (r):
```r
# Normalize the data
ifnb <- NormalizeData(ifnb)

# Find DE features between CD16 Mono and CD1 Mono
Idents(ifnb) <- "seurat_annotations"
monocyte.de.markers <- FindMarkers(ifnb, ident.1 = "CD16 Mono", ident.2 = "CD14 Mono")
# view results
head(monocyte.de.markers)
```

Example 10 (unknown):
```unknown
##        p_val avg_log2FC pct.1 pct.2 p_val_adj
## VMO1       0   5.700274 0.778 0.084         0
## MS4A4A     0   3.349751 0.748 0.143         0
## FCGR3A     0   3.281942 0.982 0.418         0
## PLAC8      0   3.268470 0.636 0.124         0
## CXCL16     0   2.014758 0.938 0.475         0
## MS4A7      0   2.386436 0.978 0.558         0
```

Example 11 (unknown):
```unknown
##        p_val avg_log2FC pct.1 pct.2 p_val_adj
## VMO1       0   5.700274 0.778 0.084         0
## MS4A4A     0   3.349751 0.748 0.143         0
## FCGR3A     0   3.281942 0.982 0.418         0
## PLAC8      0   3.268470 0.636 0.124         0
## CXCL16     0   2.014758 0.938 0.475         0
## MS4A7      0   2.386436 0.978 0.558         0
```

Example 12 (unknown):
```unknown
FindMarkers()
```

Example 13 (unknown):
```unknown
# Find differentially expressed features between CD14+ Monocytes and all other cells, only
# search for positive markers
monocyte.de.markers <- FindMarkers(ifnb, ident.1 = "CD16 Mono", ident.2 = NULL, only.pos = TRUE)
# view results
head(monocyte.de.markers)
```

Example 14 (r):
```r
# Find differentially expressed features between CD14+ Monocytes and all other cells, only
# search for positive markers
monocyte.de.markers <- FindMarkers(ifnb, ident.1 = "CD16 Mono", ident.2 = NULL, only.pos = TRUE)
# view results
head(monocyte.de.markers)
```

Example 15 (r):
```r
# Find differentially expressed features between CD14+ Monocytes and all other cells, only
# search for positive markers
monocyte.de.markers <- FindMarkers(ifnb, ident.1 = "CD16 Mono", ident.2 = NULL, only.pos = TRUE)
# view results
head(monocyte.de.markers)
```

Example 16 (unknown):
```unknown
##        p_val avg_log2FC pct.1 pct.2 p_val_adj
## FCGR3A     0   4.532656 0.982 0.168         0
## MS4A7      0   3.806350 0.978 0.216         0
## CXCL16     0   3.274267 0.938 0.196         0
## VMO1       0   6.254651 0.778 0.044         0
## MS4A4A     0   4.747731 0.748 0.055         0
## LST1       0   2.927351 0.912 0.228         0
```

Example 17 (unknown):
```unknown
##        p_val avg_log2FC pct.1 pct.2 p_val_adj
## FCGR3A     0   4.532656 0.982 0.168         0
## MS4A7      0   3.806350 0.978 0.216         0
## CXCL16     0   3.274267 0.938 0.196         0
## VMO1       0   6.254651 0.778 0.044         0
## MS4A4A     0   4.747731 0.748 0.055         0
## LST1       0   2.927351 0.912 0.228         0
```

Example 18 (unknown):
```unknown
FindMarkers()
```

Example 19 (unknown):
```unknown
ifnb$celltype.stim <- paste(ifnb$seurat_annotations, ifnb$stim, sep = "_")
Idents(ifnb) <- "celltype.stim"
mono.de <- FindMarkers(ifnb, ident.1 = "CD14 Mono_STIM", ident.2 = "CD14 Mono_CTRL", verbose = FALSE)
head(mono.de, n = 10)
```

Example 20 (r):
```r
ifnb$celltype.stim <- paste(ifnb$seurat_annotations, ifnb$stim, sep = "_")
Idents(ifnb) <- "celltype.stim"
mono.de <- FindMarkers(ifnb, ident.1 = "CD14 Mono_STIM", ident.2 = "CD14 Mono_CTRL", verbose = FALSE)
head(mono.de, n = 10)
```

Example 21 (r):
```r
ifnb$celltype.stim <- paste(ifnb$seurat_annotations, ifnb$stim, sep = "_")
Idents(ifnb) <- "celltype.stim"
mono.de <- FindMarkers(ifnb, ident.1 = "CD14 Mono_STIM", ident.2 = "CD14 Mono_CTRL", verbose = FALSE)
head(mono.de, n = 10)
```

Example 22 (unknown):
```unknown
##         p_val avg_log2FC pct.1 pct.2 p_val_adj
## IFIT1       0   7.319139 0.985 0.033         0
## CXCL10      0   8.036564 0.984 0.035         0
## RSAD2       0   6.741673 0.988 0.045         0
## TNFSF10     0   6.991279 0.989 0.047         0
## IFIT3       0   6.883785 0.992 0.056         0
## IFIT2       0   7.179929 0.961 0.039         0
## CXCL11      0   8.624208 0.932 0.012         0
## CCL8        0   9.134191 0.918 0.017         0
## IDO1        0   5.455898 0.965 0.089         0
## MX1         0   5.059052 0.960 0.093         0
```

Example 23 (unknown):
```unknown
##         p_val avg_log2FC pct.1 pct.2 p_val_adj
## IFIT1       0   7.319139 0.985 0.033         0
## CXCL10      0   8.036564 0.984 0.035         0
## RSAD2       0   6.741673 0.988 0.045         0
## TNFSF10     0   6.991279 0.989 0.047         0
## IFIT3       0   6.883785 0.992 0.056         0
## IFIT2       0   7.179929 0.961 0.039         0
## CXCL11      0   8.624208 0.932 0.012         0
## CCL8        0   9.134191 0.918 0.017         0
## IDO1        0   5.455898 0.965 0.089         0
## MX1         0   5.059052 0.960 0.093         0
```

Example 24 (python):
```python
# load the inferred sample IDs of each cell
ctrl <- read.table(url("https://raw.githubusercontent.com/yelabucsf/demuxlet_paper_code/master/fig3/ye1.ctrl.8.10.sm.best"), head = T, stringsAsFactors = F)
stim <- read.table(url("https://raw.githubusercontent.com/yelabucsf/demuxlet_paper_code/master/fig3/ye2.stim.8.10.sm.best"), head = T, stringsAsFactors = F)
info <- rbind(ctrl, stim)

# rename the cell IDs by substituting the '-' into '.'
info$BARCODE <- gsub(pattern = "\\-", replacement = "\\.", info$BARCODE)

# only keep the cells with high-confidence sample ID
info <- info[grep(pattern = "SNG", x = info$BEST), ]

# remove cells with duplicated IDs in both ctrl and stim groups
info <- info[!duplicated(info$BARCODE) & !duplicated(info$BARCODE, fromLast = T), ]

# now add the sample IDs to ifnb 
rownames(info) <- info$BARCODE
info <- info[, c("BEST"), drop = F]
names(info) <- c("donor_id")
ifnb <- AddMetaData(ifnb, metadata = info)

# remove cells without donor IDs
ifnb$donor_id[is.na(ifnb$donor_id)] <- "unknown"
ifnb <- subset(ifnb, subset = donor_id != "unknown")
```

Example 25 (r):
```r
# load the inferred sample IDs of each cell
ctrl <- read.table(url("https://raw.githubusercontent.com/yelabucsf/demuxlet_paper_code/master/fig3/ye1.ctrl.8.10.sm.best"), head = T, stringsAsFactors = F)
stim <- read.table(url("https://raw.githubusercontent.com/yelabucsf/demuxlet_paper_code/master/fig3/ye2.stim.8.10.sm.best"), head = T, stringsAsFactors = F)
info <- rbind(ctrl, stim)

# rename the cell IDs by substituting the '-' into '.'
info$BARCODE <- gsub(pattern = "\\-", replacement = "\\.", info$BARCODE)

# only keep the cells with high-confidence sample ID
info <- info[grep(pattern = "SNG", x = info$BEST), ]

# remove cells with duplicated IDs in both ctrl and stim groups
info <- info[!duplicated(info$BARCODE) & !duplicated(info$BARCODE, fromLast = T), ]

# now add the sample IDs to ifnb 
rownames(info) <- info$BARCODE
info <- info[, c("BEST"), drop = F]
names(info) <- c("donor_id")
ifnb <- AddMetaData(ifnb, metadata = info)

# remove cells without donor IDs
ifnb$donor_id[is.na(ifnb$donor_id)] <- "unknown"
ifnb <- subset(ifnb, subset = donor_id != "unknown")
```

Example 26 (r):
```r
# load the inferred sample IDs of each cell
ctrl <- read.table(url("https://raw.githubusercontent.com/yelabucsf/demuxlet_paper_code/master/fig3/ye1.ctrl.8.10.sm.best"), head = T, stringsAsFactors = F)
stim <- read.table(url("https://raw.githubusercontent.com/yelabucsf/demuxlet_paper_code/master/fig3/ye2.stim.8.10.sm.best"), head = T, stringsAsFactors = F)
info <- rbind(ctrl, stim)

# rename the cell IDs by substituting the '-' into '.'
info$BARCODE <- gsub(pattern = "\\-", replacement = "\\.", info$BARCODE)

# only keep the cells with high-confidence sample ID
info <- info[grep(pattern = "SNG", x = info$BEST), ]

# remove cells with duplicated IDs in both ctrl and stim groups
info <- info[!duplicated(info$BARCODE) & !duplicated(info$BARCODE, fromLast = T), ]

# now add the sample IDs to ifnb 
rownames(info) <- info$BARCODE
info <- info[, c("BEST"), drop = F]
names(info) <- c("donor_id")
ifnb <- AddMetaData(ifnb, metadata = info)

# remove cells without donor IDs
ifnb$donor_id[is.na(ifnb$donor_id)] <- "unknown"
ifnb <- subset(ifnb, subset = donor_id != "unknown")
```

Example 27 (unknown):
```unknown
AggregateExpression()
```

Example 28 (unknown):
```unknown
# pseudobulk the counts based on donor-condition-celltype
pseudo_ifnb <- AggregateExpression(ifnb, assays = "RNA", return.seurat = T, group.by = c("stim", "donor_id", "seurat_annotations"))

# each 'cell' is a donor-condition-celltype pseudobulk profile
tail(Cells(pseudo_ifnb))
```

Example 29 (r):
```r
# pseudobulk the counts based on donor-condition-celltype
pseudo_ifnb <- AggregateExpression(ifnb, assays = "RNA", return.seurat = T, group.by = c("stim", "donor_id", "seurat_annotations"))

# each 'cell' is a donor-condition-celltype pseudobulk profile
tail(Cells(pseudo_ifnb))
```

Example 30 (r):
```r
# pseudobulk the counts based on donor-condition-celltype
pseudo_ifnb <- AggregateExpression(ifnb, assays = "RNA", return.seurat = T, group.by = c("stim", "donor_id", "seurat_annotations"))

# each 'cell' is a donor-condition-celltype pseudobulk profile
tail(Cells(pseudo_ifnb))
```

Example 31 (unknown):
```unknown
## [1] "STIM_SNG-1488_NK"          "STIM_SNG-1488_DC"         
## [3] "STIM_SNG-1488_B Activated" "STIM_SNG-1488_Mk"         
## [5] "STIM_SNG-1488_pDC"         "STIM_SNG-1488_Eryth"
```

Example 32 (unknown):
```unknown
## [1] "STIM_SNG-1488_NK"          "STIM_SNG-1488_DC"         
## [3] "STIM_SNG-1488_B Activated" "STIM_SNG-1488_Mk"         
## [5] "STIM_SNG-1488_pDC"         "STIM_SNG-1488_Eryth"
```

Example 33 (unknown):
```unknown
pseudo_ifnb$celltype.stim <- paste(pseudo_ifnb$seurat_annotations, pseudo_ifnb$stim, sep = "_")
```

Example 34 (r):
```r
pseudo_ifnb$celltype.stim <- paste(pseudo_ifnb$seurat_annotations, pseudo_ifnb$stim, sep = "_")
```

Example 35 (r):
```r
pseudo_ifnb$celltype.stim <- paste(pseudo_ifnb$seurat_annotations, pseudo_ifnb$stim, sep = "_")
```

Example 36 (unknown):
```unknown
Idents(pseudo_ifnb) <- "celltype.stim"

bulk.mono.de <- FindMarkers(object = pseudo_ifnb, 
                         ident.1 = "CD14 Mono_STIM", 
                         ident.2 = "CD14 Mono_CTRL",
                         test.use = "DESeq2")
head(bulk.mono.de, n = 15)
```

Example 37 (r):
```r
Idents(pseudo_ifnb) <- "celltype.stim"

bulk.mono.de <- FindMarkers(object = pseudo_ifnb, 
                         ident.1 = "CD14 Mono_STIM", 
                         ident.2 = "CD14 Mono_CTRL",
                         test.use = "DESeq2")
head(bulk.mono.de, n = 15)
```

Example 38 (r):
```r
Idents(pseudo_ifnb) <- "celltype.stim"

bulk.mono.de <- FindMarkers(object = pseudo_ifnb, 
                         ident.1 = "CD14 Mono_STIM", 
                         ident.2 = "CD14 Mono_CTRL",
                         test.use = "DESeq2")
head(bulk.mono.de, n = 15)
```

Example 39 (unknown):
```unknown
##                  p_val avg_log2FC pct.1 pct.2     p_val_adj
## IL1RN    3.701542e-275   6.160156     1     1 5.201777e-271
## IFITM2   1.955626e-250   4.318976     1     1 2.748242e-246
## SSB      2.699554e-203   3.066647     1     1 3.793684e-199
## NT5C3A   2.239898e-198   5.412972     1     1 3.147729e-194
## RTCB     5.700554e-162   3.133362     1     1 8.010989e-158
## RABGAP1L 4.743010e-161   5.562364     1     1 6.665352e-157
## DYNLT1   9.735640e-159   2.402726     1     1 1.368150e-154
## PLSCR1   3.191691e-146   2.676047     1     1 4.485284e-142
## ISG20    9.664488e-145   5.443114     1     1 1.358150e-140
## NAPA     2.858013e-144   1.977719     1     1 4.016365e-140
## DDX58    5.957026e-142   4.640111     1     1 8.371409e-138
## HERC5    6.333722e-133   5.266515     1     1 8.900780e-129
## OASL     3.892853e-130   3.946745     1     1 5.470627e-126
## EIF2AK2  6.636434e-128   3.940167     1     1 9.326180e-124
## TMEM50A  6.731955e-117   1.355947     1     1 9.460417e-113
```

Example 40 (unknown):
```unknown
##                  p_val avg_log2FC pct.1 pct.2     p_val_adj
## IL1RN    3.701542e-275   6.160156     1     1 5.201777e-271
## IFITM2   1.955626e-250   4.318976     1     1 2.748242e-246
## SSB      2.699554e-203   3.066647     1     1 3.793684e-199
## NT5C3A   2.239898e-198   5.412972     1     1 3.147729e-194
## RTCB     5.700554e-162   3.133362     1     1 8.010989e-158
## RABGAP1L 4.743010e-161   5.562364     1     1 6.665352e-157
## DYNLT1   9.735640e-159   2.402726     1     1 1.368150e-154
## PLSCR1   3.191691e-146   2.676047     1     1 4.485284e-142
## ISG20    9.664488e-145   5.443114     1     1 1.358150e-140
## NAPA     2.858013e-144   1.977719     1     1 4.016365e-140
## DDX58    5.957026e-142   4.640111     1     1 8.371409e-138
## HERC5    6.333722e-133   5.266515     1     1 8.900780e-129
## OASL     3.892853e-130   3.946745     1     1 5.470627e-126
## EIF2AK2  6.636434e-128   3.940167     1     1 9.326180e-124
## TMEM50A  6.731955e-117   1.355947     1     1 9.460417e-113
```

Example 41 (python):
```python
# compare the DE P-values between the single-cell level and the pseudobulk level results
names(bulk.mono.de) <- paste0(names(bulk.mono.de), ".bulk")
bulk.mono.de$gene <- rownames(bulk.mono.de)

names(mono.de) <- paste0(names(mono.de), ".sc")
mono.de$gene <- rownames(mono.de)

merge_dat <- merge(mono.de, bulk.mono.de, by = "gene")
merge_dat <- merge_dat[order(merge_dat$p_val.bulk), ]

# Number of genes that are marginally significant in both; marginally significant only in bulk; and marginally significant only in single-cell
common <- merge_dat$gene[which(merge_dat$p_val.bulk < 0.05 & 
                                merge_dat$p_val.sc < 0.05)]
only_sc <- merge_dat$gene[which(merge_dat$p_val.bulk > 0.05 & 
                                  merge_dat$p_val.sc < 0.05)]
only_bulk <- merge_dat$gene[which(merge_dat$p_val.bulk < 0.05 & 
                                    merge_dat$p_val.sc > 0.05)]
print(paste0('# Common: ',length(common)))
```

Example 42 (r):
```r
# compare the DE P-values between the single-cell level and the pseudobulk level results
names(bulk.mono.de) <- paste0(names(bulk.mono.de), ".bulk")
bulk.mono.de$gene <- rownames(bulk.mono.de)

names(mono.de) <- paste0(names(mono.de), ".sc")
mono.de$gene <- rownames(mono.de)

merge_dat <- merge(mono.de, bulk.mono.de, by = "gene")
merge_dat <- merge_dat[order(merge_dat$p_val.bulk), ]

# Number of genes that are marginally significant in both; marginally significant only in bulk; and marginally significant only in single-cell
common <- merge_dat$gene[which(merge_dat$p_val.bulk < 0.05 & 
                                merge_dat$p_val.sc < 0.05)]
only_sc <- merge_dat$gene[which(merge_dat$p_val.bulk > 0.05 & 
                                  merge_dat$p_val.sc < 0.05)]
only_bulk <- merge_dat$gene[which(merge_dat$p_val.bulk < 0.05 & 
                                    merge_dat$p_val.sc > 0.05)]
print(paste0('# Common: ',length(common)))
```

Example 43 (r):
```r
# compare the DE P-values between the single-cell level and the pseudobulk level results
names(bulk.mono.de) <- paste0(names(bulk.mono.de), ".bulk")
bulk.mono.de$gene <- rownames(bulk.mono.de)

names(mono.de) <- paste0(names(mono.de), ".sc")
mono.de$gene <- rownames(mono.de)

merge_dat <- merge(mono.de, bulk.mono.de, by = "gene")
merge_dat <- merge_dat[order(merge_dat$p_val.bulk), ]

# Number of genes that are marginally significant in both; marginally significant only in bulk; and marginally significant only in single-cell
common <- merge_dat$gene[which(merge_dat$p_val.bulk < 0.05 & 
                                merge_dat$p_val.sc < 0.05)]
only_sc <- merge_dat$gene[which(merge_dat$p_val.bulk > 0.05 & 
                                  merge_dat$p_val.sc < 0.05)]
only_bulk <- merge_dat$gene[which(merge_dat$p_val.bulk < 0.05 & 
                                    merge_dat$p_val.sc > 0.05)]
print(paste0('# Common: ',length(common)))
```

Example 44 (unknown):
```unknown
## [1] "# Common: 3519"
```

Example 45 (unknown):
```unknown
## [1] "# Common: 3519"
```

Example 46 (python):
```python
print(paste0('# Only in single-cell: ',length(only_sc)))
```

Example 47 (r):
```r
print(paste0('# Only in single-cell: ',length(only_sc)))
```

Example 48 (r):
```r
print(paste0('# Only in single-cell: ',length(only_sc)))
```

Example 49 (unknown):
```unknown
## [1] "# Only in single-cell: 1649"
```

Example 50 (unknown):
```unknown
## [1] "# Only in single-cell: 1649"
```

Example 51 (python):
```python
print(paste0('# Only in bulk: ',length(only_bulk)))
```

Example 52 (r):
```r
print(paste0('# Only in bulk: ',length(only_bulk)))
```

Example 53 (r):
```r
print(paste0('# Only in bulk: ',length(only_bulk)))
```

Example 54 (unknown):
```unknown
## [1] "# Only in bulk: 204"
```

Example 55 (unknown):
```unknown
## [1] "# Only in bulk: 204"
```

Example 56 (python):
```python
# create a new column to annotate sample-condition-celltype in the single-cell dataset
ifnb$donor_id.stim <- paste0(ifnb$stim, "-", ifnb$donor_id)

# generate violin plot 
Idents(ifnb) <- "celltype.stim"
print(merge_dat[merge_dat$gene%in%common[1:2],c('gene','p_val.sc','p_val.bulk')])
```

Example 57 (r):
```r
# create a new column to annotate sample-condition-celltype in the single-cell dataset
ifnb$donor_id.stim <- paste0(ifnb$stim, "-", ifnb$donor_id)

# generate violin plot 
Idents(ifnb) <- "celltype.stim"
print(merge_dat[merge_dat$gene%in%common[1:2],c('gene','p_val.sc','p_val.bulk')])
```

Example 58 (r):
```r
# create a new column to annotate sample-condition-celltype in the single-cell dataset
ifnb$donor_id.stim <- paste0(ifnb$stim, "-", ifnb$donor_id)

# generate violin plot 
Idents(ifnb) <- "celltype.stim"
print(merge_dat[merge_dat$gene%in%common[1:2],c('gene','p_val.sc','p_val.bulk')])
```

Example 59 (unknown):
```unknown
##        gene p_val.sc    p_val.bulk
## 2785  IL1RN        0 3.701542e-275
## 2739 IFITM2        0 1.955626e-250
```

Example 60 (unknown):
```unknown
##        gene p_val.sc    p_val.bulk
## 2785  IL1RN        0 3.701542e-275
## 2739 IFITM2        0 1.955626e-250
```

Example 61 (unknown):
```unknown
VlnPlot(ifnb, features = common[1:2], idents = c("CD14 Mono_CTRL", "CD14 Mono_STIM"), group.by = "stim")
```

Example 62 (r):
```r
VlnPlot(ifnb, features = common[1:2], idents = c("CD14 Mono_CTRL", "CD14 Mono_STIM"), group.by = "stim")
```

Example 63 (r):
```r
VlnPlot(ifnb, features = common[1:2], idents = c("CD14 Mono_CTRL", "CD14 Mono_STIM"), group.by = "stim")
```

Example 64 (unknown):
```unknown
VlnPlot(ifnb, features = common[1:2], idents = c("CD14 Mono_CTRL", "CD14 Mono_STIM"), group.by = "donor_id.stim", ncol = 1)
```

Example 65 (r):
```r
VlnPlot(ifnb, features = common[1:2], idents = c("CD14 Mono_CTRL", "CD14 Mono_STIM"), group.by = "donor_id.stim", ncol = 1)
```

Example 66 (r):
```r
VlnPlot(ifnb, features = common[1:2], idents = c("CD14 Mono_CTRL", "CD14 Mono_STIM"), group.by = "donor_id.stim", ncol = 1)
```

Example 67 (python):
```python
print(merge_dat[merge_dat$gene%in%c('SRGN','HLA-DRA'),c('gene','p_val.sc','p_val.bulk')])
```

Example 68 (r):
```r
print(merge_dat[merge_dat$gene%in%c('SRGN','HLA-DRA'),c('gene','p_val.sc','p_val.bulk')])
```

Example 69 (r):
```r
print(merge_dat[merge_dat$gene%in%c('SRGN','HLA-DRA'),c('gene','p_val.sc','p_val.bulk')])
```

Example 70 (unknown):
```unknown
##         gene     p_val.sc p_val.bulk
## 5710    SRGN 4.025076e-21  0.1823188
## 2603 HLA-DRA 4.989863e-09  0.1851302
```

Example 71 (unknown):
```unknown
##         gene     p_val.sc p_val.bulk
## 5710    SRGN 4.025076e-21  0.1823188
## 2603 HLA-DRA 4.989863e-09  0.1851302
```

Example 72 (unknown):
```unknown
VlnPlot(ifnb, features <- c('SRGN','HLA-DRA'), idents = c("CD14 Mono_CTRL", "CD14 Mono_STIM"), group.by = "stim")
```

Example 73 (r):
```r
VlnPlot(ifnb, features <- c('SRGN','HLA-DRA'), idents = c("CD14 Mono_CTRL", "CD14 Mono_STIM"), group.by = "stim")
```

Example 74 (r):
```r
VlnPlot(ifnb, features <- c('SRGN','HLA-DRA'), idents = c("CD14 Mono_CTRL", "CD14 Mono_STIM"), group.by = "stim")
```

Example 75 (unknown):
```unknown
VlnPlot(ifnb, features <- c('SRGN','HLA-DRA'), idents = c("CD14 Mono_CTRL", "CD14 Mono_STIM"), group.by = "donor_id.stim", ncol = 1)
```

Example 76 (r):
```r
VlnPlot(ifnb, features <- c('SRGN','HLA-DRA'), idents = c("CD14 Mono_CTRL", "CD14 Mono_STIM"), group.by = "donor_id.stim", ncol = 1)
```

Example 77 (r):
```r
VlnPlot(ifnb, features <- c('SRGN','HLA-DRA'), idents = c("CD14 Mono_CTRL", "CD14 Mono_STIM"), group.by = "donor_id.stim", ncol = 1)
```

Example 78 (unknown):
```unknown
# Test for DE features using the MAST package
Idents(ifnb) <- "seurat_annotations"
head(FindMarkers(ifnb, ident.1 = "CD14 Mono", ident.2 = "CD16 Mono", test.use = "MAST"))
```

Example 79 (r):
```r
# Test for DE features using the MAST package
Idents(ifnb) <- "seurat_annotations"
head(FindMarkers(ifnb, ident.1 = "CD14 Mono", ident.2 = "CD16 Mono", test.use = "MAST"))
```

Example 80 (r):
```r
# Test for DE features using the MAST package
Idents(ifnb) <- "seurat_annotations"
head(FindMarkers(ifnb, ident.1 = "CD14 Mono", ident.2 = "CD16 Mono", test.use = "MAST"))
```

---

## Analysis, visualization, and integration of Visium HD spatial datasets with Seurat • Seurat

**URL:** http://127.0.0.1:9173/seurat/articles/seurat5_integration_bridge/index.html

**Contents:**
- Dictionary Learning for cross-modality integration
    - Compiled: October 31, 2023
    - Azimuth ATAC for Bridge Integration
  - Load the bridge, query, and reference datasets
- Preprocessing/normalization for all datasets
  - Map scATAC-seq dataset using bridge integration
  - Assessing the mapping
- Contents

In the same way that read mapping tools have transformed genome sequence analysis, the ability to map new datasets to established references represents an exciting opportunity for the field of single-cell genomics. Along with others in the community, we have developed tools to map and interpret query datasets, and have also constructed a set of scRNA-seq datasets for diverse mammalian tissues.

A key challenge is to extend this reference mapping framework to technologies that do not measure gene expression, even if the underlying reference is based on scRNA-seq. In Hao et al, Nat Biotechnol 2023, we introduce ‘bridge integration’, which enables the mapping of complementary technologies (like scATAC-seq, scDNAme, CyTOF), onto scRNA-seq references, using a ‘multi-omic’ dataset as a molecular bridge. In this vignette, we demonstrate how to map an scATAC-seq dataset of human PBMC, onto our previously constructed PBMC reference. We use a publicly available 10x multiome dataset, which simultaneously measures gene expression and chromatin accessibility in the same cell, as a bridge dataset.

In this vignette we demonstrate:

Users can now automatically run bridge integration for PBMC and Bone Marrow scATAC-seq queries with the newly released Azimuth ATAC workflow on the Azimuth website or in R. For more details on running locally in R, see the section on ATAC data in this vignette.

We start by loading a 10x multiome dataset, consisting of ~12,000 PBMC from a healthy donor. The dataset measures RNA-seq and ATAC-seq in the same cell, and is available for download from 10x Genomics here. We follow the loading instructions from the Signac package vignettes. Note that when using Signac, please make sure you are using the latest version of Bioconductor, as users have reported errors when using older BioC versions.

Load and setup the 10x multiome object

The scATAC-seq query dataset represents ~10,000 PBMC from a healthy donor, and is available for download here. We load in the peak/cell matrix, store the path to the fragments file, and add gene annotations to the object, following the steps as with the ATAC data in the multiome experiment.

We note that it is important to quantify the same set of genomic features in the query dataset as are quantified in the multi-omic bridge. We therefore requantify the set of scATAC-seq peaks using the FeatureMatrix command. This is also described in the Signac vignettes and shown below.

Load and setup the 10x scATAC-seq query

We load the reference (download here) from our recent paper. This reference is stored as an h5Seurat file, a format that enables on-disk storage of multimodal Seurat objects (more details on h5Seurat and SeuratDisk can be found here).

What if I want to use my own reference dataset?

As an alternative to using a pre-built reference, you can also use your own reference. To demonstrate, you can download a scRNA-seq dataset of 23,837 human PBMC here, which we have already annotated.

When using your own reference, set reference.reduction = "pca" in the PrepareBridgeReference function.

Prior to performing bridge integration, we normalize and pre-process each of the datasets (note that the reference has already been normalized). We normalize gene expression data using sctransform, and ATAC data using TF-IDF.

Now that we have the reference, query, and bridge datasets set up, we can begin integration. The bridge dataset enables translation between the scRNA-seq reference and the scATAC-seq query, effectively augmenting the reference so that it can map a new data type. We call this an extended reference, and first set it up. Note that you can save the results of this function and map multiple scATAC-seq datasets without having to rerun.

First, we drop the first dimension of the ATAC reduction.

Now, we can directly find anchors between the extended reference and query objects. We use the FindBridgeTransferAnchors function, which translates the query dataset using the same dictionary as was used to translate the reference, and then identifies anchors in this space. The function is meant to mimic our FindTransferAnchors function, but to identify correspondences across modalities.

Once we have identified anchors, we can map the query dataset onto the reference. The MapQuery function is the same as we have previously introduced for reference mapping . It transfers cell annotations from the reference dataset, and also visualizes the query dataset on a previously computed UMAP embedding. Since our reference dataset contains cell type annotations at three levels of resolution (l1 - l3), we can transfer each level to the query dataset.

Now we can visualize the results, plotting the scATAC-seq cells based on their predicted annotations, on the reference UMAP embedding. You can see that each scATAC-seq cell has been assigned a cell name based on the scRNA-seq defined cell ontology.

To assess the mapping and cell type predictions, we will first see if the predicted cell type labels are concordant with an unsupervised analysis of the scATAC-seq dataset. We follow the standard unsupervised processing workflow for scATAC-seq data:

Now, we visualize the predicted cluster labels on the unsupervised UMAP emebdding. We can see that predicted cluster labels (from the scRNA-seq reference) are concordant with the structure of the scATAC-seq data. However, there are some cell types (i.e. Treg), that do not appear to separate in unsupervised analysis. These may be prediction errors, or cases where the reference mapping provides additional resolution.

Lastly, we validate the predicted cell types for the scATAC-seq data by examining their chromatin accessibility profiles at canonical loci. We use the CoveragePlot function to visualize accessibility patterns at the CD8A, FOXP3, and RORC, after grouping cells by their predicted labels. We see expected patterns in each case. For example, the PAX5 locus exhibits peaks that are accessible exclusively in B cells, and the CD8A locus shows the same in CD8 T cell subsets. Similarly, the accessibility of FOXP3, a canonical marker of regulatory T cells (Tregs), in predicted Tregs provides strong support for the accuracy of our prediction.

Developed by Rahul Satija, Satija Lab and Collaborators.

Site built with pkgdown 2.0.7.

**Examples:**

Example 1 (unknown):
```unknown
vignettes/seurat5_integration_bridge.Rmd
```

Example 2 (unknown):
```unknown
seurat5_integration_bridge.Rmd
```

Example 3 (unknown):
```unknown
library(Seurat)
library(Signac)
library(EnsDb.Hsapiens.v86)
library(dplyr)
library(ggplot2)
```

Example 4 (r):
```r
library(Seurat)
library(Signac)
library(EnsDb.Hsapiens.v86)
library(dplyr)
library(ggplot2)
```

Example 5 (r):
```r
library(Seurat)
library(Signac)
library(EnsDb.Hsapiens.v86)
library(dplyr)
library(ggplot2)
```

Example 6 (unknown):
```unknown
# the 10x hdf5 file contains both data types.
inputdata.10x <- Read10X_h5("/brahms/hartmana/vignette_data/pbmc_cellranger_arc_2/pbmc_granulocyte_sorted_10k_filtered_feature_bc_matrix.h5")
# extract RNA and ATAC data
rna_counts <- inputdata.10x$`Gene Expression`
atac_counts <- inputdata.10x$Peaks
# Create Seurat object
obj.multi <- CreateSeuratObject(counts = rna_counts)
# Get % of mitochondrial genes
obj.multi[["percent.mt"]] <- PercentageFeatureSet(obj.multi, pattern = "^MT-")

# add the ATAC-seq assay
grange.counts <- StringToGRanges(rownames(atac_counts), sep = c(":", "-"))
grange.use <- seqnames(grange.counts) %in% standardChromosomes(grange.counts)
atac_counts <- atac_counts[as.vector(grange.use), ]
# Get gene annotations
annotations <- GetGRangesFromEnsDb(ensdb = EnsDb.Hsapiens.v86)
# Change style to UCSC
seqlevelsStyle(annotations) <- 'UCSC'
genome(annotations) <- "hg38"
# File with ATAC per fragment information file
frag.file <- "/brahms/hartmana/vignette_data/pbmc_cellranger_arc_2/pbmc_granulocyte_sorted_10k_atac_fragments.tsv.gz"
# Add in ATAC-seq data as ChromatinAssay object
chrom_assay <- CreateChromatinAssay(
  counts = atac_counts,
  sep = c(":", "-"),
  genome = 'hg38',
  fragments = frag.file,
  min.cells = 10,
  annotation = annotations
)
# Add the ATAC assay to the multiome object
obj.multi[["ATAC"]] <- chrom_assay
# Filter ATAC data based on QC metrics
obj.multi <- subset(
  x = obj.multi,
  subset = nCount_ATAC < 7e4 &
    nCount_ATAC > 5e3 &
    nCount_RNA < 25000 &
    nCount_RNA > 1000 &
    percent.mt < 20
)
```

Example 7 (r):
```r
# the 10x hdf5 file contains both data types.
inputdata.10x <- Read10X_h5("/brahms/hartmana/vignette_data/pbmc_cellranger_arc_2/pbmc_granulocyte_sorted_10k_filtered_feature_bc_matrix.h5")
# extract RNA and ATAC data
rna_counts <- inputdata.10x$`Gene Expression`
atac_counts <- inputdata.10x$Peaks
# Create Seurat object
obj.multi <- CreateSeuratObject(counts = rna_counts)
# Get % of mitochondrial genes
obj.multi[["percent.mt"]] <- PercentageFeatureSet(obj.multi, pattern = "^MT-")

# add the ATAC-seq assay
grange.counts <- StringToGRanges(rownames(atac_counts), sep = c(":", "-"))
grange.use <- seqnames(grange.counts) %in% standardChromosomes(grange.counts)
atac_counts <- atac_counts[as.vector(grange.use), ]
# Get gene annotations
annotations <- GetGRangesFromEnsDb(ensdb = EnsDb.Hsapiens.v86)
# Change style to UCSC
seqlevelsStyle(annotations) <- 'UCSC'
genome(annotations) <- "hg38"
# File with ATAC per fragment information file
frag.file <- "/brahms/hartmana/vignette_data/pbmc_cellranger_arc_2/pbmc_granulocyte_sorted_10k_atac_fragments.tsv.gz"
# Add in ATAC-seq data as ChromatinAssay object
chrom_assay <- CreateChromatinAssay(
  counts = atac_counts,
  sep = c(":", "-"),
  genome = 'hg38',
  fragments = frag.file,
  min.cells = 10,
  annotation = annotations
)
# Add the ATAC assay to the multiome object
obj.multi[["ATAC"]] <- chrom_assay
# Filter ATAC data based on QC metrics
obj.multi <- subset(
  x = obj.multi,
  subset = nCount_ATAC < 7e4 &
    nCount_ATAC > 5e3 &
    nCount_RNA < 25000 &
    nCount_RNA > 1000 &
    percent.mt < 20
)
```

Example 8 (r):
```r
# the 10x hdf5 file contains both data types.
inputdata.10x <- Read10X_h5("/brahms/hartmana/vignette_data/pbmc_cellranger_arc_2/pbmc_granulocyte_sorted_10k_filtered_feature_bc_matrix.h5")
# extract RNA and ATAC data
rna_counts <- inputdata.10x$`Gene Expression`
atac_counts <- inputdata.10x$Peaks
# Create Seurat object
obj.multi <- CreateSeuratObject(counts = rna_counts)
# Get % of mitochondrial genes
obj.multi[["percent.mt"]] <- PercentageFeatureSet(obj.multi, pattern = "^MT-")

# add the ATAC-seq assay
grange.counts <- StringToGRanges(rownames(atac_counts), sep = c(":", "-"))
grange.use <- seqnames(grange.counts) %in% standardChromosomes(grange.counts)
atac_counts <- atac_counts[as.vector(grange.use), ]
# Get gene annotations
annotations <- GetGRangesFromEnsDb(ensdb = EnsDb.Hsapiens.v86)
# Change style to UCSC
seqlevelsStyle(annotations) <- 'UCSC'
genome(annotations) <- "hg38"
# File with ATAC per fragment information file
frag.file <- "/brahms/hartmana/vignette_data/pbmc_cellranger_arc_2/pbmc_granulocyte_sorted_10k_atac_fragments.tsv.gz"
# Add in ATAC-seq data as ChromatinAssay object
chrom_assay <- CreateChromatinAssay(
  counts = atac_counts,
  sep = c(":", "-"),
  genome = 'hg38',
  fragments = frag.file,
  min.cells = 10,
  annotation = annotations
)
# Add the ATAC assay to the multiome object
obj.multi[["ATAC"]] <- chrom_assay
# Filter ATAC data based on QC metrics
obj.multi <- subset(
  x = obj.multi,
  subset = nCount_ATAC < 7e4 &
    nCount_ATAC > 5e3 &
    nCount_RNA < 25000 &
    nCount_RNA > 1000 &
    percent.mt < 20
)
```

Example 9 (unknown):
```unknown
FeatureMatrix
```

Example 10 (unknown):
```unknown
# Load ATAC dataset
atac_pbmc_data <- Read10X_h5(filename = "/brahms/hartmana/vignette_data/10k_PBMC_ATAC_nextgem_Chromium_X_filtered_peak_bc_matrix.h5") 
fragpath <- "/brahms/hartmana/vignette_data/10k_PBMC_ATAC_nextgem_Chromium_X_fragments.tsv.gz"
# Get gene annotations
annotation <- GetGRangesFromEnsDb(ensdb = EnsDb.Hsapiens.v86)
# Change to UCSC style 
seqlevelsStyle(annotation) <- 'UCSC'
# Create ChromatinAssay for ATAC data
atac_pbmc_assay <- CreateChromatinAssay(
  counts = atac_pbmc_data,
  sep = c(":", "-"),
  fragments = fragpath,
  annotation = annotation
)
# Requantify query ATAC to have same features as multiome ATAC dataset
requant_multiome_ATAC <- FeatureMatrix(
  fragments = Fragments(atac_pbmc_assay),
  features = granges(obj.multi[['ATAC']]),
  cells = Cells(atac_pbmc_assay)
)
# Create assay with requantified ATAC data
ATAC_assay <- CreateChromatinAssay(
  counts = requant_multiome_ATAC,
  fragments = fragpath,
  annotation = annotation
)
# Create Seurat sbject
obj.atac  <- CreateSeuratObject(counts = ATAC_assay,assay = 'ATAC')
obj.atac[['peak.orig']] <- atac_pbmc_assay
obj.atac <- subset(obj.atac, subset = nCount_ATAC < 7e4 & nCount_ATAC > 2000)
```

Example 11 (r):
```r
# Load ATAC dataset
atac_pbmc_data <- Read10X_h5(filename = "/brahms/hartmana/vignette_data/10k_PBMC_ATAC_nextgem_Chromium_X_filtered_peak_bc_matrix.h5") 
fragpath <- "/brahms/hartmana/vignette_data/10k_PBMC_ATAC_nextgem_Chromium_X_fragments.tsv.gz"
# Get gene annotations
annotation <- GetGRangesFromEnsDb(ensdb = EnsDb.Hsapiens.v86)
# Change to UCSC style 
seqlevelsStyle(annotation) <- 'UCSC'
# Create ChromatinAssay for ATAC data
atac_pbmc_assay <- CreateChromatinAssay(
  counts = atac_pbmc_data,
  sep = c(":", "-"),
  fragments = fragpath,
  annotation = annotation
)
# Requantify query ATAC to have same features as multiome ATAC dataset
requant_multiome_ATAC <- FeatureMatrix(
  fragments = Fragments(atac_pbmc_assay),
  features = granges(obj.multi[['ATAC']]),
  cells = Cells(atac_pbmc_assay)
)
# Create assay with requantified ATAC data
ATAC_assay <- CreateChromatinAssay(
  counts = requant_multiome_ATAC,
  fragments = fragpath,
  annotation = annotation
)
# Create Seurat sbject
obj.atac  <- CreateSeuratObject(counts = ATAC_assay,assay = 'ATAC')
obj.atac[['peak.orig']] <- atac_pbmc_assay
obj.atac <- subset(obj.atac, subset = nCount_ATAC < 7e4 & nCount_ATAC > 2000)
```

Example 12 (r):
```r
# Load ATAC dataset
atac_pbmc_data <- Read10X_h5(filename = "/brahms/hartmana/vignette_data/10k_PBMC_ATAC_nextgem_Chromium_X_filtered_peak_bc_matrix.h5") 
fragpath <- "/brahms/hartmana/vignette_data/10k_PBMC_ATAC_nextgem_Chromium_X_fragments.tsv.gz"
# Get gene annotations
annotation <- GetGRangesFromEnsDb(ensdb = EnsDb.Hsapiens.v86)
# Change to UCSC style 
seqlevelsStyle(annotation) <- 'UCSC'
# Create ChromatinAssay for ATAC data
atac_pbmc_assay <- CreateChromatinAssay(
  counts = atac_pbmc_data,
  sep = c(":", "-"),
  fragments = fragpath,
  annotation = annotation
)
# Requantify query ATAC to have same features as multiome ATAC dataset
requant_multiome_ATAC <- FeatureMatrix(
  fragments = Fragments(atac_pbmc_assay),
  features = granges(obj.multi[['ATAC']]),
  cells = Cells(atac_pbmc_assay)
)
# Create assay with requantified ATAC data
ATAC_assay <- CreateChromatinAssay(
  counts = requant_multiome_ATAC,
  fragments = fragpath,
  annotation = annotation
)
# Create Seurat sbject
obj.atac  <- CreateSeuratObject(counts = ATAC_assay,assay = 'ATAC')
obj.atac[['peak.orig']] <- atac_pbmc_assay
obj.atac <- subset(obj.atac, subset = nCount_ATAC < 7e4 & nCount_ATAC > 2000)
```

Example 13 (unknown):
```unknown
obj.rna <- readRDS("/brahms/haoy/seurat4_pbmc/pbmc_multimodal_2023.rds")
```

Example 14 (r):
```r
obj.rna <- readRDS("/brahms/haoy/seurat4_pbmc/pbmc_multimodal_2023.rds")
```

Example 15 (r):
```r
obj.rna <- readRDS("/brahms/haoy/seurat4_pbmc/pbmc_multimodal_2023.rds")
```

Example 16 (unknown):
```unknown
obj.rna = readRDS("/path/to/reference.rds")
obj.rna = SCTransform(object = obj.rna) %>%
  RunPCA() %>%
  RunUMAP(dims = 1:50, return.model = TRUE)
```

Example 17 (r):
```r
obj.rna = readRDS("/path/to/reference.rds")
obj.rna = SCTransform(object = obj.rna) %>%
  RunPCA() %>%
  RunUMAP(dims = 1:50, return.model = TRUE)
```

Example 18 (r):
```r
obj.rna = readRDS("/path/to/reference.rds")
obj.rna = SCTransform(object = obj.rna) %>%
  RunPCA() %>%
  RunUMAP(dims = 1:50, return.model = TRUE)
```

Example 19 (unknown):
```unknown
reference.reduction = "pca"
```

Example 20 (unknown):
```unknown
PrepareBridgeReference
```

Example 21 (unknown):
```unknown
# normalize multiome RNA
DefaultAssay(obj.multi) <- "RNA"
obj.multi <- SCTransform(obj.multi, verbose = FALSE)
# normalize multiome ATAC
DefaultAssay(obj.multi) <- "ATAC"
obj.multi <- RunTFIDF(obj.multi)
obj.multi <- FindTopFeatures(obj.multi, min.cutoff = "q0")
# normalize query
obj.atac <- RunTFIDF(obj.atac)
```

Example 22 (r):
```r
# normalize multiome RNA
DefaultAssay(obj.multi) <- "RNA"
obj.multi <- SCTransform(obj.multi, verbose = FALSE)
# normalize multiome ATAC
DefaultAssay(obj.multi) <- "ATAC"
obj.multi <- RunTFIDF(obj.multi)
obj.multi <- FindTopFeatures(obj.multi, min.cutoff = "q0")
# normalize query
obj.atac <- RunTFIDF(obj.atac)
```

Example 23 (r):
```r
# normalize multiome RNA
DefaultAssay(obj.multi) <- "RNA"
obj.multi <- SCTransform(obj.multi, verbose = FALSE)
# normalize multiome ATAC
DefaultAssay(obj.multi) <- "ATAC"
obj.multi <- RunTFIDF(obj.multi)
obj.multi <- FindTopFeatures(obj.multi, min.cutoff = "q0")
# normalize query
obj.atac <- RunTFIDF(obj.atac)
```

Example 24 (unknown):
```unknown
dims.atac <- 2:50
dims.rna <- 1:50
DefaultAssay(obj.multi) <-  "RNA"
DefaultAssay(obj.rna) <- "SCT"
obj.rna.ext <- PrepareBridgeReference(
  reference = obj.rna, bridge = obj.multi,
  reference.reduction = "spca", reference.dims = dims.rna,
  normalization.method = "SCT")
```

Example 25 (r):
```r
dims.atac <- 2:50
dims.rna <- 1:50
DefaultAssay(obj.multi) <-  "RNA"
DefaultAssay(obj.rna) <- "SCT"
obj.rna.ext <- PrepareBridgeReference(
  reference = obj.rna, bridge = obj.multi,
  reference.reduction = "spca", reference.dims = dims.rna,
  normalization.method = "SCT")
```

Example 26 (r):
```r
dims.atac <- 2:50
dims.rna <- 1:50
DefaultAssay(obj.multi) <-  "RNA"
DefaultAssay(obj.rna) <- "SCT"
obj.rna.ext <- PrepareBridgeReference(
  reference = obj.rna, bridge = obj.multi,
  reference.reduction = "spca", reference.dims = dims.rna,
  normalization.method = "SCT")
```

Example 27 (unknown):
```unknown
FindBridgeTransferAnchors
```

Example 28 (unknown):
```unknown
FindTransferAnchors
```

Example 29 (unknown):
```unknown
bridge.anchor <- FindBridgeTransferAnchors(
  extended.reference = obj.rna.ext, query = obj.atac,
  reduction = "lsiproject", dims = dims.atac)
```

Example 30 (r):
```r
bridge.anchor <- FindBridgeTransferAnchors(
  extended.reference = obj.rna.ext, query = obj.atac,
  reduction = "lsiproject", dims = dims.atac)
```

Example 31 (r):
```r
bridge.anchor <- FindBridgeTransferAnchors(
  extended.reference = obj.rna.ext, query = obj.atac,
  reduction = "lsiproject", dims = dims.atac)
```

Example 32 (unknown):
```unknown
obj.atac <- MapQuery(
  anchorset = bridge.anchor, reference = obj.rna.ext,
  query = obj.atac,
  refdata = list(
    l1 = "celltype.l1",
    l2 = "celltype.l2",
    l3 = "celltype.l3"),
  reduction.model = "wnn.umap")
```

Example 33 (r):
```r
obj.atac <- MapQuery(
  anchorset = bridge.anchor, reference = obj.rna.ext,
  query = obj.atac,
  refdata = list(
    l1 = "celltype.l1",
    l2 = "celltype.l2",
    l3 = "celltype.l3"),
  reduction.model = "wnn.umap")
```

Example 34 (r):
```r
obj.atac <- MapQuery(
  anchorset = bridge.anchor, reference = obj.rna.ext,
  query = obj.atac,
  refdata = list(
    l1 = "celltype.l1",
    l2 = "celltype.l2",
    l3 = "celltype.l3"),
  reduction.model = "wnn.umap")
```

Example 35 (unknown):
```unknown
DimPlot(
  obj.atac, group.by = "predicted.l2",
  reduction = "ref.umap", label = TRUE
) + ggtitle("ATAC") + NoLegend()
```

Example 36 (r):
```r
DimPlot(
  obj.atac, group.by = "predicted.l2",
  reduction = "ref.umap", label = TRUE
) + ggtitle("ATAC") + NoLegend()
```

Example 37 (r):
```r
DimPlot(
  obj.atac, group.by = "predicted.l2",
  reduction = "ref.umap", label = TRUE
) + ggtitle("ATAC") + NoLegend()
```

Example 38 (unknown):
```unknown
obj.atac <- FindTopFeatures(obj.atac, min.cutoff = "q0")
obj.atac <- RunSVD(obj.atac)
obj.atac <- RunUMAP(obj.atac, reduction = "lsi", dims = 2:50)
```

Example 39 (r):
```r
obj.atac <- FindTopFeatures(obj.atac, min.cutoff = "q0")
obj.atac <- RunSVD(obj.atac)
obj.atac <- RunUMAP(obj.atac, reduction = "lsi", dims = 2:50)
```

Example 40 (r):
```r
obj.atac <- FindTopFeatures(obj.atac, min.cutoff = "q0")
obj.atac <- RunSVD(obj.atac)
obj.atac <- RunUMAP(obj.atac, reduction = "lsi", dims = 2:50)
```

Example 41 (unknown):
```unknown
DimPlot(obj.atac, group.by = "predicted.l2", reduction = "umap", label = FALSE)
```

Example 42 (r):
```r
DimPlot(obj.atac, group.by = "predicted.l2", reduction = "umap", label = FALSE)
```

Example 43 (r):
```r
DimPlot(obj.atac, group.by = "predicted.l2", reduction = "umap", label = FALSE)
```

Example 44 (unknown):
```unknown
CoveragePlot
```

Example 45 (unknown):
```unknown
CoveragePlot(
  obj.atac, region  = "PAX5", group.by = "predicted.l1",
  idents = c("B", "CD4 T", "Mono", "NK"), window = 200,
  extend.upstream = -150000)
```

Example 46 (r):
```r
CoveragePlot(
  obj.atac, region  = "PAX5", group.by = "predicted.l1",
  idents = c("B", "CD4 T", "Mono", "NK"), window = 200,
  extend.upstream = -150000)
```

Example 47 (r):
```r
CoveragePlot(
  obj.atac, region  = "PAX5", group.by = "predicted.l1",
  idents = c("B", "CD4 T", "Mono", "NK"), window = 200,
  extend.upstream = -150000)
```

Example 48 (unknown):
```unknown
CoveragePlot(
  obj.atac, region = "CD8A", group.by = "predicted.l2",
  idents = c("CD8 Naive", "CD4 Naive", "CD4 TCM", "CD8 TCM"),
  extend.downstream = 5000, extend.upstream = 5000)
```

Example 49 (r):
```r
CoveragePlot(
  obj.atac, region = "CD8A", group.by = "predicted.l2",
  idents = c("CD8 Naive", "CD4 Naive", "CD4 TCM", "CD8 TCM"),
  extend.downstream = 5000, extend.upstream = 5000)
```

Example 50 (r):
```r
CoveragePlot(
  obj.atac, region = "CD8A", group.by = "predicted.l2",
  idents = c("CD8 Naive", "CD4 Naive", "CD4 TCM", "CD8 TCM"),
  extend.downstream = 5000, extend.upstream = 5000)
```

Example 51 (unknown):
```unknown
CoveragePlot(
  obj.atac, region = "FOXP3", group.by = "predicted.l2",
  idents = c( "CD4 Naive", "CD4 TCM", "CD4 TEM", "Treg"),
  extend.downstream = 0, extend.upstream = 0)
```

Example 52 (r):
```r
CoveragePlot(
  obj.atac, region = "FOXP3", group.by = "predicted.l2",
  idents = c( "CD4 Naive", "CD4 TCM", "CD4 TEM", "Treg"),
  extend.downstream = 0, extend.upstream = 0)
```

Example 53 (r):
```r
CoveragePlot(
  obj.atac, region = "FOXP3", group.by = "predicted.l2",
  idents = c( "CD4 Naive", "CD4 TCM", "CD4 TEM", "Treg"),
  extend.downstream = 0, extend.upstream = 0)
```

Example 54 (unknown):
```unknown
CoveragePlot(
  obj.atac, region = "RORC", group.by = "predicted.l2",
  idents = c("CD8 Naive", "CD8 TEM", "CD8 TCM", "MAIT"),
  extend.downstream = 5000, extend.upstream = 5000)
```

Example 55 (r):
```r
CoveragePlot(
  obj.atac, region = "RORC", group.by = "predicted.l2",
  idents = c("CD8 Naive", "CD8 TEM", "CD8 TCM", "MAIT"),
  extend.downstream = 5000, extend.upstream = 5000)
```

Example 56 (r):
```r
CoveragePlot(
  obj.atac, region = "RORC", group.by = "predicted.l2",
  idents = c("CD8 Naive", "CD8 TEM", "CD8 TCM", "MAIT"),
  extend.downstream = 5000, extend.upstream = 5000)
```

Example 57 (unknown):
```unknown
sessionInfo()
```

Example 58 (r):
```r
sessionInfo()
```

Example 59 (r):
```r
sessionInfo()
```

Example 60 (unknown):
```unknown
## R version 4.2.2 Patched (2022-11-10 r83330)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.6 LTS
## 
## Matrix products: default
## BLAS:   /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.9.0
## LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.9.0
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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       
## 
## attached base packages:
## [1] stats4    stats     graphics  grDevices utils     datasets  methods  
## [8] base     
## 
## other attached packages:
##  [1] ggplot2_3.4.4             dplyr_1.1.3              
##  [3] EnsDb.Hsapiens.v86_2.99.0 ensembldb_2.22.0         
##  [5] AnnotationFilter_1.22.0   GenomicFeatures_1.50.4   
##  [7] AnnotationDbi_1.60.2      Biobase_2.58.0           
##  [9] GenomicRanges_1.50.2      GenomeInfoDb_1.34.9      
## [11] IRanges_2.32.0            S4Vectors_0.36.2         
## [13] BiocGenerics_0.44.0       Signac_1.12.9000         
## [15] Seurat_5.0.0              SeuratObject_5.0.0       
## [17] sp_2.1-1                 
## 
## loaded via a namespace (and not attached):
##   [1] rappdirs_0.3.3              rtracklayer_1.58.0         
##   [3] scattermore_1.2             R.methodsS3_1.8.2          
##   [5] ragg_1.2.5                  tidyr_1.3.0                
##   [7] bit64_4.0.5                 knitr_1.45                 
##   [9] irlba_2.3.5.1               DelayedArray_0.24.0        
##  [11] R.utils_2.12.2              styler_1.10.2              
##  [13] data.table_1.14.8           rpart_4.1.19               
##  [15] KEGGREST_1.38.0             RCurl_1.98-1.12            
##  [17] generics_0.1.3              cowplot_1.1.1              
##  [19] RSQLite_2.3.1               RANN_2.6.1                 
##  [21] future_1.33.0               bit_4.0.5                  
##  [23] spatstat.data_3.0-3         xml2_1.3.5                 
##  [25] httpuv_1.6.12               SummarizedExperiment_1.28.0
##  [27] xfun_0.40                   hms_1.1.3                  
##  [29] jquerylib_0.1.4             evaluate_0.22              
##  [31] promises_1.2.1              fansi_1.0.5                
##  [33] restfulr_0.0.15             progress_1.2.2             
##  [35] dbplyr_2.3.4                igraph_1.5.1               
##  [37] DBI_1.1.3                   htmlwidgets_1.6.2          
##  [39] spatstat.geom_3.2-7         purrr_1.0.2                
##  [41] ellipsis_0.3.2              RSpectra_0.16-1            
##  [43] backports_1.4.1             biomaRt_2.54.1             
##  [45] deldir_1.0-9                sparseMatrixStats_1.10.0   
##  [47] MatrixGenerics_1.10.0       vctrs_0.6.4                
##  [49] ROCR_1.0-11                 abind_1.4-5                
##  [51] cachem_1.0.8                withr_2.5.2                
##  [53] BSgenome_1.66.3             progressr_0.14.0           
##  [55] checkmate_2.2.0             sctransform_0.4.1          
##  [57] GenomicAlignments_1.34.1    prettyunits_1.1.1          
##  [59] goftest_1.2-3               cluster_2.1.4              
##  [61] dotCall64_1.1-0             lazyeval_0.2.2             
##  [63] crayon_1.5.2                hdf5r_1.3.8                
##  [65] spatstat.explore_3.2-5      pkgconfig_2.0.3            
##  [67] labeling_0.4.3              nlme_3.1-162               
##  [69] ProtGenerics_1.30.0         nnet_7.3-18                
##  [71] rlang_1.1.1                 globals_0.16.2             
##  [73] lifecycle_1.0.3             miniUI_0.1.1.1             
##  [75] filelock_1.0.2              fastDummies_1.7.3          
##  [77] BiocFileCache_2.6.1         dichromat_2.0-0.1          
##  [79] rprojroot_2.0.3             polyclip_1.10-6            
##  [81] RcppHNSW_0.5.0              matrixStats_1.0.0          
##  [83] lmtest_0.9-40               Matrix_1.6-1.1             
##  [85] zoo_1.8-12                  base64enc_0.1-3            
##  [87] ggridges_0.5.4              png_0.1-8                  
##  [89] viridisLite_0.4.2           rjson_0.2.21               
##  [91] bitops_1.0-7                R.oo_1.25.0                
##  [93] KernSmooth_2.23-22          spam_2.10-0                
##  [95] Biostrings_2.66.0           blob_1.2.4                 
##  [97] DelayedMatrixStats_1.20.0   stringr_1.5.0              
##  [99] parallelly_1.36.0           spatstat.random_3.2-1      
## [101] R.cache_0.16.0              scales_1.2.1               
## [103] memoise_2.0.1               magrittr_2.0.3             
## [105] plyr_1.8.9                  ica_1.0-3                  
## [107] zlibbioc_1.44.0             compiler_4.2.2             
## [109] BiocIO_1.8.0                RColorBrewer_1.1-3         
## [111] fitdistrplus_1.1-11         Rsamtools_2.14.0           
## [113] cli_3.6.1                   XVector_0.38.0             
## [115] listenv_0.9.0               patchwork_1.1.3            
## [117] pbapply_1.7-2               htmlTable_2.4.1            
## [119] Formula_1.2-5               MASS_7.3-58.2              
## [121] tidyselect_1.2.0            stringi_1.7.12             
## [123] textshaping_0.3.6           glmGamPoi_1.10.2           
## [125] highr_0.10                  yaml_2.3.7                 
## [127] ggrepel_0.9.4               grid_4.2.2                 
## [129] sass_0.4.7                  VariantAnnotation_1.44.1   
## [131] fastmatch_1.1-4             tools_4.2.2                
## [133] future.apply_1.11.0         parallel_4.2.2             
## [135] rstudioapi_0.14             foreign_0.8-84             
## [137] gridExtra_2.3               farver_2.1.1               
## [139] Rtsne_0.16                  digest_0.6.33              
## [141] shiny_1.7.5.1               Rcpp_1.0.11                
## [143] later_1.3.1                 RcppAnnoy_0.0.21           
## [145] httr_1.4.7                  biovizBase_1.46.0          
## [147] colorspace_2.1-0            XML_3.99-0.14              
## [149] fs_1.6.3                    tensor_1.5                 
## [151] reticulate_1.34.0           splines_4.2.2              
## [153] uwot_0.1.16                 RcppRoll_0.3.0             
## [155] spatstat.utils_3.0-4        pkgdown_2.0.7              
## [157] plotly_4.10.3               systemfonts_1.0.4          
## [159] xtable_1.8-4                jsonlite_1.8.7             
## [161] R6_2.5.1                    Hmisc_5.1-1                
## [163] pillar_1.9.0                htmltools_0.5.6.1          
## [165] mime_0.12                   glue_1.6.2                 
## [167] fastmap_1.1.1               BiocParallel_1.32.6        
## [169] codetools_0.2-19            utf8_1.2.4                 
## [171] lattice_0.21-9              bslib_0.5.1                
## [173] spatstat.sparse_3.0-3       tibble_3.2.1               
## [175] curl_5.1.0                  leiden_0.4.3               
## [177] survival_3.5-7              rmarkdown_2.25             
## [179] desc_1.4.2                  munsell_0.5.0              
## [181] GenomeInfoDbData_1.2.9      reshape2_1.4.4             
## [183] gtable_0.3.4
```

Example 61 (unknown):
```unknown
## R version 4.2.2 Patched (2022-11-10 r83330)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.6 LTS
## 
## Matrix products: default
## BLAS:   /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.9.0
## LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.9.0
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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       
## 
## attached base packages:
## [1] stats4    stats     graphics  grDevices utils     datasets  methods  
## [8] base     
## 
## other attached packages:
##  [1] ggplot2_3.4.4             dplyr_1.1.3              
##  [3] EnsDb.Hsapiens.v86_2.99.0 ensembldb_2.22.0         
##  [5] AnnotationFilter_1.22.0   GenomicFeatures_1.50.4   
##  [7] AnnotationDbi_1.60.2      Biobase_2.58.0           
##  [9] GenomicRanges_1.50.2      GenomeInfoDb_1.34.9      
## [11] IRanges_2.32.0            S4Vectors_0.36.2         
## [13] BiocGenerics_0.44.0       Signac_1.12.9000         
## [15] Seurat_5.0.0              SeuratObject_5.0.0       
## [17] sp_2.1-1                 
## 
## loaded via a namespace (and not attached):
##   [1] rappdirs_0.3.3              rtracklayer_1.58.0         
##   [3] scattermore_1.2             R.methodsS3_1.8.2          
##   [5] ragg_1.2.5                  tidyr_1.3.0                
##   [7] bit64_4.0.5                 knitr_1.45                 
##   [9] irlba_2.3.5.1               DelayedArray_0.24.0        
##  [11] R.utils_2.12.2              styler_1.10.2              
##  [13] data.table_1.14.8           rpart_4.1.19               
##  [15] KEGGREST_1.38.0             RCurl_1.98-1.12            
##  [17] generics_0.1.3              cowplot_1.1.1              
##  [19] RSQLite_2.3.1               RANN_2.6.1                 
##  [21] future_1.33.0               bit_4.0.5                  
##  [23] spatstat.data_3.0-3         xml2_1.3.5                 
##  [25] httpuv_1.6.12               SummarizedExperiment_1.28.0
##  [27] xfun_0.40                   hms_1.1.3                  
##  [29] jquerylib_0.1.4             evaluate_0.22              
##  [31] promises_1.2.1              fansi_1.0.5                
##  [33] restfulr_0.0.15             progress_1.2.2             
##  [35] dbplyr_2.3.4                igraph_1.5.1               
##  [37] DBI_1.1.3                   htmlwidgets_1.6.2          
##  [39] spatstat.geom_3.2-7         purrr_1.0.2                
##  [41] ellipsis_0.3.2              RSpectra_0.16-1            
##  [43] backports_1.4.1             biomaRt_2.54.1             
##  [45] deldir_1.0-9                sparseMatrixStats_1.10.0   
##  [47] MatrixGenerics_1.10.0       vctrs_0.6.4                
##  [49] ROCR_1.0-11                 abind_1.4-5                
##  [51] cachem_1.0.8                withr_2.5.2                
##  [53] BSgenome_1.66.3             progressr_0.14.0           
##  [55] checkmate_2.2.0             sctransform_0.4.1          
##  [57] GenomicAlignments_1.34.1    prettyunits_1.1.1          
##  [59] goftest_1.2-3               cluster_2.1.4              
##  [61] dotCall64_1.1-0             lazyeval_0.2.2             
##  [63] crayon_1.5.2                hdf5r_1.3.8                
##  [65] spatstat.explore_3.2-5      pkgconfig_2.0.3            
##  [67] labeling_0.4.3              nlme_3.1-162               
##  [69] ProtGenerics_1.30.0         nnet_7.3-18                
##  [71] rlang_1.1.1                 globals_0.16.2             
##  [73] lifecycle_1.0.3             miniUI_0.1.1.1             
##  [75] filelock_1.0.2              fastDummies_1.7.3          
##  [77] BiocFileCache_2.6.1         dichromat_2.0-0.1          
##  [79] rprojroot_2.0.3             polyclip_1.10-6            
##  [81] RcppHNSW_0.5.0              matrixStats_1.0.0          
##  [83] lmtest_0.9-40               Matrix_1.6-1.1             
##  [85] zoo_1.8-12                  base64enc_0.1-3            
##  [87] ggridges_0.5.4              png_0.1-8                  
##  [89] viridisLite_0.4.2           rjson_0.2.21               
##  [91] bitops_1.0-7                R.oo_1.25.0                
##  [93] KernSmooth_2.23-22          spam_2.10-0                
##  [95] Biostrings_2.66.0           blob_1.2.4                 
##  [97] DelayedMatrixStats_1.20.0   stringr_1.5.0              
##  [99] parallelly_1.36.0           spatstat.random_3.2-1      
## [101] R.cache_0.16.0              scales_1.2.1               
## [103] memoise_2.0.1               magrittr_2.0.3             
## [105] plyr_1.8.9                  ica_1.0-3                  
## [107] zlibbioc_1.44.0             compiler_4.2.2             
## [109] BiocIO_1.8.0                RColorBrewer_1.1-3         
## [111] fitdistrplus_1.1-11         Rsamtools_2.14.0           
## [113] cli_3.6.1                   XVector_0.38.0             
## [115] listenv_0.9.0               patchwork_1.1.3            
## [117] pbapply_1.7-2               htmlTable_2.4.1            
## [119] Formula_1.2-5               MASS_7.3-58.2              
## [121] tidyselect_1.2.0            stringi_1.7.12             
## [123] textshaping_0.3.6           glmGamPoi_1.10.2           
## [125] highr_0.10                  yaml_2.3.7                 
## [127] ggrepel_0.9.4               grid_4.2.2                 
## [129] sass_0.4.7                  VariantAnnotation_1.44.1   
## [131] fastmatch_1.1-4             tools_4.2.2                
## [133] future.apply_1.11.0         parallel_4.2.2             
## [135] rstudioapi_0.14             foreign_0.8-84             
## [137] gridExtra_2.3               farver_2.1.1               
## [139] Rtsne_0.16                  digest_0.6.33              
## [141] shiny_1.7.5.1               Rcpp_1.0.11                
## [143] later_1.3.1                 RcppAnnoy_0.0.21           
## [145] httr_1.4.7                  biovizBase_1.46.0          
## [147] colorspace_2.1-0            XML_3.99-0.14              
## [149] fs_1.6.3                    tensor_1.5                 
## [151] reticulate_1.34.0           splines_4.2.2              
## [153] uwot_0.1.16                 RcppRoll_0.3.0             
## [155] spatstat.utils_3.0-4        pkgdown_2.0.7              
## [157] plotly_4.10.3               systemfonts_1.0.4          
## [159] xtable_1.8-4                jsonlite_1.8.7             
## [161] R6_2.5.1                    Hmisc_5.1-1                
## [163] pillar_1.9.0                htmltools_0.5.6.1          
## [165] mime_0.12                   glue_1.6.2                 
## [167] fastmap_1.1.1               BiocParallel_1.32.6        
## [169] codetools_0.2-19            utf8_1.2.4                 
## [171] lattice_0.21-9              bslib_0.5.1                
## [173] spatstat.sparse_3.0-3       tibble_3.2.1               
## [175] curl_5.1.0                  leiden_0.4.3               
## [177] survival_3.5-7              rmarkdown_2.25             
## [179] desc_1.4.2                  munsell_0.5.0              
## [181] GenomeInfoDbData_1.2.9      reshape2_1.4.4             
## [183] gtable_0.3.4
```

---

## PBMC scATAC-seq Vignette

**URL:** http://127.0.0.1:9173/seurat/archive/v3.1/atacseq_integration_vignette/index.html

**Contents:**
- PBMC scATAC-seq Vignette
    - Compiled: April 17, 2020
- Gene activity quantification
- Object setup
- Data preprocessing
- Co-embedding

Update February 2020: we now have developed a separate package, Signac, for the analysis and integration of scATAC-seq data. See the Signac website for up-to-date vignettes and documentation for analysing scATAC-seq data.

In this vignette, we demonstrate our new data transfer method in the context of scATAC-seq to

For this example we’ll be working with the 10X PBMC datasets that contain ~10K cells for both scRNA-seq and scATAC-seq. You can download those here: scATAC-seq, scATAC-seq metadata, scRNA-seq

Overall our integration procedure consists of the following steps:

First, we load in the provided peak matrix and collapse the peak matrix to a “gene activity matrix”. Here, we make the simplifying assumption that a gene’s activity can be quantified by simply summing all counts within the gene body + 2kb upstream but our method is compatible with any method that returns a gene by cell matrix (e.g. Cicero).

Next, we’ll set up the Seurat object and store both the original peak counts in the “ATAC” Assay and the gene activity matrix in the “RNA” Assay. As a QC step, we also filter out all cells here with fewer than 5K total counts in the scATAC-seq data, though you may need to modify this threshold for your experiment.

Here, we process the gene activity matrix in order to find anchors between cells in the scATAC-seq dataset and the scRNA-seq dataset.

We also process the peak matrix. Here we perform latent semantic indexing to reduce the dimensionality of the scATAC-seq data. This procedure learns an ‘internal’ structure for the scRNA-seq data, and is important when determining the appropriate weights for the anchors when transferring information. We utilize Latent Semantic Indexing (LSI) to learn the structure of ATAC-seq data, as proposed in Cusanovich et al, Science 2015 and implemented in the RunLSI function. LSI is implemented here by performing computing the term frequency-inverse document frequency (TF-IDF) followed by SVD.

We use all peaks that have at least 100 reads across all cells, and reduce dimensionality to 50. The parameters chosen here are inspired by previous scATAC-seq analyses, and we do not typically change them, but you can do so.

We have previously pre-processed and clustered a scRNA-seq dataset using the standard workflow in Seurat, and provide the object here. You can see that we can identify standard clusters of myeloid and lymphoid PBMCs.

Now, we can identify anchors between the scATAC-seq dataset and the scRNA-seq dataset and use these anchors to transfer the celltype labels we learned from the 10K scRNA-seq data to the scATAC-seq cells.

To transfer the cluster ids, we provide a vector of previously annotated cell type labels for the RNA to the refdata parameter. The output will contain a matrix with predictions and confidence scores for each ATAC-seq cell.

Why do you choose different (non-default) values for reduction and weight.reduction?

In FindTransferAnchors, we typically project the PCA structure from the reference onto the query when transferring between scRNA-seq datasets. However, when transferring across modalities we find that CCA better captures the shared feature correlation structure and therefore set reduction = 'cca' here. Additionally, by default in TransferData we use the same projected PCA structure to compute the weights of the local neighborhood of anchors that influence each cell’s prediction. In the case of scRNA-seq to scATA-seq transfer, we use the low dimensional space learned by computing an LSI on the ATAC-seq data to compute these weights as this better captures the “internal” structure of the ATAC-seq data.

We can then examine the distribution of prediction scores and optionally filter out those cells with low scores. Here, we find that over 95% of the cells receive a score of 0.5 or greater.

We can then view the predicted cell types on a UMAP representation of the scATAC-seq data and find that the transferred labels are highly consistent with the UMAP structure.

After transferring cell type labels, you can then perform downstream analyses on a cell type specific level. For example, you could find sets of enhancers that are specific for certain cell types and look for motif enrichment. While not all of these types of downstream analyses are directly supported in Seurat, stay tuned for updates in this space.

Finally, to visualize all the cells together, we can co-embed the scRNA-seq and scATAC-seq cells in the same low dimensional space. Here, we use the same anchors used earlier to transfer cell type labels to impute RNA-seq values for the scATAC-seq cells. We then merge the measured and imputed scRNA-seq data and run a standard UMAP analysis to visualize all the cells together. Note that this step is for visualization purposes only and is not a necessary part of the data transfer analysis.

Here we plot all cells colored by either their assigned cell type (from the 10K dataset) or their predicted cell type from the data transfer procedure.

How can I further investigate unmatched groups of cells that only appear in one assay?

Upon inspection of the UMAP embeddings, there appeared several groups of cells that appeared to be present only in a single assay. First, the platelet cells appeared only in the scRNA-seq data. These cells are thought to be undergoing biogenesis from megakaryocytes to platelets and therefore either completely lack nuclear material or their chromatin state is uncoupled from their transcriptome. As a result, we would not expect these to align in this analysis.

Additionally, there appeared to be a population next to the B cell progenitors that is composed entirely of scATAC-seq cells and is not integrated well with the scRNA-seq cells. Further examination of the metadata for these cells revealed a high number of reads mapping to blacklisted regions (as provided by the 10x Genomics QC metrics). This suggests that these barcodes could represent dead or dying cells, ambient DNA, or another technical artifact not represented in the scRNA-seq dataset.

How can I evaluate the success of cross-modality integration?

There are several lines of evidence here that give us confidence in this analysis.

Additionally, we have performed a similar analysis, transferring cell type labels from scRNA-seq to scATAC-seq data in the context of the mouse brain and have observed good performance based on similar reasoning to the points above ( Figure 3). These analyses make the assumption that there is generally a positive correlation between chromatin accessibility and gene expression. In cases such as developing systems, where accessibility may not be a good indicator of transcription, the method demonstrated here may not be able to form good anchors and the resulting integration across these specific modalities may be of limited value.

**Examples:**

Example 1 (r):
```r
library(Seurat)
library(ggplot2)
library(patchwork)
peaks <- Read10X_h5("../data/atac_v1_pbmc_10k_filtered_peak_bc_matrix.h5")
# create a gene activity matrix from the peak matrix and GTF, using chromosomes 1:22, X, and Y.
# Peaks that fall within gene bodies, or 2kb upstream of a gene, are considered
activity.matrix <- CreateGeneActivityMatrix(peak.matrix = peaks, annotation.file = "../data/Homo_sapiens.GRCh37.82.gtf", 
    seq.levels = c(1:22, "X", "Y"), upstream = 2000, verbose = TRUE)
```

Example 2 (r):
```r
library(Seurat)
library(ggplot2)
library(patchwork)
peaks <- Read10X_h5("../data/atac_v1_pbmc_10k_filtered_peak_bc_matrix.h5")
# create a gene activity matrix from the peak matrix and GTF, using chromosomes 1:22, X, and Y.
# Peaks that fall within gene bodies, or 2kb upstream of a gene, are considered
activity.matrix <- CreateGeneActivityMatrix(peak.matrix = peaks, annotation.file = "../data/Homo_sapiens.GRCh37.82.gtf", 
    seq.levels = c(1:22, "X", "Y"), upstream = 2000, verbose = TRUE)
```

Example 3 (r):
```r
pbmc.atac <- CreateSeuratObject(counts = peaks, assay = "ATAC", project = "10x_ATAC")
pbmc.atac[["ACTIVITY"]] <- CreateAssayObject(counts = activity.matrix)
meta <- read.table("../data/atac_v1_pbmc_10k_singlecell.csv", sep = ",", header = TRUE, row.names = 1, 
    stringsAsFactors = FALSE)
meta <- meta[colnames(pbmc.atac), ]
pbmc.atac <- AddMetaData(pbmc.atac, metadata = meta)
pbmc.atac <- subset(pbmc.atac, subset = nCount_ATAC > 5000)
pbmc.atac$tech <- "atac"
```

Example 4 (r):
```r
pbmc.atac <- CreateSeuratObject(counts = peaks, assay = "ATAC", project = "10x_ATAC")
pbmc.atac[["ACTIVITY"]] <- CreateAssayObject(counts = activity.matrix)
meta <- read.table("../data/atac_v1_pbmc_10k_singlecell.csv", sep = ",", header = TRUE, row.names = 1, 
    stringsAsFactors = FALSE)
meta <- meta[colnames(pbmc.atac), ]
pbmc.atac <- AddMetaData(pbmc.atac, metadata = meta)
pbmc.atac <- subset(pbmc.atac, subset = nCount_ATAC > 5000)
pbmc.atac$tech <- "atac"
```

Example 5 (r):
```r
DefaultAssay(pbmc.atac) <- "ACTIVITY"
pbmc.atac <- FindVariableFeatures(pbmc.atac)
pbmc.atac <- NormalizeData(pbmc.atac)
pbmc.atac <- ScaleData(pbmc.atac)
```

Example 6 (r):
```r
DefaultAssay(pbmc.atac) <- "ACTIVITY"
pbmc.atac <- FindVariableFeatures(pbmc.atac)
pbmc.atac <- NormalizeData(pbmc.atac)
pbmc.atac <- ScaleData(pbmc.atac)
```

Example 7 (r):
```r
DefaultAssay(pbmc.atac) <- "ATAC"
VariableFeatures(pbmc.atac) <- names(which(Matrix::rowSums(pbmc.atac) > 100))
pbmc.atac <- RunLSI(pbmc.atac, n = 50, scale.max = NULL)
pbmc.atac <- RunUMAP(pbmc.atac, reduction = "lsi", dims = 1:50)
```

Example 8 (r):
```r
DefaultAssay(pbmc.atac) <- "ATAC"
VariableFeatures(pbmc.atac) <- names(which(Matrix::rowSums(pbmc.atac) > 100))
pbmc.atac <- RunLSI(pbmc.atac, n = 50, scale.max = NULL)
pbmc.atac <- RunUMAP(pbmc.atac, reduction = "lsi", dims = 1:50)
```

Example 9 (r):
```r
pbmc.rna <- readRDS("../data/pbmc_10k_v3.rds")
pbmc.rna$tech <- "rna"
```

Example 10 (r):
```r
pbmc.rna <- readRDS("../data/pbmc_10k_v3.rds")
pbmc.rna$tech <- "rna"
```

Example 11 (r):
```r
p1 <- DimPlot(pbmc.atac, reduction = "umap") + NoLegend() + ggtitle("scATAC-seq")
p2 <- DimPlot(pbmc.rna, group.by = "celltype", label = TRUE, repel = TRUE) + NoLegend() + ggtitle("scRNA-seq")
p1 + p2
```

Example 12 (r):
```r
p1 <- DimPlot(pbmc.atac, reduction = "umap") + NoLegend() + ggtitle("scATAC-seq")
p2 <- DimPlot(pbmc.rna, group.by = "celltype", label = TRUE, repel = TRUE) + NoLegend() + ggtitle("scRNA-seq")
p1 + p2
```

Example 13 (r):
```r
transfer.anchors <- FindTransferAnchors(reference = pbmc.rna, query = pbmc.atac, features = VariableFeatures(object = pbmc.rna), 
    reference.assay = "RNA", query.assay = "ACTIVITY", reduction = "cca")
```

Example 14 (r):
```r
transfer.anchors <- FindTransferAnchors(reference = pbmc.rna, query = pbmc.atac, features = VariableFeatures(object = pbmc.rna), 
    reference.assay = "RNA", query.assay = "ACTIVITY", reduction = "cca")
```

Example 15 (r):
```r
celltype.predictions <- TransferData(anchorset = transfer.anchors, refdata = pbmc.rna$celltype, 
    weight.reduction = pbmc.atac[["lsi"]])
pbmc.atac <- AddMetaData(pbmc.atac, metadata = celltype.predictions)
```

Example 16 (r):
```r
celltype.predictions <- TransferData(anchorset = transfer.anchors, refdata = pbmc.rna$celltype, 
    weight.reduction = pbmc.atac[["lsi"]])
pbmc.atac <- AddMetaData(pbmc.atac, metadata = celltype.predictions)
```

Example 17 (unknown):
```unknown
FindTransferAnchors
```

Example 18 (unknown):
```unknown
reduction = 'cca'
```

Example 19 (unknown):
```unknown
TransferData
```

Example 20 (r):
```r
hist(pbmc.atac$prediction.score.max)
abline(v = 0.5, col = "red")
```

Example 21 (r):
```r
hist(pbmc.atac$prediction.score.max)
abline(v = 0.5, col = "red")
```

Example 22 (r):
```r
table(pbmc.atac$prediction.score.max > 0.5)
```

Example 23 (r):
```r
table(pbmc.atac$prediction.score.max > 0.5)
```

Example 24 (unknown):
```unknown
## 
## FALSE  TRUE 
##   290  7576
```

Example 25 (unknown):
```unknown
## 
## FALSE  TRUE 
##   290  7576
```

Example 26 (r):
```r
pbmc.atac.filtered <- subset(pbmc.atac, subset = prediction.score.max > 0.5)
pbmc.atac.filtered$predicted.id <- factor(pbmc.atac.filtered$predicted.id, levels = levels(pbmc.rna))  # to make the colors match
p1 <- DimPlot(pbmc.atac.filtered, group.by = "predicted.id", label = TRUE, repel = TRUE) + ggtitle("scATAC-seq cells") + 
    NoLegend() + scale_colour_hue(drop = FALSE)
p2 <- DimPlot(pbmc.rna, group.by = "celltype", label = TRUE, repel = TRUE) + ggtitle("scRNA-seq cells") + 
    NoLegend()
p1 + p2
```

Example 27 (r):
```r
pbmc.atac.filtered <- subset(pbmc.atac, subset = prediction.score.max > 0.5)
pbmc.atac.filtered$predicted.id <- factor(pbmc.atac.filtered$predicted.id, levels = levels(pbmc.rna))  # to make the colors match
p1 <- DimPlot(pbmc.atac.filtered, group.by = "predicted.id", label = TRUE, repel = TRUE) + ggtitle("scATAC-seq cells") + 
    NoLegend() + scale_colour_hue(drop = FALSE)
p2 <- DimPlot(pbmc.rna, group.by = "celltype", label = TRUE, repel = TRUE) + ggtitle("scRNA-seq cells") + 
    NoLegend()
p1 + p2
```

Example 28 (r):
```r
# note that we restrict the imputation to variable genes from scRNA-seq, but could impute the
# full transcriptome if we wanted to
genes.use <- VariableFeatures(pbmc.rna)
refdata <- GetAssayData(pbmc.rna, assay = "RNA", slot = "data")[genes.use, ]

# refdata (input) contains a scRNA-seq expression matrix for the scRNA-seq cells.  imputation
# (output) will contain an imputed scRNA-seq matrix for each of the ATAC cells
imputation <- TransferData(anchorset = transfer.anchors, refdata = refdata, weight.reduction = pbmc.atac[["lsi"]])

# this line adds the imputed data matrix to the pbmc.atac object
pbmc.atac[["RNA"]] <- imputation
coembed <- merge(x = pbmc.rna, y = pbmc.atac)

# Finally, we run PCA and UMAP on this combined object, to visualize the co-embedding of both
# datasets
coembed <- ScaleData(coembed, features = genes.use, do.scale = FALSE)
coembed <- RunPCA(coembed, features = genes.use, verbose = FALSE)
coembed <- RunUMAP(coembed, dims = 1:30)
coembed$celltype <- ifelse(!is.na(coembed$celltype), coembed$celltype, coembed$predicted.id)
```

Example 29 (r):
```r
# note that we restrict the imputation to variable genes from scRNA-seq, but could impute the
# full transcriptome if we wanted to
genes.use <- VariableFeatures(pbmc.rna)
refdata <- GetAssayData(pbmc.rna, assay = "RNA", slot = "data")[genes.use, ]

# refdata (input) contains a scRNA-seq expression matrix for the scRNA-seq cells.  imputation
# (output) will contain an imputed scRNA-seq matrix for each of the ATAC cells
imputation <- TransferData(anchorset = transfer.anchors, refdata = refdata, weight.reduction = pbmc.atac[["lsi"]])

# this line adds the imputed data matrix to the pbmc.atac object
pbmc.atac[["RNA"]] <- imputation
coembed <- merge(x = pbmc.rna, y = pbmc.atac)

# Finally, we run PCA and UMAP on this combined object, to visualize the co-embedding of both
# datasets
coembed <- ScaleData(coembed, features = genes.use, do.scale = FALSE)
coembed <- RunPCA(coembed, features = genes.use, verbose = FALSE)
coembed <- RunUMAP(coembed, dims = 1:30)
coembed$celltype <- ifelse(!is.na(coembed$celltype), coembed$celltype, coembed$predicted.id)
```

Example 30 (r):
```r
p1 <- DimPlot(coembed, group.by = "tech")
p2 <- DimPlot(coembed, group.by = "celltype", label = TRUE, repel = TRUE)
p1 + p2
```

Example 31 (r):
```r
p1 <- DimPlot(coembed, group.by = "tech")
p2 <- DimPlot(coembed, group.by = "celltype", label = TRUE, repel = TRUE)
p1 + p2
```

Example 32 (r):
```r
DimPlot(coembed, split.by = "tech", group.by = "celltype", label = TRUE, repel = TRUE) + NoLegend()
```

Example 33 (r):
```r
DimPlot(coembed, split.by = "tech", group.by = "celltype", label = TRUE, repel = TRUE) + NoLegend()
```

Example 34 (r):
```r
coembed$blacklist_region_fragments[is.na(coembed$blacklist_region_fragments)] <- 0
FeaturePlot(coembed, features = "blacklist_region_fragments", max.cutoff = 500)
```

Example 35 (r):
```r
coembed$blacklist_region_fragments[is.na(coembed$blacklist_region_fragments)] <- 0
FeaturePlot(coembed, features = "blacklist_region_fragments", max.cutoff = 500)
```

---

## Analysis, visualization, and integration of Visium HD spatial datasets with Seurat • Seurat

**URL:** http://127.0.0.1:9173/seurat/articles/cell_cycle_vignette/index.html

**Contents:**
- Cell-Cycle Scoring and Regression
    - Compiled: 2023-10-31
- Assign Cell-Cycle Scores
- Regress out cell cycle scores during data scaling
- Alternate Workflow
- Contents

We demonstrate how to mitigate the effects of cell cycle heterogeneity in scRNA-seq data by calculating cell cycle phase scores based on canonical markers, and regressing these out of the data during pre-processing. We demonstrate this on a dataset of murine hematopoietic progenitors (Nestorowa et al., Blood 2016).You can download the files needed to run this vignette here.

If we run a PCA on our object, using the variable genes we found in FindVariableFeatures() above, we see that while most of the variance can be explained by lineage, PC8 and PC10 are split on cell-cycle genes including TOP2A and MKI67. We will attempt to regress this signal from the data, so that cell-cycle heterogeneity does not contribute to PCA or downstream analysis.

First, we assign each cell a score, based on its expression of G2/M and S phase markers. These marker sets should be anticorrelated in their expression levels, and cells expressing neither are likely not cycling and in G1 phase.

We assign scores in the CellCycleScoring() function, which stores S and G2/M scores in object meta data, along with the predicted classification of each cell in either G2M, S or G1 phase. CellCycleScoring() can also set the identity of the Seurat object to the cell-cycle phase by passing set.ident = TRUE (the original identities are stored as old.ident). Please note that Seurat does not use the discrete classifications (G2M/G1/S) in downstream cell cycle regression. Instead, it uses the quantitative scores for G2M and S phase. However, we provide our predicted classifications in case they are of interest.

We score single cells based on the scoring strategy described in Tirosh et al. 2016. See ?AddModuleScore() in Seurat for more information, this function can be used to calculate supervised module scores for any gene list.

We now attempt to subtract (‘regress out’) this source of heterogeneity from the data. For users of Seurat v1.4, this was implemented in RegressOut. However, as the results of this procedure are stored in the scaled data slot (therefore overwriting the output of ScaleData()), we now merge this functionality into the ScaleData() function itself.

For each gene, Seurat models the relationship between gene expression and the S and G2M cell cycle scores. The scaled residuals of this model represent a ‘corrected’ expression matrix, that can be used downstream for dimensional reduction.

As the best cell cycle markers are extremely well conserved across tissues and species, we have found this procedure to work robustly and reliably on diverse datasets.

The procedure above removes all signal associated with cell cycle. In some cases, we’ve found that this can negatively impact downstream analysis, particularly in differentiating processes (like murine hematopoiesis), where stem cells are quiescent and differentiated cells are proliferating (or vice versa). In this case, regressing out all cell cycle effects can blur the distinction between stem and progenitor cells as well.

As an alternative, we suggest regressing out the difference between the G2M and S phase scores. This means that signals separating non-cycling cells and cycling cells will be maintained, but differences in cell cycle phase among proliferating cells (which are often uninteresting), will be regressed out of the data

Developed by Rahul Satija, Satija Lab and Collaborators.

Site built with pkgdown 2.0.7.

**Examples:**

Example 1 (unknown):
```unknown
vignettes/cell_cycle_vignette.Rmd
```

Example 2 (unknown):
```unknown
cell_cycle_vignette.Rmd
```

Example 3 (python):
```python
library(Seurat)

# Read in the expression matrix The first row is a header row, the first column is rownames
exp.mat <- read.table(file = "/brahms/shared/vignette-data/cell_cycle_vignette_files/nestorawa_forcellcycle_expressionMatrix.txt",
    header = TRUE, as.is = TRUE, row.names = 1)

# A list of cell cycle markers, from Tirosh et al, 2015, is loaded with Seurat.  We can
# segregate this list into markers of G2/M phase and markers of S phase
s.genes <- cc.genes$s.genes
g2m.genes <- cc.genes$g2m.genes

# Create our Seurat object and complete the initalization steps
marrow <- CreateSeuratObject(counts = Matrix::Matrix(as.matrix(exp.mat), sparse = T))
marrow <- NormalizeData(marrow)
marrow <- FindVariableFeatures(marrow, selection.method = "vst")
marrow <- ScaleData(marrow, features = rownames(marrow))
```

Example 4 (r):
```r
library(Seurat)

# Read in the expression matrix The first row is a header row, the first column is rownames
exp.mat <- read.table(file = "/brahms/shared/vignette-data/cell_cycle_vignette_files/nestorawa_forcellcycle_expressionMatrix.txt",
    header = TRUE, as.is = TRUE, row.names = 1)

# A list of cell cycle markers, from Tirosh et al, 2015, is loaded with Seurat.  We can
# segregate this list into markers of G2/M phase and markers of S phase
s.genes <- cc.genes$s.genes
g2m.genes <- cc.genes$g2m.genes

# Create our Seurat object and complete the initalization steps
marrow <- CreateSeuratObject(counts = Matrix::Matrix(as.matrix(exp.mat), sparse = T))
marrow <- NormalizeData(marrow)
marrow <- FindVariableFeatures(marrow, selection.method = "vst")
marrow <- ScaleData(marrow, features = rownames(marrow))
```

Example 5 (r):
```r
library(Seurat)

# Read in the expression matrix The first row is a header row, the first column is rownames
exp.mat <- read.table(file = "/brahms/shared/vignette-data/cell_cycle_vignette_files/nestorawa_forcellcycle_expressionMatrix.txt",
    header = TRUE, as.is = TRUE, row.names = 1)

# A list of cell cycle markers, from Tirosh et al, 2015, is loaded with Seurat.  We can
# segregate this list into markers of G2/M phase and markers of S phase
s.genes <- cc.genes$s.genes
g2m.genes <- cc.genes$g2m.genes

# Create our Seurat object and complete the initalization steps
marrow <- CreateSeuratObject(counts = Matrix::Matrix(as.matrix(exp.mat), sparse = T))
marrow <- NormalizeData(marrow)
marrow <- FindVariableFeatures(marrow, selection.method = "vst")
marrow <- ScaleData(marrow, features = rownames(marrow))
```

Example 6 (unknown):
```unknown
FindVariableFeatures()
```

Example 7 (unknown):
```unknown
marrow <- RunPCA(marrow, features = VariableFeatures(marrow), ndims.print = 6:10, nfeatures.print = 10)
```

Example 8 (r):
```r
marrow <- RunPCA(marrow, features = VariableFeatures(marrow), ndims.print = 6:10, nfeatures.print = 10)
```

Example 9 (r):
```r
marrow <- RunPCA(marrow, features = VariableFeatures(marrow), ndims.print = 6:10, nfeatures.print = 10)
```

Example 10 (unknown):
```unknown
## PC_ 6 
## Positive:  SELL, ARL6IP1, CCL9, CD34, ADGRL4, BPIFC, NUSAP1, FAM64A, CD244, C030034L19RIK 
## Negative:  LY6C2, AA467197, CYBB, MGST2, ITGB2, PF4, CD74, ATP1B1, GP1BB, TREM3 
## PC_ 7 
## Positive:  F13A1, LY86, CFP, IRF8, CSF1R, TIFAB, IFI209, CCR2, TNS4, MS4A6C 
## Negative:  HDC, CPA3, PGLYRP1, MS4A3, NKG7, UBE2C, CCNB1, NUSAP1, PLK1, FUT8 
## PC_ 8 
## Positive:  NUSAP1, UBE2C, KIF23, PLK1, CENPF, FAM64A, CCNB1, H2AFX, ID2, CDC20 
## Negative:  WFDC17, SLC35D3, ADGRL4, VLDLR, CD33, H2AFY, P2RY14, IFI206, CCL9, CD34 
## PC_ 9 
## Positive:  IGKC, JCHAIN, LY6D, MZB1, CD74, IGLC2, FCRLA, IGKV4-50, IGHM, IGHV9-1 
## Negative:  SLC2A6, HBA-A1, HBA-A2, IGHV8-7, FCER1G, F13A1, HBB-BS, PLD4, HBB-BT, IGFBP4 
## PC_ 10 
## Positive:  H2AFX, FAM64A, ZFP383, NUSAP1, CDC25B, CENPF, GBP10, TOP2A, GBP6, GFRA1 
## Negative:  CTSW, XKRX, PRR5L, RORA, MBOAT4, A630014C17RIK, ZFP105, COL9A3, CLEC2I, TRAT1
```

Example 11 (unknown):
```unknown
## PC_ 6 
## Positive:  SELL, ARL6IP1, CCL9, CD34, ADGRL4, BPIFC, NUSAP1, FAM64A, CD244, C030034L19RIK 
## Negative:  LY6C2, AA467197, CYBB, MGST2, ITGB2, PF4, CD74, ATP1B1, GP1BB, TREM3 
## PC_ 7 
## Positive:  F13A1, LY86, CFP, IRF8, CSF1R, TIFAB, IFI209, CCR2, TNS4, MS4A6C 
## Negative:  HDC, CPA3, PGLYRP1, MS4A3, NKG7, UBE2C, CCNB1, NUSAP1, PLK1, FUT8 
## PC_ 8 
## Positive:  NUSAP1, UBE2C, KIF23, PLK1, CENPF, FAM64A, CCNB1, H2AFX, ID2, CDC20 
## Negative:  WFDC17, SLC35D3, ADGRL4, VLDLR, CD33, H2AFY, P2RY14, IFI206, CCL9, CD34 
## PC_ 9 
## Positive:  IGKC, JCHAIN, LY6D, MZB1, CD74, IGLC2, FCRLA, IGKV4-50, IGHM, IGHV9-1 
## Negative:  SLC2A6, HBA-A1, HBA-A2, IGHV8-7, FCER1G, F13A1, HBB-BS, PLD4, HBB-BT, IGFBP4 
## PC_ 10 
## Positive:  H2AFX, FAM64A, ZFP383, NUSAP1, CDC25B, CENPF, GBP10, TOP2A, GBP6, GFRA1 
## Negative:  CTSW, XKRX, PRR5L, RORA, MBOAT4, A630014C17RIK, ZFP105, COL9A3, CLEC2I, TRAT1
```

Example 12 (unknown):
```unknown
DimHeatmap(marrow, dims = c(8, 10))
```

Example 13 (r):
```r
DimHeatmap(marrow, dims = c(8, 10))
```

Example 14 (r):
```r
DimHeatmap(marrow, dims = c(8, 10))
```

Example 15 (unknown):
```unknown
CellCycleScoring()
```

Example 16 (unknown):
```unknown
CellCycleScoring()
```

Example 17 (unknown):
```unknown
set.ident = TRUE
```

Example 18 (unknown):
```unknown
marrow <- CellCycleScoring(marrow, s.features = s.genes, g2m.features = g2m.genes, set.ident = TRUE)

# view cell cycle scores and phase assignments
head(marrow[[]])
```

Example 19 (r):
```r
marrow <- CellCycleScoring(marrow, s.features = s.genes, g2m.features = g2m.genes, set.ident = TRUE)

# view cell cycle scores and phase assignments
head(marrow[[]])
```

Example 20 (r):
```r
marrow <- CellCycleScoring(marrow, s.features = s.genes, g2m.features = g2m.genes, set.ident = TRUE)

# view cell cycle scores and phase assignments
head(marrow[[]])
```

Example 21 (unknown):
```unknown
##          orig.ident nCount_RNA nFeature_RNA     S.Score  G2M.Score Phase
## Prog_013       Prog    2563089        10211 -0.14248691 -0.4680395    G1
## Prog_019       Prog    3030620         9991 -0.16915786  0.5851766   G2M
## Prog_031       Prog    1293487        10192 -0.34627038 -0.3971879    G1
## Prog_037       Prog    1357987         9599 -0.44270212  0.6820229   G2M
## Prog_008       Prog    4079891        10540  0.55854051  0.1284359     S
## Prog_014       Prog    2569783        10788  0.07116218  0.3166073   G2M
##          old.ident
## Prog_013      Prog
## Prog_019      Prog
## Prog_031      Prog
## Prog_037      Prog
## Prog_008      Prog
## Prog_014      Prog
```

Example 22 (unknown):
```unknown
##          orig.ident nCount_RNA nFeature_RNA     S.Score  G2M.Score Phase
## Prog_013       Prog    2563089        10211 -0.14248691 -0.4680395    G1
## Prog_019       Prog    3030620         9991 -0.16915786  0.5851766   G2M
## Prog_031       Prog    1293487        10192 -0.34627038 -0.3971879    G1
## Prog_037       Prog    1357987         9599 -0.44270212  0.6820229   G2M
## Prog_008       Prog    4079891        10540  0.55854051  0.1284359     S
## Prog_014       Prog    2569783        10788  0.07116218  0.3166073   G2M
##          old.ident
## Prog_013      Prog
## Prog_019      Prog
## Prog_031      Prog
## Prog_037      Prog
## Prog_008      Prog
## Prog_014      Prog
```

Example 23 (unknown):
```unknown
# Visualize the distribution of cell cycle markers across
RidgePlot(marrow, features = c("PCNA", "TOP2A", "MCM6", "MKI67"), ncol = 2)
```

Example 24 (r):
```r
# Visualize the distribution of cell cycle markers across
RidgePlot(marrow, features = c("PCNA", "TOP2A", "MCM6", "MKI67"), ncol = 2)
```

Example 25 (r):
```r
# Visualize the distribution of cell cycle markers across
RidgePlot(marrow, features = c("PCNA", "TOP2A", "MCM6", "MKI67"), ncol = 2)
```

Example 26 (unknown):
```unknown
# Running a PCA on cell cycle genes reveals, unsurprisingly, that cells separate entirely by
# phase
marrow <- RunPCA(marrow, features = c(s.genes, g2m.genes))
DimPlot(marrow)
```

Example 27 (r):
```r
# Running a PCA on cell cycle genes reveals, unsurprisingly, that cells separate entirely by
# phase
marrow <- RunPCA(marrow, features = c(s.genes, g2m.genes))
DimPlot(marrow)
```

Example 28 (r):
```r
# Running a PCA on cell cycle genes reveals, unsurprisingly, that cells separate entirely by
# phase
marrow <- RunPCA(marrow, features = c(s.genes, g2m.genes))
DimPlot(marrow)
```

Example 29 (unknown):
```unknown
library(ggplot2)
plot <- DimPlot(marrow) + theme(axis.title = element_text(size = 18), legend.text = element_text(size = 18)) +
    guides(colour = guide_legend(override.aes = list(size = 10)))
ggsave(filename = "../output/images/cell_cycle_vignette.jpg", height = 7, width = 12, plot = plot,
    quality = 50)
```

Example 30 (r):
```r
library(ggplot2)
plot <- DimPlot(marrow) + theme(axis.title = element_text(size = 18), legend.text = element_text(size = 18)) +
    guides(colour = guide_legend(override.aes = list(size = 10)))
ggsave(filename = "../output/images/cell_cycle_vignette.jpg", height = 7, width = 12, plot = plot,
    quality = 50)
```

Example 31 (r):
```r
library(ggplot2)
plot <- DimPlot(marrow) + theme(axis.title = element_text(size = 18), legend.text = element_text(size = 18)) +
    guides(colour = guide_legend(override.aes = list(size = 10)))
ggsave(filename = "../output/images/cell_cycle_vignette.jpg", height = 7, width = 12, plot = plot,
    quality = 50)
```

Example 32 (unknown):
```unknown
?AddModuleScore()
```

Example 33 (unknown):
```unknown
ScaleData()
```

Example 34 (unknown):
```unknown
ScaleData()
```

Example 35 (unknown):
```unknown
marrow <- ScaleData(marrow, vars.to.regress = c("S.Score", "G2M.Score"), features = rownames(marrow))
```

Example 36 (r):
```r
marrow <- ScaleData(marrow, vars.to.regress = c("S.Score", "G2M.Score"), features = rownames(marrow))
```

Example 37 (r):
```r
marrow <- ScaleData(marrow, vars.to.regress = c("S.Score", "G2M.Score"), features = rownames(marrow))
```

Example 38 (unknown):
```unknown
# Now, a PCA on the variable genes no longer returns components associated with cell cycle
marrow <- RunPCA(marrow, features = VariableFeatures(marrow), nfeatures.print = 10)
```

Example 39 (r):
```r
# Now, a PCA on the variable genes no longer returns components associated with cell cycle
marrow <- RunPCA(marrow, features = VariableFeatures(marrow), nfeatures.print = 10)
```

Example 40 (r):
```r
# Now, a PCA on the variable genes no longer returns components associated with cell cycle
marrow <- RunPCA(marrow, features = VariableFeatures(marrow), nfeatures.print = 10)
```

Example 41 (unknown):
```unknown
## PC_ 1 
## Positive:  BLVRB, CAR2, KLF1, AQP1, CES2G, ERMAP, CAR1, FAM132A, RHD, SPHK1 
## Negative:  TMSB4X, H2AFY, CORO1A, PLAC8, EMB, MPO, PRTN3, CD34, LCP1, BC035044 
## PC_ 2 
## Positive:  ANGPT1, ADGRG1, MEIS1, ITGA2B, MPL, DAPP1, APOE, RAB37, GATA2, F2R 
## Negative:  LY6C2, ELANE, HP, IGSF6, ANXA3, CTSG, CLEC12A, TIFAB, SLPI, ALAS1 
## PC_ 3 
## Positive:  APOE, GATA2, NKG7, MUC13, MS4A3, RAB44, HDC, CPA3, FCGR3, TUBA8 
## Negative:  FLT3, DNTT, LSP1, WFDC17, MYL10, GIMAP6, LAX1, GPR171, TBXA2R, SATB1 
## PC_ 4 
## Positive:  CSRP3, ST8SIA6, DNTT, MPEG1, SCIN, LGALS1, CMAH, RGL1, APOE, MFSD2B 
## Negative:  PROCR, MPL, HLF, MMRN1, SERPINA3G, ESAM, GSTM1, D630039A03RIK, MYL10, LY6A 
## PC_ 5 
## Positive:  CPA3, LMO4, IKZF2, IFITM1, FUT8, MS4A2, SIGLECF, CSRP3, HDC, RAB44 
## Negative:  PF4, GP1BB, SDPR, F2RL2, RAB27B, SLC14A1, TREML1, PBX1, F2R, TUBA8
```

Example 42 (unknown):
```unknown
## PC_ 1 
## Positive:  BLVRB, CAR2, KLF1, AQP1, CES2G, ERMAP, CAR1, FAM132A, RHD, SPHK1 
## Negative:  TMSB4X, H2AFY, CORO1A, PLAC8, EMB, MPO, PRTN3, CD34, LCP1, BC035044 
## PC_ 2 
## Positive:  ANGPT1, ADGRG1, MEIS1, ITGA2B, MPL, DAPP1, APOE, RAB37, GATA2, F2R 
## Negative:  LY6C2, ELANE, HP, IGSF6, ANXA3, CTSG, CLEC12A, TIFAB, SLPI, ALAS1 
## PC_ 3 
## Positive:  APOE, GATA2, NKG7, MUC13, MS4A3, RAB44, HDC, CPA3, FCGR3, TUBA8 
## Negative:  FLT3, DNTT, LSP1, WFDC17, MYL10, GIMAP6, LAX1, GPR171, TBXA2R, SATB1 
## PC_ 4 
## Positive:  CSRP3, ST8SIA6, DNTT, MPEG1, SCIN, LGALS1, CMAH, RGL1, APOE, MFSD2B 
## Negative:  PROCR, MPL, HLF, MMRN1, SERPINA3G, ESAM, GSTM1, D630039A03RIK, MYL10, LY6A 
## PC_ 5 
## Positive:  CPA3, LMO4, IKZF2, IFITM1, FUT8, MS4A2, SIGLECF, CSRP3, HDC, RAB44 
## Negative:  PF4, GP1BB, SDPR, F2RL2, RAB27B, SLC14A1, TREML1, PBX1, F2R, TUBA8
```

Example 43 (unknown):
```unknown
# When running a PCA on only cell cycle genes, cells no longer separate by cell-cycle phase
marrow <- RunPCA(marrow, features = c(s.genes, g2m.genes))
DimPlot(marrow)
```

Example 44 (r):
```r
# When running a PCA on only cell cycle genes, cells no longer separate by cell-cycle phase
marrow <- RunPCA(marrow, features = c(s.genes, g2m.genes))
DimPlot(marrow)
```

Example 45 (r):
```r
# When running a PCA on only cell cycle genes, cells no longer separate by cell-cycle phase
marrow <- RunPCA(marrow, features = c(s.genes, g2m.genes))
DimPlot(marrow)
```

Example 46 (unknown):
```unknown
marrow$CC.Difference <- marrow$S.Score - marrow$G2M.Score
marrow <- ScaleData(marrow, vars.to.regress = "CC.Difference", features = rownames(marrow))
```

Example 47 (r):
```r
marrow$CC.Difference <- marrow$S.Score - marrow$G2M.Score
marrow <- ScaleData(marrow, vars.to.regress = "CC.Difference", features = rownames(marrow))
```

Example 48 (r):
```r
marrow$CC.Difference <- marrow$S.Score - marrow$G2M.Score
marrow <- ScaleData(marrow, vars.to.regress = "CC.Difference", features = rownames(marrow))
```

Example 49 (unknown):
```unknown
# cell cycle effects strongly mitigated in PCA
marrow <- RunPCA(marrow, features = VariableFeatures(marrow), nfeatures.print = 10)
```

Example 50 (r):
```r
# cell cycle effects strongly mitigated in PCA
marrow <- RunPCA(marrow, features = VariableFeatures(marrow), nfeatures.print = 10)
```

Example 51 (r):
```r
# cell cycle effects strongly mitigated in PCA
marrow <- RunPCA(marrow, features = VariableFeatures(marrow), nfeatures.print = 10)
```

Example 52 (unknown):
```unknown
## PC_ 1 
## Positive:  BLVRB, KLF1, ERMAP, FAM132A, CAR2, RHD, CES2G, SPHK1, AQP1, SLC38A5 
## Negative:  TMSB4X, CORO1A, PLAC8, H2AFY, LAPTM5, CD34, LCP1, TMEM176B, IGFBP4, EMB 
## PC_ 2 
## Positive:  APOE, GATA2, RAB37, ANGPT1, ADGRG1, MEIS1, MPL, F2R, PDZK1IP1, DAPP1 
## Negative:  CTSG, ELANE, LY6C2, HP, CLEC12A, ANXA3, IGSF6, TIFAB, SLPI, MPO 
## PC_ 3 
## Positive:  APOE, GATA2, NKG7, MUC13, ITGA2B, TUBA8, CPA3, RAB44, SLC18A2, CD9 
## Negative:  DNTT, FLT3, WFDC17, LSP1, MYL10, LAX1, GIMAP6, IGHM, CD24A, MN1 
## PC_ 4 
## Positive:  CSRP3, ST8SIA6, SCIN, LGALS1, APOE, ITGB7, MFSD2B, RGL1, DNTT, IGHV1-23 
## Negative:  MPL, MMRN1, PROCR, HLF, SERPINA3G, ESAM, PTGS1, D630039A03RIK, NDN, PPIC 
## PC_ 5 
## Positive:  GP1BB, PF4, SDPR, F2RL2, TREML1, RAB27B, SLC14A1, PBX1, PLEK, TUBA8 
## Negative:  HDC, LMO4, CSRP3, IFITM1, FCGR3, HLF, CPA3, PROCR, PGLYRP1, IKZF2
```

Example 53 (unknown):
```unknown
## PC_ 1 
## Positive:  BLVRB, KLF1, ERMAP, FAM132A, CAR2, RHD, CES2G, SPHK1, AQP1, SLC38A5 
## Negative:  TMSB4X, CORO1A, PLAC8, H2AFY, LAPTM5, CD34, LCP1, TMEM176B, IGFBP4, EMB 
## PC_ 2 
## Positive:  APOE, GATA2, RAB37, ANGPT1, ADGRG1, MEIS1, MPL, F2R, PDZK1IP1, DAPP1 
## Negative:  CTSG, ELANE, LY6C2, HP, CLEC12A, ANXA3, IGSF6, TIFAB, SLPI, MPO 
## PC_ 3 
## Positive:  APOE, GATA2, NKG7, MUC13, ITGA2B, TUBA8, CPA3, RAB44, SLC18A2, CD9 
## Negative:  DNTT, FLT3, WFDC17, LSP1, MYL10, LAX1, GIMAP6, IGHM, CD24A, MN1 
## PC_ 4 
## Positive:  CSRP3, ST8SIA6, SCIN, LGALS1, APOE, ITGB7, MFSD2B, RGL1, DNTT, IGHV1-23 
## Negative:  MPL, MMRN1, PROCR, HLF, SERPINA3G, ESAM, PTGS1, D630039A03RIK, NDN, PPIC 
## PC_ 5 
## Positive:  GP1BB, PF4, SDPR, F2RL2, TREML1, RAB27B, SLC14A1, PBX1, PLEK, TUBA8 
## Negative:  HDC, LMO4, CSRP3, IFITM1, FCGR3, HLF, CPA3, PROCR, PGLYRP1, IKZF2
```

Example 54 (python):
```python
# when running a PCA on cell cycle genes, actively proliferating cells remain distinct from G1
# cells however, within actively proliferating cells, G2M and S phase cells group together
marrow <- RunPCA(marrow, features = c(s.genes, g2m.genes))
DimPlot(marrow)
```

Example 55 (r):
```r
# when running a PCA on cell cycle genes, actively proliferating cells remain distinct from G1
# cells however, within actively proliferating cells, G2M and S phase cells group together
marrow <- RunPCA(marrow, features = c(s.genes, g2m.genes))
DimPlot(marrow)
```

Example 56 (r):
```r
# when running a PCA on cell cycle genes, actively proliferating cells remain distinct from G1
# cells however, within actively proliferating cells, G2M and S phase cells group together
marrow <- RunPCA(marrow, features = c(s.genes, g2m.genes))
DimPlot(marrow)
```

Example 57 (unknown):
```unknown
sessionInfo()
```

Example 58 (r):
```r
sessionInfo()
```

Example 59 (r):
```r
sessionInfo()
```

Example 60 (unknown):
```unknown
## R version 4.2.2 Patched (2022-11-10 r83330)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.6 LTS
## 
## Matrix products: default
## BLAS:   /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.9.0
## LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.9.0
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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       
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
## [1] ggplot2_3.4.4      Seurat_5.0.0       SeuratObject_5.0.0 sp_2.1-1          
## 
## loaded via a namespace (and not attached):
##   [1] ggbeeswarm_0.7.1       Rtsne_0.16             colorspace_2.1-0      
##   [4] deldir_1.0-9           ellipsis_0.3.2         ggridges_0.5.4        
##   [7] rprojroot_2.0.3        RcppHNSW_0.5.0         fs_1.6.3              
##  [10] spatstat.data_3.0-3    farver_2.1.1           leiden_0.4.3          
##  [13] listenv_0.9.0          ggrepel_0.9.4          RSpectra_0.16-1       
##  [16] fansi_1.0.5            codetools_0.2-19       splines_4.2.2         
##  [19] cachem_1.0.8           knitr_1.45             polyclip_1.10-6       
##  [22] spam_2.10-0            jsonlite_1.8.7         ica_1.0-3             
##  [25] cluster_2.1.4          png_0.1-8              uwot_0.1.16           
##  [28] spatstat.sparse_3.0-3  sctransform_0.4.1      shiny_1.7.5.1         
##  [31] compiler_4.2.2         httr_1.4.7             Matrix_1.6-1.1        
##  [34] fastmap_1.1.1          lazyeval_0.2.2         cli_3.6.1             
##  [37] later_1.3.1            formatR_1.14           htmltools_0.5.6.1     
##  [40] tools_4.2.2            igraph_1.5.1           dotCall64_1.1-0       
##  [43] gtable_0.3.4           glue_1.6.2             reshape2_1.4.4        
##  [46] RANN_2.6.1             dplyr_1.1.3            Rcpp_1.0.11           
##  [49] scattermore_1.2        jquerylib_0.1.4        pkgdown_2.0.7         
##  [52] vctrs_0.6.4            nlme_3.1-162           spatstat.explore_3.2-5
##  [55] progressr_0.14.0       lmtest_0.9-40          spatstat.random_3.2-1 
##  [58] xfun_0.40              stringr_1.5.0          globals_0.16.2        
##  [61] mime_0.12              miniUI_0.1.1.1         lifecycle_1.0.3       
##  [64] irlba_2.3.5.1          goftest_1.2-3          future_1.33.0         
##  [67] MASS_7.3-58.2          zoo_1.8-12             scales_1.2.1          
##  [70] spatstat.utils_3.0-4   ragg_1.2.5             promises_1.2.1        
##  [73] parallel_4.2.2         RColorBrewer_1.1-3     yaml_2.3.7            
##  [76] gridExtra_2.3          memoise_2.0.1          reticulate_1.34.0     
##  [79] pbapply_1.7-2          ggrastr_1.0.1          sass_0.4.7            
##  [82] stringi_1.7.12         highr_0.10             desc_1.4.2            
##  [85] fastDummies_1.7.3      rlang_1.1.1            pkgconfig_2.0.3       
##  [88] systemfonts_1.0.4      matrixStats_1.0.0      evaluate_0.22         
##  [91] lattice_0.21-9         tensor_1.5             ROCR_1.0-11           
##  [94] purrr_1.0.2            labeling_0.4.3         patchwork_1.1.3       
##  [97] htmlwidgets_1.6.2      cowplot_1.1.1          tidyselect_1.2.0      
## [100] parallelly_1.36.0      RcppAnnoy_0.0.21       plyr_1.8.9            
## [103] magrittr_2.0.3         R6_2.5.1               generics_0.1.3        
## [106] withr_2.5.2            pillar_1.9.0           fitdistrplus_1.1-11   
## [109] abind_1.4-5            survival_3.5-7         tibble_3.2.1          
## [112] future.apply_1.11.0    KernSmooth_2.23-22     utf8_1.2.4            
## [115] spatstat.geom_3.2-7    plotly_4.10.3          rmarkdown_2.25        
## [118] grid_4.2.2             data.table_1.14.8      digest_0.6.33         
## [121] xtable_1.8-4           tidyr_1.3.0            httpuv_1.6.12         
## [124] textshaping_0.3.6      munsell_0.5.0          beeswarm_0.4.0        
## [127] viridisLite_0.4.2      vipor_0.4.5            bslib_0.5.1
```

Example 61 (unknown):
```unknown
## R version 4.2.2 Patched (2022-11-10 r83330)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.6 LTS
## 
## Matrix products: default
## BLAS:   /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.9.0
## LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.9.0
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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       
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
## [1] ggplot2_3.4.4      Seurat_5.0.0       SeuratObject_5.0.0 sp_2.1-1          
## 
## loaded via a namespace (and not attached):
##   [1] ggbeeswarm_0.7.1       Rtsne_0.16             colorspace_2.1-0      
##   [4] deldir_1.0-9           ellipsis_0.3.2         ggridges_0.5.4        
##   [7] rprojroot_2.0.3        RcppHNSW_0.5.0         fs_1.6.3              
##  [10] spatstat.data_3.0-3    farver_2.1.1           leiden_0.4.3          
##  [13] listenv_0.9.0          ggrepel_0.9.4          RSpectra_0.16-1       
##  [16] fansi_1.0.5            codetools_0.2-19       splines_4.2.2         
##  [19] cachem_1.0.8           knitr_1.45             polyclip_1.10-6       
##  [22] spam_2.10-0            jsonlite_1.8.7         ica_1.0-3             
##  [25] cluster_2.1.4          png_0.1-8              uwot_0.1.16           
##  [28] spatstat.sparse_3.0-3  sctransform_0.4.1      shiny_1.7.5.1         
##  [31] compiler_4.2.2         httr_1.4.7             Matrix_1.6-1.1        
##  [34] fastmap_1.1.1          lazyeval_0.2.2         cli_3.6.1             
##  [37] later_1.3.1            formatR_1.14           htmltools_0.5.6.1     
##  [40] tools_4.2.2            igraph_1.5.1           dotCall64_1.1-0       
##  [43] gtable_0.3.4           glue_1.6.2             reshape2_1.4.4        
##  [46] RANN_2.6.1             dplyr_1.1.3            Rcpp_1.0.11           
##  [49] scattermore_1.2        jquerylib_0.1.4        pkgdown_2.0.7         
##  [52] vctrs_0.6.4            nlme_3.1-162           spatstat.explore_3.2-5
##  [55] progressr_0.14.0       lmtest_0.9-40          spatstat.random_3.2-1 
##  [58] xfun_0.40              stringr_1.5.0          globals_0.16.2        
##  [61] mime_0.12              miniUI_0.1.1.1         lifecycle_1.0.3       
##  [64] irlba_2.3.5.1          goftest_1.2-3          future_1.33.0         
##  [67] MASS_7.3-58.2          zoo_1.8-12             scales_1.2.1          
##  [70] spatstat.utils_3.0-4   ragg_1.2.5             promises_1.2.1        
##  [73] parallel_4.2.2         RColorBrewer_1.1-3     yaml_2.3.7            
##  [76] gridExtra_2.3          memoise_2.0.1          reticulate_1.34.0     
##  [79] pbapply_1.7-2          ggrastr_1.0.1          sass_0.4.7            
##  [82] stringi_1.7.12         highr_0.10             desc_1.4.2            
##  [85] fastDummies_1.7.3      rlang_1.1.1            pkgconfig_2.0.3       
##  [88] systemfonts_1.0.4      matrixStats_1.0.0      evaluate_0.22         
##  [91] lattice_0.21-9         tensor_1.5             ROCR_1.0-11           
##  [94] purrr_1.0.2            labeling_0.4.3         patchwork_1.1.3       
##  [97] htmlwidgets_1.6.2      cowplot_1.1.1          tidyselect_1.2.0      
## [100] parallelly_1.36.0      RcppAnnoy_0.0.21       plyr_1.8.9            
## [103] magrittr_2.0.3         R6_2.5.1               generics_0.1.3        
## [106] withr_2.5.2            pillar_1.9.0           fitdistrplus_1.1-11   
## [109] abind_1.4-5            survival_3.5-7         tibble_3.2.1          
## [112] future.apply_1.11.0    KernSmooth_2.23-22     utf8_1.2.4            
## [115] spatstat.geom_3.2-7    plotly_4.10.3          rmarkdown_2.25        
## [118] grid_4.2.2             data.table_1.14.8      digest_0.6.33         
## [121] xtable_1.8-4           tidyr_1.3.0            httpuv_1.6.12         
## [124] textshaping_0.3.6      munsell_0.5.0          beeswarm_0.4.0        
## [127] viridisLite_0.4.2      vipor_0.4.5            bslib_0.5.1
```

---

## PBMC scATAC-seq Vignette

**URL:** http://127.0.0.1:9173/archive_v3.0_atacseq_integration_vignette.html

**Contents:**
- PBMC scATAC-seq Vignette
    - Compiled: June 06, 2019
- Gene activity quantification
- Object setup
- Data preprocessing
- Co-embedding

In this vignette, we demonstrate our new data transfer method in the context of scATAC-seq to

For this example we’ll be working with the 10X PBMC datasets that contain ~10K cells for both scRNA-seq and scATAC-seq. You can download those here: scATAC-seq, scATAC-seq metadata, scRNA-seq

Overall our integration procedure consists of the following steps:

First, we load in the provided peak matrix and collapse the peak matrix to a “gene activity matrix”. Here, we make the simplifying assumption that a gene’s activity can be quantified by simply summing all counts within the gene body + 2kb upstream but our method is compatible with any method that returns a gene by cell matrix (e.g. Cicero).

Next, we’ll set up the Seurat object and store both the original peak counts in the “ATAC” Assay and the gene activity matrix in the “RNA” Assay. As a QC step, we also filter out all cells here with fewer than 5K total counts in the scATAC-seq data, though you may need to modify this threshold for your experiment.

Here, we process the gene activity matrix in order to find anchors between cells in the scATAC-seq dataset and the scRNA-seq dataset.

We also process the peak matrix. Here we perform latent semantic indexing to reduce the dimensionality of the scATAC-seq data. This procedure learns an ‘internal’ structure for the scRNA-seq data, and is important when determining the appropriate weights for the anchors when transferring information. We utilize Latent Semantic Indexing (LSI) to learn the structure of ATAC-seq data, as proposed in Cusanovich et al, Science 2015 and implemented in the RunLSI function. LSI is implemented here by performing computing the term frequency-inverse document frequency (TF-IDF) followed by SVD.

We use all peaks that have at least 100 reads across all cells, and reduce dimensionality to 50. The parameters chosen here are inspired by previous scATAC-seq analyses, and we do not typically change them, but you can do so.

We have previously pre-processed and clustered a scRNA-seq dataset using the standard workflow in Seurat, and provide the object here. You can see that we can identify standard clusters of myeloid and lymphoid PBMCs.

Now, we can identify anchors between the scATAC-seq dataset and the scRNA-seq dataset and use these anchors to transfer the celltype labels we learned from the 10K scRNA-seq data to the scATAC-seq cells.

To transfer the cluster ids, we provide a vector of previously annotated cell type labels for the RNA to the refdata parameter. The output will contain a matrix with predictions and confidence scores for each ATAC-seq cell.

Why do you choose different (non-default) values for reduction and weight.reduction?

In FindTransferAnchors, we typically project the PCA structure from the reference onto the query when transferring between scRNA-seq datasets. However, when transferring across modalities we find that CCA better captures the shared feature correlation structure and therefore set reduction = 'cca' here. Additionally, by default in TransferData we use the same projected PCA structure to compute the weights of the local neighborhood of anchors that influence each cell’s prediction. In the case of scRNA-seq to scATA-seq transfer, we use the low dimensional space learned by computing an LSI on the ATAC-seq data to compute these weights as this better captures the “internal” structure of the ATAC-seq data.

We can then examine the distribution of prediction scores and optionally filter out those cells with low scores. Here, we find that over 95% of the cells receive a score of 0.5 or greater.

We can then view the predicted cell types on a UMAP representation of the scATAC-seq data and find that the transferred labels are highly consistent with the UMAP structure.

After transferring cell type labels, you can then perform downstream analyses on a cell type specific level. For example, you could find sets of enhancers that are specific for certain cell types and look for motif enrichment. While not all of these types of downstream analyses are directly supported in Seurat, stay tuned for updates in this space.

Finally, to visualize all the cells together, we can co-embed the scRNA-seq and scATAC-seq cells in the same low dimensional space. Here, we use the same anchors used earlier to transfer cell type labels to impute RNA-seq values for the scATAC-seq cells. We then merge the measured and imputed scRNA-seq data and run a standard UMAP analysis to visualize all the cells together. Note that this step is for visualization purposes only and is not a necessary part of the data transfer analysis.

Here we plot all cells colored by either their assigned cell type (from the 10K dataset) or their predicted cell type from the data transfer procedure.

How can I further investigate unmatched groups of cells that only appear in one assay?

Upon inspection of the UMAP embeddings, there appeared several groups of cells that appeared to be present only in a single assay. First, the platelet cells appeared only in the scRNA-seq data. These cells are thought to be undergoing biogenesis from megakaryocytes to platelets and therefore either completely lack nuclear material or their chromatin state is uncoupled from their transcriptome. As a result, we would not expect these to align in this analysis.

Additionally, there appeared to be a population next to the B cell progenitors that is composed entirely of scATAC-seq cells and is not integrated well with the scRNA-seq cells. Further examination of the metadata for these cells revealed a high number of reads mapping to blacklisted regions (as provided by the 10x Genomics QC metrics). This suggests that these barcodes could represent dead or dying cells, ambient DNA, or another technical artifact not represented in the scRNA-seq dataset.

How can I evaluate the success of cross-modality integration?

There are several lines of evidence here that give us confidence in this analysis.

Additionally, we have performed a similar analysis, transferring cell type labels from scRNA-seq to scATAC-seq data in the context of the mouse brain and have observed good performance based on similar reasoning to the points above ( Figure 3). These analyses make the assumption that there is generally a positive correlation between chromatin accessibility and gene expression. In cases such as developing systems, where accessibility may not be a good indicator of transcription, the method demonstrated here may not be able to form good anchors and the resulting integration across these specific modalities may be of limited value.

**Examples:**

Example 1 (r):
```r
library(Seurat)
library(ggplot2)
peaks <- Read10X_h5("../data/atac_v1_pbmc_10k_filtered_peak_bc_matrix.h5")
# create a gene activity matrix from the peak matrix and GTF, using chromosomes 1:22, X, and Y.
# Peaks that fall within gene bodies, or 2kb upstream of a gene, are considered
activity.matrix <- CreateGeneActivityMatrix(peak.matrix = peaks, annotation.file = "../data/Homo_sapiens.GRCh37.82.gtf", 
    seq.levels = c(1:22, "X", "Y"), upstream = 2000, verbose = TRUE)
```

Example 2 (r):
```r
library(Seurat)
library(ggplot2)
peaks <- Read10X_h5("../data/atac_v1_pbmc_10k_filtered_peak_bc_matrix.h5")
# create a gene activity matrix from the peak matrix and GTF, using chromosomes 1:22, X, and Y.
# Peaks that fall within gene bodies, or 2kb upstream of a gene, are considered
activity.matrix <- CreateGeneActivityMatrix(peak.matrix = peaks, annotation.file = "../data/Homo_sapiens.GRCh37.82.gtf", 
    seq.levels = c(1:22, "X", "Y"), upstream = 2000, verbose = TRUE)
```

Example 3 (r):
```r
pbmc.atac <- CreateSeuratObject(counts = peaks, assay = "ATAC", project = "10x_ATAC")
pbmc.atac[["ACTIVITY"]] <- CreateAssayObject(counts = activity.matrix)
meta <- read.table("../data/atac_v1_pbmc_10k_singlecell.csv", sep = ",", header = TRUE, row.names = 1, 
    stringsAsFactors = FALSE)
meta <- meta[colnames(pbmc.atac), ]
pbmc.atac <- AddMetaData(pbmc.atac, metadata = meta)
pbmc.atac <- subset(pbmc.atac, subset = nCount_ATAC > 5000)
pbmc.atac$tech <- "atac"
```

Example 4 (r):
```r
pbmc.atac <- CreateSeuratObject(counts = peaks, assay = "ATAC", project = "10x_ATAC")
pbmc.atac[["ACTIVITY"]] <- CreateAssayObject(counts = activity.matrix)
meta <- read.table("../data/atac_v1_pbmc_10k_singlecell.csv", sep = ",", header = TRUE, row.names = 1, 
    stringsAsFactors = FALSE)
meta <- meta[colnames(pbmc.atac), ]
pbmc.atac <- AddMetaData(pbmc.atac, metadata = meta)
pbmc.atac <- subset(pbmc.atac, subset = nCount_ATAC > 5000)
pbmc.atac$tech <- "atac"
```

Example 5 (r):
```r
DefaultAssay(pbmc.atac) <- "ACTIVITY"
pbmc.atac <- FindVariableFeatures(pbmc.atac)
pbmc.atac <- NormalizeData(pbmc.atac)
pbmc.atac <- ScaleData(pbmc.atac)
```

Example 6 (r):
```r
DefaultAssay(pbmc.atac) <- "ACTIVITY"
pbmc.atac <- FindVariableFeatures(pbmc.atac)
pbmc.atac <- NormalizeData(pbmc.atac)
pbmc.atac <- ScaleData(pbmc.atac)
```

Example 7 (r):
```r
DefaultAssay(pbmc.atac) <- "ATAC"
VariableFeatures(pbmc.atac) <- names(which(Matrix::rowSums(pbmc.atac) > 100))
pbmc.atac <- RunLSI(pbmc.atac, n = 50, scale.max = NULL)
pbmc.atac <- RunUMAP(pbmc.atac, reduction = "lsi", dims = 1:50)
```

Example 8 (r):
```r
DefaultAssay(pbmc.atac) <- "ATAC"
VariableFeatures(pbmc.atac) <- names(which(Matrix::rowSums(pbmc.atac) > 100))
pbmc.atac <- RunLSI(pbmc.atac, n = 50, scale.max = NULL)
pbmc.atac <- RunUMAP(pbmc.atac, reduction = "lsi", dims = 1:50)
```

Example 9 (r):
```r
pbmc.rna <- readRDS("../data/pbmc_10k_v3.rds")
pbmc.rna$tech <- "rna"
```

Example 10 (r):
```r
pbmc.rna <- readRDS("../data/pbmc_10k_v3.rds")
pbmc.rna$tech <- "rna"
```

Example 11 (r):
```r
p1 <- DimPlot(pbmc.atac, reduction = "umap") + NoLegend() + ggtitle("scATAC-seq")
p2 <- DimPlot(pbmc.rna, group.by = "celltype", label = TRUE, repel = TRUE) + NoLegend() + ggtitle("scRNA-seq")
CombinePlots(plots = list(p1, p2))
```

Example 12 (r):
```r
p1 <- DimPlot(pbmc.atac, reduction = "umap") + NoLegend() + ggtitle("scATAC-seq")
p2 <- DimPlot(pbmc.rna, group.by = "celltype", label = TRUE, repel = TRUE) + NoLegend() + ggtitle("scRNA-seq")
CombinePlots(plots = list(p1, p2))
```

Example 13 (r):
```r
transfer.anchors <- FindTransferAnchors(reference = pbmc.rna, query = pbmc.atac, features = VariableFeatures(object = pbmc.rna), 
    reference.assay = "RNA", query.assay = "ACTIVITY", reduction = "cca")
```

Example 14 (r):
```r
transfer.anchors <- FindTransferAnchors(reference = pbmc.rna, query = pbmc.atac, features = VariableFeatures(object = pbmc.rna), 
    reference.assay = "RNA", query.assay = "ACTIVITY", reduction = "cca")
```

Example 15 (r):
```r
celltype.predictions <- TransferData(anchorset = transfer.anchors, refdata = pbmc.rna$celltype, 
    weight.reduction = pbmc.atac[["lsi"]])
pbmc.atac <- AddMetaData(pbmc.atac, metadata = celltype.predictions)
```

Example 16 (r):
```r
celltype.predictions <- TransferData(anchorset = transfer.anchors, refdata = pbmc.rna$celltype, 
    weight.reduction = pbmc.atac[["lsi"]])
pbmc.atac <- AddMetaData(pbmc.atac, metadata = celltype.predictions)
```

Example 17 (unknown):
```unknown
FindTransferAnchors
```

Example 18 (unknown):
```unknown
reduction = 'cca'
```

Example 19 (unknown):
```unknown
TransferData
```

Example 20 (r):
```r
hist(pbmc.atac$prediction.score.max)
abline(v = 0.5, col = "red")
```

Example 21 (r):
```r
hist(pbmc.atac$prediction.score.max)
abline(v = 0.5, col = "red")
```

Example 22 (r):
```r
table(pbmc.atac$prediction.score.max > 0.5)
```

Example 23 (r):
```r
table(pbmc.atac$prediction.score.max > 0.5)
```

Example 24 (unknown):
```unknown
## 
## FALSE  TRUE 
##   280  7586
```

Example 25 (unknown):
```unknown
## 
## FALSE  TRUE 
##   280  7586
```

Example 26 (r):
```r
pbmc.atac.filtered <- subset(pbmc.atac, subset = prediction.score.max > 0.5)
pbmc.atac.filtered$predicted.id <- factor(pbmc.atac.filtered$predicted.id, levels = levels(pbmc.rna))  # to make the colors match
p1 <- DimPlot(pbmc.atac.filtered, group.by = "predicted.id", label = TRUE, repel = TRUE) + ggtitle("scATAC-seq cells") + 
    NoLegend() + scale_colour_hue(drop = FALSE)
p2 <- DimPlot(pbmc.rna, group.by = "celltype", label = TRUE, repel = TRUE) + ggtitle("scRNA-seq cells") + 
    NoLegend()
CombinePlots(plots = list(p1, p2))
```

Example 27 (r):
```r
pbmc.atac.filtered <- subset(pbmc.atac, subset = prediction.score.max > 0.5)
pbmc.atac.filtered$predicted.id <- factor(pbmc.atac.filtered$predicted.id, levels = levels(pbmc.rna))  # to make the colors match
p1 <- DimPlot(pbmc.atac.filtered, group.by = "predicted.id", label = TRUE, repel = TRUE) + ggtitle("scATAC-seq cells") + 
    NoLegend() + scale_colour_hue(drop = FALSE)
p2 <- DimPlot(pbmc.rna, group.by = "celltype", label = TRUE, repel = TRUE) + ggtitle("scRNA-seq cells") + 
    NoLegend()
CombinePlots(plots = list(p1, p2))
```

Example 28 (r):
```r
# note that we restrict the imputation to variable genes from scRNA-seq, but could impute the
# full transcriptome if we wanted to
genes.use <- VariableFeatures(pbmc.rna)
refdata <- GetAssayData(pbmc.rna, assay = "RNA", slot = "data")[genes.use, ]

# refdata (input) contains a scRNA-seq expression matrix for the scRNA-seq cells.  imputation
# (output) will contain an imputed scRNA-seq matrix for each of the ATAC cells
imputation <- TransferData(anchorset = transfer.anchors, refdata = refdata, weight.reduction = pbmc.atac[["lsi"]])

# this line adds the imputed data matrix to the pbmc.atac object
pbmc.atac[["RNA"]] <- imputation
coembed <- merge(x = pbmc.rna, y = pbmc.atac)

# Finally, we run PCA and UMAP on this combined object, to visualize the co-embedding of both
# datasets
coembed <- ScaleData(coembed, features = genes.use, do.scale = FALSE)
coembed <- RunPCA(coembed, features = genes.use, verbose = FALSE)
coembed <- RunUMAP(coembed, dims = 1:30)
coembed$celltype <- ifelse(!is.na(coembed$celltype), coembed$celltype, coembed$predicted.id)
```

Example 29 (r):
```r
# note that we restrict the imputation to variable genes from scRNA-seq, but could impute the
# full transcriptome if we wanted to
genes.use <- VariableFeatures(pbmc.rna)
refdata <- GetAssayData(pbmc.rna, assay = "RNA", slot = "data")[genes.use, ]

# refdata (input) contains a scRNA-seq expression matrix for the scRNA-seq cells.  imputation
# (output) will contain an imputed scRNA-seq matrix for each of the ATAC cells
imputation <- TransferData(anchorset = transfer.anchors, refdata = refdata, weight.reduction = pbmc.atac[["lsi"]])

# this line adds the imputed data matrix to the pbmc.atac object
pbmc.atac[["RNA"]] <- imputation
coembed <- merge(x = pbmc.rna, y = pbmc.atac)

# Finally, we run PCA and UMAP on this combined object, to visualize the co-embedding of both
# datasets
coembed <- ScaleData(coembed, features = genes.use, do.scale = FALSE)
coembed <- RunPCA(coembed, features = genes.use, verbose = FALSE)
coembed <- RunUMAP(coembed, dims = 1:30)
coembed$celltype <- ifelse(!is.na(coembed$celltype), coembed$celltype, coembed$predicted.id)
```

Example 30 (r):
```r
p1 <- DimPlot(coembed, group.by = "tech")
p2 <- DimPlot(coembed, group.by = "celltype", label = TRUE, repel = TRUE)
CombinePlots(list(p1, p2))
```

Example 31 (r):
```r
p1 <- DimPlot(coembed, group.by = "tech")
p2 <- DimPlot(coembed, group.by = "celltype", label = TRUE, repel = TRUE)
CombinePlots(list(p1, p2))
```

Example 32 (r):
```r
DimPlot(coembed, split.by = "tech", group.by = "celltype", label = TRUE, repel = TRUE) + NoLegend()
```

Example 33 (r):
```r
DimPlot(coembed, split.by = "tech", group.by = "celltype", label = TRUE, repel = TRUE) + NoLegend()
```

Example 34 (r):
```r
coembed$blacklist_region_fragments[is.na(coembed$blacklist_region_fragments)] <- 0
FeaturePlot(coembed, features = "blacklist_region_fragments", max.cutoff = 500)
```

Example 35 (r):
```r
coembed$blacklist_region_fragments[is.na(coembed$blacklist_region_fragments)] <- 0
FeaturePlot(coembed, features = "blacklist_region_fragments", max.cutoff = 500)
```

---

## Differential expression testing

**URL:** http://127.0.0.1:9173/seurat/v3.0/de_vignette.html

**Contents:**
- Differential expression testing
    - Compiled: 2019-06-24
  - Load in the data
  - Perform default differential expression tests
  - Prefilter features or cells to increase the speed of DE testing
  - Perform DE analysis using alternative tests
  - Acknowledgements

This vignette highlights some example workflows for performing differential expression in Seurat. For demonstration purposes, we will be using the 2,700 PBMC object that is created in the first guided tutorial. You can download the pre-computed object here.

The bulk of Seurat’s differential expression features can be accessed through the FindMarkers function. As a default, Seurat performs differential expression based on the non-parameteric Wilcoxon rank sum test. This replaces the previous default test (‘bimod’). To test for differential expression between two specific groups of cells, specify the ident.1 and ident.2 parameters.

The results data frame has the following columns :

If the ident.2 parameter is omitted or set to NULL, FindMarkers will test for differentially expressed features between the group specified by ident.1 and all other cells.

To increase the speed of marker discovery, particularly for large datasets, Seurat allows for pre-filtering of features or cells. For example, features that are very infrequently detected in either group of cells, or features that are expressed at similar average levels, are unlikely to be differentially expressed. Example use cases of the min.pct, logfc.threshold, min.diff.pct, and max.cells.per.ident parameters are demonstrated below.

The following differential expression tests are currently supported:

For MAST and DESeq2 please ensure that these packages are installed separately in order to use them as part of Seurat. Once installed, use the test.use parameter can be used to specify which DE test to use.

We thank the authors of the MAST and DESeq2 packages for their kind assistance and advice. We also point users to the following study by Charlotte Soneson and Mark Robinson, which performs careful and extensive evaluation of methods for single cell differential expression testing.

**Examples:**

Example 1 (r):
```r
library(Seurat)
pbmc <- readRDS(file = "../data/pbmc3k_final.rds")
```

Example 2 (r):
```r
library(Seurat)
pbmc <- readRDS(file = "../data/pbmc3k_final.rds")
```

Example 3 (unknown):
```unknown
FindMarkers
```

Example 4 (r):
```r
# list options for groups to perform differential expression on
levels(pbmc)
```

Example 5 (r):
```r
# list options for groups to perform differential expression on
levels(pbmc)
```

Example 6 (unknown):
```unknown
## [1] "Naive CD4 T"  "Memory CD4 T" "CD14+ Mono"   "B"           
## [5] "CD8 T"        "FCGR3A+ Mono" "NK"           "DC"          
## [9] "Platelet"
```

Example 7 (unknown):
```unknown
## [1] "Naive CD4 T"  "Memory CD4 T" "CD14+ Mono"   "B"           
## [5] "CD8 T"        "FCGR3A+ Mono" "NK"           "DC"          
## [9] "Platelet"
```

Example 8 (r):
```r
# Find differentially expressed features between CD14+ and FCGR3A+ Monocytes
monocyte.de.markers <- FindMarkers(pbmc, ident.1 = "CD14+ Mono", ident.2 = "FCGR3A+ Mono")
# view results
head(monocyte.de.markers)
```

Example 9 (r):
```r
# Find differentially expressed features between CD14+ and FCGR3A+ Monocytes
monocyte.de.markers <- FindMarkers(pbmc, ident.1 = "CD14+ Mono", ident.2 = "FCGR3A+ Mono")
# view results
head(monocyte.de.markers)
```

Example 10 (unknown):
```unknown
FindMarkers
```

Example 11 (r):
```r
# Find differentially expressed features between CD14+ Monocytes and all other cells, only
# search for positive markers
monocyte.de.markers <- FindMarkers(pbmc, ident.1 = "CD14+ Mono", ident.2 = NULL, only.pos = TRUE)
# view results
head(monocyte.de.markers)
```

Example 12 (r):
```r
# Find differentially expressed features between CD14+ Monocytes and all other cells, only
# search for positive markers
monocyte.de.markers <- FindMarkers(pbmc, ident.1 = "CD14+ Mono", ident.2 = NULL, only.pos = TRUE)
# view results
head(monocyte.de.markers)
```

Example 13 (unknown):
```unknown
logfc.threshold
```

Example 14 (unknown):
```unknown
min.diff.pct
```

Example 15 (unknown):
```unknown
max.cells.per.ident
```

Example 16 (r):
```r
# Pre-filter features that are detected at <50% frequency in either CD14+ Monocytes or FCGR3A+
# Monocytes
head(FindMarkers(pbmc, ident.1 = "CD14+ Mono", ident.2 = "FCGR3A+ Mono", min.pct = 0.5))
```

Example 17 (r):
```r
# Pre-filter features that are detected at <50% frequency in either CD14+ Monocytes or FCGR3A+
# Monocytes
head(FindMarkers(pbmc, ident.1 = "CD14+ Mono", ident.2 = "FCGR3A+ Mono", min.pct = 0.5))
```

Example 18 (r):
```r
# Pre-filter features that have less than a two-fold change between the average expression of
# CD14+ Monocytes vs FCGR3A+ Monocytes
head(FindMarkers(pbmc, ident.1 = "CD14+ Mono", ident.2 = "FCGR3A+ Mono", logfc.threshold = log(2)))
```

Example 19 (r):
```r
# Pre-filter features that have less than a two-fold change between the average expression of
# CD14+ Monocytes vs FCGR3A+ Monocytes
head(FindMarkers(pbmc, ident.1 = "CD14+ Mono", ident.2 = "FCGR3A+ Mono", logfc.threshold = log(2)))
```

Example 20 (r):
```r
# Pre-filter features whose detection percentages across the two groups are similar (within
# 0.25)
head(FindMarkers(pbmc, ident.1 = "CD14+ Mono", ident.2 = "FCGR3A+ Mono", min.diff.pct = 0.25))
```

Example 21 (r):
```r
# Pre-filter features whose detection percentages across the two groups are similar (within
# 0.25)
head(FindMarkers(pbmc, ident.1 = "CD14+ Mono", ident.2 = "FCGR3A+ Mono", min.diff.pct = 0.25))
```

Example 22 (r):
```r
# Increasing min.pct, logfc.threshold, and min.diff.pct, will increase the speed of DE testing,
# but could also miss features that are prefiltered

# Subsample each group to a maximum of 200 cells. Can be very useful for large clusters, or
# computationally-intensive DE tests
head(FindMarkers(pbmc, ident.1 = "CD14+ Mono", ident.2 = "FCGR3A+ Mono", max.cells.per.ident = 200))
```

Example 23 (r):
```r
# Increasing min.pct, logfc.threshold, and min.diff.pct, will increase the speed of DE testing,
# but could also miss features that are prefiltered

# Subsample each group to a maximum of 200 cells. Can be very useful for large clusters, or
# computationally-intensive DE tests
head(FindMarkers(pbmc, ident.1 = "CD14+ Mono", ident.2 = "FCGR3A+ Mono", max.cells.per.ident = 200))
```

Example 24 (r):
```r
# Test for DE features using the MAST package
head(FindMarkers(pbmc, ident.1 = "CD14+ Mono", ident.2 = "FCGR3A+ Mono", test.use = "MAST"))
```

Example 25 (r):
```r
# Test for DE features using the MAST package
head(FindMarkers(pbmc, ident.1 = "CD14+ Mono", ident.2 = "FCGR3A+ Mono", test.use = "MAST"))
```

Example 26 (r):
```r
# Test for DE features using the DESeq2 package. Throws an error if DESeq2 has not already been
# installed Note that the DESeq2 workflows can be computationally intensive for large datasets,
# but are incompatible with some feature pre-filtering options We therefore suggest initially
# limiting the number of cells used for testing
head(FindMarkers(pbmc, ident.1 = "CD14+ Mono", ident.2 = "FCGR3A+ Mono", test.use = "DESeq2", max.cells.per.ident = 50))
```

Example 27 (r):
```r
# Test for DE features using the DESeq2 package. Throws an error if DESeq2 has not already been
# installed Note that the DESeq2 workflows can be computationally intensive for large datasets,
# but are incompatible with some feature pre-filtering options We therefore suggest initially
# limiting the number of cells used for testing
head(FindMarkers(pbmc, ident.1 = "CD14+ Mono", ident.2 = "FCGR3A+ Mono", test.use = "DESeq2", max.cells.per.ident = 50))
```

---

## Interoperability between single-cell object formats • Seurat

**URL:** http://127.0.0.1:9173/seurat/archive/v4.3/conversion_vignette/index.html

**Contents:**
- Interoperability between single-cell object formats
    - Compiled: 2022-01-11
- Converting to/from SingleCellExperiment
- Converting to/from loom
- Converting to/from AnnData
- Acknowledgments
- Contents

In this vignette, we demonstrate the ability to convert between Seurat objects, SingleCellExperiment objects, and anndata objects.

SingleCellExperiment is a class for storing single-cell experiment data, created by Davide Risso, Aaron Lun, and Keegan Korthauer, and is used by many Bioconductor analysis packages. Here we demonstrate converting the Seurat object produced in our 3k PBMC tutorial to SingleCellExperiment for use with Davis McCarthy’s scater package.

Seurat also allows conversion from SingleCellExperiment objects to Seurat objects; we demonstrate this on some publicly available data downloaded from a repository maintained by Martin Hemberg’s group.

The loom format is a file structure imposed on HDF5 files designed by Sten Linnarsson’s group. It is designed to efficiently hold large single-cell genomics datasets. The ability to save Seurat objects as loom files is implemented in SeuratDisk For more details about the loom format, please see the loom file format specification.

Seurat can also read in loom files connected via SeuratDisk into a Seurat object; we demonstrate this on a subset of the Mouse Brain Atlas created by the Linnarsson lab.

For more details about interacting with loom files in R and Seurat, please see loomR on GitHub.

AnnData provides a Python class, created by Alex Wolf and Philipp Angerer, that can be used to store single-cell data. This data format is also use for storage in their Scanpy package for which we now support interoperability. Support for reading data from and saving data to AnnData files is provided by SeuratDisk; please see their vignette showcasing the interoperability.

Many thanks to Davis McCarthy and Alex Wolf for their help in drafting the conversion functions.

Developed by Paul Hoffman, Satija Lab and Collaborators.

Site built with pkgdown 1.6.1.

**Examples:**

Example 1 (unknown):
```unknown
vignettes/conversion_vignette.Rmd
```

Example 2 (unknown):
```unknown
conversion_vignette.Rmd
```

Example 3 (python):
```python
# install scater https://bioconductor.org/packages/release/bioc/html/scater.html
library(scater)
library(Seurat)
# install SeuratDisk from GitHub using the remotes package remotes::install_github(repo =
# 'mojaveazure/seurat-disk', ref = 'develop')
library(SeuratDisk)
library(SeuratData)
library(patchwork)
```

Example 4 (r):
```r
# install scater https://bioconductor.org/packages/release/bioc/html/scater.html
library(scater)
library(Seurat)
# install SeuratDisk from GitHub using the remotes package remotes::install_github(repo =
# 'mojaveazure/seurat-disk', ref = 'develop')
library(SeuratDisk)
library(SeuratData)
library(patchwork)
```

Example 5 (r):
```r
# install scater https://bioconductor.org/packages/release/bioc/html/scater.html
library(scater)
library(Seurat)
# install SeuratDisk from GitHub using the remotes package remotes::install_github(repo =
# 'mojaveazure/seurat-disk', ref = 'develop')
library(SeuratDisk)
library(SeuratData)
library(patchwork)
```

Example 6 (unknown):
```unknown
SingleCellExperiment
```

Example 7 (unknown):
```unknown
SingleCellExperiment
```

Example 8 (python):
```python
# Use PBMC3K from SeuratData
InstallData("pbmc3k")
pbmc <- LoadData(ds = "pbmc3k", type = "pbmc3k.final")
pbmc.sce <- as.SingleCellExperiment(pbmc)
p1 <- plotExpression(pbmc.sce, features = "MS4A1", x = "ident") + theme(axis.text.x = element_text(angle = 45,
    hjust = 1))
p2 <- plotPCA(pbmc.sce, colour_by = "ident")
p1 + p2
```

Example 9 (r):
```r
# Use PBMC3K from SeuratData
InstallData("pbmc3k")
pbmc <- LoadData(ds = "pbmc3k", type = "pbmc3k.final")
pbmc.sce <- as.SingleCellExperiment(pbmc)
p1 <- plotExpression(pbmc.sce, features = "MS4A1", x = "ident") + theme(axis.text.x = element_text(angle = 45,
    hjust = 1))
p2 <- plotPCA(pbmc.sce, colour_by = "ident")
p1 + p2
```

Example 10 (r):
```r
# Use PBMC3K from SeuratData
InstallData("pbmc3k")
pbmc <- LoadData(ds = "pbmc3k", type = "pbmc3k.final")
pbmc.sce <- as.SingleCellExperiment(pbmc)
p1 <- plotExpression(pbmc.sce, features = "MS4A1", x = "ident") + theme(axis.text.x = element_text(angle = 45,
    hjust = 1))
p2 <- plotPCA(pbmc.sce, colour_by = "ident")
p1 + p2
```

Example 11 (unknown):
```unknown
SingleCellExperiment
```

Example 12 (python):
```python
# download from hemberg lab
# https://scrnaseq-public-datasets.s3.amazonaws.com/scater-objects/manno_human.rds
manno <- readRDS(file = "../data/manno_human.rds")
manno <- runPCA(manno)
manno.seurat <- as.Seurat(manno, counts = "counts", data = "logcounts")
# gives the same results; but omits defaults provided in the last line
manno.seurat <- as.Seurat(manno)
Idents(manno.seurat) <- "cell_type1"
p1 <- DimPlot(manno.seurat, reduction = "PCA", group.by = "Source") + NoLegend()
p2 <- RidgePlot(manno.seurat, features = "ACTB", group.by = "Source")
p1 + p2
```

Example 13 (r):
```r
# download from hemberg lab
# https://scrnaseq-public-datasets.s3.amazonaws.com/scater-objects/manno_human.rds
manno <- readRDS(file = "../data/manno_human.rds")
manno <- runPCA(manno)
manno.seurat <- as.Seurat(manno, counts = "counts", data = "logcounts")
# gives the same results; but omits defaults provided in the last line
manno.seurat <- as.Seurat(manno)
Idents(manno.seurat) <- "cell_type1"
p1 <- DimPlot(manno.seurat, reduction = "PCA", group.by = "Source") + NoLegend()
p2 <- RidgePlot(manno.seurat, features = "ACTB", group.by = "Source")
p1 + p2
```

Example 14 (r):
```r
# download from hemberg lab
# https://scrnaseq-public-datasets.s3.amazonaws.com/scater-objects/manno_human.rds
manno <- readRDS(file = "../data/manno_human.rds")
manno <- runPCA(manno)
manno.seurat <- as.Seurat(manno, counts = "counts", data = "logcounts")
# gives the same results; but omits defaults provided in the last line
manno.seurat <- as.Seurat(manno)
Idents(manno.seurat) <- "cell_type1"
p1 <- DimPlot(manno.seurat, reduction = "PCA", group.by = "Source") + NoLegend()
p2 <- RidgePlot(manno.seurat, features = "ACTB", group.by = "Source")
p1 + p2
```

Example 15 (unknown):
```unknown
pbmc.loom <- as.loom(pbmc, filename = "../output/pbmc3k.loom", verbose = FALSE)
pbmc.loom
```

Example 16 (r):
```r
pbmc.loom <- as.loom(pbmc, filename = "../output/pbmc3k.loom", verbose = FALSE)
pbmc.loom
```

Example 17 (r):
```r
pbmc.loom <- as.loom(pbmc, filename = "../output/pbmc3k.loom", verbose = FALSE)
pbmc.loom
```

Example 18 (unknown):
```unknown
## Class: loom
## Filename: /seurat-private/output/pbmc3k.loom
## Access type: H5F_ACC_RDWR
## Listing:
##        name    obj_type dataset.dims dataset.type_class
##       attrs   H5I_GROUP         <NA>               <NA>
##   col_attrs   H5I_GROUP         <NA>               <NA>
##  col_graphs   H5I_GROUP         <NA>               <NA>
##      layers   H5I_GROUP         <NA>               <NA>
##      matrix H5I_DATASET 2638 x 13714          H5T_FLOAT
##   row_attrs   H5I_GROUP         <NA>               <NA>
##  row_graphs   H5I_GROUP         <NA>               <NA>
```

Example 19 (unknown):
```unknown
## Class: loom
## Filename: /seurat-private/output/pbmc3k.loom
## Access type: H5F_ACC_RDWR
## Listing:
##        name    obj_type dataset.dims dataset.type_class
##       attrs   H5I_GROUP         <NA>               <NA>
##   col_attrs   H5I_GROUP         <NA>               <NA>
##  col_graphs   H5I_GROUP         <NA>               <NA>
##      layers   H5I_GROUP         <NA>               <NA>
##      matrix H5I_DATASET 2638 x 13714          H5T_FLOAT
##   row_attrs   H5I_GROUP         <NA>               <NA>
##  row_graphs   H5I_GROUP         <NA>               <NA>
```

Example 20 (unknown):
```unknown
# Always remember to close loom files when done
pbmc.loom$close_all()
```

Example 21 (r):
```r
# Always remember to close loom files when done
pbmc.loom$close_all()
```

Example 22 (r):
```r
# Always remember to close loom files when done
pbmc.loom$close_all()
```

Example 23 (python):
```python
# download from linnarsson lab
# https://storage.googleapis.com/linnarsson-lab-loom/l6_r1_immune_cells.loom
l6.immune <- Connect(filename = "../data/l6_r1_immune_cells.loom", mode = "r")
l6.immune
```

Example 24 (r):
```r
# download from linnarsson lab
# https://storage.googleapis.com/linnarsson-lab-loom/l6_r1_immune_cells.loom
l6.immune <- Connect(filename = "../data/l6_r1_immune_cells.loom", mode = "r")
l6.immune
```

Example 25 (r):
```r
# download from linnarsson lab
# https://storage.googleapis.com/linnarsson-lab-loom/l6_r1_immune_cells.loom
l6.immune <- Connect(filename = "../data/l6_r1_immune_cells.loom", mode = "r")
l6.immune
```

Example 26 (unknown):
```unknown
## Class: loom
## Filename: /seurat-private/data/l6_r1_immune_cells.loom
## Access type: H5F_ACC_RDONLY
## Attributes: CreationDate, last_modified
## Listing:
##        name    obj_type  dataset.dims dataset.type_class
##   col_attrs   H5I_GROUP          <NA>               <NA>
##  col_graphs   H5I_GROUP          <NA>               <NA>
##      layers   H5I_GROUP          <NA>               <NA>
##      matrix H5I_DATASET 14908 x 27998          H5T_FLOAT
##   row_attrs   H5I_GROUP          <NA>               <NA>
##  row_graphs   H5I_GROUP          <NA>               <NA>
```

Example 27 (unknown):
```unknown
## Class: loom
## Filename: /seurat-private/data/l6_r1_immune_cells.loom
## Access type: H5F_ACC_RDONLY
## Attributes: CreationDate, last_modified
## Listing:
##        name    obj_type  dataset.dims dataset.type_class
##   col_attrs   H5I_GROUP          <NA>               <NA>
##  col_graphs   H5I_GROUP          <NA>               <NA>
##      layers   H5I_GROUP          <NA>               <NA>
##      matrix H5I_DATASET 14908 x 27998          H5T_FLOAT
##   row_attrs   H5I_GROUP          <NA>               <NA>
##  row_graphs   H5I_GROUP          <NA>               <NA>
```

Example 28 (unknown):
```unknown
l6.seurat <- as.Seurat(l6.immune)
Idents(l6.seurat) <- "ClusterName"
VlnPlot(l6.seurat, features = c("Sparc", "Ftl1", "Junb", "Ccl4"), ncol = 2)
```

Example 29 (r):
```r
l6.seurat <- as.Seurat(l6.immune)
Idents(l6.seurat) <- "ClusterName"
VlnPlot(l6.seurat, features = c("Sparc", "Ftl1", "Junb", "Ccl4"), ncol = 2)
```

Example 30 (r):
```r
l6.seurat <- as.Seurat(l6.immune)
Idents(l6.seurat) <- "ClusterName"
VlnPlot(l6.seurat, features = c("Sparc", "Ftl1", "Junb", "Ccl4"), ncol = 2)
```

Example 31 (unknown):
```unknown
# Always remember to close loom files when done
l6.immune$close_all()
```

Example 32 (r):
```r
# Always remember to close loom files when done
l6.immune$close_all()
```

Example 33 (r):
```r
# Always remember to close loom files when done
l6.immune$close_all()
```

Example 34 (unknown):
```unknown
sessionInfo()
```

Example 35 (r):
```r
sessionInfo()
```

Example 36 (r):
```r
sessionInfo()
```

Example 37 (unknown):
```unknown
## R version 4.1.0 (2021-05-18)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.2 LTS
## 
## Matrix products: default
## BLAS/LAPACK: /usr/lib/x86_64-linux-gnu/openblas-pthread/libopenblasp-r0.3.8.so
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [5] LC_MONETARY=en_US.UTF-8    LC_MESSAGES=C             
##  [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       
## 
## attached base packages:
## [1] parallel  stats4    stats     graphics  grDevices utils     datasets 
## [8] methods   base     
## 
## other attached packages:
##  [1] patchwork_1.1.1               thp1.eccite.SeuratData_3.1.5 
##  [3] stxBrain.SeuratData_0.1.1     ssHippo.SeuratData_3.1.4     
##  [5] pbmcsca.SeuratData_3.0.0      pbmcMultiome.SeuratData_0.1.1
##  [7] pbmc3k.SeuratData_3.1.4       panc8.SeuratData_3.0.2       
##  [9] ifnb.SeuratData_3.1.0         hcabm40k.SeuratData_3.0.0    
## [11] bmcite.SeuratData_0.3.0       SeuratData_0.2.1             
## [13] SeuratDisk_0.0.0.9019         SeuratObject_4.0.4           
## [15] Seurat_4.0.6                  scater_1.20.1                
## [17] ggplot2_3.3.5                 scuttle_1.2.1                
## [19] SingleCellExperiment_1.14.1   SummarizedExperiment_1.22.0  
## [21] Biobase_2.52.0                GenomicRanges_1.44.0         
## [23] GenomeInfoDb_1.28.1           IRanges_2.26.0               
## [25] S4Vectors_0.30.0              BiocGenerics_0.38.0          
## [27] MatrixGenerics_1.4.2          matrixStats_0.61.0           
## 
## loaded via a namespace (and not attached):
##   [1] utf8_1.2.2                reticulate_1.22          
##   [3] tidyselect_1.1.1          htmlwidgets_1.5.4        
##   [5] grid_4.1.0                BiocParallel_1.26.1      
##   [7] Rtsne_0.15                munsell_0.5.0            
##   [9] ScaledMatrix_1.0.0        codetools_0.2-18         
##  [11] ragg_1.1.3                ica_1.0-2                
##  [13] future_1.23.0             miniUI_0.1.1.1           
##  [15] withr_2.4.3               colorspace_2.0-2         
##  [17] highr_0.9                 knitr_1.33               
##  [19] ROCR_1.0-11               tensor_1.5               
##  [21] listenv_0.8.0             labeling_0.4.2           
##  [23] GenomeInfoDbData_1.2.6    polyclip_1.10-0          
##  [25] farver_2.1.0              bit64_4.0.5              
##  [27] rprojroot_2.0.2           parallelly_1.30.0        
##  [29] vctrs_0.3.8               generics_0.1.1           
##  [31] xfun_0.25                 R6_2.5.1                 
##  [33] ggbeeswarm_0.6.0          rsvd_1.0.5               
##  [35] hdf5r_1.3.3               bitops_1.0-7             
##  [37] spatstat.utils_2.3-0      cachem_1.0.6             
##  [39] DelayedArray_0.18.0       assertthat_0.2.1         
##  [41] promises_1.2.0.1          scales_1.1.1             
##  [43] beeswarm_0.4.0            gtable_0.3.0             
##  [45] beachmat_2.8.0            globals_0.14.0           
##  [47] goftest_1.2-3             rlang_0.4.12             
##  [49] systemfonts_1.0.2         splines_4.1.0            
##  [51] lazyeval_0.2.2            spatstat.geom_2.3-1      
##  [53] yaml_2.2.1                reshape2_1.4.4           
##  [55] abind_1.4-5               httpuv_1.6.5             
##  [57] tools_4.1.0               ellipsis_0.3.2           
##  [59] spatstat.core_2.3-2       jquerylib_0.1.4          
##  [61] RColorBrewer_1.1-2        ggridges_0.5.3           
##  [63] Rcpp_1.0.7                plyr_1.8.6               
##  [65] sparseMatrixStats_1.4.2   zlibbioc_1.38.0          
##  [67] purrr_0.3.4               RCurl_1.98-1.3           
##  [69] rpart_4.1-15              deldir_1.0-6             
##  [71] pbapply_1.5-0             viridis_0.6.1            
##  [73] cowplot_1.1.1             zoo_1.8-9                
##  [75] ggrepel_0.9.1             cluster_2.1.2            
##  [77] fs_1.5.2                  magrittr_2.0.1           
##  [79] data.table_1.14.2         scattermore_0.7          
##  [81] lmtest_0.9-39             RANN_2.6.1               
##  [83] fitdistrplus_1.1-6        mime_0.12                
##  [85] evaluate_0.14             xtable_1.8-4             
##  [87] gridExtra_2.3             compiler_4.1.0           
##  [89] tibble_3.1.6              KernSmooth_2.23-20       
##  [91] crayon_1.4.2              htmltools_0.5.2          
##  [93] mgcv_1.8-35               later_1.3.0              
##  [95] tidyr_1.1.4               DBI_1.1.1                
##  [97] formatR_1.11              MASS_7.3-54              
##  [99] rappdirs_0.3.3            Matrix_1.3-3             
## [101] cli_3.1.0                 igraph_1.2.11            
## [103] pkgconfig_2.0.3           pkgdown_1.6.1            
## [105] plotly_4.10.0             spatstat.sparse_2.1-0    
## [107] vipor_0.4.5               bslib_0.3.1              
## [109] XVector_0.32.0            stringr_1.4.0            
## [111] digest_0.6.29             sctransform_0.3.2        
## [113] RcppAnnoy_0.0.19          spatstat.data_2.1-2      
## [115] rmarkdown_2.10            leiden_0.3.9             
## [117] uwot_0.1.11               DelayedMatrixStats_1.14.2
## [119] shiny_1.7.1               lifecycle_1.0.1          
## [121] nlme_3.1-152              jsonlite_1.7.2           
## [123] BiocNeighbors_1.10.0      desc_1.4.0               
## [125] viridisLite_0.4.0         fansi_1.0.0              
## [127] pillar_1.6.4              lattice_0.20-44          
## [129] fastmap_1.1.0             httr_1.4.2               
## [131] survival_3.2-11           glue_1.6.0               
## [133] png_0.1-7                 bit_4.0.4                
## [135] stringi_1.7.6             sass_0.4.0               
## [137] textshaping_0.3.5         BiocSingular_1.8.1       
## [139] memoise_2.0.0             dplyr_1.0.7              
## [141] irlba_2.3.5               future.apply_1.8.1
```

Example 38 (unknown):
```unknown
## R version 4.1.0 (2021-05-18)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.2 LTS
## 
## Matrix products: default
## BLAS/LAPACK: /usr/lib/x86_64-linux-gnu/openblas-pthread/libopenblasp-r0.3.8.so
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [5] LC_MONETARY=en_US.UTF-8    LC_MESSAGES=C             
##  [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       
## 
## attached base packages:
## [1] parallel  stats4    stats     graphics  grDevices utils     datasets 
## [8] methods   base     
## 
## other attached packages:
##  [1] patchwork_1.1.1               thp1.eccite.SeuratData_3.1.5 
##  [3] stxBrain.SeuratData_0.1.1     ssHippo.SeuratData_3.1.4     
##  [5] pbmcsca.SeuratData_3.0.0      pbmcMultiome.SeuratData_0.1.1
##  [7] pbmc3k.SeuratData_3.1.4       panc8.SeuratData_3.0.2       
##  [9] ifnb.SeuratData_3.1.0         hcabm40k.SeuratData_3.0.0    
## [11] bmcite.SeuratData_0.3.0       SeuratData_0.2.1             
## [13] SeuratDisk_0.0.0.9019         SeuratObject_4.0.4           
## [15] Seurat_4.0.6                  scater_1.20.1                
## [17] ggplot2_3.3.5                 scuttle_1.2.1                
## [19] SingleCellExperiment_1.14.1   SummarizedExperiment_1.22.0  
## [21] Biobase_2.52.0                GenomicRanges_1.44.0         
## [23] GenomeInfoDb_1.28.1           IRanges_2.26.0               
## [25] S4Vectors_0.30.0              BiocGenerics_0.38.0          
## [27] MatrixGenerics_1.4.2          matrixStats_0.61.0           
## 
## loaded via a namespace (and not attached):
##   [1] utf8_1.2.2                reticulate_1.22          
##   [3] tidyselect_1.1.1          htmlwidgets_1.5.4        
##   [5] grid_4.1.0                BiocParallel_1.26.1      
##   [7] Rtsne_0.15                munsell_0.5.0            
##   [9] ScaledMatrix_1.0.0        codetools_0.2-18         
##  [11] ragg_1.1.3                ica_1.0-2                
##  [13] future_1.23.0             miniUI_0.1.1.1           
##  [15] withr_2.4.3               colorspace_2.0-2         
##  [17] highr_0.9                 knitr_1.33               
##  [19] ROCR_1.0-11               tensor_1.5               
##  [21] listenv_0.8.0             labeling_0.4.2           
##  [23] GenomeInfoDbData_1.2.6    polyclip_1.10-0          
##  [25] farver_2.1.0              bit64_4.0.5              
##  [27] rprojroot_2.0.2           parallelly_1.30.0        
##  [29] vctrs_0.3.8               generics_0.1.1           
##  [31] xfun_0.25                 R6_2.5.1                 
##  [33] ggbeeswarm_0.6.0          rsvd_1.0.5               
##  [35] hdf5r_1.3.3               bitops_1.0-7             
##  [37] spatstat.utils_2.3-0      cachem_1.0.6             
##  [39] DelayedArray_0.18.0       assertthat_0.2.1         
##  [41] promises_1.2.0.1          scales_1.1.1             
##  [43] beeswarm_0.4.0            gtable_0.3.0             
##  [45] beachmat_2.8.0            globals_0.14.0           
##  [47] goftest_1.2-3             rlang_0.4.12             
##  [49] systemfonts_1.0.2         splines_4.1.0            
##  [51] lazyeval_0.2.2            spatstat.geom_2.3-1      
##  [53] yaml_2.2.1                reshape2_1.4.4           
##  [55] abind_1.4-5               httpuv_1.6.5             
##  [57] tools_4.1.0               ellipsis_0.3.2           
##  [59] spatstat.core_2.3-2       jquerylib_0.1.4          
##  [61] RColorBrewer_1.1-2        ggridges_0.5.3           
##  [63] Rcpp_1.0.7                plyr_1.8.6               
##  [65] sparseMatrixStats_1.4.2   zlibbioc_1.38.0          
##  [67] purrr_0.3.4               RCurl_1.98-1.3           
##  [69] rpart_4.1-15              deldir_1.0-6             
##  [71] pbapply_1.5-0             viridis_0.6.1            
##  [73] cowplot_1.1.1             zoo_1.8-9                
##  [75] ggrepel_0.9.1             cluster_2.1.2            
##  [77] fs_1.5.2                  magrittr_2.0.1           
##  [79] data.table_1.14.2         scattermore_0.7          
##  [81] lmtest_0.9-39             RANN_2.6.1               
##  [83] fitdistrplus_1.1-6        mime_0.12                
##  [85] evaluate_0.14             xtable_1.8-4             
##  [87] gridExtra_2.3             compiler_4.1.0           
##  [89] tibble_3.1.6              KernSmooth_2.23-20       
##  [91] crayon_1.4.2              htmltools_0.5.2          
##  [93] mgcv_1.8-35               later_1.3.0              
##  [95] tidyr_1.1.4               DBI_1.1.1                
##  [97] formatR_1.11              MASS_7.3-54              
##  [99] rappdirs_0.3.3            Matrix_1.3-3             
## [101] cli_3.1.0                 igraph_1.2.11            
## [103] pkgconfig_2.0.3           pkgdown_1.6.1            
## [105] plotly_4.10.0             spatstat.sparse_2.1-0    
## [107] vipor_0.4.5               bslib_0.3.1              
## [109] XVector_0.32.0            stringr_1.4.0            
## [111] digest_0.6.29             sctransform_0.3.2        
## [113] RcppAnnoy_0.0.19          spatstat.data_2.1-2      
## [115] rmarkdown_2.10            leiden_0.3.9             
## [117] uwot_0.1.11               DelayedMatrixStats_1.14.2
## [119] shiny_1.7.1               lifecycle_1.0.1          
## [121] nlme_3.1-152              jsonlite_1.7.2           
## [123] BiocNeighbors_1.10.0      desc_1.4.0               
## [125] viridisLite_0.4.0         fansi_1.0.0              
## [127] pillar_1.6.4              lattice_0.20-44          
## [129] fastmap_1.1.0             httr_1.4.2               
## [131] survival_3.2-11           glue_1.6.0               
## [133] png_0.1-7                 bit_4.0.4                
## [135] stringi_1.7.6             sass_0.4.0               
## [137] textshaping_0.3.5         BiocSingular_1.8.1       
## [139] memoise_2.0.0             dplyr_1.0.7              
## [141] irlba_2.3.5               future.apply_1.8.1
```

---

## Analysis, visualization, and integration of Visium HD spatial datasets with Seurat • Seurat

**URL:** http://127.0.0.1:9173/articles_parsebio_sketch_integration.html

**Contents:**
- Sketch integration using a 1 million cell dataset from Parse Biosciences
    - Compiled: 2023-11-15
- Create a Seurat object containing data from 24 patients
- Sample representative cells from each dataset
- Perform integration on the sketched cells across samples
- Integrate the full datasets
- Compare healthy and diabetic samples
- Contents

The recent increase in publicly available single-cell datasets poses a significant challenge for integrative analysis. For example, multiple tissues have now been profiled across dozens of studies, representing hundreds of individuals and millions of cells. In Hao et al, 2023 proposed a dictionary learning based method, atomic sketch integration, could also enable efficient and large-scale integrative analysis. Our procedure enables the integration of large compendiums of datasets without ever needing to load the full scale of data into memory. In our manuscript we use atomic sketch integration to integrate millions of scRNA-seq from human lung and human PBMC.

In this vignette, we demonstrate how to use atomic sketch integration to harmonize scRNA-seq experiments 1M cells, though we have used this procedure to integrate datasets of 10M+ cells as well. We analyze a dataset from Parse Biosciences, in which PBMC from 24 human samples (12 healthy donors, 12 Type-1 diabetes donors), which is available here.

Prior to running this vignette, please install Seurat v5, as well as the BPCells package, which we use for on-disk storage. You can read more about using BPCells in Seurat v5 here. We also recommend reading the Sketch-based analysis in Seurat v5 vignette, which introduces the concept of on-disk and in-memory storage in Seurat v5.

We downloaded the original dataset and donor metadata from Parse Biosciences. While the BPCells package can work directly with h5ad files, for optimal performance, we converted the dataset to the compressed sparse format used by BPCells, as described here. We create a Seurat object for this dataset. Since the input to CreateSeuratObject is a BPCells matrix, the data remains on-disk and is not loaded into memory. After creating the object, we split the dataset into 24 layers, one for each sample (i.e. patient), to facilitate integration.

Inspired by pioneering work aiming to identify ‘sketches’ of scRNA-seq data, our first step is to sample a representative set of cells from each dataset. We compute a leverage score (estimate of ‘statistical leverage’) for each cell, which helps to identify cells that are likely to be member of rare subpopulations and ensure that these are included in our representative sample. Importantly, the estimation of leverage scores only requires data normalization, can be computed efficiently for sparse datasets, and does not require any intensive computation or dimensional reduction steps. We load each object separately, perform basic preprocessing (normalization and variable feature selection), and select and store 5,000 representative cells from each dataset. Since there are 24 datasets, the sketched dataset now contains 120,000 cells. These cells are stored in a new sketch assay, and are loaded in-memory.

Next we perform integrative analysis on the ‘atoms’ from each of the datasets. Here, we perform integration using the streamlined Seurat v5 integration worfklow, and utilize the reference-based RPCAIntegration method. The function performs all corrections in low-dimensional space (rather than on the expression values themselves) to further improve speed and memory usage, and outputs a merged Seurat object where all cells have been placed in an integrated low-dimensional space (stored as integrated.rpca). However, we emphasize that you can perform integration here using any analysis technique that places cells across datasets into a shared space. This includes CCA Integration, Harmony, and scVI. We demonstrate how to use these tools in Seurat v5 here.

Now that we have integrated the subset of atoms of each dataset, placing them each in an integrated low-dimensional space, we can now place each cell from each dataset in this space as well. We load the full datasets back in individually, and use the ProjectIntegration function to integrate all cells. After this function is run, the integrated.rpca.full space now embeds all cells in the dataset.Even though all cells in the dataset have been integrated together, the non-sketched cells are not loaded into memory. Users can still switch between the sketch (sketched cells, in-memory) and RNA (full dataset, on disk) for analysis. After integration, we can also project cell type labels from the sketched cells onto the full dataset using ProjectData.

By integrating all samples together, we can now compare healthy and diabetic cells in matched cell states. To maximize statistical power, we want to use all cells - not just the sketched cells - to perform this analysis. As recommended by Soneson et all. and Crowell et al., we use an aggregation-based (pseudobulk) workflow. We aggregate all cells within the same cell type and sample using the AggregateExpression function. This returns a Seurat object where each ‘cell’ represents the pseudobulk profile of one cell type in one individual.

After we aggregate cells, we can perform celltype-specific differential expression between healthy and diabetic samples using DESeq2. We demonstrate this for CD14 monocytes.

Developed by Rahul Satija, Satija Lab and Collaborators.

Site built with pkgdown 2.0.7.

**Examples:**

Example 1 (unknown):
```unknown
vignettes/ParseBio_sketch_integration.Rmd
```

Example 2 (unknown):
```unknown
ParseBio_sketch_integration.Rmd
```

Example 3 (unknown):
```unknown
library(Seurat)
library(BPCells)
library(dplyr)
library(ggplot2)
library(ggrepel)
library(patchwork)
# set this option when analyzing large datasets
options(future.globals.maxSize = 3e+09)
```

Example 4 (r):
```r
library(Seurat)
library(BPCells)
library(dplyr)
library(ggplot2)
library(ggrepel)
library(patchwork)
# set this option when analyzing large datasets
options(future.globals.maxSize = 3e+09)
```

Example 5 (r):
```r
library(Seurat)
library(BPCells)
library(dplyr)
library(ggplot2)
library(ggrepel)
library(patchwork)
# set this option when analyzing large datasets
options(future.globals.maxSize = 3e+09)
```

Example 6 (unknown):
```unknown
CreateSeuratObject
```

Example 7 (python):
```python
parse.mat <- open_matrix_dir(dir = "/brahms/hartmana/vignette_data/bpcells/parse_1m_pbmc")
# need to move
metadata <- readRDS("/brahms/haoy/vignette_data/ParseBio_PBMC_meta.rds")
object <- CreateSeuratObject(counts = parse.mat, meta.data = metadata)

object <- NormalizeData(object)
# split assay into 24 layers
object[["RNA"]] <- split(object[["RNA"]], f = object$sample)
object <- FindVariableFeatures(object, verbose = FALSE)
```

Example 8 (r):
```r
parse.mat <- open_matrix_dir(dir = "/brahms/hartmana/vignette_data/bpcells/parse_1m_pbmc")
# need to move
metadata <- readRDS("/brahms/haoy/vignette_data/ParseBio_PBMC_meta.rds")
object <- CreateSeuratObject(counts = parse.mat, meta.data = metadata)

object <- NormalizeData(object)
# split assay into 24 layers
object[["RNA"]] <- split(object[["RNA"]], f = object$sample)
object <- FindVariableFeatures(object, verbose = FALSE)
```

Example 9 (r):
```r
parse.mat <- open_matrix_dir(dir = "/brahms/hartmana/vignette_data/bpcells/parse_1m_pbmc")
# need to move
metadata <- readRDS("/brahms/haoy/vignette_data/ParseBio_PBMC_meta.rds")
object <- CreateSeuratObject(counts = parse.mat, meta.data = metadata)

object <- NormalizeData(object)
# split assay into 24 layers
object[["RNA"]] <- split(object[["RNA"]], f = object$sample)
object <- FindVariableFeatures(object, verbose = FALSE)
```

Example 10 (unknown):
```unknown
object <- SketchData(object = object, ncells = 5000, method = "LeverageScore", sketched.assay = "sketch")
object
```

Example 11 (r):
```r
object <- SketchData(object = object, ncells = 5000, method = "LeverageScore", sketched.assay = "sketch")
object
```

Example 12 (r):
```r
object <- SketchData(object = object, ncells = 5000, method = "LeverageScore", sketched.assay = "sketch")
object
```

Example 13 (python):
```python
## An object of class Seurat 
## 121328 features across 966344 samples within 2 assays 
## Active assay: sketch (60664 features, 2000 variable features)
##  48 layers present: counts.H_3128, counts.H_3060, counts.H_409, counts.H_7108, counts.H_120, counts.D_504, counts.H_2928, counts.H_727, counts.H_4579, counts.H_6625, counts.H_630, counts.D_500, counts.D_501, counts.D_610, counts.H_4119, counts.D_609, counts.D_644, counts.D_498, counts.H_1334, counts.D_497, counts.D_505, counts.D_506, counts.D_502, counts.D_503, data.H_3128, data.H_3060, data.H_409, data.H_7108, data.H_120, data.D_504, data.H_2928, data.H_727, data.H_4579, data.H_6625, data.H_630, data.D_500, data.D_501, data.D_610, data.H_4119, data.D_609, data.D_644, data.D_498, data.H_1334, data.D_497, data.D_505, data.D_506, data.D_502, data.D_503
##  1 other assay present: RNA
```

Example 14 (python):
```python
## An object of class Seurat 
## 121328 features across 966344 samples within 2 assays 
## Active assay: sketch (60664 features, 2000 variable features)
##  48 layers present: counts.H_3128, counts.H_3060, counts.H_409, counts.H_7108, counts.H_120, counts.D_504, counts.H_2928, counts.H_727, counts.H_4579, counts.H_6625, counts.H_630, counts.D_500, counts.D_501, counts.D_610, counts.H_4119, counts.D_609, counts.D_644, counts.D_498, counts.H_1334, counts.D_497, counts.D_505, counts.D_506, counts.D_502, counts.D_503, data.H_3128, data.H_3060, data.H_409, data.H_7108, data.H_120, data.D_504, data.H_2928, data.H_727, data.H_4579, data.H_6625, data.H_630, data.D_500, data.D_501, data.D_610, data.H_4119, data.D_609, data.D_644, data.D_498, data.H_1334, data.D_497, data.D_505, data.D_506, data.D_502, data.D_503
##  1 other assay present: RNA
```

Example 15 (unknown):
```unknown
RPCAIntegration
```

Example 16 (unknown):
```unknown
integrated.rpca
```

Example 17 (unknown):
```unknown
DefaultAssay(object) <- "sketch"
object <- FindVariableFeatures(object, verbose = F)
object <- ScaleData(object, verbose = F)
object <- RunPCA(object, verbose = F)
# integrate the datasets
object <- IntegrateLayers(object, method = RPCAIntegration, orig = "pca", new.reduction = "integrated.rpca",
    dims = 1:30, k.anchor = 20, reference = which(Layers(object, search = "data") %in% c("data.H_3060")),
    verbose = F)
# cluster the integrated data
object <- FindNeighbors(object, reduction = "integrated.rpca", dims = 1:30)
object <- FindClusters(object, resolution = 2)
```

Example 18 (r):
```r
DefaultAssay(object) <- "sketch"
object <- FindVariableFeatures(object, verbose = F)
object <- ScaleData(object, verbose = F)
object <- RunPCA(object, verbose = F)
# integrate the datasets
object <- IntegrateLayers(object, method = RPCAIntegration, orig = "pca", new.reduction = "integrated.rpca",
    dims = 1:30, k.anchor = 20, reference = which(Layers(object, search = "data") %in% c("data.H_3060")),
    verbose = F)
# cluster the integrated data
object <- FindNeighbors(object, reduction = "integrated.rpca", dims = 1:30)
object <- FindClusters(object, resolution = 2)
```

Example 19 (r):
```r
DefaultAssay(object) <- "sketch"
object <- FindVariableFeatures(object, verbose = F)
object <- ScaleData(object, verbose = F)
object <- RunPCA(object, verbose = F)
# integrate the datasets
object <- IntegrateLayers(object, method = RPCAIntegration, orig = "pca", new.reduction = "integrated.rpca",
    dims = 1:30, k.anchor = 20, reference = which(Layers(object, search = "data") %in% c("data.H_3060")),
    verbose = F)
# cluster the integrated data
object <- FindNeighbors(object, reduction = "integrated.rpca", dims = 1:30)
object <- FindClusters(object, resolution = 2)
```

Example 20 (unknown):
```unknown
## Modularity Optimizer version 1.3.0 by Ludo Waltman and Nees Jan van Eck
## 
## Number of nodes: 120000
## Number of edges: 5137782
## 
## Running Louvain algorithm...
## Maximum modularity in 10 random starts: 0.8765
## Number of communities: 47
## Elapsed time: 83 seconds
```

Example 21 (unknown):
```unknown
## Modularity Optimizer version 1.3.0 by Ludo Waltman and Nees Jan van Eck
## 
## Number of nodes: 120000
## Number of edges: 5137782
## 
## Running Louvain algorithm...
## Maximum modularity in 10 random starts: 0.8765
## Number of communities: 47
## Elapsed time: 83 seconds
```

Example 22 (unknown):
```unknown
object <- RunUMAP(object, reduction = "integrated.rpca", dims = 1:30, return.model = T, verbose = F)
```

Example 23 (r):
```r
object <- RunUMAP(object, reduction = "integrated.rpca", dims = 1:30, return.model = T, verbose = F)
```

Example 24 (r):
```r
object <- RunUMAP(object, reduction = "integrated.rpca", dims = 1:30, return.model = T, verbose = F)
```

Example 25 (unknown):
```unknown
# you can now rejoin the layers in the sketched assay this is required to perform differential
# expression
object[["sketch"]] <- JoinLayers(object[["sketch"]])
c10_markers <- FindMarkers(object = object, ident.1 = 10, max.cells.per.ident = 500, only.pos = TRUE)
head(c10_markers)
```

Example 26 (r):
```r
# you can now rejoin the layers in the sketched assay this is required to perform differential
# expression
object[["sketch"]] <- JoinLayers(object[["sketch"]])
c10_markers <- FindMarkers(object = object, ident.1 = 10, max.cells.per.ident = 500, only.pos = TRUE)
head(c10_markers)
```

Example 27 (r):
```r
# you can now rejoin the layers in the sketched assay this is required to perform differential
# expression
object[["sketch"]] <- JoinLayers(object[["sketch"]])
c10_markers <- FindMarkers(object = object, ident.1 = 10, max.cells.per.ident = 500, only.pos = TRUE)
head(c10_markers)
```

Example 28 (unknown):
```unknown
##                  p_val avg_log2FC pct.1 pct.2     p_val_adj
## BANK1    8.652285e-142   3.183046 0.980 0.183 5.248822e-137
## RALGPS2  1.870876e-134   3.168787 0.949 0.215 1.134948e-129
## OSBPL10  4.406924e-133   3.556864 0.890 0.118 2.673417e-128
## ARHGAP24 1.666152e-121   2.957065 0.916 0.263 1.010754e-116
## AFF3     6.864595e-107   2.248398 0.978 0.306 4.164338e-102
## EBF1     7.805461e-107   2.994191 0.841 0.126 4.735105e-102
```

Example 29 (unknown):
```unknown
##                  p_val avg_log2FC pct.1 pct.2     p_val_adj
## BANK1    8.652285e-142   3.183046 0.980 0.183 5.248822e-137
## RALGPS2  1.870876e-134   3.168787 0.949 0.215 1.134948e-129
## OSBPL10  4.406924e-133   3.556864 0.890 0.118 2.673417e-128
## ARHGAP24 1.666152e-121   2.957065 0.916 0.263 1.010754e-116
## AFF3     6.864595e-107   2.248398 0.978 0.306 4.164338e-102
## EBF1     7.805461e-107   2.994191 0.841 0.126 4.735105e-102
```

Example 30 (python):
```python
# You can now annotate clusters using marker genes.  We performed this step, and include the
# results in the 'sketch.celltype' metadata column

plot.s1 <- DimPlot(object, group.by = "sample", reduction = "umap")
plot.s2 <- DimPlot(object, group.by = "celltype.manual", reduction = "umap")
```

Example 31 (r):
```r
# You can now annotate clusters using marker genes.  We performed this step, and include the
# results in the 'sketch.celltype' metadata column

plot.s1 <- DimPlot(object, group.by = "sample", reduction = "umap")
plot.s2 <- DimPlot(object, group.by = "celltype.manual", reduction = "umap")
```

Example 32 (r):
```r
# You can now annotate clusters using marker genes.  We performed this step, and include the
# results in the 'sketch.celltype' metadata column

plot.s1 <- DimPlot(object, group.by = "sample", reduction = "umap")
plot.s2 <- DimPlot(object, group.by = "celltype.manual", reduction = "umap")
```

Example 33 (unknown):
```unknown
plot.s1 + plot.s2 + plot_layout(ncol = 1)
```

Example 34 (r):
```r
plot.s1 + plot.s2 + plot_layout(ncol = 1)
```

Example 35 (r):
```r
plot.s1 + plot.s2 + plot_layout(ncol = 1)
```

Example 36 (unknown):
```unknown
ProjectIntegration
```

Example 37 (unknown):
```unknown
integrated.rpca.full
```

Example 38 (unknown):
```unknown
ProjectData
```

Example 39 (unknown):
```unknown
# resplit the sketched cell assay into layers this is required to project the integration onto
# all cells
object[["sketch"]] <- split(object[["sketch"]], f = object$sample)

object <- ProjectIntegration(object = object, sketched.assay = "sketch", assay = "RNA", reduction = "integrated.rpca")


object <- ProjectData(object = object, sketched.assay = "sketch", assay = "RNA", sketched.reduction = "integrated.rpca.full",
    full.reduction = "integrated.rpca.full", dims = 1:30, refdata = list(celltype.full = "celltype.manual"))
```

Example 40 (r):
```r
# resplit the sketched cell assay into layers this is required to project the integration onto
# all cells
object[["sketch"]] <- split(object[["sketch"]], f = object$sample)

object <- ProjectIntegration(object = object, sketched.assay = "sketch", assay = "RNA", reduction = "integrated.rpca")


object <- ProjectData(object = object, sketched.assay = "sketch", assay = "RNA", sketched.reduction = "integrated.rpca.full",
    full.reduction = "integrated.rpca.full", dims = 1:30, refdata = list(celltype.full = "celltype.manual"))
```

Example 41 (r):
```r
# resplit the sketched cell assay into layers this is required to project the integration onto
# all cells
object[["sketch"]] <- split(object[["sketch"]], f = object$sample)

object <- ProjectIntegration(object = object, sketched.assay = "sketch", assay = "RNA", reduction = "integrated.rpca")


object <- ProjectData(object = object, sketched.assay = "sketch", assay = "RNA", sketched.reduction = "integrated.rpca.full",
    full.reduction = "integrated.rpca.full", dims = 1:30, refdata = list(celltype.full = "celltype.manual"))
```

Example 42 (unknown):
```unknown
object <- RunUMAP(object, reduction = "integrated.rpca.full", dims = 1:30, reduction.name = "umap.full",
    reduction.key = "UMAP_full_")
```

Example 43 (r):
```r
object <- RunUMAP(object, reduction = "integrated.rpca.full", dims = 1:30, reduction.name = "umap.full",
    reduction.key = "UMAP_full_")
```

Example 44 (r):
```r
object <- RunUMAP(object, reduction = "integrated.rpca.full", dims = 1:30, reduction.name = "umap.full",
    reduction.key = "UMAP_full_")
```

Example 45 (unknown):
```unknown
p1 <- DimPlot(object, reduction = "umap.full", group.by = "sample", alpha = 0.1)
p2 <- DimPlot(object, reduction = "umap.full", group.by = "celltype.full", alpha = 0.1)
p1 + p2 + plot_layout(ncol = 1)
```

Example 46 (r):
```r
p1 <- DimPlot(object, reduction = "umap.full", group.by = "sample", alpha = 0.1)
p2 <- DimPlot(object, reduction = "umap.full", group.by = "celltype.full", alpha = 0.1)
p1 + p2 + plot_layout(ncol = 1)
```

Example 47 (r):
```r
p1 <- DimPlot(object, reduction = "umap.full", group.by = "sample", alpha = 0.1)
p2 <- DimPlot(object, reduction = "umap.full", group.by = "celltype.full", alpha = 0.1)
p1 + p2 + plot_layout(ncol = 1)
```

Example 48 (unknown):
```unknown
AggregateExpression
```

Example 49 (unknown):
```unknown
bulk <- AggregateExpression(object, return.seurat = T, slot = "counts", assays = "RNA", group.by = c("celltype.full",
    "sample", "disease"))
```

Example 50 (r):
```r
bulk <- AggregateExpression(object, return.seurat = T, slot = "counts", assays = "RNA", group.by = c("celltype.full",
    "sample", "disease"))
```

Example 51 (r):
```r
bulk <- AggregateExpression(object, return.seurat = T, slot = "counts", assays = "RNA", group.by = c("celltype.full",
    "sample", "disease"))
```

Example 52 (unknown):
```unknown
# each sample is an individual-specific celltype-specific pseudobulk profile
tail(Cells(bulk))
```

Example 53 (r):
```r
# each sample is an individual-specific celltype-specific pseudobulk profile
tail(Cells(bulk))
```

Example 54 (r):
```r
# each sample is an individual-specific celltype-specific pseudobulk profile
tail(Cells(bulk))
```

Example 55 (unknown):
```unknown
## [1] "Treg_H-4119_H" "Treg_H-4579_H" "Treg_H-630_H"  "Treg_H-6625_H"
## [5] "Treg_H-7108_H" "Treg_H-727_H"
```

Example 56 (unknown):
```unknown
## [1] "Treg_H-4119_H" "Treg_H-4579_H" "Treg_H-630_H"  "Treg_H-6625_H"
## [5] "Treg_H-7108_H" "Treg_H-727_H"
```

Example 57 (unknown):
```unknown
cd14.bulk <- subset(bulk, celltype.full == "CD14 Mono")
  Idents(cd14.bulk) <- "disease"
  de_markers <- FindMarkers(cd14.bulk, ident.1 = "D", ident.2 = "H", slot = "counts", test.use = "DESeq2",
      verbose = F)
  de_markers$gene <- rownames(de_markers)
  ggplot(de_markers, aes(avg_log2FC, -log10(p_val))) + geom_point(size = 0.5, alpha = 0.5) + theme_bw() +
      ylab("-log10(unadjusted p-value)") + geom_text_repel(aes(label = ifelse(p_val_adj < 0.01, gene,
      "")), colour = "red", size = 3)
```

Example 58 (r):
```r
cd14.bulk <- subset(bulk, celltype.full == "CD14 Mono")
  Idents(cd14.bulk) <- "disease"
  de_markers <- FindMarkers(cd14.bulk, ident.1 = "D", ident.2 = "H", slot = "counts", test.use = "DESeq2",
      verbose = F)
  de_markers$gene <- rownames(de_markers)
  ggplot(de_markers, aes(avg_log2FC, -log10(p_val))) + geom_point(size = 0.5, alpha = 0.5) + theme_bw() +
      ylab("-log10(unadjusted p-value)") + geom_text_repel(aes(label = ifelse(p_val_adj < 0.01, gene,
      "")), colour = "red", size = 3)
```

Example 59 (r):
```r
cd14.bulk <- subset(bulk, celltype.full == "CD14 Mono")
  Idents(cd14.bulk) <- "disease"
  de_markers <- FindMarkers(cd14.bulk, ident.1 = "D", ident.2 = "H", slot = "counts", test.use = "DESeq2",
      verbose = F)
  de_markers$gene <- rownames(de_markers)
  ggplot(de_markers, aes(avg_log2FC, -log10(p_val))) + geom_point(size = 0.5, alpha = 0.5) + theme_bw() +
      ylab("-log10(unadjusted p-value)") + geom_text_repel(aes(label = ifelse(p_val_adj < 0.01, gene,
      "")), colour = "red", size = 3)
```

Example 60 (unknown):
```unknown
sessionInfo()
```

Example 61 (r):
```r
sessionInfo()
```

Example 62 (r):
```r
sessionInfo()
```

Example 63 (unknown):
```unknown
## R version 4.2.2 Patched (2022-11-10 r83330)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.6 LTS
## 
## Matrix products: default
## BLAS:   /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.9.0
## LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.9.0
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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       
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
## [1] patchwork_1.1.3    ggrepel_0.9.4      ggplot2_3.4.4      dplyr_1.1.3       
## [5] BPCells_0.1.0      Seurat_5.0.1       SeuratObject_5.0.1 sp_2.1-1          
## 
## loaded via a namespace (and not attached):
##   [1] spam_2.10-0            systemfonts_1.0.4      plyr_1.8.9            
##   [4] igraph_1.5.1           lazyeval_0.2.2         splines_4.2.2         
##   [7] RcppHNSW_0.5.0         listenv_0.9.0          scattermore_1.2       
##  [10] GenomeInfoDb_1.34.9    digest_0.6.33          htmltools_0.5.6.1     
##  [13] fansi_1.0.5            magrittr_2.0.3         memoise_2.0.1         
##  [16] tensor_1.5             cluster_2.1.4          ROCR_1.0-11           
##  [19] limma_3.54.1           globals_0.16.2         matrixStats_1.0.0     
##  [22] pkgdown_2.0.7          spatstat.sparse_3.0-3  colorspace_2.1-0      
##  [25] textshaping_0.3.6      xfun_0.40              RCurl_1.98-1.12       
##  [28] jsonlite_1.8.7         progressr_0.14.0       spatstat.data_3.0-3   
##  [31] survival_3.5-7         zoo_1.8-12             glue_1.6.2            
##  [34] polyclip_1.10-6        gtable_0.3.4           zlibbioc_1.44.0       
##  [37] XVector_0.38.0         leiden_0.4.3           future.apply_1.11.0   
##  [40] BiocGenerics_0.44.0    abind_1.4-5            scales_1.2.1          
##  [43] spatstat.random_3.2-1  miniUI_0.1.1.1         Rcpp_1.0.11           
##  [46] viridisLite_0.4.2      xtable_1.8-4           reticulate_1.34.0     
##  [49] dotCall64_1.1-0        stats4_4.2.2           htmlwidgets_1.6.2     
##  [52] httr_1.4.7             RColorBrewer_1.1-3     ellipsis_0.3.2        
##  [55] ica_1.0-3              farver_2.1.1           pkgconfig_2.0.3       
##  [58] sass_0.4.7             uwot_0.1.16            deldir_1.0-9          
##  [61] utf8_1.2.4             labeling_0.4.3         tidyselect_1.2.0      
##  [64] rlang_1.1.1            reshape2_1.4.4         later_1.3.1           
##  [67] munsell_0.5.0          tools_4.2.2            cachem_1.0.8          
##  [70] cli_3.6.1              generics_0.1.3         ggridges_0.5.4        
##  [73] evaluate_0.22          stringr_1.5.0          fastmap_1.1.1         
##  [76] yaml_2.3.7             ragg_1.2.5             goftest_1.2-3         
##  [79] knitr_1.45             fs_1.6.3               fitdistrplus_1.1-11   
##  [82] purrr_1.0.2            RANN_2.6.1             pbapply_1.7-2         
##  [85] future_1.33.0          nlme_3.1-162           mime_0.12             
##  [88] formatR_1.14           compiler_4.2.2         plotly_4.10.3         
##  [91] png_0.1-8              spatstat.utils_3.0-4   tibble_3.2.1          
##  [94] bslib_0.5.1            stringi_1.7.12         highr_0.10            
##  [97] desc_1.4.2             RSpectra_0.16-1        lattice_0.21-9        
## [100] Matrix_1.6-1.1         vctrs_0.6.4            pillar_1.9.0          
## [103] lifecycle_1.0.4        spatstat.geom_3.2-7    lmtest_0.9-40         
## [106] jquerylib_0.1.4        RcppAnnoy_0.0.21       data.table_1.14.8     
## [109] cowplot_1.1.1          bitops_1.0-7           irlba_2.3.5.1         
## [112] httpuv_1.6.12          GenomicRanges_1.50.2   R6_2.5.1              
## [115] promises_1.2.1         KernSmooth_2.23-22     gridExtra_2.3         
## [118] IRanges_2.32.0         parallelly_1.36.0      codetools_0.2-19      
## [121] fastDummies_1.7.3      MASS_7.3-58.2          rprojroot_2.0.4       
## [124] withr_2.5.2            presto_1.0.0           sctransform_0.4.1     
## [127] S4Vectors_0.36.2       GenomeInfoDbData_1.2.9 parallel_4.2.2        
## [130] grid_4.2.2             tidyr_1.3.0            rmarkdown_2.25        
## [133] Rtsne_0.16             spatstat.explore_3.2-5 shiny_1.7.5.1
```

Example 64 (unknown):
```unknown
## R version 4.2.2 Patched (2022-11-10 r83330)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.6 LTS
## 
## Matrix products: default
## BLAS:   /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.9.0
## LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.9.0
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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       
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
## [1] patchwork_1.1.3    ggrepel_0.9.4      ggplot2_3.4.4      dplyr_1.1.3       
## [5] BPCells_0.1.0      Seurat_5.0.1       SeuratObject_5.0.1 sp_2.1-1          
## 
## loaded via a namespace (and not attached):
##   [1] spam_2.10-0            systemfonts_1.0.4      plyr_1.8.9            
##   [4] igraph_1.5.1           lazyeval_0.2.2         splines_4.2.2         
##   [7] RcppHNSW_0.5.0         listenv_0.9.0          scattermore_1.2       
##  [10] GenomeInfoDb_1.34.9    digest_0.6.33          htmltools_0.5.6.1     
##  [13] fansi_1.0.5            magrittr_2.0.3         memoise_2.0.1         
##  [16] tensor_1.5             cluster_2.1.4          ROCR_1.0-11           
##  [19] limma_3.54.1           globals_0.16.2         matrixStats_1.0.0     
##  [22] pkgdown_2.0.7          spatstat.sparse_3.0-3  colorspace_2.1-0      
##  [25] textshaping_0.3.6      xfun_0.40              RCurl_1.98-1.12       
##  [28] jsonlite_1.8.7         progressr_0.14.0       spatstat.data_3.0-3   
##  [31] survival_3.5-7         zoo_1.8-12             glue_1.6.2            
##  [34] polyclip_1.10-6        gtable_0.3.4           zlibbioc_1.44.0       
##  [37] XVector_0.38.0         leiden_0.4.3           future.apply_1.11.0   
##  [40] BiocGenerics_0.44.0    abind_1.4-5            scales_1.2.1          
##  [43] spatstat.random_3.2-1  miniUI_0.1.1.1         Rcpp_1.0.11           
##  [46] viridisLite_0.4.2      xtable_1.8-4           reticulate_1.34.0     
##  [49] dotCall64_1.1-0        stats4_4.2.2           htmlwidgets_1.6.2     
##  [52] httr_1.4.7             RColorBrewer_1.1-3     ellipsis_0.3.2        
##  [55] ica_1.0-3              farver_2.1.1           pkgconfig_2.0.3       
##  [58] sass_0.4.7             uwot_0.1.16            deldir_1.0-9          
##  [61] utf8_1.2.4             labeling_0.4.3         tidyselect_1.2.0      
##  [64] rlang_1.1.1            reshape2_1.4.4         later_1.3.1           
##  [67] munsell_0.5.0          tools_4.2.2            cachem_1.0.8          
##  [70] cli_3.6.1              generics_0.1.3         ggridges_0.5.4        
##  [73] evaluate_0.22          stringr_1.5.0          fastmap_1.1.1         
##  [76] yaml_2.3.7             ragg_1.2.5             goftest_1.2-3         
##  [79] knitr_1.45             fs_1.6.3               fitdistrplus_1.1-11   
##  [82] purrr_1.0.2            RANN_2.6.1             pbapply_1.7-2         
##  [85] future_1.33.0          nlme_3.1-162           mime_0.12             
##  [88] formatR_1.14           compiler_4.2.2         plotly_4.10.3         
##  [91] png_0.1-8              spatstat.utils_3.0-4   tibble_3.2.1          
##  [94] bslib_0.5.1            stringi_1.7.12         highr_0.10            
##  [97] desc_1.4.2             RSpectra_0.16-1        lattice_0.21-9        
## [100] Matrix_1.6-1.1         vctrs_0.6.4            pillar_1.9.0          
## [103] lifecycle_1.0.4        spatstat.geom_3.2-7    lmtest_0.9-40         
## [106] jquerylib_0.1.4        RcppAnnoy_0.0.21       data.table_1.14.8     
## [109] cowplot_1.1.1          bitops_1.0-7           irlba_2.3.5.1         
## [112] httpuv_1.6.12          GenomicRanges_1.50.2   R6_2.5.1              
## [115] promises_1.2.1         KernSmooth_2.23-22     gridExtra_2.3         
## [118] IRanges_2.32.0         parallelly_1.36.0      codetools_0.2-19      
## [121] fastDummies_1.7.3      MASS_7.3-58.2          rprojroot_2.0.4       
## [124] withr_2.5.2            presto_1.0.0           sctransform_0.4.1     
## [127] S4Vectors_0.36.2       GenomeInfoDbData_1.2.9 parallel_4.2.2        
## [130] grid_4.2.2             tidyr_1.3.0            rmarkdown_2.25        
## [133] Rtsne_0.16             spatstat.explore_3.2-5 shiny_1.7.5.1
```

---

## Analysis, visualization, and integration of Visium HD spatial datasets with Seurat • Seurat

**URL:** http://127.0.0.1:9173/articles_integration_mapping.html

**Contents:**
- Mapping and annotating query datasets
    - Compiled: 2023-10-31
- Introduction to single-cell reference mapping
- Dataset preprocessing
- Cell type classification using an integrated reference
- Unimodal UMAP Projection
- Contents

In this vignette, we first build an integrated reference and then demonstrate how to leverage this reference to annotate new query datasets. Generating an integrated reference follows the same workflow described in more detail in the integration introduction vignette. Once generated, this reference can be used to analyze additional query datasets through tasks like cell type label transfer and projecting query cells onto reference UMAPs. Notably, this does not require correction of the underlying raw query data and can therefore be an efficient strategy if a high quality reference is available.

For the purposes of this example, we’ve chosen human pancreatic islet cell datasets produced across four technologies, CelSeq (GSE81076) CelSeq2 (GSE85241), Fluidigm C1 (GSE86469), and SMART-Seq2 (E-MTAB-5061). For convenience, we distribute this dataset through our SeuratData package. The metadata contains the technology (tech column) and cell type annotations (celltype column) for each cell in the four datasets.

As a demonstration, we will use a subset of technologies to construct a reference. We will then map the remaining datasets onto this reference. We start by selecting cells from four technologies, and performing an analysis without integration.

Next, we integrate the datasets into a shared reference. Please see our introduction to integration vignette

Seurat also supports the projection of reference data (or meta data) onto a query object. While many of the methods are conserved (both procedures begin by identifying anchors), there are two important distinctions between data transfer and integration:

After finding anchors, we use the TransferData() function to classify the query cells based on reference data (a vector of reference cell type labels). TransferData() returns a matrix with predicted IDs and prediction scores, which we can add to the query metadata.

Because we have the original label annotations from our full integrated analysis, we can evaluate how well our predicted cell type annotations match the full reference. In this example, we find that there is a high agreement in cell type classification, with over 96% of cells being labeled correctly.

To verify this further, we can examine some canonical cell type markers for specific pancreatic islet cell populations. Note that even though some of these cell types are only represented by one or two cells (e.g. epsilon cells), we are still able to classify them correctly.

We also enable projection of a query onto the reference UMAP structure. This can be achieved by computing the reference UMAP model and then calling MapQuery() instead of TransferData().

What is MapQuery doing?

MapQuery() is a wrapper around three functions: TransferData(), IntegrateEmbeddings(), and ProjectUMAP(). TransferData() is used to transfer cell type labels and impute the ADT values; IntegrateEmbeddings() is used to integrate reference with query by correcting the query’s projected low-dimensional embeddings; and finally ProjectUMAP() is used to project the query data onto the UMAP structure of the reference. The equivalent code for doing this with the intermediate functions is below:

We can now visualize the query cells alongside our reference.

Developed by Rahul Satija, Satija Lab and Collaborators.

Site built with pkgdown 2.0.7.

**Examples:**

Example 1 (unknown):
```unknown
vignettes/integration_mapping.Rmd
```

Example 2 (unknown):
```unknown
integration_mapping.Rmd
```

Example 3 (unknown):
```unknown
library(Seurat)
library(SeuratData)
library(ggplot2)
```

Example 4 (r):
```r
library(Seurat)
library(SeuratData)
library(ggplot2)
```

Example 5 (r):
```r
library(Seurat)
library(SeuratData)
library(ggplot2)
```

Example 6 (unknown):
```unknown
InstallData("panc8")
```

Example 7 (r):
```r
InstallData("panc8")
```

Example 8 (r):
```r
InstallData("panc8")
```

Example 9 (unknown):
```unknown
panc8 <- LoadData("panc8")
table(panc8$tech)
```

Example 10 (r):
```r
panc8 <- LoadData("panc8")
table(panc8$tech)
```

Example 11 (r):
```r
panc8 <- LoadData("panc8")
table(panc8$tech)
```

Example 12 (unknown):
```unknown
## 
##     celseq    celseq2 fluidigmc1     indrop  smartseq2 
##       1004       2285        638       8569       2394
```

Example 13 (unknown):
```unknown
## 
##     celseq    celseq2 fluidigmc1     indrop  smartseq2 
##       1004       2285        638       8569       2394
```

Example 14 (python):
```python
# we will use data from 2 technologies for the reference
pancreas.ref <- subset(panc8, tech %in% c("celseq2", "smartseq2"))
pancreas.ref[["RNA"]] <- split(pancreas.ref[["RNA"]], f = pancreas.ref$tech)

# pre-process dataset (without integration)
pancreas.ref <- NormalizeData(pancreas.ref)
pancreas.ref <- FindVariableFeatures(pancreas.ref)
pancreas.ref <- ScaleData(pancreas.ref)
pancreas.ref <- RunPCA(pancreas.ref)
pancreas.ref <- FindNeighbors(pancreas.ref, dims = 1:30)
pancreas.ref <- FindClusters(pancreas.ref)
```

Example 15 (r):
```r
# we will use data from 2 technologies for the reference
pancreas.ref <- subset(panc8, tech %in% c("celseq2", "smartseq2"))
pancreas.ref[["RNA"]] <- split(pancreas.ref[["RNA"]], f = pancreas.ref$tech)

# pre-process dataset (without integration)
pancreas.ref <- NormalizeData(pancreas.ref)
pancreas.ref <- FindVariableFeatures(pancreas.ref)
pancreas.ref <- ScaleData(pancreas.ref)
pancreas.ref <- RunPCA(pancreas.ref)
pancreas.ref <- FindNeighbors(pancreas.ref, dims = 1:30)
pancreas.ref <- FindClusters(pancreas.ref)
```

Example 16 (r):
```r
# we will use data from 2 technologies for the reference
pancreas.ref <- subset(panc8, tech %in% c("celseq2", "smartseq2"))
pancreas.ref[["RNA"]] <- split(pancreas.ref[["RNA"]], f = pancreas.ref$tech)

# pre-process dataset (without integration)
pancreas.ref <- NormalizeData(pancreas.ref)
pancreas.ref <- FindVariableFeatures(pancreas.ref)
pancreas.ref <- ScaleData(pancreas.ref)
pancreas.ref <- RunPCA(pancreas.ref)
pancreas.ref <- FindNeighbors(pancreas.ref, dims = 1:30)
pancreas.ref <- FindClusters(pancreas.ref)
```

Example 17 (unknown):
```unknown
## Modularity Optimizer version 1.3.0 by Ludo Waltman and Nees Jan van Eck
## 
## Number of nodes: 4679
## Number of edges: 174953
## 
## Running Louvain algorithm...
## Maximum modularity in 10 random starts: 0.9180
## Number of communities: 19
## Elapsed time: 0 seconds
```

Example 18 (unknown):
```unknown
## Modularity Optimizer version 1.3.0 by Ludo Waltman and Nees Jan van Eck
## 
## Number of nodes: 4679
## Number of edges: 174953
## 
## Running Louvain algorithm...
## Maximum modularity in 10 random starts: 0.9180
## Number of communities: 19
## Elapsed time: 0 seconds
```

Example 19 (unknown):
```unknown
pancreas.ref <- RunUMAP(pancreas.ref, dims = 1:30)
DimPlot(pancreas.ref, group.by = c("celltytpe", "tech"))
```

Example 20 (r):
```r
pancreas.ref <- RunUMAP(pancreas.ref, dims = 1:30)
DimPlot(pancreas.ref, group.by = c("celltytpe", "tech"))
```

Example 21 (r):
```r
pancreas.ref <- RunUMAP(pancreas.ref, dims = 1:30)
DimPlot(pancreas.ref, group.by = c("celltytpe", "tech"))
```

Example 22 (unknown):
```unknown
pancreas.ref <- IntegrateLayers(object = pancreas.ref, method = CCAIntegration, orig.reduction = "pca",
    new.reduction = "integrated.cca", verbose = FALSE)
pancreas.ref <- FindNeighbors(pancreas.ref, reduction = "integrated.cca", dims = 1:30)
pancreas.ref <- FindClusters(pancreas.ref)
```

Example 23 (r):
```r
pancreas.ref <- IntegrateLayers(object = pancreas.ref, method = CCAIntegration, orig.reduction = "pca",
    new.reduction = "integrated.cca", verbose = FALSE)
pancreas.ref <- FindNeighbors(pancreas.ref, reduction = "integrated.cca", dims = 1:30)
pancreas.ref <- FindClusters(pancreas.ref)
```

Example 24 (r):
```r
pancreas.ref <- IntegrateLayers(object = pancreas.ref, method = CCAIntegration, orig.reduction = "pca",
    new.reduction = "integrated.cca", verbose = FALSE)
pancreas.ref <- FindNeighbors(pancreas.ref, reduction = "integrated.cca", dims = 1:30)
pancreas.ref <- FindClusters(pancreas.ref)
```

Example 25 (unknown):
```unknown
## Modularity Optimizer version 1.3.0 by Ludo Waltman and Nees Jan van Eck
## 
## Number of nodes: 4679
## Number of edges: 190152
## 
## Running Louvain algorithm...
## Maximum modularity in 10 random starts: 0.8680
## Number of communities: 15
## Elapsed time: 0 seconds
```

Example 26 (unknown):
```unknown
## Modularity Optimizer version 1.3.0 by Ludo Waltman and Nees Jan van Eck
## 
## Number of nodes: 4679
## Number of edges: 190152
## 
## Running Louvain algorithm...
## Maximum modularity in 10 random starts: 0.8680
## Number of communities: 15
## Elapsed time: 0 seconds
```

Example 27 (unknown):
```unknown
pancreas.ref <- RunUMAP(pancreas.ref, reduction = "integrated.cca", dims = 1:30)
DimPlot(pancreas.ref, group.by = c("tech", "celltype"))
```

Example 28 (r):
```r
pancreas.ref <- RunUMAP(pancreas.ref, reduction = "integrated.cca", dims = 1:30)
DimPlot(pancreas.ref, group.by = c("tech", "celltype"))
```

Example 29 (r):
```r
pancreas.ref <- RunUMAP(pancreas.ref, reduction = "integrated.cca", dims = 1:30)
DimPlot(pancreas.ref, group.by = c("tech", "celltype"))
```

Example 30 (unknown):
```unknown
TransferData()
```

Example 31 (unknown):
```unknown
TransferData()
```

Example 32 (python):
```python
# select two technologies for the query datasets
pancreas.query <- subset(panc8, tech %in% c("fluidigmc1", "celseq"))
pancreas.query <- NormalizeData(pancreas.query)
pancreas.anchors <- FindTransferAnchors(reference = pancreas.ref, query = pancreas.query, dims = 1:30,
    reference.reduction = "pca")
predictions <- TransferData(anchorset = pancreas.anchors, refdata = pancreas.ref$celltype, dims = 1:30)
pancreas.query <- AddMetaData(pancreas.query, metadata = predictions)
```

Example 33 (r):
```r
# select two technologies for the query datasets
pancreas.query <- subset(panc8, tech %in% c("fluidigmc1", "celseq"))
pancreas.query <- NormalizeData(pancreas.query)
pancreas.anchors <- FindTransferAnchors(reference = pancreas.ref, query = pancreas.query, dims = 1:30,
    reference.reduction = "pca")
predictions <- TransferData(anchorset = pancreas.anchors, refdata = pancreas.ref$celltype, dims = 1:30)
pancreas.query <- AddMetaData(pancreas.query, metadata = predictions)
```

Example 34 (r):
```r
# select two technologies for the query datasets
pancreas.query <- subset(panc8, tech %in% c("fluidigmc1", "celseq"))
pancreas.query <- NormalizeData(pancreas.query)
pancreas.anchors <- FindTransferAnchors(reference = pancreas.ref, query = pancreas.query, dims = 1:30,
    reference.reduction = "pca")
predictions <- TransferData(anchorset = pancreas.anchors, refdata = pancreas.ref$celltype, dims = 1:30)
pancreas.query <- AddMetaData(pancreas.query, metadata = predictions)
```

Example 35 (unknown):
```unknown
pancreas.query$prediction.match <- pancreas.query$predicted.id == pancreas.query$celltype
table(pancreas.query$prediction.match)
```

Example 36 (r):
```r
pancreas.query$prediction.match <- pancreas.query$predicted.id == pancreas.query$celltype
table(pancreas.query$prediction.match)
```

Example 37 (r):
```r
pancreas.query$prediction.match <- pancreas.query$predicted.id == pancreas.query$celltype
table(pancreas.query$prediction.match)
```

Example 38 (unknown):
```unknown
## 
## FALSE  TRUE 
##    63  1579
```

Example 39 (unknown):
```unknown
## 
## FALSE  TRUE 
##    63  1579
```

Example 40 (unknown):
```unknown
table(pancreas.query$predicted.id)
```

Example 41 (r):
```r
table(pancreas.query$predicted.id)
```

Example 42 (r):
```r
table(pancreas.query$predicted.id)
```

Example 43 (unknown):
```unknown
## 
##             acinar activated_stellate              alpha               beta 
##                262                 39                436                419 
##              delta             ductal        endothelial              gamma 
##                 73                330                 19                 41 
##         macrophage               mast            schwann 
##                 15                  2                  6
```

Example 44 (unknown):
```unknown
## 
##             acinar activated_stellate              alpha               beta 
##                262                 39                436                419 
##              delta             ductal        endothelial              gamma 
##                 73                330                 19                 41 
##         macrophage               mast            schwann 
##                 15                  2                  6
```

Example 45 (unknown):
```unknown
VlnPlot(pancreas.query, c("REG1A", "PPY", "SST", "GHRL", "VWF", "SOX10"), group.by = "predicted.id")
```

Example 46 (r):
```r
VlnPlot(pancreas.query, c("REG1A", "PPY", "SST", "GHRL", "VWF", "SOX10"), group.by = "predicted.id")
```

Example 47 (r):
```r
VlnPlot(pancreas.query, c("REG1A", "PPY", "SST", "GHRL", "VWF", "SOX10"), group.by = "predicted.id")
```

Example 48 (unknown):
```unknown
TransferData()
```

Example 49 (unknown):
```unknown
pancreas.ref <- RunUMAP(pancreas.ref, dims = 1:30, reduction = "integrated.cca", return.model = TRUE)
pancreas.query <- MapQuery(anchorset = pancreas.anchors, reference = pancreas.ref, query = pancreas.query,
    refdata = list(celltype = "celltype"), reference.reduction = "pca", reduction.model = "umap")
```

Example 50 (r):
```r
pancreas.ref <- RunUMAP(pancreas.ref, dims = 1:30, reduction = "integrated.cca", return.model = TRUE)
pancreas.query <- MapQuery(anchorset = pancreas.anchors, reference = pancreas.ref, query = pancreas.query,
    refdata = list(celltype = "celltype"), reference.reduction = "pca", reduction.model = "umap")
```

Example 51 (r):
```r
pancreas.ref <- RunUMAP(pancreas.ref, dims = 1:30, reduction = "integrated.cca", return.model = TRUE)
pancreas.query <- MapQuery(anchorset = pancreas.anchors, reference = pancreas.ref, query = pancreas.query,
    refdata = list(celltype = "celltype"), reference.reduction = "pca", reduction.model = "umap")
```

Example 52 (unknown):
```unknown
TransferData()
```

Example 53 (unknown):
```unknown
IntegrateEmbeddings()
```

Example 54 (unknown):
```unknown
ProjectUMAP()
```

Example 55 (unknown):
```unknown
TransferData()
```

Example 56 (unknown):
```unknown
IntegrateEmbeddings()
```

Example 57 (unknown):
```unknown
ProjectUMAP()
```

Example 58 (unknown):
```unknown
pancreas.query <- TransferData(anchorset = pancreas.anchors, reference = pancreas.ref, query = pancreas.query,
    refdata = list(celltype = "celltype"))
pancreas.query <- IntegrateEmbeddings(anchorset = pancreas.anchors, reference = pancreas.ref, query = pancreas.query,
    new.reduction.name = "ref.pca")
pancreas.query <- ProjectUMAP(query = pancreas.query, query.reduction = "ref.pca", reference = pancreas.ref,
    reference.reduction = "pca", reduction.model = "umap")
```

Example 59 (r):
```r
pancreas.query <- TransferData(anchorset = pancreas.anchors, reference = pancreas.ref, query = pancreas.query,
    refdata = list(celltype = "celltype"))
pancreas.query <- IntegrateEmbeddings(anchorset = pancreas.anchors, reference = pancreas.ref, query = pancreas.query,
    new.reduction.name = "ref.pca")
pancreas.query <- ProjectUMAP(query = pancreas.query, query.reduction = "ref.pca", reference = pancreas.ref,
    reference.reduction = "pca", reduction.model = "umap")
```

Example 60 (r):
```r
pancreas.query <- TransferData(anchorset = pancreas.anchors, reference = pancreas.ref, query = pancreas.query,
    refdata = list(celltype = "celltype"))
pancreas.query <- IntegrateEmbeddings(anchorset = pancreas.anchors, reference = pancreas.ref, query = pancreas.query,
    new.reduction.name = "ref.pca")
pancreas.query <- ProjectUMAP(query = pancreas.query, query.reduction = "ref.pca", reference = pancreas.ref,
    reference.reduction = "pca", reduction.model = "umap")
```

Example 61 (unknown):
```unknown
p1 <- DimPlot(pancreas.ref, reduction = "umap", group.by = "celltype", label = TRUE, label.size = 3,
    repel = TRUE) + NoLegend() + ggtitle("Reference annotations")
p2 <- DimPlot(pancreas.query, reduction = "ref.umap", group.by = "predicted.celltype", label = TRUE,
    label.size = 3, repel = TRUE) + NoLegend() + ggtitle("Query transferred labels")
p1 + p2
```

Example 62 (r):
```r
p1 <- DimPlot(pancreas.ref, reduction = "umap", group.by = "celltype", label = TRUE, label.size = 3,
    repel = TRUE) + NoLegend() + ggtitle("Reference annotations")
p2 <- DimPlot(pancreas.query, reduction = "ref.umap", group.by = "predicted.celltype", label = TRUE,
    label.size = 3, repel = TRUE) + NoLegend() + ggtitle("Query transferred labels")
p1 + p2
```

Example 63 (r):
```r
p1 <- DimPlot(pancreas.ref, reduction = "umap", group.by = "celltype", label = TRUE, label.size = 3,
    repel = TRUE) + NoLegend() + ggtitle("Reference annotations")
p2 <- DimPlot(pancreas.query, reduction = "ref.umap", group.by = "predicted.celltype", label = TRUE,
    label.size = 3, repel = TRUE) + NoLegend() + ggtitle("Query transferred labels")
p1 + p2
```

Example 64 (unknown):
```unknown
sessionInfo()
```

Example 65 (r):
```r
sessionInfo()
```

Example 66 (r):
```r
sessionInfo()
```

Example 67 (unknown):
```unknown
## R version 4.2.2 Patched (2022-11-10 r83330)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.6 LTS
## 
## Matrix products: default
## BLAS:   /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.9.0
## LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.9.0
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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       
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
##  [1] ggplot2_3.4.4                 thp1.eccite.SeuratData_3.1.5 
##  [3] stxBrain.SeuratData_0.1.1     ssHippo.SeuratData_3.1.4     
##  [5] pbmcsca.SeuratData_3.0.0      pbmcref.SeuratData_1.0.0     
##  [7] pbmcMultiome.SeuratData_0.1.4 pbmc3k.SeuratData_3.1.4      
##  [9] panc8.SeuratData_3.0.2        ifnb.SeuratData_3.0.0        
## [11] hcabm40k.SeuratData_3.0.0     cbmc.SeuratData_3.1.4        
## [13] bmcite.SeuratData_0.3.0       SeuratData_0.2.2.9001        
## [15] Seurat_5.0.0                  SeuratObject_5.0.0           
## [17] sp_2.1-1                     
## 
## loaded via a namespace (and not attached):
##   [1] spam_2.10-0            systemfonts_1.0.4      plyr_1.8.9            
##   [4] igraph_1.5.1           lazyeval_0.2.2         splines_4.2.2         
##   [7] RcppHNSW_0.5.0         listenv_0.9.0          scattermore_1.2       
##  [10] digest_0.6.33          htmltools_0.5.6.1      fansi_1.0.5           
##  [13] magrittr_2.0.3         memoise_2.0.1          tensor_1.5            
##  [16] cluster_2.1.4          ROCR_1.0-11            globals_0.16.2        
##  [19] matrixStats_1.0.0      pkgdown_2.0.7          spatstat.sparse_3.0-3 
##  [22] colorspace_2.1-0       rappdirs_0.3.3         ggrepel_0.9.4         
##  [25] textshaping_0.3.6      xfun_0.40              dplyr_1.1.3           
##  [28] crayon_1.5.2           jsonlite_1.8.7         progressr_0.14.0      
##  [31] spatstat.data_3.0-3    survival_3.5-7         zoo_1.8-12            
##  [34] glue_1.6.2             polyclip_1.10-6        gtable_0.3.4          
##  [37] leiden_0.4.3           future.apply_1.11.0    abind_1.4-5           
##  [40] scales_1.2.1           spatstat.random_3.2-1  miniUI_0.1.1.1        
##  [43] Rcpp_1.0.11            viridisLite_0.4.2      xtable_1.8-4          
##  [46] reticulate_1.34.0      dotCall64_1.1-0        htmlwidgets_1.6.2     
##  [49] httr_1.4.7             RColorBrewer_1.1-3     ellipsis_0.3.2        
##  [52] ica_1.0-3              farver_2.1.1           pkgconfig_2.0.3       
##  [55] sass_0.4.7             uwot_0.1.16            deldir_1.0-9          
##  [58] utf8_1.2.4             labeling_0.4.3         tidyselect_1.2.0      
##  [61] rlang_1.1.1            reshape2_1.4.4         later_1.3.1           
##  [64] munsell_0.5.0          tools_4.2.2            cachem_1.0.8          
##  [67] cli_3.6.1              generics_0.1.3         ggridges_0.5.4        
##  [70] evaluate_0.22          stringr_1.5.0          fastmap_1.1.1         
##  [73] yaml_2.3.7             ragg_1.2.5             goftest_1.2-3         
##  [76] knitr_1.45             fs_1.6.3               fitdistrplus_1.1-11   
##  [79] purrr_1.0.2            RANN_2.6.1             pbapply_1.7-2         
##  [82] future_1.33.0          nlme_3.1-162           mime_0.12             
##  [85] formatR_1.14           ggrastr_1.0.1          compiler_4.2.2        
##  [88] beeswarm_0.4.0         plotly_4.10.3          png_0.1-8             
##  [91] spatstat.utils_3.0-4   tibble_3.2.1           bslib_0.5.1           
##  [94] stringi_1.7.12         highr_0.10             desc_1.4.2            
##  [97] RSpectra_0.16-1        lattice_0.21-9         Matrix_1.6-1.1        
## [100] vctrs_0.6.4            pillar_1.9.0           lifecycle_1.0.3       
## [103] spatstat.geom_3.2-7    lmtest_0.9-40          jquerylib_0.1.4       
## [106] RcppAnnoy_0.0.21       data.table_1.14.8      cowplot_1.1.1         
## [109] irlba_2.3.5.1          httpuv_1.6.12          patchwork_1.1.3       
## [112] R6_2.5.1               promises_1.2.1         KernSmooth_2.23-22    
## [115] gridExtra_2.3          vipor_0.4.5            parallelly_1.36.0     
## [118] codetools_0.2-19       fastDummies_1.7.3      MASS_7.3-58.2         
## [121] rprojroot_2.0.3        withr_2.5.2            sctransform_0.4.1     
## [124] parallel_4.2.2         grid_4.2.2             tidyr_1.3.0           
## [127] rmarkdown_2.25         Rtsne_0.16             spatstat.explore_3.2-5
## [130] shiny_1.7.5.1          ggbeeswarm_0.7.1
```

Example 68 (unknown):
```unknown
## R version 4.2.2 Patched (2022-11-10 r83330)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.6 LTS
## 
## Matrix products: default
## BLAS:   /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.9.0
## LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.9.0
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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       
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
##  [1] ggplot2_3.4.4                 thp1.eccite.SeuratData_3.1.5 
##  [3] stxBrain.SeuratData_0.1.1     ssHippo.SeuratData_3.1.4     
##  [5] pbmcsca.SeuratData_3.0.0      pbmcref.SeuratData_1.0.0     
##  [7] pbmcMultiome.SeuratData_0.1.4 pbmc3k.SeuratData_3.1.4      
##  [9] panc8.SeuratData_3.0.2        ifnb.SeuratData_3.0.0        
## [11] hcabm40k.SeuratData_3.0.0     cbmc.SeuratData_3.1.4        
## [13] bmcite.SeuratData_0.3.0       SeuratData_0.2.2.9001        
## [15] Seurat_5.0.0                  SeuratObject_5.0.0           
## [17] sp_2.1-1                     
## 
## loaded via a namespace (and not attached):
##   [1] spam_2.10-0            systemfonts_1.0.4      plyr_1.8.9            
##   [4] igraph_1.5.1           lazyeval_0.2.2         splines_4.2.2         
##   [7] RcppHNSW_0.5.0         listenv_0.9.0          scattermore_1.2       
##  [10] digest_0.6.33          htmltools_0.5.6.1      fansi_1.0.5           
##  [13] magrittr_2.0.3         memoise_2.0.1          tensor_1.5            
##  [16] cluster_2.1.4          ROCR_1.0-11            globals_0.16.2        
##  [19] matrixStats_1.0.0      pkgdown_2.0.7          spatstat.sparse_3.0-3 
##  [22] colorspace_2.1-0       rappdirs_0.3.3         ggrepel_0.9.4         
##  [25] textshaping_0.3.6      xfun_0.40              dplyr_1.1.3           
##  [28] crayon_1.5.2           jsonlite_1.8.7         progressr_0.14.0      
##  [31] spatstat.data_3.0-3    survival_3.5-7         zoo_1.8-12            
##  [34] glue_1.6.2             polyclip_1.10-6        gtable_0.3.4          
##  [37] leiden_0.4.3           future.apply_1.11.0    abind_1.4-5           
##  [40] scales_1.2.1           spatstat.random_3.2-1  miniUI_0.1.1.1        
##  [43] Rcpp_1.0.11            viridisLite_0.4.2      xtable_1.8-4          
##  [46] reticulate_1.34.0      dotCall64_1.1-0        htmlwidgets_1.6.2     
##  [49] httr_1.4.7             RColorBrewer_1.1-3     ellipsis_0.3.2        
##  [52] ica_1.0-3              farver_2.1.1           pkgconfig_2.0.3       
##  [55] sass_0.4.7             uwot_0.1.16            deldir_1.0-9          
##  [58] utf8_1.2.4             labeling_0.4.3         tidyselect_1.2.0      
##  [61] rlang_1.1.1            reshape2_1.4.4         later_1.3.1           
##  [64] munsell_0.5.0          tools_4.2.2            cachem_1.0.8          
##  [67] cli_3.6.1              generics_0.1.3         ggridges_0.5.4        
##  [70] evaluate_0.22          stringr_1.5.0          fastmap_1.1.1         
##  [73] yaml_2.3.7             ragg_1.2.5             goftest_1.2-3         
##  [76] knitr_1.45             fs_1.6.3               fitdistrplus_1.1-11   
##  [79] purrr_1.0.2            RANN_2.6.1             pbapply_1.7-2         
##  [82] future_1.33.0          nlme_3.1-162           mime_0.12             
##  [85] formatR_1.14           ggrastr_1.0.1          compiler_4.2.2        
##  [88] beeswarm_0.4.0         plotly_4.10.3          png_0.1-8             
##  [91] spatstat.utils_3.0-4   tibble_3.2.1           bslib_0.5.1           
##  [94] stringi_1.7.12         highr_0.10             desc_1.4.2            
##  [97] RSpectra_0.16-1        lattice_0.21-9         Matrix_1.6-1.1        
## [100] vctrs_0.6.4            pillar_1.9.0           lifecycle_1.0.3       
## [103] spatstat.geom_3.2-7    lmtest_0.9-40          jquerylib_0.1.4       
## [106] RcppAnnoy_0.0.21       data.table_1.14.8      cowplot_1.1.1         
## [109] irlba_2.3.5.1          httpuv_1.6.12          patchwork_1.1.3       
## [112] R6_2.5.1               promises_1.2.1         KernSmooth_2.23-22    
## [115] gridExtra_2.3          vipor_0.4.5            parallelly_1.36.0     
## [118] codetools_0.2-19       fastDummies_1.7.3      MASS_7.3-58.2         
## [121] rprojroot_2.0.3        withr_2.5.2            sctransform_0.4.1     
## [124] parallel_4.2.2         grid_4.2.2             tidyr_1.3.0           
## [127] rmarkdown_2.25         Rtsne_0.16             spatstat.explore_3.2-5
## [130] shiny_1.7.5.1          ggbeeswarm_0.7.1
```

---

## Demultiplexing with hashtag oligos (HTOs)

**URL:** http://127.0.0.1:9173/seurat/archive/v3.1/hashing_vignette/index.html

**Contents:**
- Demultiplexing with hashtag oligos (HTOs)
    - Compiled: 2020-04-17
- 8-HTO dataset from human PBMCs
  - Basic setup
  - Adding HTO data as an independent assay
  - Demultiplex cells based on HTO enrichment
  - Visualize demultiplexing results
- 12-HTO dataset from four human cell lines
  - Create Seurat object, add HTO data and perform normalization
  - Demultiplex data
  - Visualize demultiplexing results
  - Visualize RNA clustering

Developed in collaboration with the Technology Innovation Group at NYGC, Cell Hashing uses oligo-tagged antibodies against ubuquitously expressed surface proteins to place a “sample barcode” on each single cell, enabling different samples to be multiplexed together and run in a single experiment. For more information, please refer to this paper.

This vignette will give a brief demonstration on how to work with data produced with Cell Hashing in Seurat. Applied to two datasets, we can successfully demultiplex cells to their the original sample-of-origin, and identify cross-sample doublets.

Setup Seurat object and add in the HTO data

You can read more about working with multi-modal data here

Here we use the Seurat function HTODemux() to assign single cells back to their sample origins.

Output from running HTODemux() is saved in the object metadata. We can visualize how many cells are classified as singlets, doublets and negative/ambiguous cells.

Visualize enrichment for selected HTOs with ridge plots

Visualize pairs of HTO signals to confirm mutual exclusivity in singlets

Compare number of UMIs for singlets, doublets and negative cells

Generate a two dimensional tSNE embedding for HTOs.Here we are grouping cells by singlets and doublets for simplicity.

Create an HTO heatmap, based on Figure 1C in the Cell Hashing paper.

Cluster and visualize cells using the usual scRNA-seq workflow, and examine for the potential presence of batch effects.

Distribution of selected HTOs grouped by classification, displayed by ridge plots

Visualize HTO signals in a heatmap

**Examples:**

Example 1 (r):
```r
library(Seurat)
```

Example 2 (r):
```r
library(Seurat)
```

Example 3 (r):
```r
# Load in the UMI matrix
pbmc.umis <- readRDS("../data/pbmc_umi_mtx.rds")

# For generating a hashtag count matrix from FASTQ files, please refer to
# https://github.com/Hoohm/CITE-seq-Count.  Load in the HTO count matrix
pbmc.htos <- readRDS("../data/pbmc_hto_mtx.rds")

# Select cell barcodes detected by both RNA and HTO In the example datasets we have already
# filtered the cells for you, but perform this step for clarity.
joint.bcs <- intersect(colnames(pbmc.umis), colnames(pbmc.htos))

# Subset RNA and HTO counts by joint cell barcodes
pbmc.umis <- pbmc.umis[, joint.bcs]
pbmc.htos <- as.matrix(pbmc.htos[, joint.bcs])

# Confirm that the HTO have the correct names
rownames(pbmc.htos)
```

Example 4 (r):
```r
# Load in the UMI matrix
pbmc.umis <- readRDS("../data/pbmc_umi_mtx.rds")

# For generating a hashtag count matrix from FASTQ files, please refer to
# https://github.com/Hoohm/CITE-seq-Count.  Load in the HTO count matrix
pbmc.htos <- readRDS("../data/pbmc_hto_mtx.rds")

# Select cell barcodes detected by both RNA and HTO In the example datasets we have already
# filtered the cells for you, but perform this step for clarity.
joint.bcs <- intersect(colnames(pbmc.umis), colnames(pbmc.htos))

# Subset RNA and HTO counts by joint cell barcodes
pbmc.umis <- pbmc.umis[, joint.bcs]
pbmc.htos <- as.matrix(pbmc.htos[, joint.bcs])

# Confirm that the HTO have the correct names
rownames(pbmc.htos)
```

Example 5 (unknown):
```unknown
## [1] "HTO_A" "HTO_B" "HTO_C" "HTO_D" "HTO_E" "HTO_F" "HTO_G" "HTO_H"
```

Example 6 (unknown):
```unknown
## [1] "HTO_A" "HTO_B" "HTO_C" "HTO_D" "HTO_E" "HTO_F" "HTO_G" "HTO_H"
```

Example 7 (r):
```r
# Setup Seurat object
pbmc.hashtag <- CreateSeuratObject(counts = pbmc.umis)

# Normalize RNA data with log normalization
pbmc.hashtag <- NormalizeData(pbmc.hashtag)
# Find and scale variable features
pbmc.hashtag <- FindVariableFeatures(pbmc.hashtag, selection.method = "mean.var.plot")
pbmc.hashtag <- ScaleData(pbmc.hashtag, features = VariableFeatures(pbmc.hashtag))
```

Example 8 (r):
```r
# Setup Seurat object
pbmc.hashtag <- CreateSeuratObject(counts = pbmc.umis)

# Normalize RNA data with log normalization
pbmc.hashtag <- NormalizeData(pbmc.hashtag)
# Find and scale variable features
pbmc.hashtag <- FindVariableFeatures(pbmc.hashtag, selection.method = "mean.var.plot")
pbmc.hashtag <- ScaleData(pbmc.hashtag, features = VariableFeatures(pbmc.hashtag))
```

Example 9 (r):
```r
# Add HTO data as a new assay independent from RNA
pbmc.hashtag[["HTO"]] <- CreateAssayObject(counts = pbmc.htos)
# Normalize HTO data, here we use centered log-ratio (CLR) transformation
pbmc.hashtag <- NormalizeData(pbmc.hashtag, assay = "HTO", normalization.method = "CLR")
```

Example 10 (r):
```r
# Add HTO data as a new assay independent from RNA
pbmc.hashtag[["HTO"]] <- CreateAssayObject(counts = pbmc.htos)
# Normalize HTO data, here we use centered log-ratio (CLR) transformation
pbmc.hashtag <- NormalizeData(pbmc.hashtag, assay = "HTO", normalization.method = "CLR")
```

Example 11 (r):
```r
# If you have a very large dataset we suggest using k_function = 'clara'. This is a k-medoid
# clustering function for large applications You can also play with additional parameters (see
# documentation for HTODemux()) to adjust the threshold for classification Here we are using the
# default settings
pbmc.hashtag <- HTODemux(pbmc.hashtag, assay = "HTO", positive.quantile = 0.99)
```

Example 12 (r):
```r
# If you have a very large dataset we suggest using k_function = 'clara'. This is a k-medoid
# clustering function for large applications You can also play with additional parameters (see
# documentation for HTODemux()) to adjust the threshold for classification Here we are using the
# default settings
pbmc.hashtag <- HTODemux(pbmc.hashtag, assay = "HTO", positive.quantile = 0.99)
```

Example 13 (r):
```r
# Global classification results
table(pbmc.hashtag$HTO_classification.global)
```

Example 14 (r):
```r
# Global classification results
table(pbmc.hashtag$HTO_classification.global)
```

Example 15 (javascript):
```javascript
## 
##  Doublet Negative  Singlet 
##     2598      346    13972
```

Example 16 (javascript):
```javascript
## 
##  Doublet Negative  Singlet 
##     2598      346    13972
```

Example 17 (r):
```r
# Group cells based on the max HTO signal
Idents(pbmc.hashtag) <- "HTO_maxID"
RidgePlot(pbmc.hashtag, assay = "HTO", features = rownames(pbmc.hashtag[["HTO"]])[1:2], ncol = 2)
```

Example 18 (r):
```r
# Group cells based on the max HTO signal
Idents(pbmc.hashtag) <- "HTO_maxID"
RidgePlot(pbmc.hashtag, assay = "HTO", features = rownames(pbmc.hashtag[["HTO"]])[1:2], ncol = 2)
```

Example 19 (r):
```r
FeatureScatter(pbmc.hashtag, feature1 = "hto_HTO-A", feature2 = "hto_HTO-B")
```

Example 20 (r):
```r
FeatureScatter(pbmc.hashtag, feature1 = "hto_HTO-A", feature2 = "hto_HTO-B")
```

Example 21 (r):
```r
Idents(pbmc.hashtag) <- "HTO_classification.global"
VlnPlot(pbmc.hashtag, features = "nCount_RNA", pt.size = 0.1, log = TRUE)
```

Example 22 (r):
```r
Idents(pbmc.hashtag) <- "HTO_classification.global"
VlnPlot(pbmc.hashtag, features = "nCount_RNA", pt.size = 0.1, log = TRUE)
```

Example 23 (r):
```r
# First, we will remove negative cells from the object
pbmc.hashtag.subset <- subset(pbmc.hashtag, idents = "Negative", invert = TRUE)

# Calculate a distance matrix using HTO
hto.dist.mtx <- as.matrix(dist(t(GetAssayData(object = pbmc.hashtag.subset, assay = "HTO"))))

# Calculate tSNE embeddings with a distance matrix
pbmc.hashtag.subset <- RunTSNE(pbmc.hashtag.subset, distance.matrix = hto.dist.mtx, perplexity = 100)
DimPlot(pbmc.hashtag.subset)
```

Example 24 (r):
```r
# First, we will remove negative cells from the object
pbmc.hashtag.subset <- subset(pbmc.hashtag, idents = "Negative", invert = TRUE)

# Calculate a distance matrix using HTO
hto.dist.mtx <- as.matrix(dist(t(GetAssayData(object = pbmc.hashtag.subset, assay = "HTO"))))

# Calculate tSNE embeddings with a distance matrix
pbmc.hashtag.subset <- RunTSNE(pbmc.hashtag.subset, distance.matrix = hto.dist.mtx, perplexity = 100)
DimPlot(pbmc.hashtag.subset)
```

Example 25 (r):
```r
# You can also visualize the more detailed classification result by running Idents(object) <-
# 'HTO_classification' beofre plotting. Here, you can see that each of the small clouds on the
# tSNE plot corresponds to one of the 28 possible doublet combinations.
```

Example 26 (r):
```r
# You can also visualize the more detailed classification result by running Idents(object) <-
# 'HTO_classification' beofre plotting. Here, you can see that each of the small clouds on the
# tSNE plot corresponds to one of the 28 possible doublet combinations.
```

Example 27 (r):
```r
# To increase the efficiency of plotting, you can subsample cells using the num.cells argument
HTOHeatmap(pbmc.hashtag, assay = "HTO", ncells = 5000)
```

Example 28 (r):
```r
# To increase the efficiency of plotting, you can subsample cells using the num.cells argument
HTOHeatmap(pbmc.hashtag, assay = "HTO", ncells = 5000)
```

Example 29 (r):
```r
# Extract the singlets
pbmc.singlet <- subset(pbmc.hashtag, idents = "Singlet")

# Select the top 1000 most variable features
pbmc.singlet <- FindVariableFeatures(pbmc.singlet, selection.method = "mean.var.plot")

# Scaling RNA data, we only scale the variable features here for efficiency
pbmc.singlet <- ScaleData(pbmc.singlet, features = VariableFeatures(pbmc.singlet))

# Run PCA
pbmc.singlet <- RunPCA(pbmc.singlet, features = VariableFeatures(pbmc.singlet))
```

Example 30 (r):
```r
# Extract the singlets
pbmc.singlet <- subset(pbmc.hashtag, idents = "Singlet")

# Select the top 1000 most variable features
pbmc.singlet <- FindVariableFeatures(pbmc.singlet, selection.method = "mean.var.plot")

# Scaling RNA data, we only scale the variable features here for efficiency
pbmc.singlet <- ScaleData(pbmc.singlet, features = VariableFeatures(pbmc.singlet))

# Run PCA
pbmc.singlet <- RunPCA(pbmc.singlet, features = VariableFeatures(pbmc.singlet))
```

Example 31 (r):
```r
# We select the top 10 PCs for clustering and tSNE based on PCElbowPlot
pbmc.singlet <- FindNeighbors(pbmc.singlet, reduction = "pca", dims = 1:10)
pbmc.singlet <- FindClusters(pbmc.singlet, resolution = 0.6, verbose = FALSE)
pbmc.singlet <- RunTSNE(pbmc.singlet, reduction = "pca", dims = 1:10)

# Projecting singlet identities on TSNE visualization
DimPlot(pbmc.singlet, group.by = "HTO_classification")
```

Example 32 (r):
```r
# We select the top 10 PCs for clustering and tSNE based on PCElbowPlot
pbmc.singlet <- FindNeighbors(pbmc.singlet, reduction = "pca", dims = 1:10)
pbmc.singlet <- FindClusters(pbmc.singlet, resolution = 0.6, verbose = FALSE)
pbmc.singlet <- RunTSNE(pbmc.singlet, reduction = "pca", dims = 1:10)

# Projecting singlet identities on TSNE visualization
DimPlot(pbmc.singlet, group.by = "HTO_classification")
```

Example 33 (r):
```r
# Read in UMI count matrix for RNA
hto12.umis <- readRDS("../data/hto12_umi_mtx.rds")

# Read in HTO count matrix
hto12.htos <- readRDS("../data/hto12_hto_mtx.rds")

# Select cell barcodes detected in both RNA and HTO
cells.use <- intersect(rownames(hto12.htos), colnames(hto12.umis))

# Create Seurat object and add HTO data
hto12 <- CreateSeuratObject(counts = hto12.umis[, cells.use], min.features = 300)
hto12[["HTO"]] <- CreateAssayObject(counts = t(x = hto12.htos[colnames(hto12), 1:12]))

# Normalize data
hto12 <- NormalizeData(hto12)
hto12 <- NormalizeData(hto12, assay = "HTO", normalization.method = "CLR")
```

Example 34 (r):
```r
# Read in UMI count matrix for RNA
hto12.umis <- readRDS("../data/hto12_umi_mtx.rds")

# Read in HTO count matrix
hto12.htos <- readRDS("../data/hto12_hto_mtx.rds")

# Select cell barcodes detected in both RNA and HTO
cells.use <- intersect(rownames(hto12.htos), colnames(hto12.umis))

# Create Seurat object and add HTO data
hto12 <- CreateSeuratObject(counts = hto12.umis[, cells.use], min.features = 300)
hto12[["HTO"]] <- CreateAssayObject(counts = t(x = hto12.htos[colnames(hto12), 1:12]))

# Normalize data
hto12 <- NormalizeData(hto12)
hto12 <- NormalizeData(hto12, assay = "HTO", normalization.method = "CLR")
```

Example 35 (r):
```r
hto12 <- HTODemux(hto12, assay = "HTO", positive.quantile = 0.99)
```

Example 36 (r):
```r
hto12 <- HTODemux(hto12, assay = "HTO", positive.quantile = 0.99)
```

Example 37 (r):
```r
RidgePlot(hto12, assay = "HTO", features = c("HEK-A", "K562-B", "KG1-A", "THP1-C"), ncol = 2)
```

Example 38 (r):
```r
RidgePlot(hto12, assay = "HTO", features = c("HEK-A", "K562-B", "KG1-A", "THP1-C"), ncol = 2)
```

Example 39 (r):
```r
HTOHeatmap(hto12, assay = "HTO")
```

Example 40 (r):
```r
HTOHeatmap(hto12, assay = "HTO")
```

Example 41 (r):
```r
# Remove the negative cells
hto12 <- subset(hto12, idents = "Negative", invert = TRUE)

# Run PCA on most variable features
hto12 <- FindVariableFeatures(hto12, selection.method = "mean.var.plot")
hto12 <- ScaleData(hto12, features = VariableFeatures(hto12))
hto12 <- RunPCA(hto12)
hto12 <- RunTSNE(hto12, dims = 1:5, perplexity = 100)
DimPlot(hto12) + NoLegend()
```

Example 42 (r):
```r
# Remove the negative cells
hto12 <- subset(hto12, idents = "Negative", invert = TRUE)

# Run PCA on most variable features
hto12 <- FindVariableFeatures(hto12, selection.method = "mean.var.plot")
hto12 <- ScaleData(hto12, features = VariableFeatures(hto12))
hto12 <- RunPCA(hto12)
hto12 <- RunTSNE(hto12, dims = 1:5, perplexity = 100)
DimPlot(hto12) + NoLegend()
```

---

## PBMC scATAC-seq Vignette

**URL:** http://127.0.0.1:9173/seurat/archive/v3.2/atacseq_integration_vignette/index.html

**Contents:**
- PBMC scATAC-seq Vignette
    - Compiled: October 02, 2020
- Gene activity quantification
- Object setup
- Data preprocessing
- Co-embedding

Update February 2020: we now have developed a separate package, Signac, for the analysis and integration of scATAC-seq data. See the Signac website for up-to-date vignettes and documentation for analysing scATAC-seq data.

In this vignette, we demonstrate our new data transfer method in the context of scATAC-seq to

For this example we'll be working with the 10X PBMC datasets that contain ~10K cells for both scRNA-seq and scATAC-seq. You can download those here: scATAC-seq, scATAC-seq metadata, scRNA-seq

Overall our integration procedure consists of the following steps:

First, we load in the provided peak matrix and collapse the peak matrix to a "gene activity matrix". Here, we make the simplifying assumption that a gene's activity can be quantified by simply summing all counts within the gene body + 2kb upstream but our method is compatible with any method that returns a gene by cell matrix (e.g. Cicero).

Next, we'll set up the Seurat object and store both the original peak counts in the "ATAC" Assay and the gene activity matrix in the "RNA" Assay. As a QC step, we also filter out all cells here with fewer than 5K total counts in the scATAC-seq data, though you may need to modify this threshold for your experiment.

Here, we process the gene activity matrix in order to find anchors between cells in the scATAC-seq dataset and the scRNA-seq dataset.

We also process the peak matrix. Here we perform latent semantic indexing to reduce the dimensionality of the scATAC-seq data. This procedure learns an 'internal' structure for the scRNA-seq data, and is important when determining the appropriate weights for the anchors when transferring information. We utilize Latent Semantic Indexing (LSI) to learn the structure of ATAC-seq data, as proposed in Cusanovich et al, Science 2015 and implemented in the RunLSI function. LSI is implemented here by performing computing the term frequency-inverse document frequency (TF-IDF) followed by SVD.

We use all peaks that have at least 100 reads across all cells, and reduce dimensionality to 50. The parameters chosen here are inspired by previous scATAC-seq analyses, and we do not typically change them, but you can do so.

We have previously pre-processed and clustered a scRNA-seq dataset using the standard workflow in Seurat, and provide the object here. You can see that we can identify standard clusters of myeloid and lymphoid PBMCs.

Now, we can identify anchors between the scATAC-seq dataset and the scRNA-seq dataset and use these anchors to transfer the celltype labels we learned from the 10K scRNA-seq data to the scATAC-seq cells.

To transfer the cluster ids, we provide a vector of previously annotated cell type labels for the RNA to the refdata parameter. The output will contain a matrix with predictions and confidence scores for each ATAC-seq cell.

Why do you choose different (non-default) values for reduction and weight.reduction?

In FindTransferAnchors, we typically project the PCA structure from the reference onto the query when transferring between scRNA-seq datasets. However, when transferring across modalities we find that CCA better captures the shared feature correlation structure and therefore set reduction = 'cca' here. Additionally, by default in TransferData we use the same projected PCA structure to compute the weights of the local neighborhood of anchors that influence each cell's prediction. In the case of scRNA-seq to scATA-seq transfer, we use the low dimensional space learned by computing an LSI on the ATAC-seq data to compute these weights as this better captures the "internal" structure of the ATAC-seq data.

We can then examine the distribution of prediction scores and optionally filter out those cells with low scores. Here, we find that over 95% of the cells receive a score of 0.5 or greater.

We can then view the predicted cell types on a UMAP representation of the scATAC-seq data and find that the transferred labels are highly consistent with the UMAP structure.

After transferring cell type labels, you can then perform downstream analyses on a cell type specific level. For example, you could find sets of enhancers that are specific for certain cell types and look for motif enrichment. While not all of these types of downstream analyses are directly supported in Seurat, stay tuned for updates in this space.

Finally, to visualize all the cells together, we can co-embed the scRNA-seq and scATAC-seq cells in the same low dimensional space. Here, we use the same anchors used earlier to transfer cell type labels to impute RNA-seq values for the scATAC-seq cells. We then merge the measured and imputed scRNA-seq data and run a standard UMAP analysis to visualize all the cells together. Note that this step is for visualization purposes only and is not a necessary part of the data transfer analysis.

Here we plot all cells colored by either their assigned cell type (from the 10K dataset) or their predicted cell type from the data transfer procedure.

How can I further investigate unmatched groups of cells that only appear in one assay?

Upon inspection of the UMAP embeddings, there appeared several groups of cells that appeared to be present only in a single assay. First, the platelet cells appeared only in the scRNA-seq data. These cells are thought to be undergoing biogenesis from megakaryocytes to platelets and therefore either completely lack nuclear material or their chromatin state is uncoupled from their transcriptome. As a result, we would not expect these to align in this analysis.

Additionally, there appeared to be a population next to the B cell progenitors that is composed entirely of scATAC-seq cells and is not integrated well with the scRNA-seq cells. Further examination of the metadata for these cells revealed a high number of reads mapping to blacklisted regions (as provided by the 10x Genomics QC metrics). This suggests that these barcodes could represent dead or dying cells, ambient DNA, or another technical artifact not represented in the scRNA-seq dataset.

How can I evaluate the success of cross-modality integration?

There are several lines of evidence here that give us confidence in this analysis.

Additionally, we have performed a similar analysis, transferring cell type labels from scRNA-seq to scATAC-seq data in the context of the mouse brain and have observed good performance based on similar reasoning to the points above ( Figure 3). These analyses make the assumption that there is generally a positive correlation between chromatin accessibility and gene expression. In cases such as developing systems, where accessibility may not be a good indicator of transcription, the method demonstrated here may not be able to form good anchors and the resulting integration across these specific modalities may be of limited value.

**Examples:**

Example 1 (r):
```r
library(Seurat)
library(ggplot2)
library(patchwork)
peaks <- Read10X_h5("../data/atac_v1_pbmc_10k_filtered_peak_bc_matrix.h5")
# create a gene activity matrix from the peak matrix and GTF, using chromosomes 1:22, X, and Y.
# Peaks that fall within gene bodies, or 2kb upstream of a gene, are considered
activity.matrix <- CreateGeneActivityMatrix(peak.matrix = peaks, annotation.file = "../data/Homo_sapiens.GRCh37.82.gtf", 
    seq.levels = c(1:22, "X", "Y"), upstream = 2000, verbose = TRUE)
```

Example 2 (r):
```r
library(Seurat)
library(ggplot2)
library(patchwork)
peaks <- Read10X_h5("../data/atac_v1_pbmc_10k_filtered_peak_bc_matrix.h5")
# create a gene activity matrix from the peak matrix and GTF, using chromosomes 1:22, X, and Y.
# Peaks that fall within gene bodies, or 2kb upstream of a gene, are considered
activity.matrix <- CreateGeneActivityMatrix(peak.matrix = peaks, annotation.file = "../data/Homo_sapiens.GRCh37.82.gtf", 
    seq.levels = c(1:22, "X", "Y"), upstream = 2000, verbose = TRUE)
```

Example 3 (r):
```r
pbmc.atac <- CreateSeuratObject(counts = peaks, assay = "ATAC", project = "10x_ATAC")
pbmc.atac[["ACTIVITY"]] <- CreateAssayObject(counts = activity.matrix)
meta <- read.table("../data/atac_v1_pbmc_10k_singlecell.csv", sep = ",", header = TRUE, row.names = 1, 
    stringsAsFactors = FALSE)
meta <- meta[colnames(pbmc.atac), ]
pbmc.atac <- AddMetaData(pbmc.atac, metadata = meta)
pbmc.atac <- subset(pbmc.atac, subset = nCount_ATAC > 5000)
pbmc.atac$tech <- "atac"
```

Example 4 (r):
```r
pbmc.atac <- CreateSeuratObject(counts = peaks, assay = "ATAC", project = "10x_ATAC")
pbmc.atac[["ACTIVITY"]] <- CreateAssayObject(counts = activity.matrix)
meta <- read.table("../data/atac_v1_pbmc_10k_singlecell.csv", sep = ",", header = TRUE, row.names = 1, 
    stringsAsFactors = FALSE)
meta <- meta[colnames(pbmc.atac), ]
pbmc.atac <- AddMetaData(pbmc.atac, metadata = meta)
pbmc.atac <- subset(pbmc.atac, subset = nCount_ATAC > 5000)
pbmc.atac$tech <- "atac"
```

Example 5 (r):
```r
DefaultAssay(pbmc.atac) <- "ACTIVITY"
pbmc.atac <- FindVariableFeatures(pbmc.atac)
pbmc.atac <- NormalizeData(pbmc.atac)
pbmc.atac <- ScaleData(pbmc.atac)
```

Example 6 (r):
```r
DefaultAssay(pbmc.atac) <- "ACTIVITY"
pbmc.atac <- FindVariableFeatures(pbmc.atac)
pbmc.atac <- NormalizeData(pbmc.atac)
pbmc.atac <- ScaleData(pbmc.atac)
```

Example 7 (r):
```r
DefaultAssay(pbmc.atac) <- "ATAC"
VariableFeatures(pbmc.atac) <- names(which(Matrix::rowSums(pbmc.atac) > 100))
pbmc.atac <- RunLSI(pbmc.atac, n = 50, scale.max = NULL)
pbmc.atac <- RunUMAP(pbmc.atac, reduction = "lsi", dims = 1:50)
```

Example 8 (r):
```r
DefaultAssay(pbmc.atac) <- "ATAC"
VariableFeatures(pbmc.atac) <- names(which(Matrix::rowSums(pbmc.atac) > 100))
pbmc.atac <- RunLSI(pbmc.atac, n = 50, scale.max = NULL)
pbmc.atac <- RunUMAP(pbmc.atac, reduction = "lsi", dims = 1:50)
```

Example 9 (r):
```r
pbmc.rna <- readRDS("../data/pbmc_10k_v3.rds")
pbmc.rna$tech <- "rna"
```

Example 10 (r):
```r
pbmc.rna <- readRDS("../data/pbmc_10k_v3.rds")
pbmc.rna$tech <- "rna"
```

Example 11 (r):
```r
p1 <- DimPlot(pbmc.atac, reduction = "umap") + NoLegend() + ggtitle("scATAC-seq")
p2 <- DimPlot(pbmc.rna, group.by = "celltype", label = TRUE, repel = TRUE) + NoLegend() + ggtitle("scRNA-seq")
p1 + p2
```

Example 12 (r):
```r
p1 <- DimPlot(pbmc.atac, reduction = "umap") + NoLegend() + ggtitle("scATAC-seq")
p2 <- DimPlot(pbmc.rna, group.by = "celltype", label = TRUE, repel = TRUE) + NoLegend() + ggtitle("scRNA-seq")
p1 + p2
```

Example 13 (r):
```r
transfer.anchors <- FindTransferAnchors(reference = pbmc.rna, query = pbmc.atac, features = VariableFeatures(object = pbmc.rna), 
    reference.assay = "RNA", query.assay = "ACTIVITY", reduction = "cca")
```

Example 14 (r):
```r
transfer.anchors <- FindTransferAnchors(reference = pbmc.rna, query = pbmc.atac, features = VariableFeatures(object = pbmc.rna), 
    reference.assay = "RNA", query.assay = "ACTIVITY", reduction = "cca")
```

Example 15 (r):
```r
celltype.predictions <- TransferData(anchorset = transfer.anchors, refdata = pbmc.rna$celltype, 
    weight.reduction = pbmc.atac[["lsi"]])
pbmc.atac <- AddMetaData(pbmc.atac, metadata = celltype.predictions)
```

Example 16 (r):
```r
celltype.predictions <- TransferData(anchorset = transfer.anchors, refdata = pbmc.rna$celltype, 
    weight.reduction = pbmc.atac[["lsi"]])
pbmc.atac <- AddMetaData(pbmc.atac, metadata = celltype.predictions)
```

Example 17 (unknown):
```unknown
FindTransferAnchors
```

Example 18 (unknown):
```unknown
reduction = 'cca'
```

Example 19 (unknown):
```unknown
TransferData
```

Example 20 (r):
```r
hist(pbmc.atac$prediction.score.max)
abline(v = 0.5, col = "red")
```

Example 21 (r):
```r
hist(pbmc.atac$prediction.score.max)
abline(v = 0.5, col = "red")
```

Example 22 (r):
```r
table(pbmc.atac$prediction.score.max > 0.5)
```

Example 23 (r):
```r
table(pbmc.atac$prediction.score.max > 0.5)
```

Example 24 (unknown):
```unknown
## 
## FALSE  TRUE 
##   290  7576
```

Example 25 (unknown):
```unknown
## 
## FALSE  TRUE 
##   290  7576
```

Example 26 (r):
```r
pbmc.atac.filtered <- subset(pbmc.atac, subset = prediction.score.max > 0.5)
pbmc.atac.filtered$predicted.id <- factor(pbmc.atac.filtered$predicted.id, levels = levels(pbmc.rna))  # to make the colors match
p1 <- DimPlot(pbmc.atac.filtered, group.by = "predicted.id", label = TRUE, repel = TRUE) + ggtitle("scATAC-seq cells") + 
    NoLegend() + scale_colour_hue(drop = FALSE)
p2 <- DimPlot(pbmc.rna, group.by = "celltype", label = TRUE, repel = TRUE) + ggtitle("scRNA-seq cells") + 
    NoLegend()
p1 + p2
```

Example 27 (r):
```r
pbmc.atac.filtered <- subset(pbmc.atac, subset = prediction.score.max > 0.5)
pbmc.atac.filtered$predicted.id <- factor(pbmc.atac.filtered$predicted.id, levels = levels(pbmc.rna))  # to make the colors match
p1 <- DimPlot(pbmc.atac.filtered, group.by = "predicted.id", label = TRUE, repel = TRUE) + ggtitle("scATAC-seq cells") + 
    NoLegend() + scale_colour_hue(drop = FALSE)
p2 <- DimPlot(pbmc.rna, group.by = "celltype", label = TRUE, repel = TRUE) + ggtitle("scRNA-seq cells") + 
    NoLegend()
p1 + p2
```

Example 28 (r):
```r
# note that we restrict the imputation to variable genes from scRNA-seq, but could impute the
# full transcriptome if we wanted to
genes.use <- VariableFeatures(pbmc.rna)
refdata <- GetAssayData(pbmc.rna, assay = "RNA", slot = "data")[genes.use, ]

# refdata (input) contains a scRNA-seq expression matrix for the scRNA-seq cells.  imputation
# (output) will contain an imputed scRNA-seq matrix for each of the ATAC cells
imputation <- TransferData(anchorset = transfer.anchors, refdata = refdata, weight.reduction = pbmc.atac[["lsi"]])

# this line adds the imputed data matrix to the pbmc.atac object
pbmc.atac[["RNA"]] <- imputation
coembed <- merge(x = pbmc.rna, y = pbmc.atac)

# Finally, we run PCA and UMAP on this combined object, to visualize the co-embedding of both
# datasets
coembed <- ScaleData(coembed, features = genes.use, do.scale = FALSE)
coembed <- RunPCA(coembed, features = genes.use, verbose = FALSE)
coembed <- RunUMAP(coembed, dims = 1:30)
coembed$celltype <- ifelse(!is.na(coembed$celltype), coembed$celltype, coembed$predicted.id)
```

Example 29 (r):
```r
# note that we restrict the imputation to variable genes from scRNA-seq, but could impute the
# full transcriptome if we wanted to
genes.use <- VariableFeatures(pbmc.rna)
refdata <- GetAssayData(pbmc.rna, assay = "RNA", slot = "data")[genes.use, ]

# refdata (input) contains a scRNA-seq expression matrix for the scRNA-seq cells.  imputation
# (output) will contain an imputed scRNA-seq matrix for each of the ATAC cells
imputation <- TransferData(anchorset = transfer.anchors, refdata = refdata, weight.reduction = pbmc.atac[["lsi"]])

# this line adds the imputed data matrix to the pbmc.atac object
pbmc.atac[["RNA"]] <- imputation
coembed <- merge(x = pbmc.rna, y = pbmc.atac)

# Finally, we run PCA and UMAP on this combined object, to visualize the co-embedding of both
# datasets
coembed <- ScaleData(coembed, features = genes.use, do.scale = FALSE)
coembed <- RunPCA(coembed, features = genes.use, verbose = FALSE)
coembed <- RunUMAP(coembed, dims = 1:30)
coembed$celltype <- ifelse(!is.na(coembed$celltype), coembed$celltype, coembed$predicted.id)
```

Example 30 (r):
```r
p1 <- DimPlot(coembed, group.by = "tech")
p2 <- DimPlot(coembed, group.by = "celltype", label = TRUE, repel = TRUE)
p1 + p2
```

Example 31 (r):
```r
p1 <- DimPlot(coembed, group.by = "tech")
p2 <- DimPlot(coembed, group.by = "celltype", label = TRUE, repel = TRUE)
p1 + p2
```

Example 32 (r):
```r
DimPlot(coembed, split.by = "tech", group.by = "celltype", label = TRUE, repel = TRUE) + NoLegend()
```

Example 33 (r):
```r
DimPlot(coembed, split.by = "tech", group.by = "celltype", label = TRUE, repel = TRUE) + NoLegend()
```

Example 34 (r):
```r
coembed$blacklist_region_fragments[is.na(coembed$blacklist_region_fragments)] <- 0
FeaturePlot(coembed, features = "blacklist_region_fragments", max.cutoff = 500)
```

Example 35 (r):
```r
coembed$blacklist_region_fragments[is.na(coembed$blacklist_region_fragments)] <- 0
FeaturePlot(coembed, features = "blacklist_region_fragments", max.cutoff = 500)
```

---

## Cell-Cycle Scoring and Regression

**URL:** http://127.0.0.1:9173/seurat/archive/v2.4/cell_cycle_vignette/index.html

**Contents:**
- Cell-Cycle Scoring and Regression
    - Compiled: 2018-03-24
  - Assign Cell-Cycle Scores
  - Regress out cell cycle scores during data scaling
  - Alternate Workflow

We demonstrate how to mitigate the effects of cell cycle heterogeneity in scRNA-seq data by calculating cell cycle phase scores based on canonical markers, and regressing these out of the data during pre-processing. We demonstrate this on a dataset of murine hematopoietic progenitors (Nestorowa et al., Blood 2016.You can download the files needed to run this vignette here.

If we run a PCA on our object, using the variable genes we found in FindVariableGenes above, we see that while most of the variance can be explained by lineage, PC4 is split on cell-cycle genes including TOP2A and MKI67. We will attempt to regress this signal from the data, so that cell-cycle heterogneity does not contribute to PCA or downstream analysis.

First, we assign each cell a score, based on its expression of G2/M and S phase markers. These marker sets should be anticorrelated in their expression levels, and cells expressing neither are likely not cycling and in G1 phase.

We assign scores in the CellCycleScoring function, which stores S and G2/M scores in object@meta.data, along with the predicted classification of each cell in either G2M, S or G1 phase. CellCycleScoring can also set the identity of the Seurat object to the cell-cycle phase by passing set.ident = TRUE (the original identities are stored as old.ident). Please note that Seurat does not use the discrete classifications (G2M/G1/S) in downstream cell cycle regression. Instead, it uses the quantitative scores for G2M and S phase. However, we provide our predicted classifications in case they are of interest.

We score single cells based on the scoring strategy described in Tirosh et al. 2016. See ?AddModuleScore in Seurat for more information, this function can be used to calculate supervised module scores for any gene list.

We now attempt to subtract (‘regress out’) this source of heterogeneity from the data. For users of Seurat v1.4, this was implemented in RegressOut. However, as the results of this procedure are stored in object@scale.data (therefore overwriting the output of ScaleData), we now merge this functionality into the ScaleData function itself.

For each gene, Seurat models the relationship between gene expression and the S and G2M cell cycle scores. The scaled residuals of this model represent a ‘corrected’ expression matrix, that can be used downstream for dimensional reduction.

As the best cell cycle markers are extremely well conserved across tissues and species, we have found this procedure to work robustly and reliably on diverse datasets.

The procedure above removes all signal associated with cell cycle. In some cases, we’ve found that this can negatively impact downstream analysis, particularly in differentiating processes (like murine hematopoiesis), where stem cells are quiescent and differentiated cells are proliferating (or vice versa). In this case, regressing out all cell cycle effects can blur the distinction between stem and progenitor cells as well.

As an alternative, we suggest regressing out the difference between the G2M and S phase scores. This means that signals separating non-cycling cells and cycling cells will be maintained, but differences in cell cycle phase amongst proliferating cells (which are often uninteresting), will be regressed out of the data

**Examples:**

Example 1 (r):
```r
library(Seurat)

# Read in the expression matrix The first row is a header row, the first
# column is rownames
exp.mat <- read.table(file = "~/Downloads/seurat_resources/nestorawa_forcellcycle_expressionMatrix.txt", 
    header = TRUE, as.is = TRUE, row.names = 1)

# Also read in a list of cell cycle markers, from Tirosh et al, 2015
cc.genes <- readLines(con = "~/Downloads/seurat_resources/regev_lab_cell_cycle_genes.txt")

# We can segregate this list into markers of G2/M phase and markers of S
# phase
s.genes <- cc.genes[1:43]
g2m.genes <- cc.genes[44:97]

# Create our Seurat object and complete the initalization steps
marrow <- CreateSeuratObject(raw.data = exp.mat)
marrow <- NormalizeData(object = marrow)
marrow <- FindVariableGenes(object = marrow, do.plot = FALSE, display.progress = FALSE)
marrow <- ScaleData(object = marrow, display.progress = FALSE)
```

Example 2 (r):
```r
library(Seurat)

# Read in the expression matrix The first row is a header row, the first
# column is rownames
exp.mat <- read.table(file = "~/Downloads/seurat_resources/nestorawa_forcellcycle_expressionMatrix.txt", 
    header = TRUE, as.is = TRUE, row.names = 1)

# Also read in a list of cell cycle markers, from Tirosh et al, 2015
cc.genes <- readLines(con = "~/Downloads/seurat_resources/regev_lab_cell_cycle_genes.txt")

# We can segregate this list into markers of G2/M phase and markers of S
# phase
s.genes <- cc.genes[1:43]
g2m.genes <- cc.genes[44:97]

# Create our Seurat object and complete the initalization steps
marrow <- CreateSeuratObject(raw.data = exp.mat)
marrow <- NormalizeData(object = marrow)
marrow <- FindVariableGenes(object = marrow, do.plot = FALSE, display.progress = FALSE)
marrow <- ScaleData(object = marrow, display.progress = FALSE)
```

Example 3 (unknown):
```unknown
FindVariableGenes
```

Example 4 (r):
```r
marrow <- RunPCA(object = marrow, pc.genes = marrow@var.genes, pcs.print = 1:4, 
    genes.print = 10)
```

Example 5 (r):
```r
marrow <- RunPCA(object = marrow, pc.genes = marrow@var.genes, pcs.print = 1:4, 
    genes.print = 10)
```

Example 6 (unknown):
```unknown
## [1] "PC1"
##  [1] "CORO1A"   "FXYD5"    "PLAC8"    "H2AFY"    "LAPTM5"   "PKM"     
##  [7] "CD34"     "TMEM176B" "LCP1"     "LIMD2"   
## [1] ""
##  [1] "BLVRB"   "KLF1"    "ERMAP"   "FAM132A" "CES2G"   "RHD"     "AQP1"   
##  [8] "SPHK1"   "CAR2"    "CAR1"   
## [1] ""
## [1] ""
## [1] "PC2"
##  [1] "APOE"    "GATA2"   "RAB37"   "TXNIP"   "VAMP5"   "MFSD2B"  "S100A10"
##  [8] "CTLA2A"  "F2R"     "H2-Q6"  
## [1] ""
##  [1] "CTSG"    "CLEC12A" "ELANE"   "ANXA3"   "MPO"     "HP"      "LY6C2"  
##  [8] "PRTN3"   "IGSF6"   "TYROBP" 
## [1] ""
## [1] ""
## [1] "PC3"
##  [1] "CDK6"   "APOE"   "FAM46A" "MS4A3"  "LGALS1" "FCGR3"  "RAB44" 
##  [8] "ELANE"  "NKG7"   "HDC"   
## [1] ""
##  [1] "FLT3"          "MYL10"         "LSP1"          "GIMAP6"       
##  [5] "9030619P08RIK" "WFDC17"        "DNTT"          "FTH1"         
##  [9] "CD24A"         "GCNT2"        
## [1] ""
## [1] ""
## [1] "PC4"
##  [1] "TRIB2"     "ATP1B2"    "YPEL3"     "CAR1"      "TCP11L2"  
##  [6] "LPIN1"     "AQP9"      "IFNGR1"    "PLD4"      "HIST1H2BC"
## [1] ""
##  [1] "NUSAP1"   "TOP2A"    "FAM64A"   "KIF11"    "MIS18BP1" "UBE2C"   
##  [7] "MKI67"    "CDK1"     "PRC1"     "SPC25"   
## [1] ""
## [1] ""
```

Example 7 (unknown):
```unknown
## [1] "PC1"
##  [1] "CORO1A"   "FXYD5"    "PLAC8"    "H2AFY"    "LAPTM5"   "PKM"     
##  [7] "CD34"     "TMEM176B" "LCP1"     "LIMD2"   
## [1] ""
##  [1] "BLVRB"   "KLF1"    "ERMAP"   "FAM132A" "CES2G"   "RHD"     "AQP1"   
##  [8] "SPHK1"   "CAR2"    "CAR1"   
## [1] ""
## [1] ""
## [1] "PC2"
##  [1] "APOE"    "GATA2"   "RAB37"   "TXNIP"   "VAMP5"   "MFSD2B"  "S100A10"
##  [8] "CTLA2A"  "F2R"     "H2-Q6"  
## [1] ""
##  [1] "CTSG"    "CLEC12A" "ELANE"   "ANXA3"   "MPO"     "HP"      "LY6C2"  
##  [8] "PRTN3"   "IGSF6"   "TYROBP" 
## [1] ""
## [1] ""
## [1] "PC3"
##  [1] "CDK6"   "APOE"   "FAM46A" "MS4A3"  "LGALS1" "FCGR3"  "RAB44" 
##  [8] "ELANE"  "NKG7"   "HDC"   
## [1] ""
##  [1] "FLT3"          "MYL10"         "LSP1"          "GIMAP6"       
##  [5] "9030619P08RIK" "WFDC17"        "DNTT"          "FTH1"         
##  [9] "CD24A"         "GCNT2"        
## [1] ""
## [1] ""
## [1] "PC4"
##  [1] "TRIB2"     "ATP1B2"    "YPEL3"     "CAR1"      "TCP11L2"  
##  [6] "LPIN1"     "AQP9"      "IFNGR1"    "PLD4"      "HIST1H2BC"
## [1] ""
##  [1] "NUSAP1"   "TOP2A"    "FAM64A"   "KIF11"    "MIS18BP1" "UBE2C"   
##  [7] "MKI67"    "CDK1"     "PRC1"     "SPC25"   
## [1] ""
## [1] ""
```

Example 8 (r):
```r
PCHeatmap(object = marrow, pc.use = 4, do.balanced = TRUE, label.columns = FALSE, 
    remove.key = TRUE)
```

Example 9 (r):
```r
PCHeatmap(object = marrow, pc.use = 4, do.balanced = TRUE, label.columns = FALSE, 
    remove.key = TRUE)
```

Example 10 (unknown):
```unknown
CellCycleScoring
```

Example 11 (unknown):
```unknown
object@meta.data
```

Example 12 (unknown):
```unknown
CellCycleScoring
```

Example 13 (unknown):
```unknown
set.ident = TRUE
```

Example 14 (r):
```r
marrow <- CellCycleScoring(object = marrow, s.genes = s.genes, g2m.genes = g2m.genes, 
    set.ident = TRUE)

# view cell cycle scores and phase assignments
head(x = marrow@meta.data)
```

Example 15 (r):
```r
marrow <- CellCycleScoring(object = marrow, s.genes = s.genes, g2m.genes = g2m.genes, 
    set.ident = TRUE)

# view cell cycle scores and phase assignments
head(x = marrow@meta.data)
```

Example 16 (unknown):
```unknown
##          nGene    nUMI orig.ident     S.Score  G2M.Score Phase old.ident
## Prog_013 10211 2563089       Prog -0.12278698 -0.4370075    G1      Prog
## Prog_019  9991 3030620       Prog -0.16508027  0.5857611   G2M      Prog
## Prog_031 10192 1293487       Prog -0.35666253 -0.3447439    G1      Prog
## Prog_037  9599 1357987       Prog -0.43064955  0.6771199   G2M      Prog
## Prog_008 10540 4079891       Prog  0.56611382  0.1376925     S      Prog
## Prog_014 10788 2569783       Prog  0.07574505  0.3079849   G2M      Prog
```

Example 17 (unknown):
```unknown
##          nGene    nUMI orig.ident     S.Score  G2M.Score Phase old.ident
## Prog_013 10211 2563089       Prog -0.12278698 -0.4370075    G1      Prog
## Prog_019  9991 3030620       Prog -0.16508027  0.5857611   G2M      Prog
## Prog_031 10192 1293487       Prog -0.35666253 -0.3447439    G1      Prog
## Prog_037  9599 1357987       Prog -0.43064955  0.6771199   G2M      Prog
## Prog_008 10540 4079891       Prog  0.56611382  0.1376925     S      Prog
## Prog_014 10788 2569783       Prog  0.07574505  0.3079849   G2M      Prog
```

Example 18 (r):
```r
# Visualize the distribution of cell cycle markers across
RidgePlot(object = marrow, features.plot = c("PCNA", "TOP2A", "MCM6", "MKI67"), 
    nCol = 2)
```

Example 19 (r):
```r
# Visualize the distribution of cell cycle markers across
RidgePlot(object = marrow, features.plot = c("PCNA", "TOP2A", "MCM6", "MKI67"), 
    nCol = 2)
```

Example 20 (r):
```r
# Running a PCA on cell cycle genes reveals, unsurprisingly, that cells
# separate entirely by phase
marrow <- RunPCA(object = marrow, pc.genes = c(s.genes, g2m.genes), do.print = FALSE)
PCAPlot(object = marrow)
```

Example 21 (r):
```r
# Running a PCA on cell cycle genes reveals, unsurprisingly, that cells
# separate entirely by phase
marrow <- RunPCA(object = marrow, pc.genes = c(s.genes, g2m.genes), do.print = FALSE)
PCAPlot(object = marrow)
```

Example 22 (unknown):
```unknown
?AddModuleScore
```

Example 23 (unknown):
```unknown
object@scale.data
```

Example 24 (r):
```r
marrow <- ScaleData(object = marrow, vars.to.regress = c("S.Score", "G2M.Score"), 
    display.progress = FALSE)

# Now, a PCA on the variable genes no longer returns components associated
# with cell cycle
marrow <- RunPCA(object = marrow, pc.genes = marrow@var.genes, genes.print = 10)
```

Example 25 (r):
```r
marrow <- ScaleData(object = marrow, vars.to.regress = c("S.Score", "G2M.Score"), 
    display.progress = FALSE)

# Now, a PCA on the variable genes no longer returns components associated
# with cell cycle
marrow <- RunPCA(object = marrow, pc.genes = marrow@var.genes, genes.print = 10)
```

Example 26 (unknown):
```unknown
## [1] "PC1"
##  [1] "FXYD5"  "H2AFY"  "CORO1A" "PKM"    "CD34"   "EMB"    "LCP1"  
##  [8] "PRTN3"  "PLAC8"  "MPO"   
## [1] ""
##  [1] "BLVRB"   "KLF1"    "CAR2"    "AQP1"    "CAR1"    "CES2G"   "ERMAP"  
##  [8] "ATP1B2"  "FAM132A" "TSPO2"  
## [1] ""
## [1] ""
## [1] "PC2"
##  [1] "CD24A"   "LY6C2"   "ELANE"   "CLEC12A" "ANXA3"   "HP"      "CTSG"   
##  [8] "IGSF6"   "ALAS1"   "RGCC"   
## [1] ""
##  [1] "APOE"    "GATA2"   "CTLA2A"  "RAB37"   "ANGPT1"  "F2R"     "MUC13"  
##  [8] "S100A10" "ITGA2B"  "TXNIP"  
## [1] ""
## [1] ""
## [1] "PC3"
##  [1] "GIMAP6"        "LSP1"          "MYL10"         "FLT3"         
##  [5] "GCNT2"         "9030619P08RIK" "WFDC17"        "HLF"          
##  [9] "LY6A"          "FTH1"         
## [1] ""
##  [1] "CDK6"   "MS4A3"  "ELANE"  "FAM46A" "LGALS1" "FCGR3"  "RAB44" 
##  [8] "APOE"   "HDC"    "IGSF6" 
## [1] ""
## [1] ""
## [1] "PC4"
##  [1] "SERPINA3G" "CD9"       "MPL"       "PF4"       "CD63"     
##  [6] "ITGA2B"    "CD63-PS"   "PPIC"      "GP1BB"     "SDPR"     
## [1] ""
##  [1] "DNTT"    "S100A10" "IRF8"    "FLT3"    "MPEG1"   "TRIB2"   "IGHM"   
##  [8] "CTSS"    "SATB1"   "HDAC7"  
## [1] ""
## [1] ""
## [1] "PC5"
##  [1] "CPA3"    "LMO4"    "HDC"     "CD63-PS" "CD63"    "MS4A2"   "IKZF2"  
##  [8] "FUT8"    "LTB4R1"  "LPCAT2" 
## [1] ""
##  [1] "SDPR"    "GP1BB"   "PF4"     "F2RL2"   "TREML1"  "F2R"     "SLC14A1"
##  [8] "MEF2C"   "RAB27B"  "LY86"   
## [1] ""
## [1] ""
```

Example 27 (unknown):
```unknown
## [1] "PC1"
##  [1] "FXYD5"  "H2AFY"  "CORO1A" "PKM"    "CD34"   "EMB"    "LCP1"  
##  [8] "PRTN3"  "PLAC8"  "MPO"   
## [1] ""
##  [1] "BLVRB"   "KLF1"    "CAR2"    "AQP1"    "CAR1"    "CES2G"   "ERMAP"  
##  [8] "ATP1B2"  "FAM132A" "TSPO2"  
## [1] ""
## [1] ""
## [1] "PC2"
##  [1] "CD24A"   "LY6C2"   "ELANE"   "CLEC12A" "ANXA3"   "HP"      "CTSG"   
##  [8] "IGSF6"   "ALAS1"   "RGCC"   
## [1] ""
##  [1] "APOE"    "GATA2"   "CTLA2A"  "RAB37"   "ANGPT1"  "F2R"     "MUC13"  
##  [8] "S100A10" "ITGA2B"  "TXNIP"  
## [1] ""
## [1] ""
## [1] "PC3"
##  [1] "GIMAP6"        "LSP1"          "MYL10"         "FLT3"         
##  [5] "GCNT2"         "9030619P08RIK" "WFDC17"        "HLF"          
##  [9] "LY6A"          "FTH1"         
## [1] ""
##  [1] "CDK6"   "MS4A3"  "ELANE"  "FAM46A" "LGALS1" "FCGR3"  "RAB44" 
##  [8] "APOE"   "HDC"    "IGSF6" 
## [1] ""
## [1] ""
## [1] "PC4"
##  [1] "SERPINA3G" "CD9"       "MPL"       "PF4"       "CD63"     
##  [6] "ITGA2B"    "CD63-PS"   "PPIC"      "GP1BB"     "SDPR"     
## [1] ""
##  [1] "DNTT"    "S100A10" "IRF8"    "FLT3"    "MPEG1"   "TRIB2"   "IGHM"   
##  [8] "CTSS"    "SATB1"   "HDAC7"  
## [1] ""
## [1] ""
## [1] "PC5"
##  [1] "CPA3"    "LMO4"    "HDC"     "CD63-PS" "CD63"    "MS4A2"   "IKZF2"  
##  [8] "FUT8"    "LTB4R1"  "LPCAT2" 
## [1] ""
##  [1] "SDPR"    "GP1BB"   "PF4"     "F2RL2"   "TREML1"  "F2R"     "SLC14A1"
##  [8] "MEF2C"   "RAB27B"  "LY86"   
## [1] ""
## [1] ""
```

Example 28 (r):
```r
# When running a PCA on only cell cycle genes, cells no longer separate by
# cell-cycle phase
marrow <- RunPCA(object = marrow, pc.genes = c(s.genes, g2m.genes), do.print = FALSE)
PCAPlot(object = marrow)
```

Example 29 (r):
```r
# When running a PCA on only cell cycle genes, cells no longer separate by
# cell-cycle phase
marrow <- RunPCA(object = marrow, pc.genes = c(s.genes, g2m.genes), do.print = FALSE)
PCAPlot(object = marrow)
```

Example 30 (r):
```r
marrow@meta.data$CC.Difference <- marrow@meta.data$S.Score - marrow@meta.data$G2M.Score
marrow <- ScaleData(object = marrow, vars.to.regress = "CC.Difference", display.progress = FALSE)

# cell cycle effects strongly mitigated in PCA
marrow <- RunPCA(object = marrow, pc.genes = marrow@var.genes, genes.print = 10)
```

Example 31 (r):
```r
marrow@meta.data$CC.Difference <- marrow@meta.data$S.Score - marrow@meta.data$G2M.Score
marrow <- ScaleData(object = marrow, vars.to.regress = "CC.Difference", display.progress = FALSE)

# cell cycle effects strongly mitigated in PCA
marrow <- RunPCA(object = marrow, pc.genes = marrow@var.genes, genes.print = 10)
```

Example 32 (unknown):
```unknown
## [1] "PC1"
##  [1] "CORO1A"   "FXYD5"    "PLAC8"    "LAPTM5"   "H2AFY"    "PKM"     
##  [7] "CD34"     "TMEM176B" "LCP1"     "LIMD2"   
## [1] ""
##  [1] "BLVRB"   "KLF1"    "ERMAP"   "FAM132A" "CES2G"   "RHD"     "SPHK1"  
##  [8] "AQP1"    "CAR2"    "SLC38A5"
## [1] ""
## [1] ""
## [1] "PC2"
##  [1] "CTSG"    "CLEC12A" "ANXA3"   "MPO"     "ELANE"   "PRTN3"   "HP"     
##  [8] "LY6C2"   "TYROBP"  "IGSF6"  
## [1] ""
##  [1] "APOE"    "GATA2"   "TXNIP"   "VAMP5"   "RAB37"   "MFSD2B"  "S100A10"
##  [8] "CTLA2A"  "F2R"     "H2-Q6"  
## [1] ""
## [1] ""
## [1] "PC3"
##  [1] "FLT3"          "MYL10"         "LSP1"          "GIMAP6"       
##  [5] "WFDC17"        "9030619P08RIK" "FTH1"          "DNTT"         
##  [9] "CD24A"         "GCNT2"        
## [1] ""
##  [1] "CDK6"   "APOE"   "FAM46A" "MS4A3"  "RAB44"  "FCGR3"  "LGALS1"
##  [8] "ELANE"  "NKG7"   "HDC"   
## [1] ""
## [1] ""
## [1] "PC4"
##  [1] "PF4"    "ITGA2B" "GP1BB"  "TUBA8"  "SDPR"   "NUSAP1" "PBX1"  
##  [8] "TOP2A"  "MPL"    "RAB27B"
## [1] ""
##  [1] "TRIB2"         "YPEL3"         "IFNGR1"        "ATP1B2"       
##  [5] "LPIN1"         "CAR1"          "TSPO2"         "SCIN"         
##  [9] "HDAC7"         "D930028M14RIK"
## [1] ""
## [1] ""
## [1] "PC5"
##  [1] "RGCC"    "CD63-PS" "CD63"    "HDC"     "FCGR3"   "MS4A3"   "PGLYRP1"
##  [8] "GSTM1"   "ELANE"   "CPA3"   
## [1] ""
##  [1] "IRF8"  "TUBB5" "LY86"  "MPEG1" "DNTT"  "TOP2A" "CTSS"  "IGHM" 
##  [9] "TPM4"  "IL12A"
## [1] ""
## [1] ""
```

Example 33 (unknown):
```unknown
## [1] "PC1"
##  [1] "CORO1A"   "FXYD5"    "PLAC8"    "LAPTM5"   "H2AFY"    "PKM"     
##  [7] "CD34"     "TMEM176B" "LCP1"     "LIMD2"   
## [1] ""
##  [1] "BLVRB"   "KLF1"    "ERMAP"   "FAM132A" "CES2G"   "RHD"     "SPHK1"  
##  [8] "AQP1"    "CAR2"    "SLC38A5"
## [1] ""
## [1] ""
## [1] "PC2"
##  [1] "CTSG"    "CLEC12A" "ANXA3"   "MPO"     "ELANE"   "PRTN3"   "HP"     
##  [8] "LY6C2"   "TYROBP"  "IGSF6"  
## [1] ""
##  [1] "APOE"    "GATA2"   "TXNIP"   "VAMP5"   "RAB37"   "MFSD2B"  "S100A10"
##  [8] "CTLA2A"  "F2R"     "H2-Q6"  
## [1] ""
## [1] ""
## [1] "PC3"
##  [1] "FLT3"          "MYL10"         "LSP1"          "GIMAP6"       
##  [5] "WFDC17"        "9030619P08RIK" "FTH1"          "DNTT"         
##  [9] "CD24A"         "GCNT2"        
## [1] ""
##  [1] "CDK6"   "APOE"   "FAM46A" "MS4A3"  "RAB44"  "FCGR3"  "LGALS1"
##  [8] "ELANE"  "NKG7"   "HDC"   
## [1] ""
## [1] ""
## [1] "PC4"
##  [1] "PF4"    "ITGA2B" "GP1BB"  "TUBA8"  "SDPR"   "NUSAP1" "PBX1"  
##  [8] "TOP2A"  "MPL"    "RAB27B"
## [1] ""
##  [1] "TRIB2"         "YPEL3"         "IFNGR1"        "ATP1B2"       
##  [5] "LPIN1"         "CAR1"          "TSPO2"         "SCIN"         
##  [9] "HDAC7"         "D930028M14RIK"
## [1] ""
## [1] ""
## [1] "PC5"
##  [1] "RGCC"    "CD63-PS" "CD63"    "HDC"     "FCGR3"   "MS4A3"   "PGLYRP1"
##  [8] "GSTM1"   "ELANE"   "CPA3"   
## [1] ""
##  [1] "IRF8"  "TUBB5" "LY86"  "MPEG1" "DNTT"  "TOP2A" "CTSS"  "IGHM" 
##  [9] "TPM4"  "IL12A"
## [1] ""
## [1] ""
```

Example 34 (r):
```r
# when running a PCA on cell cycle genes, actively proliferating cells
# remain distinct from G1 cells however, within actively proliferating
# cells, G2M and S phase cells group together
marrow <- RunPCA(object = marrow, pc.genes = c(s.genes, g2m.genes), do.print = FALSE)
PCAPlot(object = marrow)
```

Example 35 (r):
```r
# when running a PCA on cell cycle genes, actively proliferating cells
# remain distinct from G1 cells however, within actively proliferating
# cells, G2M and S phase cells group together
marrow <- RunPCA(object = marrow, pc.genes = c(s.genes, g2m.genes), do.print = FALSE)
PCAPlot(object = marrow)
```

---

## Using sctransform in Seurat

**URL:** http://127.0.0.1:9173/seurat/archive/v3.0/sctransform_vignette/index.html

**Contents:**
- Using sctransform in Seurat
    - Christoph Hafemeister & Rahul Satija
    - Compiled: 2019-06-24

This vignette shows how to use the sctransform wrapper in Seurat.

Install sctransform and Seurat v3.

Load data and create Seurat object

Apply sctransform normalization

Perform dimensionality reduction by PCA and UMAP embedding

Why can we choose more PCs when using sctransform?

In the standard Seurat workflow we focus on 10 PCs for this dataset, though we highlight that the results are similar with higher settings for this parameter. Interestingtly, we’ve found that when using sctransform, we often benefit by pushing this parameter even higher. We believe this is because the sctransform workflow performs more effective normalization, strongly removing technical effects from the data.

Even after standard log-normalization, variation in sequencing depth is still a confounding factor (see Figure 1), and this effect can subtly influence higher PCs. In sctransform, this effect is substantially mitigated (see Figure 3). This means that higher PCs are more likely to represent subtle, but biologically relevant, sources of heterogeneity – so including them may improve downstream analysis.

In addition, sctransform returns 3,000 variable features by default, instead of 2,000. The rationale is similar, the additional variable features are less likely to be driven by technical differences across cells, and instead may represent more subtle biological fluctuations. In general, we find that results produced with sctransform are less dependent on these parameters (indeed, we achieve nearly identical results when using all genes in the transcriptome, though this does reduce computational efficiency). This can help users generate more robust results, and in addition, enables the application of standard anlaysis pipelines with identical parameter settings that can quickly be applied to new datasets:

For example, the following code replicates the full end-to-end workflow, in a single command:

Where are normalized values stored for sctransform?

As described in our preprint, sctransform calculates a model of technical noise in scRNA-seq data using ‘regularized negative binomial regression’. The residuals for this model are normalized values, and can be positive or negative. Positive residuals for a given gene in a given cell indicate that we observed more UMIs than expected given the gene’s average expression in the population and cellular sequencing depth, while negative residuals indicate the converse.

The results of sctransfrom are stored in the “SCT” assay. You can learn more about multi-assay data and commands in Seurat in our vignette, command cheat sheet, or developer guide.

Users can individually annotate clusters based on canonical markers. However, the sctransform normalization reveals sharper biological distinctions compared to the standard Seurat workflow, in a few ways:

**Examples:**

Example 1 (r):
```r
install.packages("Seurat")
```

Example 2 (r):
```r
install.packages("Seurat")
```

Example 3 (r):
```r
library(Seurat)
library(ggplot2)
library(sctransform)
```

Example 4 (r):
```r
library(Seurat)
library(ggplot2)
library(sctransform)
```

Example 5 (r):
```r
pbmc_data <- Read10X(data.dir = "../data/pbmc3k/filtered_gene_bc_matrices/hg19/")
pbmc <- CreateSeuratObject(counts = pbmc_data)
```

Example 6 (r):
```r
pbmc_data <- Read10X(data.dir = "../data/pbmc3k/filtered_gene_bc_matrices/hg19/")
pbmc <- CreateSeuratObject(counts = pbmc_data)
```

Example 7 (unknown):
```unknown
NormalizeData
```

Example 8 (unknown):
```unknown
FindVariableFeatures
```

Example 9 (r):
```r
# store mitochondrial percentage in object meta data
pbmc <- PercentageFeatureSet(pbmc, pattern = "^MT-", col.name = "percent.mt")

# run sctransform
pbmc <- SCTransform(pbmc, vars.to.regress = "percent.mt", verbose = FALSE)
```

Example 10 (r):
```r
# store mitochondrial percentage in object meta data
pbmc <- PercentageFeatureSet(pbmc, pattern = "^MT-", col.name = "percent.mt")

# run sctransform
pbmc <- SCTransform(pbmc, vars.to.regress = "percent.mt", verbose = FALSE)
```

Example 11 (r):
```r
# These are now standard steps in the Seurat workflow for visualization and clustering
pbmc <- RunPCA(pbmc, verbose = FALSE)
pbmc <- RunUMAP(pbmc, dims = 1:30, verbose = FALSE)

pbmc <- FindNeighbors(pbmc, dims = 1:30, verbose = FALSE)
pbmc <- FindClusters(pbmc, verbose = FALSE)
DimPlot(pbmc, label = TRUE) + NoLegend()
```

Example 12 (r):
```r
# These are now standard steps in the Seurat workflow for visualization and clustering
pbmc <- RunPCA(pbmc, verbose = FALSE)
pbmc <- RunUMAP(pbmc, dims = 1:30, verbose = FALSE)

pbmc <- FindNeighbors(pbmc, dims = 1:30, verbose = FALSE)
pbmc <- FindClusters(pbmc, verbose = FALSE)
DimPlot(pbmc, label = TRUE) + NoLegend()
```

Example 13 (r):
```r
pbmc <- CreateSeuratObject(pbmc_data) %>% PercentageFeatureSet(pattern = "^MT-", col.name = "percent.mt") %>% 
    SCTransform(vars.to.regress = "percent.mt") %>% RunPCA() %>% FindNeighbors(dims = 1:30) %>% 
    RunUMAP(dims = 1:30) %>% FindClusters()
```

Example 14 (r):
```r
pbmc <- CreateSeuratObject(pbmc_data) %>% PercentageFeatureSet(pattern = "^MT-", col.name = "percent.mt") %>% 
    SCTransform(vars.to.regress = "percent.mt") %>% RunPCA() %>% FindNeighbors(dims = 1:30) %>% 
    RunUMAP(dims = 1:30) %>% FindClusters()
```

Example 15 (unknown):
```unknown
pbmc[["SCT"]]@scale.data
```

Example 16 (unknown):
```unknown
SCTransform
```

Example 17 (unknown):
```unknown
pbmc[["SCT"]]@counts
```

Example 18 (unknown):
```unknown
pbmc[["SCT"]]@data
```

Example 19 (r):
```r
# These are now standard steps in the Seurat workflow for visualization and clustering Visualize
# canonical marker genes as violin plots.
VlnPlot(pbmc, features = c("CD8A", "GZMK", "CCL5", "S100A4", "ANXA1", "CCR7", "ISG15", "CD3D"), 
    pt.size = 0.2, ncol = 4)
```

Example 20 (r):
```r
# These are now standard steps in the Seurat workflow for visualization and clustering Visualize
# canonical marker genes as violin plots.
VlnPlot(pbmc, features = c("CD8A", "GZMK", "CCL5", "S100A4", "ANXA1", "CCR7", "ISG15", "CD3D"), 
    pt.size = 0.2, ncol = 4)
```

Example 21 (r):
```r
# Visualize canonical marker genes on the sctransform embedding.
FeaturePlot(pbmc, features = c("CD8A", "GZMK", "CCL5", "S100A4", "ANXA1", "CCR7"), pt.size = 0.2, 
    ncol = 3)
```

Example 22 (r):
```r
# Visualize canonical marker genes on the sctransform embedding.
FeaturePlot(pbmc, features = c("CD8A", "GZMK", "CCL5", "S100A4", "ANXA1", "CCR7"), pt.size = 0.2, 
    ncol = 3)
```

Example 23 (r):
```r
FeaturePlot(pbmc, features = c("CD3D", "ISG15", "TCL1A", "FCER2", "XCL1", "FCGR3A"), pt.size = 0.2, 
    ncol = 3)
```

Example 24 (r):
```r
FeaturePlot(pbmc, features = c("CD3D", "ISG15", "TCL1A", "FCER2", "XCL1", "FCGR3A"), pt.size = 0.2, 
    ncol = 3)
```

---

## Analysis, visualization, and integration of Visium HD spatial datasets with Seurat • Seurat

**URL:** http://127.0.0.1:9173/announcements.html

**Contents:**
- News
- Changes in Seurat v5
- Contents

We are excited to release Seurat v5 on CRAN, where it is now the default version for new installs. Seurat v5 is designed to be backwards compatible with Seurat v4 so existing code will continue to run, but we have made some changes to the software that will affect user results. We note that users who aim to reproduce their previous workflows in Seurat v4 can still install this version using the instructions on our install page.

In particular, we have made changes to:

Seurat Object and Assay class: Seurat v5 now includes support for additional assay and data types, including on-disk matrices. To facilitate this, we have introduced an updated Seurat v5 assay. Users can check out this [vignette for more information]. Briefly, Seurat v5 assays store data in layers (previously referred to as ‘slots’).

For example, these layers can store: raw counts (layer='counts'), normalized data (layer='data'), or z-scored/variance-stabilized data (layer='scale.data').

Data can be accessed using the $ accessor (i.e. obj[["RNA"]]$counts), or the `LayerData function (i.e. LayerData(obj, assay="RNA", layer='counts').

We’ve designed these updates to minimize changes for users. Existing Seurat functions and workflows from v4 continue to work in v5. For example, the command GetAssayData(obj, assay="RNA", slot='counts'), will run successfully in both Seurat v4 and Seurat v5.

Integration workflow: Seurat v5 introduces a streamlined integration and data transfer workflows that performs integration in low-dimensional space, and improves speed and memory efficiency. The results of integration are not identical between the two workflows, but users can still run the v4 integration workflow in Seurat v5 if they wish.

In previous versions of Seurat, the integration workflow required a list of multiple Seurat objects as input. In Seurat v5, all the data can be kept as a single object, but prior to integration, users can simply split the layers. See our introduction to integration vignette for more information.

Differential expression: Seurat v5 now uses the presto package (from the Korunsky and Raychaudhari labs), when available, to perform differential expression analysis. Using presto can dramatically speed up DE testing, and we encourage users to install it. In addition, in Seurat v5 we implement a pseudocount (when calculating log-FC) at the group level instead of the cell level. As a result, users will observe higher logFC estimates in v5 - but should note that these estimates may be more unstable - particularly for genes that are very lowly expressed in one of the two groups. We gratefully acknowledge feedback from the McCarthy and Pachter labs on this topic.

Pseudobulk analysis: Once a single-cell dataset has been analyzed to annotate cell subpopulations, pseudobulk analyses (i.e. aggregating together cells within a given subpopulation and sample) can reduce noise, improve quantification of lowly expressed genes, and reduce the size of the data matrix. In Seurat v5, we encourage the use of the AggregateExpression function to perform pseudobulk analysis. Check out our differential expression vignette as well as our pancreatic/healthy PBMC comparison, for examples of how to use AggregateExpression to perform robust differential expression of scRNA-seq data from multiple different conditions.

Developed by Rahul Satija, Satija Lab and Collaborators.

Site built with pkgdown 2.0.7.

**Examples:**

Example 1 (unknown):
```unknown
vignettes/announcements.Rmd
```

Example 2 (unknown):
```unknown
announcements.Rmd
```

Example 3 (unknown):
```unknown
(layer='counts')
```

Example 4 (unknown):
```unknown
(layer='data')
```

Example 5 (unknown):
```unknown
(layer='scale.data')
```

Example 6 (unknown):
```unknown
obj[["RNA"]]$counts
```

Example 7 (unknown):
```unknown
LayerData(obj, assay="RNA", layer='counts')
```

Example 8 (unknown):
```unknown
GetAssayData(obj, assay="RNA", slot='counts')
```

Example 9 (unknown):
```unknown
SCTransform
```

Example 10 (unknown):
```unknown
vst.flavor = "v1"
```

Example 11 (unknown):
```unknown
SCTransform
```

Example 12 (unknown):
```unknown
AggregateExpression
```

Example 13 (unknown):
```unknown
AggregateExpression
```

---

## Analysis, visualization, and integration of Visium HD spatial datasets with Seurat • Seurat

**URL:** http://127.0.0.1:9173/seurat/articles/get_started_v5_new/index.html

**Contents:**
- Getting Started with Seurat
- Introductory Vignettes
- scRNA Data Integration
- Multi-assay data
- Flexible analysis of massively scalable datasets
- Spatial analysis
- Other
- SeuratWrappers
- Contents

We provide a series of vignettes, tutorials, and analysis walkthroughs to help users get started with Seurat. You can also check out our Reference page which contains a full list of functions available to users.

Our previous Get Started page for Seurat v4 is archived here.

For new users of Seurat, we suggest starting with a guided walk through of a dataset of 2,700 Peripheral Blood Mononuclear Cells (PBMCs) made publicly available by 10X Genomics. This tutorial implements the major components of a standard unsupervised clustering workflow including QC and data filtration, calculation of high-variance genes, dimensional reduction, graph-based clustering, and the identification of cluster markers. We provide additional vignettes introducing visualization techniques in Seurat, the sctransform normalization workflow, and storage/interaction with multimodal datasets. We also provide an ‘essential commands cheatsheet’ as a quick reference.

We have developed computational methods for integrated analysis of single-cell datasets generated across different conditions, technologies, or species. As an example, we provide a guided walk through for integrating and comparing PBMC datasets generated under different stimulation conditions. We provide additional vignettes demonstrating how to leverage an annotated scRNA-seq reference to map and label cells from a query, and to efficiently integrate large datasets.

Seurat also offers support for a suite of statistical methods for analyzing multimodal single-cell data. These include methods to integrate modalities that are simultaneously measured in the same cells, modalities that are measured in different cells, and techniques to analyze pooled CRISPR screens.

In Seurat v5, we introduce new infrastructure and methods to analyze, interpret, and explore datasets that extend to millions of cells. We introduce support for ‘sketch-based’ techniques, where a subset of representative cells are stored in memory to enable rapid and iterative exploration, while the remaining cells are stored on-disk. Users can flexibly switch between both data representations, and we leverage the BPCells package from Ben Parks in the Greenleaf lab to enable high-performance analysis of disk-backed data.

The vignettes below demonstrate three scalable analyses in Seurat v5: Unsupervised clustering analysis of a large dataset (1.3M neurons), Unsupervised integration and comparison of 1M PBMC from healthy and diabetic patients, and Supervised mapping of 1.5M immune cells from healthy and COVID donors. In all cases, the vignettes perform these analyses without ever loading the full datasets into memory.

These vignettes will help introduce users to the analysis of spatial datasets in Seurat v5, including technologies that leverage sequencing-based readouts, as well as technologies that leverage in-situ imaging-based readouts. The vignettes introduce data from multiple platforms including 10x Visium, SLIDE-seq, Vizgen MERSCOPE, 10x Xenium, Nanostring CosMx, and Akoya CODEX.

Here we provide a series of short vignettes to demonstrate a number of features that are commonly used in Seurat. We’ve focused the vignettes around questions that we frequently receive from users.

In order to facilitate the use of community tools with Seurat, we provide the Seurat Wrappers package, which contains code to run other analysis tools on Seurat objects. For the initial release, we provide wrappers for a few packages in the table below but would encourage other package developers interested in interfacing with Seurat to check out our contributor guide here.

Developed by Rahul Satija, Satija Lab and Collaborators.

Site built with pkgdown 2.0.7.

**Examples:**

Example 1 (unknown):
```unknown
vignettes/get_started_v5_new.Rmd
```

Example 2 (unknown):
```unknown
get_started_v5_new.Rmd
```

---

## Analysis, visualization, and integration of Visium HD spatial datasets with Seurat • Seurat

**URL:** http://127.0.0.1:9173/articles_get_started_v5_new.html

**Contents:**
- Getting Started with Seurat
- Introductory Vignettes
- scRNA Data Integration
- Multi-assay data
- Flexible analysis of massively scalable datasets
- Spatial analysis
- Other
- SeuratWrappers
- Contents

We provide a series of vignettes, tutorials, and analysis walkthroughs to help users get started with Seurat. You can also check out our Reference page which contains a full list of functions available to users.

Our previous Get Started page for Seurat v4 is archived here.

For new users of Seurat, we suggest starting with a guided walk through of a dataset of 2,700 Peripheral Blood Mononuclear Cells (PBMCs) made publicly available by 10X Genomics. This tutorial implements the major components of a standard unsupervised clustering workflow including QC and data filtration, calculation of high-variance genes, dimensional reduction, graph-based clustering, and the identification of cluster markers. We provide additional vignettes introducing visualization techniques in Seurat, the sctransform normalization workflow, and storage/interaction with multimodal datasets. We also provide an ‘essential commands cheatsheet’ as a quick reference.

We have developed computational methods for integrated analysis of single-cell datasets generated across different conditions, technologies, or species. As an example, we provide a guided walk through for integrating and comparing PBMC datasets generated under different stimulation conditions. We provide additional vignettes demonstrating how to leverage an annotated scRNA-seq reference to map and label cells from a query, and to efficiently integrate large datasets.

Seurat also offers support for a suite of statistical methods for analyzing multimodal single-cell data. These include methods to integrate modalities that are simultaneously measured in the same cells, modalities that are measured in different cells, and techniques to analyze pooled CRISPR screens.

In Seurat v5, we introduce new infrastructure and methods to analyze, interpret, and explore datasets that extend to millions of cells. We introduce support for ‘sketch-based’ techniques, where a subset of representative cells are stored in memory to enable rapid and iterative exploration, while the remaining cells are stored on-disk. Users can flexibly switch between both data representations, and we leverage the BPCells package from Ben Parks in the Greenleaf lab to enable high-performance analysis of disk-backed data.

The vignettes below demonstrate three scalable analyses in Seurat v5: Unsupervised clustering analysis of a large dataset (1.3M neurons), Unsupervised integration and comparison of 1M PBMC from healthy and diabetic patients, and Supervised mapping of 1.5M immune cells from healthy and COVID donors. In all cases, the vignettes perform these analyses without ever loading the full datasets into memory.

These vignettes will help introduce users to the analysis of spatial datasets in Seurat v5, including technologies that leverage sequencing-based readouts, as well as technologies that leverage in-situ imaging-based readouts. The vignettes introduce data from multiple platforms including 10x Visium, SLIDE-seq, Vizgen MERSCOPE, 10x Xenium, Nanostring CosMx, and Akoya CODEX.

Here we provide a series of short vignettes to demonstrate a number of features that are commonly used in Seurat. We’ve focused the vignettes around questions that we frequently receive from users.

In order to facilitate the use of community tools with Seurat, we provide the Seurat Wrappers package, which contains code to run other analysis tools on Seurat objects. For the initial release, we provide wrappers for a few packages in the table below but would encourage other package developers interested in interfacing with Seurat to check out our contributor guide here.

Developed by Rahul Satija, Satija Lab and Collaborators.

Site built with pkgdown 2.0.7.

**Examples:**

Example 1 (unknown):
```unknown
vignettes/get_started_v5_new.Rmd
```

Example 2 (unknown):
```unknown
get_started_v5_new.Rmd
```

---

## Analysis, visualization, and integration of Visium HD spatial datasets with Seurat • Seurat

**URL:** http://127.0.0.1:9173/seurat/articles/de_vignette/index.html

**Contents:**
- Differential expression testing
    - Compiled: 2024-03-04
  - Load in the data
  - Perform default differential expression tests
  - Perform DE analysis within the same cell type across conditions
    - Perform DE analysis after pseudobulking
  - Perform DE analysis using alternative tests

This vignette highlights some example workflows for performing differential expression in Seurat. For demonstration purposes, we will be using the interferon-beta stimulated human PBMCs dataset (ifnb) that is available via the SeuratData package.

The bulk of Seurat’s differential expression features can be accessed through the FindMarkers() function. By default, Seurat performs differential expression (DE) testing based on the non-parametric Wilcoxon rank sum test. To test for DE genes between two specific groups of cells, specify the ident.1 and ident.2 parameters.

The results data frame has the following columns :

If the ident.2 parameter is omitted or set to NULL, FindMarkers() will test for differentially expressed features between the group specified by ident.1 and all other cells. Additionally, the parameter only.pos can be set to TRUE to only search for positive markers, i.e. features that are more highly expressed in the ident.1 group.

Since this dataset contains treatment information (control versus stimulated with interferon-beta), we can also ask what genes change in different conditions for cells of the same type. First, we create a column in the meta.data slot to hold both the cell type and treatment information and switch the current Idents to that column. Then we use FindMarkers() to find the genes that are different between control and stimulated CD14 monocytes.

However, the p-values obtained from this analysis should be interpreted with caution, because these tests treat each cell as an independent replicate and ignore inherent correlations between cells originating from the same sample. Such analyses have been shown to find a large number of false positive associations, as has been demonstrated by Squair et al., 2021, Zimmerman et al., 2021, Junttila et al., 2022, and others. Below, we show how pseudobulking can be used to account for such within-sample correlation.

To pseudobulk, we will use AggregateExpression() to sum together gene counts of all the cells from the same sample for each cell type. This results in one gene expression profile per sample and cell type. We can then perform DE analysis using DESeq2 on the sample level. This treats the samples, rather than the individual cells, as independent observations.

First, we need to retrieve the sample information for each cell. This is not loaded in the metadata, so we will load it from the Github repo of the source data for the original paper.

Add sample information to the dataset

We can now perform pseudobulking (AggregateExpression()) based on the donor IDs.

Next, we perform DE testing on the pseudobulk level for CD14 monocytes, and compare it against the previous single-cell-level DE results.

We can see that while the p-values are correlated between the single-cell and pseudobulk data, the single-cell p-values are often smaller and suggest higher levels of significance. In particular, there are 3,519 genes with evidence of differential expression (prior to multiple hypothesis testing) in both analyses, 1,649 genes that only appear to be differentially expressed in the single-cell analysis, and just 204 genes that only appear to be differentially expressed in the bulk analysis. We can investigate these discrepancies using VlnPlot.

First, we can examine the top genes that are differentially expressed in both analyses.

In both the pseudobulk and single-cell analyses, the p-values for these two genes are astronomically small. For both of these genes, when just comparing all stimulated CD4 monocytes to all control CD4 monocytes across samples, we see much higher expression in the stimulated cells. When breaking down these cells by sample, we continue to see consistently higher expression levels in the stimulated samples compared to the control samples; in other words, this finding is not driven by just one or two samples. Because of this consistency, we find this signal in both analyses.

By contrast, we can examine examples of genes that are only DE under the single-cell analysis.

Here, SRGN and HLA-DRA both have very small p-values in the single-cell analysis (on the orders of \(10^{-21}\) and \(10^{-9}\)), but much larger p-values around 0.18 in the pseudobulk analysis. While there appears to be a difference between control and simulated cells when ignoring sample information, the signal is much weaker on the sample level, and we can see notable variability from sample to sample.

Finally, we also support many other DE tests using other methods. For completeness, the following tests are currently supported:

Developed by Rahul Satija, Satija Lab and Collaborators.

Site built with pkgdown 2.0.7.

**Examples:**

Example 1 (unknown):
```unknown
vignettes/de_vignette.Rmd
```

Example 2 (unknown):
```unknown
de_vignette.Rmd
```

Example 3 (unknown):
```unknown
library(Seurat)
library(SeuratData)
library(ggplot2)
ifnb <- LoadData("ifnb")
```

Example 4 (r):
```r
library(Seurat)
library(SeuratData)
library(ggplot2)
ifnb <- LoadData("ifnb")
```

Example 5 (r):
```r
library(Seurat)
library(SeuratData)
library(ggplot2)
ifnb <- LoadData("ifnb")
```

Example 6 (unknown):
```unknown
FindMarkers()
```

Example 7 (unknown):
```unknown
# Normalize the data
ifnb <- NormalizeData(ifnb)

# Find DE features between CD16 Mono and CD1 Mono
Idents(ifnb) <- "seurat_annotations"
monocyte.de.markers <- FindMarkers(ifnb, ident.1 = "CD16 Mono", ident.2 = "CD14 Mono")
# view results
head(monocyte.de.markers)
```

Example 8 (r):
```r
# Normalize the data
ifnb <- NormalizeData(ifnb)

# Find DE features between CD16 Mono and CD1 Mono
Idents(ifnb) <- "seurat_annotations"
monocyte.de.markers <- FindMarkers(ifnb, ident.1 = "CD16 Mono", ident.2 = "CD14 Mono")
# view results
head(monocyte.de.markers)
```

Example 9 (r):
```r
# Normalize the data
ifnb <- NormalizeData(ifnb)

# Find DE features between CD16 Mono and CD1 Mono
Idents(ifnb) <- "seurat_annotations"
monocyte.de.markers <- FindMarkers(ifnb, ident.1 = "CD16 Mono", ident.2 = "CD14 Mono")
# view results
head(monocyte.de.markers)
```

Example 10 (unknown):
```unknown
##        p_val avg_log2FC pct.1 pct.2 p_val_adj
## VMO1       0   5.700274 0.778 0.084         0
## MS4A4A     0   3.349751 0.748 0.143         0
## FCGR3A     0   3.281942 0.982 0.418         0
## PLAC8      0   3.268470 0.636 0.124         0
## CXCL16     0   2.014758 0.938 0.475         0
## MS4A7      0   2.386436 0.978 0.558         0
```

Example 11 (unknown):
```unknown
##        p_val avg_log2FC pct.1 pct.2 p_val_adj
## VMO1       0   5.700274 0.778 0.084         0
## MS4A4A     0   3.349751 0.748 0.143         0
## FCGR3A     0   3.281942 0.982 0.418         0
## PLAC8      0   3.268470 0.636 0.124         0
## CXCL16     0   2.014758 0.938 0.475         0
## MS4A7      0   2.386436 0.978 0.558         0
```

Example 12 (unknown):
```unknown
FindMarkers()
```

Example 13 (unknown):
```unknown
# Find differentially expressed features between CD14+ Monocytes and all other cells, only
# search for positive markers
monocyte.de.markers <- FindMarkers(ifnb, ident.1 = "CD16 Mono", ident.2 = NULL, only.pos = TRUE)
# view results
head(monocyte.de.markers)
```

Example 14 (r):
```r
# Find differentially expressed features between CD14+ Monocytes and all other cells, only
# search for positive markers
monocyte.de.markers <- FindMarkers(ifnb, ident.1 = "CD16 Mono", ident.2 = NULL, only.pos = TRUE)
# view results
head(monocyte.de.markers)
```

Example 15 (r):
```r
# Find differentially expressed features between CD14+ Monocytes and all other cells, only
# search for positive markers
monocyte.de.markers <- FindMarkers(ifnb, ident.1 = "CD16 Mono", ident.2 = NULL, only.pos = TRUE)
# view results
head(monocyte.de.markers)
```

Example 16 (unknown):
```unknown
##        p_val avg_log2FC pct.1 pct.2 p_val_adj
## FCGR3A     0   4.532656 0.982 0.168         0
## MS4A7      0   3.806350 0.978 0.216         0
## CXCL16     0   3.274267 0.938 0.196         0
## VMO1       0   6.254651 0.778 0.044         0
## MS4A4A     0   4.747731 0.748 0.055         0
## LST1       0   2.927351 0.912 0.228         0
```

Example 17 (unknown):
```unknown
##        p_val avg_log2FC pct.1 pct.2 p_val_adj
## FCGR3A     0   4.532656 0.982 0.168         0
## MS4A7      0   3.806350 0.978 0.216         0
## CXCL16     0   3.274267 0.938 0.196         0
## VMO1       0   6.254651 0.778 0.044         0
## MS4A4A     0   4.747731 0.748 0.055         0
## LST1       0   2.927351 0.912 0.228         0
```

Example 18 (unknown):
```unknown
FindMarkers()
```

Example 19 (unknown):
```unknown
ifnb$celltype.stim <- paste(ifnb$seurat_annotations, ifnb$stim, sep = "_")
Idents(ifnb) <- "celltype.stim"
mono.de <- FindMarkers(ifnb, ident.1 = "CD14 Mono_STIM", ident.2 = "CD14 Mono_CTRL", verbose = FALSE)
head(mono.de, n = 10)
```

Example 20 (r):
```r
ifnb$celltype.stim <- paste(ifnb$seurat_annotations, ifnb$stim, sep = "_")
Idents(ifnb) <- "celltype.stim"
mono.de <- FindMarkers(ifnb, ident.1 = "CD14 Mono_STIM", ident.2 = "CD14 Mono_CTRL", verbose = FALSE)
head(mono.de, n = 10)
```

Example 21 (r):
```r
ifnb$celltype.stim <- paste(ifnb$seurat_annotations, ifnb$stim, sep = "_")
Idents(ifnb) <- "celltype.stim"
mono.de <- FindMarkers(ifnb, ident.1 = "CD14 Mono_STIM", ident.2 = "CD14 Mono_CTRL", verbose = FALSE)
head(mono.de, n = 10)
```

Example 22 (unknown):
```unknown
##         p_val avg_log2FC pct.1 pct.2 p_val_adj
## IFIT1       0   7.319139 0.985 0.033         0
## CXCL10      0   8.036564 0.984 0.035         0
## RSAD2       0   6.741673 0.988 0.045         0
## TNFSF10     0   6.991279 0.989 0.047         0
## IFIT3       0   6.883785 0.992 0.056         0
## IFIT2       0   7.179929 0.961 0.039         0
## CXCL11      0   8.624208 0.932 0.012         0
## CCL8        0   9.134191 0.918 0.017         0
## IDO1        0   5.455898 0.965 0.089         0
## MX1         0   5.059052 0.960 0.093         0
```

Example 23 (unknown):
```unknown
##         p_val avg_log2FC pct.1 pct.2 p_val_adj
## IFIT1       0   7.319139 0.985 0.033         0
## CXCL10      0   8.036564 0.984 0.035         0
## RSAD2       0   6.741673 0.988 0.045         0
## TNFSF10     0   6.991279 0.989 0.047         0
## IFIT3       0   6.883785 0.992 0.056         0
## IFIT2       0   7.179929 0.961 0.039         0
## CXCL11      0   8.624208 0.932 0.012         0
## CCL8        0   9.134191 0.918 0.017         0
## IDO1        0   5.455898 0.965 0.089         0
## MX1         0   5.059052 0.960 0.093         0
```

Example 24 (python):
```python
# load the inferred sample IDs of each cell
ctrl <- read.table(url("https://raw.githubusercontent.com/yelabucsf/demuxlet_paper_code/master/fig3/ye1.ctrl.8.10.sm.best"), head = T, stringsAsFactors = F)
stim <- read.table(url("https://raw.githubusercontent.com/yelabucsf/demuxlet_paper_code/master/fig3/ye2.stim.8.10.sm.best"), head = T, stringsAsFactors = F)
info <- rbind(ctrl, stim)

# rename the cell IDs by substituting the '-' into '.'
info$BARCODE <- gsub(pattern = "\\-", replacement = "\\.", info$BARCODE)

# only keep the cells with high-confidence sample ID
info <- info[grep(pattern = "SNG", x = info$BEST), ]

# remove cells with duplicated IDs in both ctrl and stim groups
info <- info[!duplicated(info$BARCODE) & !duplicated(info$BARCODE, fromLast = T), ]

# now add the sample IDs to ifnb 
rownames(info) <- info$BARCODE
info <- info[, c("BEST"), drop = F]
names(info) <- c("donor_id")
ifnb <- AddMetaData(ifnb, metadata = info)

# remove cells without donor IDs
ifnb$donor_id[is.na(ifnb$donor_id)] <- "unknown"
ifnb <- subset(ifnb, subset = donor_id != "unknown")
```

Example 25 (r):
```r
# load the inferred sample IDs of each cell
ctrl <- read.table(url("https://raw.githubusercontent.com/yelabucsf/demuxlet_paper_code/master/fig3/ye1.ctrl.8.10.sm.best"), head = T, stringsAsFactors = F)
stim <- read.table(url("https://raw.githubusercontent.com/yelabucsf/demuxlet_paper_code/master/fig3/ye2.stim.8.10.sm.best"), head = T, stringsAsFactors = F)
info <- rbind(ctrl, stim)

# rename the cell IDs by substituting the '-' into '.'
info$BARCODE <- gsub(pattern = "\\-", replacement = "\\.", info$BARCODE)

# only keep the cells with high-confidence sample ID
info <- info[grep(pattern = "SNG", x = info$BEST), ]

# remove cells with duplicated IDs in both ctrl and stim groups
info <- info[!duplicated(info$BARCODE) & !duplicated(info$BARCODE, fromLast = T), ]

# now add the sample IDs to ifnb 
rownames(info) <- info$BARCODE
info <- info[, c("BEST"), drop = F]
names(info) <- c("donor_id")
ifnb <- AddMetaData(ifnb, metadata = info)

# remove cells without donor IDs
ifnb$donor_id[is.na(ifnb$donor_id)] <- "unknown"
ifnb <- subset(ifnb, subset = donor_id != "unknown")
```

Example 26 (r):
```r
# load the inferred sample IDs of each cell
ctrl <- read.table(url("https://raw.githubusercontent.com/yelabucsf/demuxlet_paper_code/master/fig3/ye1.ctrl.8.10.sm.best"), head = T, stringsAsFactors = F)
stim <- read.table(url("https://raw.githubusercontent.com/yelabucsf/demuxlet_paper_code/master/fig3/ye2.stim.8.10.sm.best"), head = T, stringsAsFactors = F)
info <- rbind(ctrl, stim)

# rename the cell IDs by substituting the '-' into '.'
info$BARCODE <- gsub(pattern = "\\-", replacement = "\\.", info$BARCODE)

# only keep the cells with high-confidence sample ID
info <- info[grep(pattern = "SNG", x = info$BEST), ]

# remove cells with duplicated IDs in both ctrl and stim groups
info <- info[!duplicated(info$BARCODE) & !duplicated(info$BARCODE, fromLast = T), ]

# now add the sample IDs to ifnb 
rownames(info) <- info$BARCODE
info <- info[, c("BEST"), drop = F]
names(info) <- c("donor_id")
ifnb <- AddMetaData(ifnb, metadata = info)

# remove cells without donor IDs
ifnb$donor_id[is.na(ifnb$donor_id)] <- "unknown"
ifnb <- subset(ifnb, subset = donor_id != "unknown")
```

Example 27 (unknown):
```unknown
AggregateExpression()
```

Example 28 (unknown):
```unknown
# pseudobulk the counts based on donor-condition-celltype
pseudo_ifnb <- AggregateExpression(ifnb, assays = "RNA", return.seurat = T, group.by = c("stim", "donor_id", "seurat_annotations"))

# each 'cell' is a donor-condition-celltype pseudobulk profile
tail(Cells(pseudo_ifnb))
```

Example 29 (r):
```r
# pseudobulk the counts based on donor-condition-celltype
pseudo_ifnb <- AggregateExpression(ifnb, assays = "RNA", return.seurat = T, group.by = c("stim", "donor_id", "seurat_annotations"))

# each 'cell' is a donor-condition-celltype pseudobulk profile
tail(Cells(pseudo_ifnb))
```

Example 30 (r):
```r
# pseudobulk the counts based on donor-condition-celltype
pseudo_ifnb <- AggregateExpression(ifnb, assays = "RNA", return.seurat = T, group.by = c("stim", "donor_id", "seurat_annotations"))

# each 'cell' is a donor-condition-celltype pseudobulk profile
tail(Cells(pseudo_ifnb))
```

Example 31 (unknown):
```unknown
## [1] "STIM_SNG-1488_NK"          "STIM_SNG-1488_DC"         
## [3] "STIM_SNG-1488_B Activated" "STIM_SNG-1488_Mk"         
## [5] "STIM_SNG-1488_pDC"         "STIM_SNG-1488_Eryth"
```

Example 32 (unknown):
```unknown
## [1] "STIM_SNG-1488_NK"          "STIM_SNG-1488_DC"         
## [3] "STIM_SNG-1488_B Activated" "STIM_SNG-1488_Mk"         
## [5] "STIM_SNG-1488_pDC"         "STIM_SNG-1488_Eryth"
```

Example 33 (unknown):
```unknown
pseudo_ifnb$celltype.stim <- paste(pseudo_ifnb$seurat_annotations, pseudo_ifnb$stim, sep = "_")
```

Example 34 (r):
```r
pseudo_ifnb$celltype.stim <- paste(pseudo_ifnb$seurat_annotations, pseudo_ifnb$stim, sep = "_")
```

Example 35 (r):
```r
pseudo_ifnb$celltype.stim <- paste(pseudo_ifnb$seurat_annotations, pseudo_ifnb$stim, sep = "_")
```

Example 36 (unknown):
```unknown
Idents(pseudo_ifnb) <- "celltype.stim"

bulk.mono.de <- FindMarkers(object = pseudo_ifnb, 
                         ident.1 = "CD14 Mono_STIM", 
                         ident.2 = "CD14 Mono_CTRL",
                         test.use = "DESeq2")
head(bulk.mono.de, n = 15)
```

Example 37 (r):
```r
Idents(pseudo_ifnb) <- "celltype.stim"

bulk.mono.de <- FindMarkers(object = pseudo_ifnb, 
                         ident.1 = "CD14 Mono_STIM", 
                         ident.2 = "CD14 Mono_CTRL",
                         test.use = "DESeq2")
head(bulk.mono.de, n = 15)
```

Example 38 (r):
```r
Idents(pseudo_ifnb) <- "celltype.stim"

bulk.mono.de <- FindMarkers(object = pseudo_ifnb, 
                         ident.1 = "CD14 Mono_STIM", 
                         ident.2 = "CD14 Mono_CTRL",
                         test.use = "DESeq2")
head(bulk.mono.de, n = 15)
```

Example 39 (unknown):
```unknown
##                  p_val avg_log2FC pct.1 pct.2     p_val_adj
## IL1RN    3.701542e-275   6.160156     1     1 5.201777e-271
## IFITM2   1.955626e-250   4.318976     1     1 2.748242e-246
## SSB      2.699554e-203   3.066647     1     1 3.793684e-199
## NT5C3A   2.239898e-198   5.412972     1     1 3.147729e-194
## RTCB     5.700554e-162   3.133362     1     1 8.010989e-158
## RABGAP1L 4.743010e-161   5.562364     1     1 6.665352e-157
## DYNLT1   9.735640e-159   2.402726     1     1 1.368150e-154
## PLSCR1   3.191691e-146   2.676047     1     1 4.485284e-142
## ISG20    9.664488e-145   5.443114     1     1 1.358150e-140
## NAPA     2.858013e-144   1.977719     1     1 4.016365e-140
## DDX58    5.957026e-142   4.640111     1     1 8.371409e-138
## HERC5    6.333722e-133   5.266515     1     1 8.900780e-129
## OASL     3.892853e-130   3.946745     1     1 5.470627e-126
## EIF2AK2  6.636434e-128   3.940167     1     1 9.326180e-124
## TMEM50A  6.731955e-117   1.355947     1     1 9.460417e-113
```

Example 40 (unknown):
```unknown
##                  p_val avg_log2FC pct.1 pct.2     p_val_adj
## IL1RN    3.701542e-275   6.160156     1     1 5.201777e-271
## IFITM2   1.955626e-250   4.318976     1     1 2.748242e-246
## SSB      2.699554e-203   3.066647     1     1 3.793684e-199
## NT5C3A   2.239898e-198   5.412972     1     1 3.147729e-194
## RTCB     5.700554e-162   3.133362     1     1 8.010989e-158
## RABGAP1L 4.743010e-161   5.562364     1     1 6.665352e-157
## DYNLT1   9.735640e-159   2.402726     1     1 1.368150e-154
## PLSCR1   3.191691e-146   2.676047     1     1 4.485284e-142
## ISG20    9.664488e-145   5.443114     1     1 1.358150e-140
## NAPA     2.858013e-144   1.977719     1     1 4.016365e-140
## DDX58    5.957026e-142   4.640111     1     1 8.371409e-138
## HERC5    6.333722e-133   5.266515     1     1 8.900780e-129
## OASL     3.892853e-130   3.946745     1     1 5.470627e-126
## EIF2AK2  6.636434e-128   3.940167     1     1 9.326180e-124
## TMEM50A  6.731955e-117   1.355947     1     1 9.460417e-113
```

Example 41 (python):
```python
# compare the DE P-values between the single-cell level and the pseudobulk level results
names(bulk.mono.de) <- paste0(names(bulk.mono.de), ".bulk")
bulk.mono.de$gene <- rownames(bulk.mono.de)

names(mono.de) <- paste0(names(mono.de), ".sc")
mono.de$gene <- rownames(mono.de)

merge_dat <- merge(mono.de, bulk.mono.de, by = "gene")
merge_dat <- merge_dat[order(merge_dat$p_val.bulk), ]

# Number of genes that are marginally significant in both; marginally significant only in bulk; and marginally significant only in single-cell
common <- merge_dat$gene[which(merge_dat$p_val.bulk < 0.05 & 
                                merge_dat$p_val.sc < 0.05)]
only_sc <- merge_dat$gene[which(merge_dat$p_val.bulk > 0.05 & 
                                  merge_dat$p_val.sc < 0.05)]
only_bulk <- merge_dat$gene[which(merge_dat$p_val.bulk < 0.05 & 
                                    merge_dat$p_val.sc > 0.05)]
print(paste0('# Common: ',length(common)))
```

Example 42 (r):
```r
# compare the DE P-values between the single-cell level and the pseudobulk level results
names(bulk.mono.de) <- paste0(names(bulk.mono.de), ".bulk")
bulk.mono.de$gene <- rownames(bulk.mono.de)

names(mono.de) <- paste0(names(mono.de), ".sc")
mono.de$gene <- rownames(mono.de)

merge_dat <- merge(mono.de, bulk.mono.de, by = "gene")
merge_dat <- merge_dat[order(merge_dat$p_val.bulk), ]

# Number of genes that are marginally significant in both; marginally significant only in bulk; and marginally significant only in single-cell
common <- merge_dat$gene[which(merge_dat$p_val.bulk < 0.05 & 
                                merge_dat$p_val.sc < 0.05)]
only_sc <- merge_dat$gene[which(merge_dat$p_val.bulk > 0.05 & 
                                  merge_dat$p_val.sc < 0.05)]
only_bulk <- merge_dat$gene[which(merge_dat$p_val.bulk < 0.05 & 
                                    merge_dat$p_val.sc > 0.05)]
print(paste0('# Common: ',length(common)))
```

Example 43 (r):
```r
# compare the DE P-values between the single-cell level and the pseudobulk level results
names(bulk.mono.de) <- paste0(names(bulk.mono.de), ".bulk")
bulk.mono.de$gene <- rownames(bulk.mono.de)

names(mono.de) <- paste0(names(mono.de), ".sc")
mono.de$gene <- rownames(mono.de)

merge_dat <- merge(mono.de, bulk.mono.de, by = "gene")
merge_dat <- merge_dat[order(merge_dat$p_val.bulk), ]

# Number of genes that are marginally significant in both; marginally significant only in bulk; and marginally significant only in single-cell
common <- merge_dat$gene[which(merge_dat$p_val.bulk < 0.05 & 
                                merge_dat$p_val.sc < 0.05)]
only_sc <- merge_dat$gene[which(merge_dat$p_val.bulk > 0.05 & 
                                  merge_dat$p_val.sc < 0.05)]
only_bulk <- merge_dat$gene[which(merge_dat$p_val.bulk < 0.05 & 
                                    merge_dat$p_val.sc > 0.05)]
print(paste0('# Common: ',length(common)))
```

Example 44 (unknown):
```unknown
## [1] "# Common: 3519"
```

Example 45 (unknown):
```unknown
## [1] "# Common: 3519"
```

Example 46 (python):
```python
print(paste0('# Only in single-cell: ',length(only_sc)))
```

Example 47 (r):
```r
print(paste0('# Only in single-cell: ',length(only_sc)))
```

Example 48 (r):
```r
print(paste0('# Only in single-cell: ',length(only_sc)))
```

Example 49 (unknown):
```unknown
## [1] "# Only in single-cell: 1649"
```

Example 50 (unknown):
```unknown
## [1] "# Only in single-cell: 1649"
```

Example 51 (python):
```python
print(paste0('# Only in bulk: ',length(only_bulk)))
```

Example 52 (r):
```r
print(paste0('# Only in bulk: ',length(only_bulk)))
```

Example 53 (r):
```r
print(paste0('# Only in bulk: ',length(only_bulk)))
```

Example 54 (unknown):
```unknown
## [1] "# Only in bulk: 204"
```

Example 55 (unknown):
```unknown
## [1] "# Only in bulk: 204"
```

Example 56 (python):
```python
# create a new column to annotate sample-condition-celltype in the single-cell dataset
ifnb$donor_id.stim <- paste0(ifnb$stim, "-", ifnb$donor_id)

# generate violin plot 
Idents(ifnb) <- "celltype.stim"
print(merge_dat[merge_dat$gene%in%common[1:2],c('gene','p_val.sc','p_val.bulk')])
```

Example 57 (r):
```r
# create a new column to annotate sample-condition-celltype in the single-cell dataset
ifnb$donor_id.stim <- paste0(ifnb$stim, "-", ifnb$donor_id)

# generate violin plot 
Idents(ifnb) <- "celltype.stim"
print(merge_dat[merge_dat$gene%in%common[1:2],c('gene','p_val.sc','p_val.bulk')])
```

Example 58 (r):
```r
# create a new column to annotate sample-condition-celltype in the single-cell dataset
ifnb$donor_id.stim <- paste0(ifnb$stim, "-", ifnb$donor_id)

# generate violin plot 
Idents(ifnb) <- "celltype.stim"
print(merge_dat[merge_dat$gene%in%common[1:2],c('gene','p_val.sc','p_val.bulk')])
```

Example 59 (unknown):
```unknown
##        gene p_val.sc    p_val.bulk
## 2785  IL1RN        0 3.701542e-275
## 2739 IFITM2        0 1.955626e-250
```

Example 60 (unknown):
```unknown
##        gene p_val.sc    p_val.bulk
## 2785  IL1RN        0 3.701542e-275
## 2739 IFITM2        0 1.955626e-250
```

Example 61 (unknown):
```unknown
VlnPlot(ifnb, features = common[1:2], idents = c("CD14 Mono_CTRL", "CD14 Mono_STIM"), group.by = "stim")
```

Example 62 (r):
```r
VlnPlot(ifnb, features = common[1:2], idents = c("CD14 Mono_CTRL", "CD14 Mono_STIM"), group.by = "stim")
```

Example 63 (r):
```r
VlnPlot(ifnb, features = common[1:2], idents = c("CD14 Mono_CTRL", "CD14 Mono_STIM"), group.by = "stim")
```

Example 64 (unknown):
```unknown
VlnPlot(ifnb, features = common[1:2], idents = c("CD14 Mono_CTRL", "CD14 Mono_STIM"), group.by = "donor_id.stim", ncol = 1)
```

Example 65 (r):
```r
VlnPlot(ifnb, features = common[1:2], idents = c("CD14 Mono_CTRL", "CD14 Mono_STIM"), group.by = "donor_id.stim", ncol = 1)
```

Example 66 (r):
```r
VlnPlot(ifnb, features = common[1:2], idents = c("CD14 Mono_CTRL", "CD14 Mono_STIM"), group.by = "donor_id.stim", ncol = 1)
```

Example 67 (python):
```python
print(merge_dat[merge_dat$gene%in%c('SRGN','HLA-DRA'),c('gene','p_val.sc','p_val.bulk')])
```

Example 68 (r):
```r
print(merge_dat[merge_dat$gene%in%c('SRGN','HLA-DRA'),c('gene','p_val.sc','p_val.bulk')])
```

Example 69 (r):
```r
print(merge_dat[merge_dat$gene%in%c('SRGN','HLA-DRA'),c('gene','p_val.sc','p_val.bulk')])
```

Example 70 (unknown):
```unknown
##         gene     p_val.sc p_val.bulk
## 5710    SRGN 4.025076e-21  0.1823188
## 2603 HLA-DRA 4.989863e-09  0.1851302
```

Example 71 (unknown):
```unknown
##         gene     p_val.sc p_val.bulk
## 5710    SRGN 4.025076e-21  0.1823188
## 2603 HLA-DRA 4.989863e-09  0.1851302
```

Example 72 (unknown):
```unknown
VlnPlot(ifnb, features <- c('SRGN','HLA-DRA'), idents = c("CD14 Mono_CTRL", "CD14 Mono_STIM"), group.by = "stim")
```

Example 73 (r):
```r
VlnPlot(ifnb, features <- c('SRGN','HLA-DRA'), idents = c("CD14 Mono_CTRL", "CD14 Mono_STIM"), group.by = "stim")
```

Example 74 (r):
```r
VlnPlot(ifnb, features <- c('SRGN','HLA-DRA'), idents = c("CD14 Mono_CTRL", "CD14 Mono_STIM"), group.by = "stim")
```

Example 75 (unknown):
```unknown
VlnPlot(ifnb, features <- c('SRGN','HLA-DRA'), idents = c("CD14 Mono_CTRL", "CD14 Mono_STIM"), group.by = "donor_id.stim", ncol = 1)
```

Example 76 (r):
```r
VlnPlot(ifnb, features <- c('SRGN','HLA-DRA'), idents = c("CD14 Mono_CTRL", "CD14 Mono_STIM"), group.by = "donor_id.stim", ncol = 1)
```

Example 77 (r):
```r
VlnPlot(ifnb, features <- c('SRGN','HLA-DRA'), idents = c("CD14 Mono_CTRL", "CD14 Mono_STIM"), group.by = "donor_id.stim", ncol = 1)
```

Example 78 (unknown):
```unknown
# Test for DE features using the MAST package
Idents(ifnb) <- "seurat_annotations"
head(FindMarkers(ifnb, ident.1 = "CD14 Mono", ident.2 = "CD16 Mono", test.use = "MAST"))
```

Example 79 (r):
```r
# Test for DE features using the MAST package
Idents(ifnb) <- "seurat_annotations"
head(FindMarkers(ifnb, ident.1 = "CD14 Mono", ident.2 = "CD16 Mono", test.use = "MAST"))
```

Example 80 (r):
```r
# Test for DE features using the MAST package
Idents(ifnb) <- "seurat_annotations"
head(FindMarkers(ifnb, ident.1 = "CD14 Mono", ident.2 = "CD16 Mono", test.use = "MAST"))
```

---

## Analysis, visualization, and integration of Visium HD spatial datasets with Seurat • Seurat

**URL:** http://127.0.0.1:9173/articles_essential_commands.html

**Contents:**
- Seurat Command List
    - Compiled: 2023-10-31
- Standard Seurat workflow
  - SCtransform version
- Seurat Object Data Access
  - Cell, feature, and layer names
  - Identity class labels
  - Cell metadata
  - Expression data (stored as layers in Seurat v5)
  - Dimensional reductions
  - FetchData
- Subsetting and merging
  - Subset Seurat objects
  - Split layers
  - Split objects
  - Merge objects (without integration)
  - Merge objects (with integration)
- Pseudobulk analysis
  - Group cells together, based on multiple categories
- Visualization in Seurat
- Multi-Assay Features
- Additional resources
- Contents

In Seurat v5, merging creates a single object, but keeps the expression information split into different layers for integration. If not proceeding with integration, rejoin the layers after merging.

See introduction to integration for more information.

See DE vignette for information on how to add the donor_id column to meta data.

Seurat has a vast, ggplot2-based plotting library. All plotting functions will return a ggplot2 plot by default, allowing easy customization with ggplot2.

Seurat provides many prebuilt themes that can be added to ggplot2 plots for quick customization

With Seurat, you can easily switch between different assays at the single cell level (such as ADT counts from CITE-seq, or integrated/batch-corrected data). Most functions now take an assay parameter, but you can set a Default Assay to avoid repetitive statements.

Users who are particularly interested in some of the technical changes to data storage in Seurat v5 can explore the following resources:

Developed by Rahul Satija, Satija Lab and Collaborators.

Site built with pkgdown 2.0.7.

**Examples:**

Example 1 (unknown):
```unknown
vignettes/essential_commands.Rmd
```

Example 2 (unknown):
```unknown
essential_commands.Rmd
```

Example 3 (unknown):
```unknown
pbmc <- NormalizeData(object = pbmc)
pbmc <- FindVariableFeatures(object = pbmc)
pbmc <- ScaleData(object = pbmc)
pbmc <- RunPCA(object = pbmc)
pbmc <- FindNeighbors(object = pbmc, dims = 1:30)
pbmc <- FindClusters(object = pbmc)
pbmc <- RunUMAP(object = pbmc, dims = 1:30)
DimPlot(object = pbmc, reduction = "umap")
```

Example 4 (r):
```r
pbmc <- NormalizeData(object = pbmc)
pbmc <- FindVariableFeatures(object = pbmc)
pbmc <- ScaleData(object = pbmc)
pbmc <- RunPCA(object = pbmc)
pbmc <- FindNeighbors(object = pbmc, dims = 1:30)
pbmc <- FindClusters(object = pbmc)
pbmc <- RunUMAP(object = pbmc, dims = 1:30)
DimPlot(object = pbmc, reduction = "umap")
```

Example 5 (r):
```r
pbmc <- NormalizeData(object = pbmc)
pbmc <- FindVariableFeatures(object = pbmc)
pbmc <- ScaleData(object = pbmc)
pbmc <- RunPCA(object = pbmc)
pbmc <- FindNeighbors(object = pbmc, dims = 1:30)
pbmc <- FindClusters(object = pbmc)
pbmc <- RunUMAP(object = pbmc, dims = 1:30)
DimPlot(object = pbmc, reduction = "umap")
```

Example 6 (unknown):
```unknown
pbmc <- SCTransform(object = pbmc)
pbmc <- RunPCA(object = pbmc)
pbmc <- FindNeighbors(object = pbmc, dims = 1:30)
pbmc <- FindClusters(object = pbmc)
pbmc <- RunUMAP(object = pbmc, dims = 1:30)
DimPlot(object = pbmc, reduction = "umap")
```

Example 7 (r):
```r
pbmc <- SCTransform(object = pbmc)
pbmc <- RunPCA(object = pbmc)
pbmc <- FindNeighbors(object = pbmc, dims = 1:30)
pbmc <- FindClusters(object = pbmc)
pbmc <- RunUMAP(object = pbmc, dims = 1:30)
DimPlot(object = pbmc, reduction = "umap")
```

Example 8 (r):
```r
pbmc <- SCTransform(object = pbmc)
pbmc <- RunPCA(object = pbmc)
pbmc <- FindNeighbors(object = pbmc, dims = 1:30)
pbmc <- FindClusters(object = pbmc)
pbmc <- RunUMAP(object = pbmc, dims = 1:30)
DimPlot(object = pbmc, reduction = "umap")
```

Example 9 (unknown):
```unknown
# note that you can chain multiple commands together with %>%
pbmc <- SCTransform(pbmc) %>%
    RunPCA() %>%
    FindNeighbors(dims = 1:30) %>%
    FindClusters() %>%
    RunUMAP(dims = 1:30)
```

Example 10 (r):
```r
# note that you can chain multiple commands together with %>%
pbmc <- SCTransform(pbmc) %>%
    RunPCA() %>%
    FindNeighbors(dims = 1:30) %>%
    FindClusters() %>%
    RunUMAP(dims = 1:30)
```

Example 11 (r):
```r
# note that you can chain multiple commands together with %>%
pbmc <- SCTransform(pbmc) %>%
    RunPCA() %>%
    FindNeighbors(dims = 1:30) %>%
    FindClusters() %>%
    RunUMAP(dims = 1:30)
```

Example 12 (unknown):
```unknown
# Get cell and feature names, and total numbers We show multiple ways to get the same output cell names
colnames(pbmc)
Cells(pbmc)

# feature names
Features(pbmc)
rownames(pbmc)

# number of cells/features
num_cells <- ncol(pbmc)
num_features <- nrow(pbmc)

# List of object layers
Layers(pbmc)

# working with multimodal objects list assays
Assays(cbmc)

# Assay-specific features (genes/ADT)
Features(cbmc[["RNA"]])
Features(cbmc[["ADT"]])

# Variable feature names
VariableFeatures(pbmc)
```

Example 13 (r):
```r
# Get cell and feature names, and total numbers We show multiple ways to get the same output cell names
colnames(pbmc)
Cells(pbmc)

# feature names
Features(pbmc)
rownames(pbmc)

# number of cells/features
num_cells <- ncol(pbmc)
num_features <- nrow(pbmc)

# List of object layers
Layers(pbmc)

# working with multimodal objects list assays
Assays(cbmc)

# Assay-specific features (genes/ADT)
Features(cbmc[["RNA"]])
Features(cbmc[["ADT"]])

# Variable feature names
VariableFeatures(pbmc)
```

Example 14 (r):
```r
# Get cell and feature names, and total numbers We show multiple ways to get the same output cell names
colnames(pbmc)
Cells(pbmc)

# feature names
Features(pbmc)
rownames(pbmc)

# number of cells/features
num_cells <- ncol(pbmc)
num_features <- nrow(pbmc)

# List of object layers
Layers(pbmc)

# working with multimodal objects list assays
Assays(cbmc)

# Assay-specific features (genes/ADT)
Features(cbmc[["RNA"]])
Features(cbmc[["ADT"]])

# Variable feature names
VariableFeatures(pbmc)
```

Example 15 (unknown):
```unknown
# Set variable features
VariableFeatures(cbmc) <- var.gene.names

# set for a specific assay
VariableFeatures(cbmc[["ADT"]]) <- var.gene.names
```

Example 16 (r):
```r
# Set variable features
VariableFeatures(cbmc) <- var.gene.names

# set for a specific assay
VariableFeatures(cbmc[["ADT"]]) <- var.gene.names
```

Example 17 (r):
```r
# Set variable features
VariableFeatures(cbmc) <- var.gene.names

# set for a specific assay
VariableFeatures(cbmc[["ADT"]]) <- var.gene.names
```

Example 18 (python):
```python
# Setting and retrieving cell identities

# Set identity classes to an existing column in meta data
Idents(object = pbmc) <- "seurat_annotations"

# View cell identities, get summary table
Idents(pbmc)
table(Idents(pbmc))

# Set identity to CD4 T cells for all cells
Idents(pbmc) <- "CD4 T cells"

# Set for a selected group of cells
pbmc.cells <- Cells(pbmc)
Idents(object = pbmc, cells = pbmc.cells[1:10]) <- "CD4 T cells"

# Get cell identity classes
Idents(object = pbmc)
levels(x = pbmc)

# Stash cell identity classes in metadata
pbmc[["old.ident"]] <- Idents(object = pbmc)
pbmc <- StashIdent(object = pbmc, save.name = "old.ident")

# Rename identity classes
pbmc <- RenameIdents(object = pbmc, `CD4 T cells` = "T Helper cells")
```

Example 19 (r):
```r
# Setting and retrieving cell identities

# Set identity classes to an existing column in meta data
Idents(object = pbmc) <- "seurat_annotations"

# View cell identities, get summary table
Idents(pbmc)
table(Idents(pbmc))

# Set identity to CD4 T cells for all cells
Idents(pbmc) <- "CD4 T cells"

# Set for a selected group of cells
pbmc.cells <- Cells(pbmc)
Idents(object = pbmc, cells = pbmc.cells[1:10]) <- "CD4 T cells"

# Get cell identity classes
Idents(object = pbmc)
levels(x = pbmc)

# Stash cell identity classes in metadata
pbmc[["old.ident"]] <- Idents(object = pbmc)
pbmc <- StashIdent(object = pbmc, save.name = "old.ident")

# Rename identity classes
pbmc <- RenameIdents(object = pbmc, `CD4 T cells` = "T Helper cells")
```

Example 20 (r):
```r
# Setting and retrieving cell identities

# Set identity classes to an existing column in meta data
Idents(object = pbmc) <- "seurat_annotations"

# View cell identities, get summary table
Idents(pbmc)
table(Idents(pbmc))

# Set identity to CD4 T cells for all cells
Idents(pbmc) <- "CD4 T cells"

# Set for a selected group of cells
pbmc.cells <- Cells(pbmc)
Idents(object = pbmc, cells = pbmc.cells[1:10]) <- "CD4 T cells"

# Get cell identity classes
Idents(object = pbmc)
levels(x = pbmc)

# Stash cell identity classes in metadata
pbmc[["old.ident"]] <- Idents(object = pbmc)
pbmc <- StashIdent(object = pbmc, save.name = "old.ident")

# Rename identity classes
pbmc <- RenameIdents(object = pbmc, `CD4 T cells` = "T Helper cells")
```

Example 21 (python):
```python
# View metadata data frame, stored in object@meta.data
pbmc[[]]

# Retrieve specific values from the metadata
pbmc$nCount_RNA
pbmc[[c("percent.mito", "nFeature_RNA")]]

# Add metadata, see ?AddMetaData
random_group_labels <- sample(x = c("g1", "g2"), size = ncol(x = pbmc), replace = TRUE)
pbmc$groups <- random_group_labels
```

Example 22 (r):
```r
# View metadata data frame, stored in object@meta.data
pbmc[[]]

# Retrieve specific values from the metadata
pbmc$nCount_RNA
pbmc[[c("percent.mito", "nFeature_RNA")]]

# Add metadata, see ?AddMetaData
random_group_labels <- sample(x = c("g1", "g2"), size = ncol(x = pbmc), replace = TRUE)
pbmc$groups <- random_group_labels
```

Example 23 (r):
```r
# View metadata data frame, stored in object@meta.data
pbmc[[]]

# Retrieve specific values from the metadata
pbmc$nCount_RNA
pbmc[[c("percent.mito", "nFeature_RNA")]]

# Add metadata, see ?AddMetaData
random_group_labels <- sample(x = c("g1", "g2"), size = ncol(x = pbmc), replace = TRUE)
pbmc$groups <- random_group_labels
```

Example 24 (python):
```python
# Retrieve data in an expression matrix RNA counts matrix
pbmc[["RNA"]]$counts

# Alternate accessor function with the same result
LayerData(pbmc, assay = "RNA", layer = "counts")

# GetAssayData from Seurat v4 is still supported
GetAssayData(object = pbmc, assay = "RNA", slot = "counts")

# ADT counts matrix (multimodal object)
cbmc[["ADT"]]$counts
```

Example 25 (r):
```r
# Retrieve data in an expression matrix RNA counts matrix
pbmc[["RNA"]]$counts

# Alternate accessor function with the same result
LayerData(pbmc, assay = "RNA", layer = "counts")

# GetAssayData from Seurat v4 is still supported
GetAssayData(object = pbmc, assay = "RNA", slot = "counts")

# ADT counts matrix (multimodal object)
cbmc[["ADT"]]$counts
```

Example 26 (r):
```r
# Retrieve data in an expression matrix RNA counts matrix
pbmc[["RNA"]]$counts

# Alternate accessor function with the same result
LayerData(pbmc, assay = "RNA", layer = "counts")

# GetAssayData from Seurat v4 is still supported
GetAssayData(object = pbmc, assay = "RNA", slot = "counts")

# ADT counts matrix (multimodal object)
cbmc[["ADT"]]$counts
```

Example 27 (python):
```python
# Set expression data assume new.data is a new expression matrix
pbmc[["RNA"]]$counts <- new.data

# Alternate setter function with the same result
LayerData(pbmc, assay = "RNA", layer = "counts") <- new.data

# SetAssayData from Seurat v4 is still supported
pbmc <- SetAssayData(object = pbmc, slot = "counts", new.data = new.data)
```

Example 28 (r):
```r
# Set expression data assume new.data is a new expression matrix
pbmc[["RNA"]]$counts <- new.data

# Alternate setter function with the same result
LayerData(pbmc, assay = "RNA", layer = "counts") <- new.data

# SetAssayData from Seurat v4 is still supported
pbmc <- SetAssayData(object = pbmc, slot = "counts", new.data = new.data)
```

Example 29 (r):
```r
# Set expression data assume new.data is a new expression matrix
pbmc[["RNA"]]$counts <- new.data

# Alternate setter function with the same result
LayerData(pbmc, assay = "RNA", layer = "counts") <- new.data

# SetAssayData from Seurat v4 is still supported
pbmc <- SetAssayData(object = pbmc, slot = "counts", new.data = new.data)
```

Example 30 (unknown):
```unknown
# Get cell embeddings and feature loadings stored on pbmc[['pca']]@cell.embeddings
Embeddings(pbmc, reduction = "pca")

# stored in pbmc[['pca]]@feature.loadings
Loadings(pbmc, reduction = "pca")
```

Example 31 (r):
```r
# Get cell embeddings and feature loadings stored on pbmc[['pca']]@cell.embeddings
Embeddings(pbmc, reduction = "pca")

# stored in pbmc[['pca]]@feature.loadings
Loadings(pbmc, reduction = "pca")
```

Example 32 (r):
```r
# Get cell embeddings and feature loadings stored on pbmc[['pca']]@cell.embeddings
Embeddings(pbmc, reduction = "pca")

# stored in pbmc[['pca]]@feature.loadings
Loadings(pbmc, reduction = "pca")
```

Example 33 (unknown):
```unknown
# Create custom dimensional reduction loadings matrix is optional
new_reduction <- CreateDimReducObject(embeddings = new.embeddings, loadings = new.loadings, key = "custom_pca")
pbmc[["custom_pca"]] <- new_reduction
```

Example 34 (r):
```r
# Create custom dimensional reduction loadings matrix is optional
new_reduction <- CreateDimReducObject(embeddings = new.embeddings, loadings = new.loadings, key = "custom_pca")
pbmc[["custom_pca"]] <- new_reduction
```

Example 35 (r):
```r
# Create custom dimensional reduction loadings matrix is optional
new_reduction <- CreateDimReducObject(embeddings = new.embeddings, loadings = new.loadings, key = "custom_pca")
pbmc[["custom_pca"]] <- new_reduction
```

Example 36 (python):
```python
# FetchData can access anything from expression matrices, cell embeddings, or metadata Use the previously listed
# commands to access entire matrices Use FetchData to access individual/small groups of variables
FetchData(object = pbmc, vars = c("PC_1", "nFeature_RNA", "MS4A1"), layer = "counts")
```

Example 37 (r):
```r
# FetchData can access anything from expression matrices, cell embeddings, or metadata Use the previously listed
# commands to access entire matrices Use FetchData to access individual/small groups of variables
FetchData(object = pbmc, vars = c("PC_1", "nFeature_RNA", "MS4A1"), layer = "counts")
```

Example 38 (r):
```r
# FetchData can access anything from expression matrices, cell embeddings, or metadata Use the previously listed
# commands to access entire matrices Use FetchData to access individual/small groups of variables
FetchData(object = pbmc, vars = c("PC_1", "nFeature_RNA", "MS4A1"), layer = "counts")
```

Example 39 (unknown):
```unknown
# Subset Seurat object based on identity class, also see ?SubsetData
subset(x = pbmc, idents = "B")
subset(x = pbmc, idents = c("Naive CD4 T", "CD8 T"), invert = TRUE)

# Subset on the expression level of a gene/feature
subset(x = pbmc, subset = MS4A1 > 2.5)

# Subset on a combination of criteria
subset(x = pbmc, subset = MS4A1 > 2.5 & PC_1 > 5)
subset(x = pbmc, subset = MS4A1 > 2.5, idents = "B")

# Subset on a value in the object meta data
subset(x = pbmc, subset = groups == "g1")

# Downsample the number of cells per identity class
subset(x = pbmc, downsample = 100)
```

Example 40 (r):
```r
# Subset Seurat object based on identity class, also see ?SubsetData
subset(x = pbmc, idents = "B")
subset(x = pbmc, idents = c("Naive CD4 T", "CD8 T"), invert = TRUE)

# Subset on the expression level of a gene/feature
subset(x = pbmc, subset = MS4A1 > 2.5)

# Subset on a combination of criteria
subset(x = pbmc, subset = MS4A1 > 2.5 & PC_1 > 5)
subset(x = pbmc, subset = MS4A1 > 2.5, idents = "B")

# Subset on a value in the object meta data
subset(x = pbmc, subset = groups == "g1")

# Downsample the number of cells per identity class
subset(x = pbmc, downsample = 100)
```

Example 41 (r):
```r
# Subset Seurat object based on identity class, also see ?SubsetData
subset(x = pbmc, idents = "B")
subset(x = pbmc, idents = c("Naive CD4 T", "CD8 T"), invert = TRUE)

# Subset on the expression level of a gene/feature
subset(x = pbmc, subset = MS4A1 > 2.5)

# Subset on a combination of criteria
subset(x = pbmc, subset = MS4A1 > 2.5 & PC_1 > 5)
subset(x = pbmc, subset = MS4A1 > 2.5, idents = "B")

# Subset on a value in the object meta data
subset(x = pbmc, subset = groups == "g1")

# Downsample the number of cells per identity class
subset(x = pbmc, downsample = 100)
```

Example 42 (unknown):
```unknown
# In Seurat v5, users can now split in object directly into different layers keeps expression data in one object, but
# splits multiple samples into layers can proceed directly to integration workflow after splitting layers
ifnb[["RNA"]] <- split(ifnb[["RNA"]], f = ifnb$stim)
Layers(ifnb)

# If desired, for example after intergation, the layers can be joined together again
ifnb <- JoinLayers(ifnb)
```

Example 43 (r):
```r
# In Seurat v5, users can now split in object directly into different layers keeps expression data in one object, but
# splits multiple samples into layers can proceed directly to integration workflow after splitting layers
ifnb[["RNA"]] <- split(ifnb[["RNA"]], f = ifnb$stim)
Layers(ifnb)

# If desired, for example after intergation, the layers can be joined together again
ifnb <- JoinLayers(ifnb)
```

Example 44 (r):
```r
# In Seurat v5, users can now split in object directly into different layers keeps expression data in one object, but
# splits multiple samples into layers can proceed directly to integration workflow after splitting layers
ifnb[["RNA"]] <- split(ifnb[["RNA"]], f = ifnb$stim)
Layers(ifnb)

# If desired, for example after intergation, the layers can be joined together again
ifnb <- JoinLayers(ifnb)
```

Example 45 (python):
```python
# In line with prior workflows, you can also into split your object into a list of multiple objects based on a metadata
# column creates a list of two objects
ifnb_list <- SplitObject(ifnb, split.by = "stim")
ifnb_list$CTRL
ifnb_list$STIM
```

Example 46 (r):
```r
# In line with prior workflows, you can also into split your object into a list of multiple objects based on a metadata
# column creates a list of two objects
ifnb_list <- SplitObject(ifnb, split.by = "stim")
ifnb_list$CTRL
ifnb_list$STIM
```

Example 47 (r):
```r
# In line with prior workflows, you can also into split your object into a list of multiple objects based on a metadata
# column creates a list of two objects
ifnb_list <- SplitObject(ifnb, split.by = "stim")
ifnb_list$CTRL
ifnb_list$STIM
```

Example 48 (unknown):
```unknown
# Merge two Seurat objects
merged_obj <- merge(x = ifnb_list$CTRL, y = ifnb_list$STIM)
merged_obj[["RNA"]] <- JoinLayers(merged_obj)

# Example to merge more than two Seurat objects
merge(x = pbmc1, y = list(pbmc2, pbmc3))
```

Example 49 (r):
```r
# Merge two Seurat objects
merged_obj <- merge(x = ifnb_list$CTRL, y = ifnb_list$STIM)
merged_obj[["RNA"]] <- JoinLayers(merged_obj)

# Example to merge more than two Seurat objects
merge(x = pbmc1, y = list(pbmc2, pbmc3))
```

Example 50 (r):
```r
# Merge two Seurat objects
merged_obj <- merge(x = ifnb_list$CTRL, y = ifnb_list$STIM)
merged_obj[["RNA"]] <- JoinLayers(merged_obj)

# Example to merge more than two Seurat objects
merge(x = pbmc1, y = list(pbmc2, pbmc3))
```

Example 51 (unknown):
```unknown
merged_obj <- merge(x = ifnb_list$CTRL, y = ifnb_list$STIM)
merged_obj <- NormalizeData(merged_obj)
merged_obj <- FindVariableFeatures(merged_obj)
merged_obj <- ScaleData(merged_obj)
merged_obj <- RunPCA(merged_obj)
merged_obj <- IntegrateLayers(object = obj, method = RPCAIntegration, orig.reduction = "pca", new.reduction = "integrated.rpca",
    verbose = FALSE)

# now that integration is complete, rejoin layers
merged_obj[["RNA"]] <- JoinLayers(merged_obj)
```

Example 52 (r):
```r
merged_obj <- merge(x = ifnb_list$CTRL, y = ifnb_list$STIM)
merged_obj <- NormalizeData(merged_obj)
merged_obj <- FindVariableFeatures(merged_obj)
merged_obj <- ScaleData(merged_obj)
merged_obj <- RunPCA(merged_obj)
merged_obj <- IntegrateLayers(object = obj, method = RPCAIntegration, orig.reduction = "pca", new.reduction = "integrated.rpca",
    verbose = FALSE)

# now that integration is complete, rejoin layers
merged_obj[["RNA"]] <- JoinLayers(merged_obj)
```

Example 53 (r):
```r
merged_obj <- merge(x = ifnb_list$CTRL, y = ifnb_list$STIM)
merged_obj <- NormalizeData(merged_obj)
merged_obj <- FindVariableFeatures(merged_obj)
merged_obj <- ScaleData(merged_obj)
merged_obj <- RunPCA(merged_obj)
merged_obj <- IntegrateLayers(object = obj, method = RPCAIntegration, orig.reduction = "pca", new.reduction = "integrated.rpca",
    verbose = FALSE)

# now that integration is complete, rejoin layers
merged_obj[["RNA"]] <- JoinLayers(merged_obj)
```

Example 54 (unknown):
```unknown
# pseudobulk cells only by cell type
bulk <- AggregateExpression(ifnb, group.by = "seurat_annotations", return.seurat = TRUE)
Cells(bulk)

# pseudobulk cells by stimulation condition AND cell type
bulk <- AggregateExpression(ifnb, group.by = c("stim", "seurat_annotations"), return.seurat = TRUE)
Cells(bulk)

# pseudobulk cells by stimulation condition AND cell type AND donor
bulk <- AggregateExpression(ifnb, group.by = c("stim", "seurat_annotations", "donor_id"), return.seurat = TRUE)
Cells(bulk)
```

Example 55 (r):
```r
# pseudobulk cells only by cell type
bulk <- AggregateExpression(ifnb, group.by = "seurat_annotations", return.seurat = TRUE)
Cells(bulk)

# pseudobulk cells by stimulation condition AND cell type
bulk <- AggregateExpression(ifnb, group.by = c("stim", "seurat_annotations"), return.seurat = TRUE)
Cells(bulk)

# pseudobulk cells by stimulation condition AND cell type AND donor
bulk <- AggregateExpression(ifnb, group.by = c("stim", "seurat_annotations", "donor_id"), return.seurat = TRUE)
Cells(bulk)
```

Example 56 (r):
```r
# pseudobulk cells only by cell type
bulk <- AggregateExpression(ifnb, group.by = "seurat_annotations", return.seurat = TRUE)
Cells(bulk)

# pseudobulk cells by stimulation condition AND cell type
bulk <- AggregateExpression(ifnb, group.by = c("stim", "seurat_annotations"), return.seurat = TRUE)
Cells(bulk)

# pseudobulk cells by stimulation condition AND cell type AND donor
bulk <- AggregateExpression(ifnb, group.by = c("stim", "seurat_annotations", "donor_id"), return.seurat = TRUE)
Cells(bulk)
```

Example 57 (unknown):
```unknown
# Dimensional reduction plot
DimPlot(object = pbmc, reduction = "pca")

# Dimensional reduction plot, with cells colored by a quantitative feature Defaults to UMAP if available
FeaturePlot(object = pbmc, features = "MS4A1")

# Scatter plot across single cells
FeatureScatter(object = pbmc, feature1 = "MS4A1", feature2 = "PC_1")
FeatureScatter(object = pbmc, feature1 = "MS4A1", feature2 = "CD3D")

# Scatter plot across individual features, repleaces CellPlot
CellScatter(object = pbmc, cell1 = "AGTCTACTAGGGTG", cell2 = "CACAGATGGTTTCT")

VariableFeaturePlot(object = pbmc)

# Violin and Ridge plots
VlnPlot(object = pbmc, features = c("LYZ", "CCL5", "IL32"))
RidgePlot(object = pbmc, feature = c("LYZ", "CCL5", "IL32"))
```

Example 58 (r):
```r
# Dimensional reduction plot
DimPlot(object = pbmc, reduction = "pca")

# Dimensional reduction plot, with cells colored by a quantitative feature Defaults to UMAP if available
FeaturePlot(object = pbmc, features = "MS4A1")

# Scatter plot across single cells
FeatureScatter(object = pbmc, feature1 = "MS4A1", feature2 = "PC_1")
FeatureScatter(object = pbmc, feature1 = "MS4A1", feature2 = "CD3D")

# Scatter plot across individual features, repleaces CellPlot
CellScatter(object = pbmc, cell1 = "AGTCTACTAGGGTG", cell2 = "CACAGATGGTTTCT")

VariableFeaturePlot(object = pbmc)

# Violin and Ridge plots
VlnPlot(object = pbmc, features = c("LYZ", "CCL5", "IL32"))
RidgePlot(object = pbmc, feature = c("LYZ", "CCL5", "IL32"))
```

Example 59 (r):
```r
# Dimensional reduction plot
DimPlot(object = pbmc, reduction = "pca")

# Dimensional reduction plot, with cells colored by a quantitative feature Defaults to UMAP if available
FeaturePlot(object = pbmc, features = "MS4A1")

# Scatter plot across single cells
FeatureScatter(object = pbmc, feature1 = "MS4A1", feature2 = "PC_1")
FeatureScatter(object = pbmc, feature1 = "MS4A1", feature2 = "CD3D")

# Scatter plot across individual features, repleaces CellPlot
CellScatter(object = pbmc, cell1 = "AGTCTACTAGGGTG", cell2 = "CACAGATGGTTTCT")

VariableFeaturePlot(object = pbmc)

# Violin and Ridge plots
VlnPlot(object = pbmc, features = c("LYZ", "CCL5", "IL32"))
RidgePlot(object = pbmc, feature = c("LYZ", "CCL5", "IL32"))
```

Example 60 (unknown):
```unknown
# Heatmaps (visualize scale.data slot)
DimHeatmap(object = pbmc, reduction = "pca", cells = 200)

# standard workflow
pbmc <- ScaleData(pbmc, features = heatmap_markers)
DoHeatmap(object = pbmc, features = heatmap_markers)

# sctransform workflow
pbmc <- GetResidual(pbmc, features = heatmap_markers)
DoHeatmap(object = pbmc, features = heatmap_markers)

# heatmap with maximum of 100 cells per group
DoHeatmap(pbmc, heatmap_markers, cells = subset(pbmc, downsample = 100))
```

Example 61 (r):
```r
# Heatmaps (visualize scale.data slot)
DimHeatmap(object = pbmc, reduction = "pca", cells = 200)

# standard workflow
pbmc <- ScaleData(pbmc, features = heatmap_markers)
DoHeatmap(object = pbmc, features = heatmap_markers)

# sctransform workflow
pbmc <- GetResidual(pbmc, features = heatmap_markers)
DoHeatmap(object = pbmc, features = heatmap_markers)

# heatmap with maximum of 100 cells per group
DoHeatmap(pbmc, heatmap_markers, cells = subset(pbmc, downsample = 100))
```

Example 62 (r):
```r
# Heatmaps (visualize scale.data slot)
DimHeatmap(object = pbmc, reduction = "pca", cells = 200)

# standard workflow
pbmc <- ScaleData(pbmc, features = heatmap_markers)
DoHeatmap(object = pbmc, features = heatmap_markers)

# sctransform workflow
pbmc <- GetResidual(pbmc, features = heatmap_markers)
DoHeatmap(object = pbmc, features = heatmap_markers)

# heatmap with maximum of 100 cells per group
DoHeatmap(pbmc, heatmap_markers, cells = subset(pbmc, downsample = 100))
```

Example 63 (unknown):
```unknown
# New things to try!  Note that plotting functions now return ggplot2 objects, so you can add themes, titles, and
# options onto them
VlnPlot(object = pbmc, features = "MS4A1", split.by = "groups")
DotPlot(object = pbmc, features = c("LYZ", "CCL5", "IL32"), split.by = "groups")
FeaturePlot(object = pbmc, features = c("MS4A1", "CD79A"), blend = TRUE)
DimPlot(object = pbmc) + DarkTheme()
DimPlot(object = pbmc) + labs(title = "2,700 PBMCs clustered using Seurat and viewed\non a two-dimensional UMAP")
```

Example 64 (r):
```r
# New things to try!  Note that plotting functions now return ggplot2 objects, so you can add themes, titles, and
# options onto them
VlnPlot(object = pbmc, features = "MS4A1", split.by = "groups")
DotPlot(object = pbmc, features = c("LYZ", "CCL5", "IL32"), split.by = "groups")
FeaturePlot(object = pbmc, features = c("MS4A1", "CD79A"), blend = TRUE)
DimPlot(object = pbmc) + DarkTheme()
DimPlot(object = pbmc) + labs(title = "2,700 PBMCs clustered using Seurat and viewed\non a two-dimensional UMAP")
```

Example 65 (r):
```r
# New things to try!  Note that plotting functions now return ggplot2 objects, so you can add themes, titles, and
# options onto them
VlnPlot(object = pbmc, features = "MS4A1", split.by = "groups")
DotPlot(object = pbmc, features = c("LYZ", "CCL5", "IL32"), split.by = "groups")
FeaturePlot(object = pbmc, features = c("MS4A1", "CD79A"), blend = TRUE)
DimPlot(object = pbmc) + DarkTheme()
DimPlot(object = pbmc) + labs(title = "2,700 PBMCs clustered using Seurat and viewed\non a two-dimensional UMAP")
```

Example 66 (unknown):
```unknown
RestoreLegend
```

Example 67 (unknown):
```unknown
RotatedAxis
```

Example 68 (unknown):
```unknown
# Plotting helper functions work with ggplot2-based scatter plots, such as DimPlot, FeaturePlot, CellScatter, and
# FeatureScatter
plot <- DimPlot(object = pbmc) + NoLegend()

# HoverLocator replaces the former `do.hover` argument It can also show extra data throught the `information` argument,
# designed to work smoothly with FetchData
HoverLocator(plot = plot, information = FetchData(object = pbmc, vars = c("ident", "PC_1", "nFeature_RNA")))

# FeatureLocator replaces the former `do.identify`
select.cells <- FeatureLocator(plot = plot)

# Label points on a ggplot object
LabelPoints(plot = plot, points = TopCells(object = pbmc[["pca"]]), repel = TRUE)
```

Example 69 (r):
```r
# Plotting helper functions work with ggplot2-based scatter plots, such as DimPlot, FeaturePlot, CellScatter, and
# FeatureScatter
plot <- DimPlot(object = pbmc) + NoLegend()

# HoverLocator replaces the former `do.hover` argument It can also show extra data throught the `information` argument,
# designed to work smoothly with FetchData
HoverLocator(plot = plot, information = FetchData(object = pbmc, vars = c("ident", "PC_1", "nFeature_RNA")))

# FeatureLocator replaces the former `do.identify`
select.cells <- FeatureLocator(plot = plot)

# Label points on a ggplot object
LabelPoints(plot = plot, points = TopCells(object = pbmc[["pca"]]), repel = TRUE)
```

Example 70 (r):
```r
# Plotting helper functions work with ggplot2-based scatter plots, such as DimPlot, FeaturePlot, CellScatter, and
# FeatureScatter
plot <- DimPlot(object = pbmc) + NoLegend()

# HoverLocator replaces the former `do.hover` argument It can also show extra data throught the `information` argument,
# designed to work smoothly with FetchData
HoverLocator(plot = plot, information = FetchData(object = pbmc, vars = c("ident", "PC_1", "nFeature_RNA")))

# FeatureLocator replaces the former `do.identify`
select.cells <- FeatureLocator(plot = plot)

# Label points on a ggplot object
LabelPoints(plot = plot, points = TopCells(object = pbmc[["pca"]]), repel = TRUE)
```

Example 71 (python):
```python
cbmc <- CreateSeuratObject(counts = cbmc.rna)
# Add ADT data
cbmc[["ADT"]] <- CreateAssayObject(counts = cbmc.adt)
# Run analyses by specifying the assay to use
NormalizeData(object = cbmc, assay = "RNA")
NormalizeData(object = cbmc, assay = "ADT", method = "CLR")

# Retrieve and set the default assay
DefaultAssay(object = cbmc)
DefaultAssay(object = cbmc) <- "ADT"
DefaultAssay(object = cbmc)

# Pull feature expression from both assays by using keys
FetchData(object = cbmc, vars = c("rna_CD3E", "adt_CD3"))

# Plot data from multiple assays using keys
FeatureScatter(object = cbmc, feature1 = "rna_CD3E", feature2 = "adt_CD3")
```

Example 72 (r):
```r
cbmc <- CreateSeuratObject(counts = cbmc.rna)
# Add ADT data
cbmc[["ADT"]] <- CreateAssayObject(counts = cbmc.adt)
# Run analyses by specifying the assay to use
NormalizeData(object = cbmc, assay = "RNA")
NormalizeData(object = cbmc, assay = "ADT", method = "CLR")

# Retrieve and set the default assay
DefaultAssay(object = cbmc)
DefaultAssay(object = cbmc) <- "ADT"
DefaultAssay(object = cbmc)

# Pull feature expression from both assays by using keys
FetchData(object = cbmc, vars = c("rna_CD3E", "adt_CD3"))

# Plot data from multiple assays using keys
FeatureScatter(object = cbmc, feature1 = "rna_CD3E", feature2 = "adt_CD3")
```

Example 73 (r):
```r
cbmc <- CreateSeuratObject(counts = cbmc.rna)
# Add ADT data
cbmc[["ADT"]] <- CreateAssayObject(counts = cbmc.adt)
# Run analyses by specifying the assay to use
NormalizeData(object = cbmc, assay = "RNA")
NormalizeData(object = cbmc, assay = "ADT", method = "CLR")

# Retrieve and set the default assay
DefaultAssay(object = cbmc)
DefaultAssay(object = cbmc) <- "ADT"
DefaultAssay(object = cbmc)

# Pull feature expression from both assays by using keys
FetchData(object = cbmc, vars = c("rna_CD3E", "adt_CD3"))

# Plot data from multiple assays using keys
FeatureScatter(object = cbmc, feature1 = "rna_CD3E", feature2 = "adt_CD3")
```

Example 74 (unknown):
```unknown
sessionInfo()
```

Example 75 (r):
```r
sessionInfo()
```

Example 76 (r):
```r
sessionInfo()
```

---

## Cell-Cycle Scoring and Regression • Seurat

**URL:** http://127.0.0.1:9173/seurat/archive/v4.3/cell_cycle_vignette/index.html

**Contents:**
- Cell-Cycle Scoring and Regression
    - Compiled: 2023-03-27
- Assign Cell-Cycle Scores
- Regress out cell cycle scores during data scaling
- Alternate Workflow
- Contents

We demonstrate how to mitigate the effects of cell cycle heterogeneity in scRNA-seq data by calculating cell cycle phase scores based on canonical markers, and regressing these out of the data during pre-processing. We demonstrate this on a dataset of murine hematopoietic progenitors (Nestorowa et al., Blood 2016).You can download the files needed to run this vignette here. library(Seurat) # Read in the expression matrix The first row is a header row, the first column is rownames exp.mat <- read.table(file = "../data/nestorawa_forcellcycle_expressionMatrix.txt", header = TRUE, as.is = TRUE, row.names = 1) # A list of cell cycle markers, from Tirosh et al, 2015, is loaded with Seurat. We can # segregate this list into markers of G2/M phase and markers of S phase s.genes <- cc.genes$s.genes g2m.genes <- cc.genes$g2m.genes # Create our Seurat object and complete the initalization steps marrow <- CreateSeuratObject(counts = exp.mat) marrow <- NormalizeData(marrow) marrow <- FindVariableFeatures(marrow, selection.method = "vst") marrow <- ScaleData(marrow, features = rownames(marrow))If we run a PCA on our object, using the variable genes we found in FindVariableFeatures() above, we see that while most of the variance can be explained by lineage, PC8 and PC10 are split on cell-cycle genes including TOP2A and MKI67. We will attempt to regress this signal from the data, so that cell-cycle heterogeneity does not contribute to PCA or downstream analysis. marrow <- RunPCA(marrow, features = VariableFeatures(marrow), ndims.print = 6:10, nfeatures.print = 10)## PC_ 6 ## Positive: SELL, ARL6IP1, CCL9, CD34, ADGRL4, BPIFC, NUSAP1, FAM64A, CD244, C030034L19RIK ## Negative: LY6C2, AA467197, CYBB, MGST2, ITGB2, PF4, CD74, ATP1B1, GP1BB, TREM3 ## PC_ 7 ## Positive: HDC, CPA3, PGLYRP1, MS4A3, NKG7, UBE2C, CCNB1, NUSAP1, PLK1, FUT8 ## Negative: F13A1, LY86, CFP, IRF8, CSF1R, TIFAB, IFI209, CCR2, TNS4, MS4A6C ## PC_ 8 ## Positive: WFDC17, SLC35D3, ADGRL4, VLDLR, CD33, H2AFY, P2RY14, IFI206, CCL9, CD34 ## Negative: NUSAP1, UBE2C, KIF23, PLK1, CENPF, FAM64A, CCNB1, H2AFX, ID2, CDC20 ## PC_ 9 ## Positive: SLC2A6, HBA-A1, HBA-A2, IGHV8-7, FCER1G, F13A1, HBB-BS, PLD4, HBB-BT, IGFBP4 ## Negative: IGKC, JCHAIN, LY6D, MZB1, CD74, IGLC2, FCRLA, IGKV4-50, IGHM, IGHV9-1 ## PC_ 10 ## Positive: CTSW, XKRX, PRR5L, RORA, MBOAT4, A630014C17RIK, ZFP105, COL9A3, CLEC2I, TRAT1 ## Negative: H2AFX, FAM64A, ZFP383, NUSAP1, CDC25B, CENPF, GBP10, TOP2A, GBP6, GFRA1 DimHeatmap(marrow, dims = c(8, 10))Assign Cell-Cycle ScoresFirst, we assign each cell a score, based on its expression of G2/M and S phase markers. These marker sets should be anticorrelated in their expression levels, and cells expressing neither are likely not cycling and in G1 phase.We assign scores in the CellCycleScoring() function, which stores S and G2/M scores in object meta data, along with the predicted classification of each cell in either G2M, S or G1 phase. CellCycleScoring() can also set the identity of the Seurat object to the cell-cycle phase by passing set.ident = TRUE (the original identities are stored as old.ident). Please note that Seurat does not use the discrete classifications (G2M/G1/S) in downstream cell cycle regression. Instead, it uses the quantitative scores for G2M and S phase. However, we provide our predicted classifications in case they are of interest. marrow <- CellCycleScoring(marrow, s.features = s.genes, g2m.features = g2m.genes, set.ident = TRUE) # view cell cycle scores and phase assignments head(marrow[[]])## orig.ident nCount_RNA nFeature_RNA S.Score G2M.Score Phase ## Prog_013 Prog 2563089 10211 -0.14248691 -0.4680395 G1 ## Prog_019 Prog 3030620 9991 -0.16915786 0.5851766 G2M ## Prog_031 Prog 1293487 10192 -0.34627038 -0.3971879 G1 ## Prog_037 Prog 1357987 9599 -0.44270212 0.6820229 G2M ## Prog_008 Prog 4079891 10540 0.55854051 0.1284359 S ## Prog_014 Prog 2569783 10788 0.07116218 0.3166073 G2M ## old.ident ## Prog_013 Prog ## Prog_019 Prog ## Prog_031 Prog ## Prog_037 Prog ## Prog_008 Prog ## Prog_014 Prog # Visualize the distribution of cell cycle markers across RidgePlot(marrow, features = c("PCNA", "TOP2A", "MCM6", "MKI67"), ncol = 2) # Running a PCA on cell cycle genes reveals, unsurprisingly, that cells separate entirely by # phase marrow <- RunPCA(marrow, features = c(s.genes, g2m.genes)) DimPlot(marrow)We score single cells based on the scoring strategy described in Tirosh et al. 2016. See ?AddModuleScore() in Seurat for more information, this function can be used to calculate supervised module scores for any gene list.Regress out cell cycle scores during data scalingWe now attempt to subtract (‘regress out’) this source of heterogeneity from the data. For users of Seurat v1.4, this was implemented in RegressOut. However, as the results of this procedure are stored in the scaled data slot (therefore overwriting the output of ScaleData()), we now merge this functionality into the ScaleData() function itself.For each gene, Seurat models the relationship between gene expression and the S and G2M cell cycle scores. The scaled residuals of this model represent a ‘corrected’ expression matrix, that can be used downstream for dimensional reduction. marrow <- ScaleData(marrow, vars.to.regress = c("S.Score", "G2M.Score"), features = rownames(marrow)) # Now, a PCA on the variable genes no longer returns components associated with cell cycle marrow <- RunPCA(marrow, features = VariableFeatures(marrow), nfeatures.print = 10)## PC_ 1 ## Positive: BLVRB, CAR2, KLF1, AQP1, CES2G, ERMAP, CAR1, FAM132A, RHD, SPHK1 ## Negative: TMSB4X, H2AFY, CORO1A, PLAC8, EMB, MPO, PRTN3, CD34, LCP1, BC035044 ## PC_ 2 ## Positive: ANGPT1, ADGRG1, MEIS1, ITGA2B, MPL, DAPP1, APOE, RAB37, GATA2, F2R ## Negative: LY6C2, ELANE, HP, IGSF6, ANXA3, CTSG, CLEC12A, TIFAB, SLPI, ALAS1 ## PC_ 3 ## Positive: APOE, GATA2, NKG7, MUC13, MS4A3, RAB44, HDC, CPA3, FCGR3, TUBA8 ## Negative: FLT3, DNTT, LSP1, WFDC17, MYL10, GIMAP6, LAX1, GPR171, TBXA2R, SATB1 ## PC_ 4 ## Positive: CSRP3, ST8SIA6, DNTT, MPEG1, SCIN, LGALS1, CMAH, RGL1, APOE, MFSD2B ## Negative: PROCR, MPL, HLF, MMRN1, SERPINA3G, ESAM, GSTM1, D630039A03RIK, MYL10, LY6A ## PC_ 5 ## Positive: PF4, GP1BB, SDPR, F2RL2, RAB27B, SLC14A1, TREML1, PBX1, F2R, TUBA8 ## Negative: CPA3, LMO4, IKZF2, IFITM1, FUT8, MS4A2, SIGLECF, CSRP3, HDC, RAB44 # When running a PCA on only cell cycle genes, cells no longer separate by cell-cycle phase marrow <- RunPCA(marrow, features = c(s.genes, g2m.genes)) DimPlot(marrow)As the best cell cycle markers are extremely well conserved across tissues and species, we have found this procedure to work robustly and reliably on diverse datasets.Alternate WorkflowThe procedure above removes all signal associated with cell cycle. In some cases, we’ve found that this can negatively impact downstream analysis, particularly in differentiating processes (like murine hematopoiesis), where stem cells are quiescent and differentiated cells are proliferating (or vice versa). In this case, regressing out all cell cycle effects can blur the distinction between stem and progenitor cells as well.As an alternative, we suggest regressing out the difference between the G2M and S phase scores. This means that signals separating non-cycling cells and cycling cells will be maintained, but differences in cell cycle phase among proliferating cells (which are often uninteresting), will be regressed out of the data marrow$CC.Difference <- marrow$S.Score - marrow$G2M.Score marrow <- ScaleData(marrow, vars.to.regress = "CC.Difference", features = rownames(marrow)) # cell cycle effects strongly mitigated in PCA marrow <- RunPCA(marrow, features = VariableFeatures(marrow), nfeatures.print = 10)## PC_ 1 ## Positive: BLVRB, KLF1, ERMAP, FAM132A, CAR2, RHD, CES2G, SPHK1, AQP1, SLC38A5 ## Negative: TMSB4X, CORO1A, PLAC8, H2AFY, LAPTM5, CD34, LCP1, TMEM176B, IGFBP4, EMB ## PC_ 2 ## Positive: APOE, GATA2, RAB37, ANGPT1, ADGRG1, MEIS1, MPL, F2R, PDZK1IP1, DAPP1 ## Negative: CTSG, ELANE, LY6C2, HP, CLEC12A, ANXA3, IGSF6, TIFAB, SLPI, MPO ## PC_ 3 ## Positive: APOE, GATA2, NKG7, MUC13, ITGA2B, TUBA8, CPA3, RAB44, SLC18A2, CD9 ## Negative: DNTT, FLT3, WFDC17, LSP1, MYL10, LAX1, GIMAP6, IGHM, CD24A, MN1 ## PC_ 4 ## Positive: CSRP3, ST8SIA6, SCIN, LGALS1, APOE, ITGB7, MFSD2B, RGL1, DNTT, IGHV1-23 ## Negative: MPL, MMRN1, PROCR, HLF, SERPINA3G, ESAM, PTGS1, D630039A03RIK, NDN, PPIC ## PC_ 5 ## Positive: HDC, LMO4, CSRP3, IFITM1, FCGR3, HLF, CPA3, PROCR, PGLYRP1, IKZF2 ## Negative: GP1BB, PF4, SDPR, F2RL2, TREML1, RAB27B, SLC14A1, PBX1, PLEK, TUBA8 # when running a PCA on cell cycle genes, actively proliferating cells remain distinct from G1 # cells however, within actively proliferating cells, G2M and S phase cells group together marrow <- RunPCA(marrow, features = c(s.genes, g2m.genes)) DimPlot(marrow)Session Info sessionInfo()## R version 4.2.0 (2022-04-22) ## Platform: x86_64-pc-linux-gnu (64-bit) ## Running under: Ubuntu 20.04.5 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/liblapack.so.3 ## ## locale: ## [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C ## [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8 ## [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 ## ## attached base packages: ## [1] stats graphics grDevices utils datasets methods base ## ## other attached packages: ## [1] ggplot2_3.4.1 SeuratObject_4.1.3 Seurat_4.3.0 ## ## loaded via a namespace (and not attached): ## [1] Rtsne_0.16 colorspace_2.1-0 deldir_1.0-6 ## [4] ellipsis_0.3.2 ggridges_0.5.4 rprojroot_2.0.3 ## [7] fs_1.6.1 spatstat.data_3.0-0 farver_2.1.1 ## [10] leiden_0.4.3 listenv_0.9.0 ggrepel_0.9.3 ## [13] fansi_1.0.4 codetools_0.2-18 splines_4.2.0 ## [16] cachem_1.0.7 knitr_1.42 polyclip_1.10-4 ## [19] jsonlite_1.8.4 ica_1.0-3 cluster_2.1.3 ## [22] png_0.1-8 uwot_0.1.14 spatstat.sparse_3.0-0 ## [25] shiny_1.7.4 sctransform_0.3.5 compiler_4.2.0 ## [28] httr_1.4.5 Matrix_1.5-3 fastmap_1.1.1 ## [31] lazyeval_0.2.2 cli_3.6.0 later_1.3.0 ## [34] formatR_1.14 htmltools_0.5.4 tools_4.2.0 ## [37] igraph_1.4.1 gtable_0.3.1 glue_1.6.2 ## [40] RANN_2.6.1 reshape2_1.4.4 dplyr_1.1.0 ## [43] Rcpp_1.0.10 scattermore_0.8 jquerylib_0.1.4 ## [46] pkgdown_2.0.7 vctrs_0.5.2 nlme_3.1-157 ## [49] spatstat.explore_3.0-6 progressr_0.13.0 lmtest_0.9-40 ## [52] spatstat.random_3.1-3 xfun_0.37 stringr_1.5.0 ## [55] globals_0.16.2 mime_0.12 miniUI_0.1.1.1 ## [58] lifecycle_1.0.3 irlba_2.3.5.1 goftest_1.2-3 ## [61] future_1.31.0 MASS_7.3-56 zoo_1.8-11 ## [64] scales_1.2.1 ragg_1.2.5 promises_1.2.0.1 ## [67] spatstat.utils_3.0-1 parallel_4.2.0 RColorBrewer_1.1-3 ## [70] yaml_2.3.7 memoise_2.0.1 reticulate_1.28 ## [73] pbapply_1.7-0 gridExtra_2.3 sass_0.4.5 ## [76] stringi_1.7.12 highr_0.10 desc_1.4.2 ## [79] rlang_1.0.6 pkgconfig_2.0.3 systemfonts_1.0.4 ## [82] matrixStats_0.63.0 evaluate_0.20 lattice_0.20-45 ## [85] tensor_1.5 ROCR_1.0-11 purrr_1.0.1 ## [88] labeling_0.4.2 patchwork_1.1.2 htmlwidgets_1.6.1 ## [91] cowplot_1.1.1 tidyselect_1.2.0 parallelly_1.34.0 ## [94] RcppAnnoy_0.0.20 plyr_1.8.8 magrittr_2.0.3 ## [97] R6_2.5.1 generics_0.1.3 withr_2.5.0 ## [100] pillar_1.8.1 fitdistrplus_1.1-8 abind_1.4-5 ## [103] survival_3.3-1 sp_1.6-0 tibble_3.1.8 ## [106] future.apply_1.10.0 KernSmooth_2.23-20 utf8_1.2.3 ## [109] spatstat.geom_3.0-6 plotly_4.10.1 rmarkdown_2.20 ## [112] grid_4.2.0 data.table_1.14.8 digest_0.6.31 ## [115] xtable_1.8-4 tidyr_1.3.0 httpuv_1.6.9 ## [118] textshaping_0.3.6 munsell_0.5.0 viridisLite_0.4.1 ## [121] bslib_0.4.2

If we run a PCA on our object, using the variable genes we found in FindVariableFeatures() above, we see that while most of the variance can be explained by lineage, PC8 and PC10 are split on cell-cycle genes including TOP2A and MKI67. We will attempt to regress this signal from the data, so that cell-cycle heterogeneity does not contribute to PCA or downstream analysis. marrow <- RunPCA(marrow, features = VariableFeatures(marrow), ndims.print = 6:10, nfeatures.print = 10)## PC_ 6 ## Positive: SELL, ARL6IP1, CCL9, CD34, ADGRL4, BPIFC, NUSAP1, FAM64A, CD244, C030034L19RIK ## Negative: LY6C2, AA467197, CYBB, MGST2, ITGB2, PF4, CD74, ATP1B1, GP1BB, TREM3 ## PC_ 7 ## Positive: HDC, CPA3, PGLYRP1, MS4A3, NKG7, UBE2C, CCNB1, NUSAP1, PLK1, FUT8 ## Negative: F13A1, LY86, CFP, IRF8, CSF1R, TIFAB, IFI209, CCR2, TNS4, MS4A6C ## PC_ 8 ## Positive: WFDC17, SLC35D3, ADGRL4, VLDLR, CD33, H2AFY, P2RY14, IFI206, CCL9, CD34 ## Negative: NUSAP1, UBE2C, KIF23, PLK1, CENPF, FAM64A, CCNB1, H2AFX, ID2, CDC20 ## PC_ 9 ## Positive: SLC2A6, HBA-A1, HBA-A2, IGHV8-7, FCER1G, F13A1, HBB-BS, PLD4, HBB-BT, IGFBP4 ## Negative: IGKC, JCHAIN, LY6D, MZB1, CD74, IGLC2, FCRLA, IGKV4-50, IGHM, IGHV9-1 ## PC_ 10 ## Positive: CTSW, XKRX, PRR5L, RORA, MBOAT4, A630014C17RIK, ZFP105, COL9A3, CLEC2I, TRAT1 ## Negative: H2AFX, FAM64A, ZFP383, NUSAP1, CDC25B, CENPF, GBP10, TOP2A, GBP6, GFRA1 DimHeatmap(marrow, dims = c(8, 10))Assign Cell-Cycle ScoresFirst, we assign each cell a score, based on its expression of G2/M and S phase markers. These marker sets should be anticorrelated in their expression levels, and cells expressing neither are likely not cycling and in G1 phase.We assign scores in the CellCycleScoring() function, which stores S and G2/M scores in object meta data, along with the predicted classification of each cell in either G2M, S or G1 phase. CellCycleScoring() can also set the identity of the Seurat object to the cell-cycle phase by passing set.ident = TRUE (the original identities are stored as old.ident). Please note that Seurat does not use the discrete classifications (G2M/G1/S) in downstream cell cycle regression. Instead, it uses the quantitative scores for G2M and S phase. However, we provide our predicted classifications in case they are of interest. marrow <- CellCycleScoring(marrow, s.features = s.genes, g2m.features = g2m.genes, set.ident = TRUE) # view cell cycle scores and phase assignments head(marrow[[]])## orig.ident nCount_RNA nFeature_RNA S.Score G2M.Score Phase ## Prog_013 Prog 2563089 10211 -0.14248691 -0.4680395 G1 ## Prog_019 Prog 3030620 9991 -0.16915786 0.5851766 G2M ## Prog_031 Prog 1293487 10192 -0.34627038 -0.3971879 G1 ## Prog_037 Prog 1357987 9599 -0.44270212 0.6820229 G2M ## Prog_008 Prog 4079891 10540 0.55854051 0.1284359 S ## Prog_014 Prog 2569783 10788 0.07116218 0.3166073 G2M ## old.ident ## Prog_013 Prog ## Prog_019 Prog ## Prog_031 Prog ## Prog_037 Prog ## Prog_008 Prog ## Prog_014 Prog # Visualize the distribution of cell cycle markers across RidgePlot(marrow, features = c("PCNA", "TOP2A", "MCM6", "MKI67"), ncol = 2) # Running a PCA on cell cycle genes reveals, unsurprisingly, that cells separate entirely by # phase marrow <- RunPCA(marrow, features = c(s.genes, g2m.genes)) DimPlot(marrow)We score single cells based on the scoring strategy described in Tirosh et al. 2016. See ?AddModuleScore() in Seurat for more information, this function can be used to calculate supervised module scores for any gene list.Regress out cell cycle scores during data scalingWe now attempt to subtract (‘regress out’) this source of heterogeneity from the data. For users of Seurat v1.4, this was implemented in RegressOut. However, as the results of this procedure are stored in the scaled data slot (therefore overwriting the output of ScaleData()), we now merge this functionality into the ScaleData() function itself.For each gene, Seurat models the relationship between gene expression and the S and G2M cell cycle scores. The scaled residuals of this model represent a ‘corrected’ expression matrix, that can be used downstream for dimensional reduction. marrow <- ScaleData(marrow, vars.to.regress = c("S.Score", "G2M.Score"), features = rownames(marrow)) # Now, a PCA on the variable genes no longer returns components associated with cell cycle marrow <- RunPCA(marrow, features = VariableFeatures(marrow), nfeatures.print = 10)## PC_ 1 ## Positive: BLVRB, CAR2, KLF1, AQP1, CES2G, ERMAP, CAR1, FAM132A, RHD, SPHK1 ## Negative: TMSB4X, H2AFY, CORO1A, PLAC8, EMB, MPO, PRTN3, CD34, LCP1, BC035044 ## PC_ 2 ## Positive: ANGPT1, ADGRG1, MEIS1, ITGA2B, MPL, DAPP1, APOE, RAB37, GATA2, F2R ## Negative: LY6C2, ELANE, HP, IGSF6, ANXA3, CTSG, CLEC12A, TIFAB, SLPI, ALAS1 ## PC_ 3 ## Positive: APOE, GATA2, NKG7, MUC13, MS4A3, RAB44, HDC, CPA3, FCGR3, TUBA8 ## Negative: FLT3, DNTT, LSP1, WFDC17, MYL10, GIMAP6, LAX1, GPR171, TBXA2R, SATB1 ## PC_ 4 ## Positive: CSRP3, ST8SIA6, DNTT, MPEG1, SCIN, LGALS1, CMAH, RGL1, APOE, MFSD2B ## Negative: PROCR, MPL, HLF, MMRN1, SERPINA3G, ESAM, GSTM1, D630039A03RIK, MYL10, LY6A ## PC_ 5 ## Positive: PF4, GP1BB, SDPR, F2RL2, RAB27B, SLC14A1, TREML1, PBX1, F2R, TUBA8 ## Negative: CPA3, LMO4, IKZF2, IFITM1, FUT8, MS4A2, SIGLECF, CSRP3, HDC, RAB44 # When running a PCA on only cell cycle genes, cells no longer separate by cell-cycle phase marrow <- RunPCA(marrow, features = c(s.genes, g2m.genes)) DimPlot(marrow)As the best cell cycle markers are extremely well conserved across tissues and species, we have found this procedure to work robustly and reliably on diverse datasets.Alternate WorkflowThe procedure above removes all signal associated with cell cycle. In some cases, we’ve found that this can negatively impact downstream analysis, particularly in differentiating processes (like murine hematopoiesis), where stem cells are quiescent and differentiated cells are proliferating (or vice versa). In this case, regressing out all cell cycle effects can blur the distinction between stem and progenitor cells as well.As an alternative, we suggest regressing out the difference between the G2M and S phase scores. This means that signals separating non-cycling cells and cycling cells will be maintained, but differences in cell cycle phase among proliferating cells (which are often uninteresting), will be regressed out of the data marrow$CC.Difference <- marrow$S.Score - marrow$G2M.Score marrow <- ScaleData(marrow, vars.to.regress = "CC.Difference", features = rownames(marrow)) # cell cycle effects strongly mitigated in PCA marrow <- RunPCA(marrow, features = VariableFeatures(marrow), nfeatures.print = 10)## PC_ 1 ## Positive: BLVRB, KLF1, ERMAP, FAM132A, CAR2, RHD, CES2G, SPHK1, AQP1, SLC38A5 ## Negative: TMSB4X, CORO1A, PLAC8, H2AFY, LAPTM5, CD34, LCP1, TMEM176B, IGFBP4, EMB ## PC_ 2 ## Positive: APOE, GATA2, RAB37, ANGPT1, ADGRG1, MEIS1, MPL, F2R, PDZK1IP1, DAPP1 ## Negative: CTSG, ELANE, LY6C2, HP, CLEC12A, ANXA3, IGSF6, TIFAB, SLPI, MPO ## PC_ 3 ## Positive: APOE, GATA2, NKG7, MUC13, ITGA2B, TUBA8, CPA3, RAB44, SLC18A2, CD9 ## Negative: DNTT, FLT3, WFDC17, LSP1, MYL10, LAX1, GIMAP6, IGHM, CD24A, MN1 ## PC_ 4 ## Positive: CSRP3, ST8SIA6, SCIN, LGALS1, APOE, ITGB7, MFSD2B, RGL1, DNTT, IGHV1-23 ## Negative: MPL, MMRN1, PROCR, HLF, SERPINA3G, ESAM, PTGS1, D630039A03RIK, NDN, PPIC ## PC_ 5 ## Positive: HDC, LMO4, CSRP3, IFITM1, FCGR3, HLF, CPA3, PROCR, PGLYRP1, IKZF2 ## Negative: GP1BB, PF4, SDPR, F2RL2, TREML1, RAB27B, SLC14A1, PBX1, PLEK, TUBA8 # when running a PCA on cell cycle genes, actively proliferating cells remain distinct from G1 # cells however, within actively proliferating cells, G2M and S phase cells group together marrow <- RunPCA(marrow, features = c(s.genes, g2m.genes)) DimPlot(marrow)Session Info sessionInfo()## R version 4.2.0 (2022-04-22) ## Platform: x86_64-pc-linux-gnu (64-bit) ## Running under: Ubuntu 20.04.5 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/liblapack.so.3 ## ## locale: ## [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C ## [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8 ## [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 ## ## attached base packages: ## [1] stats graphics grDevices utils datasets methods base ## ## other attached packages: ## [1] ggplot2_3.4.1 SeuratObject_4.1.3 Seurat_4.3.0 ## ## loaded via a namespace (and not attached): ## [1] Rtsne_0.16 colorspace_2.1-0 deldir_1.0-6 ## [4] ellipsis_0.3.2 ggridges_0.5.4 rprojroot_2.0.3 ## [7] fs_1.6.1 spatstat.data_3.0-0 farver_2.1.1 ## [10] leiden_0.4.3 listenv_0.9.0 ggrepel_0.9.3 ## [13] fansi_1.0.4 codetools_0.2-18 splines_4.2.0 ## [16] cachem_1.0.7 knitr_1.42 polyclip_1.10-4 ## [19] jsonlite_1.8.4 ica_1.0-3 cluster_2.1.3 ## [22] png_0.1-8 uwot_0.1.14 spatstat.sparse_3.0-0 ## [25] shiny_1.7.4 sctransform_0.3.5 compiler_4.2.0 ## [28] httr_1.4.5 Matrix_1.5-3 fastmap_1.1.1 ## [31] lazyeval_0.2.2 cli_3.6.0 later_1.3.0 ## [34] formatR_1.14 htmltools_0.5.4 tools_4.2.0 ## [37] igraph_1.4.1 gtable_0.3.1 glue_1.6.2 ## [40] RANN_2.6.1 reshape2_1.4.4 dplyr_1.1.0 ## [43] Rcpp_1.0.10 scattermore_0.8 jquerylib_0.1.4 ## [46] pkgdown_2.0.7 vctrs_0.5.2 nlme_3.1-157 ## [49] spatstat.explore_3.0-6 progressr_0.13.0 lmtest_0.9-40 ## [52] spatstat.random_3.1-3 xfun_0.37 stringr_1.5.0 ## [55] globals_0.16.2 mime_0.12 miniUI_0.1.1.1 ## [58] lifecycle_1.0.3 irlba_2.3.5.1 goftest_1.2-3 ## [61] future_1.31.0 MASS_7.3-56 zoo_1.8-11 ## [64] scales_1.2.1 ragg_1.2.5 promises_1.2.0.1 ## [67] spatstat.utils_3.0-1 parallel_4.2.0 RColorBrewer_1.1-3 ## [70] yaml_2.3.7 memoise_2.0.1 reticulate_1.28 ## [73] pbapply_1.7-0 gridExtra_2.3 sass_0.4.5 ## [76] stringi_1.7.12 highr_0.10 desc_1.4.2 ## [79] rlang_1.0.6 pkgconfig_2.0.3 systemfonts_1.0.4 ## [82] matrixStats_0.63.0 evaluate_0.20 lattice_0.20-45 ## [85] tensor_1.5 ROCR_1.0-11 purrr_1.0.1 ## [88] labeling_0.4.2 patchwork_1.1.2 htmlwidgets_1.6.1 ## [91] cowplot_1.1.1 tidyselect_1.2.0 parallelly_1.34.0 ## [94] RcppAnnoy_0.0.20 plyr_1.8.8 magrittr_2.0.3 ## [97] R6_2.5.1 generics_0.1.3 withr_2.5.0 ## [100] pillar_1.8.1 fitdistrplus_1.1-8 abind_1.4-5 ## [103] survival_3.3-1 sp_1.6-0 tibble_3.1.8 ## [106] future.apply_1.10.0 KernSmooth_2.23-20 utf8_1.2.3 ## [109] spatstat.geom_3.0-6 plotly_4.10.1 rmarkdown_2.20 ## [112] grid_4.2.0 data.table_1.14.8 digest_0.6.31 ## [115] xtable_1.8-4 tidyr_1.3.0 httpuv_1.6.9 ## [118] textshaping_0.3.6 munsell_0.5.0 viridisLite_0.4.1 ## [121] bslib_0.4.2

Assign Cell-Cycle ScoresFirst, we assign each cell a score, based on its expression of G2/M and S phase markers. These marker sets should be anticorrelated in their expression levels, and cells expressing neither are likely not cycling and in G1 phase.We assign scores in the CellCycleScoring() function, which stores S and G2/M scores in object meta data, along with the predicted classification of each cell in either G2M, S or G1 phase. CellCycleScoring() can also set the identity of the Seurat object to the cell-cycle phase by passing set.ident = TRUE (the original identities are stored as old.ident). Please note that Seurat does not use the discrete classifications (G2M/G1/S) in downstream cell cycle regression. Instead, it uses the quantitative scores for G2M and S phase. However, we provide our predicted classifications in case they are of interest. marrow <- CellCycleScoring(marrow, s.features = s.genes, g2m.features = g2m.genes, set.ident = TRUE) # view cell cycle scores and phase assignments head(marrow[[]])## orig.ident nCount_RNA nFeature_RNA S.Score G2M.Score Phase ## Prog_013 Prog 2563089 10211 -0.14248691 -0.4680395 G1 ## Prog_019 Prog 3030620 9991 -0.16915786 0.5851766 G2M ## Prog_031 Prog 1293487 10192 -0.34627038 -0.3971879 G1 ## Prog_037 Prog 1357987 9599 -0.44270212 0.6820229 G2M ## Prog_008 Prog 4079891 10540 0.55854051 0.1284359 S ## Prog_014 Prog 2569783 10788 0.07116218 0.3166073 G2M ## old.ident ## Prog_013 Prog ## Prog_019 Prog ## Prog_031 Prog ## Prog_037 Prog ## Prog_008 Prog ## Prog_014 Prog # Visualize the distribution of cell cycle markers across RidgePlot(marrow, features = c("PCNA", "TOP2A", "MCM6", "MKI67"), ncol = 2) # Running a PCA on cell cycle genes reveals, unsurprisingly, that cells separate entirely by # phase marrow <- RunPCA(marrow, features = c(s.genes, g2m.genes)) DimPlot(marrow)We score single cells based on the scoring strategy described in Tirosh et al. 2016. See ?AddModuleScore() in Seurat for more information, this function can be used to calculate supervised module scores for any gene list.Regress out cell cycle scores during data scalingWe now attempt to subtract (‘regress out’) this source of heterogeneity from the data. For users of Seurat v1.4, this was implemented in RegressOut. However, as the results of this procedure are stored in the scaled data slot (therefore overwriting the output of ScaleData()), we now merge this functionality into the ScaleData() function itself.For each gene, Seurat models the relationship between gene expression and the S and G2M cell cycle scores. The scaled residuals of this model represent a ‘corrected’ expression matrix, that can be used downstream for dimensional reduction. marrow <- ScaleData(marrow, vars.to.regress = c("S.Score", "G2M.Score"), features = rownames(marrow)) # Now, a PCA on the variable genes no longer returns components associated with cell cycle marrow <- RunPCA(marrow, features = VariableFeatures(marrow), nfeatures.print = 10)## PC_ 1 ## Positive: BLVRB, CAR2, KLF1, AQP1, CES2G, ERMAP, CAR1, FAM132A, RHD, SPHK1 ## Negative: TMSB4X, H2AFY, CORO1A, PLAC8, EMB, MPO, PRTN3, CD34, LCP1, BC035044 ## PC_ 2 ## Positive: ANGPT1, ADGRG1, MEIS1, ITGA2B, MPL, DAPP1, APOE, RAB37, GATA2, F2R ## Negative: LY6C2, ELANE, HP, IGSF6, ANXA3, CTSG, CLEC12A, TIFAB, SLPI, ALAS1 ## PC_ 3 ## Positive: APOE, GATA2, NKG7, MUC13, MS4A3, RAB44, HDC, CPA3, FCGR3, TUBA8 ## Negative: FLT3, DNTT, LSP1, WFDC17, MYL10, GIMAP6, LAX1, GPR171, TBXA2R, SATB1 ## PC_ 4 ## Positive: CSRP3, ST8SIA6, DNTT, MPEG1, SCIN, LGALS1, CMAH, RGL1, APOE, MFSD2B ## Negative: PROCR, MPL, HLF, MMRN1, SERPINA3G, ESAM, GSTM1, D630039A03RIK, MYL10, LY6A ## PC_ 5 ## Positive: PF4, GP1BB, SDPR, F2RL2, RAB27B, SLC14A1, TREML1, PBX1, F2R, TUBA8 ## Negative: CPA3, LMO4, IKZF2, IFITM1, FUT8, MS4A2, SIGLECF, CSRP3, HDC, RAB44 # When running a PCA on only cell cycle genes, cells no longer separate by cell-cycle phase marrow <- RunPCA(marrow, features = c(s.genes, g2m.genes)) DimPlot(marrow)As the best cell cycle markers are extremely well conserved across tissues and species, we have found this procedure to work robustly and reliably on diverse datasets.Alternate WorkflowThe procedure above removes all signal associated with cell cycle. In some cases, we’ve found that this can negatively impact downstream analysis, particularly in differentiating processes (like murine hematopoiesis), where stem cells are quiescent and differentiated cells are proliferating (or vice versa). In this case, regressing out all cell cycle effects can blur the distinction between stem and progenitor cells as well.As an alternative, we suggest regressing out the difference between the G2M and S phase scores. This means that signals separating non-cycling cells and cycling cells will be maintained, but differences in cell cycle phase among proliferating cells (which are often uninteresting), will be regressed out of the data marrow$CC.Difference <- marrow$S.Score - marrow$G2M.Score marrow <- ScaleData(marrow, vars.to.regress = "CC.Difference", features = rownames(marrow)) # cell cycle effects strongly mitigated in PCA marrow <- RunPCA(marrow, features = VariableFeatures(marrow), nfeatures.print = 10)## PC_ 1 ## Positive: BLVRB, KLF1, ERMAP, FAM132A, CAR2, RHD, CES2G, SPHK1, AQP1, SLC38A5 ## Negative: TMSB4X, CORO1A, PLAC8, H2AFY, LAPTM5, CD34, LCP1, TMEM176B, IGFBP4, EMB ## PC_ 2 ## Positive: APOE, GATA2, RAB37, ANGPT1, ADGRG1, MEIS1, MPL, F2R, PDZK1IP1, DAPP1 ## Negative: CTSG, ELANE, LY6C2, HP, CLEC12A, ANXA3, IGSF6, TIFAB, SLPI, MPO ## PC_ 3 ## Positive: APOE, GATA2, NKG7, MUC13, ITGA2B, TUBA8, CPA3, RAB44, SLC18A2, CD9 ## Negative: DNTT, FLT3, WFDC17, LSP1, MYL10, LAX1, GIMAP6, IGHM, CD24A, MN1 ## PC_ 4 ## Positive: CSRP3, ST8SIA6, SCIN, LGALS1, APOE, ITGB7, MFSD2B, RGL1, DNTT, IGHV1-23 ## Negative: MPL, MMRN1, PROCR, HLF, SERPINA3G, ESAM, PTGS1, D630039A03RIK, NDN, PPIC ## PC_ 5 ## Positive: HDC, LMO4, CSRP3, IFITM1, FCGR3, HLF, CPA3, PROCR, PGLYRP1, IKZF2 ## Negative: GP1BB, PF4, SDPR, F2RL2, TREML1, RAB27B, SLC14A1, PBX1, PLEK, TUBA8 # when running a PCA on cell cycle genes, actively proliferating cells remain distinct from G1 # cells however, within actively proliferating cells, G2M and S phase cells group together marrow <- RunPCA(marrow, features = c(s.genes, g2m.genes)) DimPlot(marrow)Session Info sessionInfo()## R version 4.2.0 (2022-04-22) ## Platform: x86_64-pc-linux-gnu (64-bit) ## Running under: Ubuntu 20.04.5 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/liblapack.so.3 ## ## locale: ## [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C ## [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8 ## [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 ## ## attached base packages: ## [1] stats graphics grDevices utils datasets methods base ## ## other attached packages: ## [1] ggplot2_3.4.1 SeuratObject_4.1.3 Seurat_4.3.0 ## ## loaded via a namespace (and not attached): ## [1] Rtsne_0.16 colorspace_2.1-0 deldir_1.0-6 ## [4] ellipsis_0.3.2 ggridges_0.5.4 rprojroot_2.0.3 ## [7] fs_1.6.1 spatstat.data_3.0-0 farver_2.1.1 ## [10] leiden_0.4.3 listenv_0.9.0 ggrepel_0.9.3 ## [13] fansi_1.0.4 codetools_0.2-18 splines_4.2.0 ## [16] cachem_1.0.7 knitr_1.42 polyclip_1.10-4 ## [19] jsonlite_1.8.4 ica_1.0-3 cluster_2.1.3 ## [22] png_0.1-8 uwot_0.1.14 spatstat.sparse_3.0-0 ## [25] shiny_1.7.4 sctransform_0.3.5 compiler_4.2.0 ## [28] httr_1.4.5 Matrix_1.5-3 fastmap_1.1.1 ## [31] lazyeval_0.2.2 cli_3.6.0 later_1.3.0 ## [34] formatR_1.14 htmltools_0.5.4 tools_4.2.0 ## [37] igraph_1.4.1 gtable_0.3.1 glue_1.6.2 ## [40] RANN_2.6.1 reshape2_1.4.4 dplyr_1.1.0 ## [43] Rcpp_1.0.10 scattermore_0.8 jquerylib_0.1.4 ## [46] pkgdown_2.0.7 vctrs_0.5.2 nlme_3.1-157 ## [49] spatstat.explore_3.0-6 progressr_0.13.0 lmtest_0.9-40 ## [52] spatstat.random_3.1-3 xfun_0.37 stringr_1.5.0 ## [55] globals_0.16.2 mime_0.12 miniUI_0.1.1.1 ## [58] lifecycle_1.0.3 irlba_2.3.5.1 goftest_1.2-3 ## [61] future_1.31.0 MASS_7.3-56 zoo_1.8-11 ## [64] scales_1.2.1 ragg_1.2.5 promises_1.2.0.1 ## [67] spatstat.utils_3.0-1 parallel_4.2.0 RColorBrewer_1.1-3 ## [70] yaml_2.3.7 memoise_2.0.1 reticulate_1.28 ## [73] pbapply_1.7-0 gridExtra_2.3 sass_0.4.5 ## [76] stringi_1.7.12 highr_0.10 desc_1.4.2 ## [79] rlang_1.0.6 pkgconfig_2.0.3 systemfonts_1.0.4 ## [82] matrixStats_0.63.0 evaluate_0.20 lattice_0.20-45 ## [85] tensor_1.5 ROCR_1.0-11 purrr_1.0.1 ## [88] labeling_0.4.2 patchwork_1.1.2 htmlwidgets_1.6.1 ## [91] cowplot_1.1.1 tidyselect_1.2.0 parallelly_1.34.0 ## [94] RcppAnnoy_0.0.20 plyr_1.8.8 magrittr_2.0.3 ## [97] R6_2.5.1 generics_0.1.3 withr_2.5.0 ## [100] pillar_1.8.1 fitdistrplus_1.1-8 abind_1.4-5 ## [103] survival_3.3-1 sp_1.6-0 tibble_3.1.8 ## [106] future.apply_1.10.0 KernSmooth_2.23-20 utf8_1.2.3 ## [109] spatstat.geom_3.0-6 plotly_4.10.1 rmarkdown_2.20 ## [112] grid_4.2.0 data.table_1.14.8 digest_0.6.31 ## [115] xtable_1.8-4 tidyr_1.3.0 httpuv_1.6.9 ## [118] textshaping_0.3.6 munsell_0.5.0 viridisLite_0.4.1 ## [121] bslib_0.4.2

First, we assign each cell a score, based on its expression of G2/M and S phase markers. These marker sets should be anticorrelated in their expression levels, and cells expressing neither are likely not cycling and in G1 phase.We assign scores in the CellCycleScoring() function, which stores S and G2/M scores in object meta data, along with the predicted classification of each cell in either G2M, S or G1 phase. CellCycleScoring() can also set the identity of the Seurat object to the cell-cycle phase by passing set.ident = TRUE (the original identities are stored as old.ident). Please note that Seurat does not use the discrete classifications (G2M/G1/S) in downstream cell cycle regression. Instead, it uses the quantitative scores for G2M and S phase. However, we provide our predicted classifications in case they are of interest. marrow <- CellCycleScoring(marrow, s.features = s.genes, g2m.features = g2m.genes, set.ident = TRUE) # view cell cycle scores and phase assignments head(marrow[[]])## orig.ident nCount_RNA nFeature_RNA S.Score G2M.Score Phase ## Prog_013 Prog 2563089 10211 -0.14248691 -0.4680395 G1 ## Prog_019 Prog 3030620 9991 -0.16915786 0.5851766 G2M ## Prog_031 Prog 1293487 10192 -0.34627038 -0.3971879 G1 ## Prog_037 Prog 1357987 9599 -0.44270212 0.6820229 G2M ## Prog_008 Prog 4079891 10540 0.55854051 0.1284359 S ## Prog_014 Prog 2569783 10788 0.07116218 0.3166073 G2M ## old.ident ## Prog_013 Prog ## Prog_019 Prog ## Prog_031 Prog ## Prog_037 Prog ## Prog_008 Prog ## Prog_014 Prog # Visualize the distribution of cell cycle markers across RidgePlot(marrow, features = c("PCNA", "TOP2A", "MCM6", "MKI67"), ncol = 2) # Running a PCA on cell cycle genes reveals, unsurprisingly, that cells separate entirely by # phase marrow <- RunPCA(marrow, features = c(s.genes, g2m.genes)) DimPlot(marrow)We score single cells based on the scoring strategy described in Tirosh et al. 2016. See ?AddModuleScore() in Seurat for more information, this function can be used to calculate supervised module scores for any gene list.

We assign scores in the CellCycleScoring() function, which stores S and G2/M scores in object meta data, along with the predicted classification of each cell in either G2M, S or G1 phase. CellCycleScoring() can also set the identity of the Seurat object to the cell-cycle phase by passing set.ident = TRUE (the original identities are stored as old.ident). Please note that Seurat does not use the discrete classifications (G2M/G1/S) in downstream cell cycle regression. Instead, it uses the quantitative scores for G2M and S phase. However, we provide our predicted classifications in case they are of interest. marrow <- CellCycleScoring(marrow, s.features = s.genes, g2m.features = g2m.genes, set.ident = TRUE) # view cell cycle scores and phase assignments head(marrow[[]])## orig.ident nCount_RNA nFeature_RNA S.Score G2M.Score Phase ## Prog_013 Prog 2563089 10211 -0.14248691 -0.4680395 G1 ## Prog_019 Prog 3030620 9991 -0.16915786 0.5851766 G2M ## Prog_031 Prog 1293487 10192 -0.34627038 -0.3971879 G1 ## Prog_037 Prog 1357987 9599 -0.44270212 0.6820229 G2M ## Prog_008 Prog 4079891 10540 0.55854051 0.1284359 S ## Prog_014 Prog 2569783 10788 0.07116218 0.3166073 G2M ## old.ident ## Prog_013 Prog ## Prog_019 Prog ## Prog_031 Prog ## Prog_037 Prog ## Prog_008 Prog ## Prog_014 Prog # Visualize the distribution of cell cycle markers across RidgePlot(marrow, features = c("PCNA", "TOP2A", "MCM6", "MKI67"), ncol = 2) # Running a PCA on cell cycle genes reveals, unsurprisingly, that cells separate entirely by # phase marrow <- RunPCA(marrow, features = c(s.genes, g2m.genes)) DimPlot(marrow)We score single cells based on the scoring strategy described in Tirosh et al. 2016. See ?AddModuleScore() in Seurat for more information, this function can be used to calculate supervised module scores for any gene list.

# Running a PCA on cell cycle genes reveals, unsurprisingly, that cells separate entirely by # phase marrow <- RunPCA(marrow, features = c(s.genes, g2m.genes)) DimPlot(marrow)We score single cells based on the scoring strategy described in Tirosh et al. 2016. See ?AddModuleScore() in Seurat for more information, this function can be used to calculate supervised module scores for any gene list.

We score single cells based on the scoring strategy described in Tirosh et al. 2016. See ?AddModuleScore() in Seurat for more information, this function can be used to calculate supervised module scores for any gene list.

We score single cells based on the scoring strategy described in Tirosh et al. 2016. See ?AddModuleScore() in Seurat for more information, this function can be used to calculate supervised module scores for any gene list.

We now attempt to subtract (‘regress out’) this source of heterogeneity from the data. For users of Seurat v1.4, this was implemented in RegressOut. However, as the results of this procedure are stored in the scaled data slot (therefore overwriting the output of ScaleData()), we now merge this functionality into the ScaleData() function itself.For each gene, Seurat models the relationship between gene expression and the S and G2M cell cycle scores. The scaled residuals of this model represent a ‘corrected’ expression matrix, that can be used downstream for dimensional reduction. marrow <- ScaleData(marrow, vars.to.regress = c("S.Score", "G2M.Score"), features = rownames(marrow)) # Now, a PCA on the variable genes no longer returns components associated with cell cycle marrow <- RunPCA(marrow, features = VariableFeatures(marrow), nfeatures.print = 10)## PC_ 1 ## Positive: BLVRB, CAR2, KLF1, AQP1, CES2G, ERMAP, CAR1, FAM132A, RHD, SPHK1 ## Negative: TMSB4X, H2AFY, CORO1A, PLAC8, EMB, MPO, PRTN3, CD34, LCP1, BC035044 ## PC_ 2 ## Positive: ANGPT1, ADGRG1, MEIS1, ITGA2B, MPL, DAPP1, APOE, RAB37, GATA2, F2R ## Negative: LY6C2, ELANE, HP, IGSF6, ANXA3, CTSG, CLEC12A, TIFAB, SLPI, ALAS1 ## PC_ 3 ## Positive: APOE, GATA2, NKG7, MUC13, MS4A3, RAB44, HDC, CPA3, FCGR3, TUBA8 ## Negative: FLT3, DNTT, LSP1, WFDC17, MYL10, GIMAP6, LAX1, GPR171, TBXA2R, SATB1 ## PC_ 4 ## Positive: CSRP3, ST8SIA6, DNTT, MPEG1, SCIN, LGALS1, CMAH, RGL1, APOE, MFSD2B ## Negative: PROCR, MPL, HLF, MMRN1, SERPINA3G, ESAM, GSTM1, D630039A03RIK, MYL10, LY6A ## PC_ 5 ## Positive: PF4, GP1BB, SDPR, F2RL2, RAB27B, SLC14A1, TREML1, PBX1, F2R, TUBA8 ## Negative: CPA3, LMO4, IKZF2, IFITM1, FUT8, MS4A2, SIGLECF, CSRP3, HDC, RAB44 # When running a PCA on only cell cycle genes, cells no longer separate by cell-cycle phase marrow <- RunPCA(marrow, features = c(s.genes, g2m.genes)) DimPlot(marrow)As the best cell cycle markers are extremely well conserved across tissues and species, we have found this procedure to work robustly and reliably on diverse datasets.

For each gene, Seurat models the relationship between gene expression and the S and G2M cell cycle scores. The scaled residuals of this model represent a ‘corrected’ expression matrix, that can be used downstream for dimensional reduction. marrow <- ScaleData(marrow, vars.to.regress = c("S.Score", "G2M.Score"), features = rownames(marrow)) # Now, a PCA on the variable genes no longer returns components associated with cell cycle marrow <- RunPCA(marrow, features = VariableFeatures(marrow), nfeatures.print = 10)## PC_ 1 ## Positive: BLVRB, CAR2, KLF1, AQP1, CES2G, ERMAP, CAR1, FAM132A, RHD, SPHK1 ## Negative: TMSB4X, H2AFY, CORO1A, PLAC8, EMB, MPO, PRTN3, CD34, LCP1, BC035044 ## PC_ 2 ## Positive: ANGPT1, ADGRG1, MEIS1, ITGA2B, MPL, DAPP1, APOE, RAB37, GATA2, F2R ## Negative: LY6C2, ELANE, HP, IGSF6, ANXA3, CTSG, CLEC12A, TIFAB, SLPI, ALAS1 ## PC_ 3 ## Positive: APOE, GATA2, NKG7, MUC13, MS4A3, RAB44, HDC, CPA3, FCGR3, TUBA8 ## Negative: FLT3, DNTT, LSP1, WFDC17, MYL10, GIMAP6, LAX1, GPR171, TBXA2R, SATB1 ## PC_ 4 ## Positive: CSRP3, ST8SIA6, DNTT, MPEG1, SCIN, LGALS1, CMAH, RGL1, APOE, MFSD2B ## Negative: PROCR, MPL, HLF, MMRN1, SERPINA3G, ESAM, GSTM1, D630039A03RIK, MYL10, LY6A ## PC_ 5 ## Positive: PF4, GP1BB, SDPR, F2RL2, RAB27B, SLC14A1, TREML1, PBX1, F2R, TUBA8 ## Negative: CPA3, LMO4, IKZF2, IFITM1, FUT8, MS4A2, SIGLECF, CSRP3, HDC, RAB44 # When running a PCA on only cell cycle genes, cells no longer separate by cell-cycle phase marrow <- RunPCA(marrow, features = c(s.genes, g2m.genes)) DimPlot(marrow)As the best cell cycle markers are extremely well conserved across tissues and species, we have found this procedure to work robustly and reliably on diverse datasets.

As the best cell cycle markers are extremely well conserved across tissues and species, we have found this procedure to work robustly and reliably on diverse datasets.

As the best cell cycle markers are extremely well conserved across tissues and species, we have found this procedure to work robustly and reliably on diverse datasets.

The procedure above removes all signal associated with cell cycle. In some cases, we’ve found that this can negatively impact downstream analysis, particularly in differentiating processes (like murine hematopoiesis), where stem cells are quiescent and differentiated cells are proliferating (or vice versa). In this case, regressing out all cell cycle effects can blur the distinction between stem and progenitor cells as well.As an alternative, we suggest regressing out the difference between the G2M and S phase scores. This means that signals separating non-cycling cells and cycling cells will be maintained, but differences in cell cycle phase among proliferating cells (which are often uninteresting), will be regressed out of the data marrow$CC.Difference <- marrow$S.Score - marrow$G2M.Score marrow <- ScaleData(marrow, vars.to.regress = "CC.Difference", features = rownames(marrow)) # cell cycle effects strongly mitigated in PCA marrow <- RunPCA(marrow, features = VariableFeatures(marrow), nfeatures.print = 10)## PC_ 1 ## Positive: BLVRB, KLF1, ERMAP, FAM132A, CAR2, RHD, CES2G, SPHK1, AQP1, SLC38A5 ## Negative: TMSB4X, CORO1A, PLAC8, H2AFY, LAPTM5, CD34, LCP1, TMEM176B, IGFBP4, EMB ## PC_ 2 ## Positive: APOE, GATA2, RAB37, ANGPT1, ADGRG1, MEIS1, MPL, F2R, PDZK1IP1, DAPP1 ## Negative: CTSG, ELANE, LY6C2, HP, CLEC12A, ANXA3, IGSF6, TIFAB, SLPI, MPO ## PC_ 3 ## Positive: APOE, GATA2, NKG7, MUC13, ITGA2B, TUBA8, CPA3, RAB44, SLC18A2, CD9 ## Negative: DNTT, FLT3, WFDC17, LSP1, MYL10, LAX1, GIMAP6, IGHM, CD24A, MN1 ## PC_ 4 ## Positive: CSRP3, ST8SIA6, SCIN, LGALS1, APOE, ITGB7, MFSD2B, RGL1, DNTT, IGHV1-23 ## Negative: MPL, MMRN1, PROCR, HLF, SERPINA3G, ESAM, PTGS1, D630039A03RIK, NDN, PPIC ## PC_ 5 ## Positive: HDC, LMO4, CSRP3, IFITM1, FCGR3, HLF, CPA3, PROCR, PGLYRP1, IKZF2 ## Negative: GP1BB, PF4, SDPR, F2RL2, TREML1, RAB27B, SLC14A1, PBX1, PLEK, TUBA8 # when running a PCA on cell cycle genes, actively proliferating cells remain distinct from G1 # cells however, within actively proliferating cells, G2M and S phase cells group together marrow <- RunPCA(marrow, features = c(s.genes, g2m.genes)) DimPlot(marrow)Session Info sessionInfo()## R version 4.2.0 (2022-04-22) ## Platform: x86_64-pc-linux-gnu (64-bit) ## Running under: Ubuntu 20.04.5 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/liblapack.so.3 ## ## locale: ## [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C ## [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8 ## [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 ## ## attached base packages: ## [1] stats graphics grDevices utils datasets methods base ## ## other attached packages: ## [1] ggplot2_3.4.1 SeuratObject_4.1.3 Seurat_4.3.0 ## ## loaded via a namespace (and not attached): ## [1] Rtsne_0.16 colorspace_2.1-0 deldir_1.0-6 ## [4] ellipsis_0.3.2 ggridges_0.5.4 rprojroot_2.0.3 ## [7] fs_1.6.1 spatstat.data_3.0-0 farver_2.1.1 ## [10] leiden_0.4.3 listenv_0.9.0 ggrepel_0.9.3 ## [13] fansi_1.0.4 codetools_0.2-18 splines_4.2.0 ## [16] cachem_1.0.7 knitr_1.42 polyclip_1.10-4 ## [19] jsonlite_1.8.4 ica_1.0-3 cluster_2.1.3 ## [22] png_0.1-8 uwot_0.1.14 spatstat.sparse_3.0-0 ## [25] shiny_1.7.4 sctransform_0.3.5 compiler_4.2.0 ## [28] httr_1.4.5 Matrix_1.5-3 fastmap_1.1.1 ## [31] lazyeval_0.2.2 cli_3.6.0 later_1.3.0 ## [34] formatR_1.14 htmltools_0.5.4 tools_4.2.0 ## [37] igraph_1.4.1 gtable_0.3.1 glue_1.6.2 ## [40] RANN_2.6.1 reshape2_1.4.4 dplyr_1.1.0 ## [43] Rcpp_1.0.10 scattermore_0.8 jquerylib_0.1.4 ## [46] pkgdown_2.0.7 vctrs_0.5.2 nlme_3.1-157 ## [49] spatstat.explore_3.0-6 progressr_0.13.0 lmtest_0.9-40 ## [52] spatstat.random_3.1-3 xfun_0.37 stringr_1.5.0 ## [55] globals_0.16.2 mime_0.12 miniUI_0.1.1.1 ## [58] lifecycle_1.0.3 irlba_2.3.5.1 goftest_1.2-3 ## [61] future_1.31.0 MASS_7.3-56 zoo_1.8-11 ## [64] scales_1.2.1 ragg_1.2.5 promises_1.2.0.1 ## [67] spatstat.utils_3.0-1 parallel_4.2.0 RColorBrewer_1.1-3 ## [70] yaml_2.3.7 memoise_2.0.1 reticulate_1.28 ## [73] pbapply_1.7-0 gridExtra_2.3 sass_0.4.5 ## [76] stringi_1.7.12 highr_0.10 desc_1.4.2 ## [79] rlang_1.0.6 pkgconfig_2.0.3 systemfonts_1.0.4 ## [82] matrixStats_0.63.0 evaluate_0.20 lattice_0.20-45 ## [85] tensor_1.5 ROCR_1.0-11 purrr_1.0.1 ## [88] labeling_0.4.2 patchwork_1.1.2 htmlwidgets_1.6.1 ## [91] cowplot_1.1.1 tidyselect_1.2.0 parallelly_1.34.0 ## [94] RcppAnnoy_0.0.20 plyr_1.8.8 magrittr_2.0.3 ## [97] R6_2.5.1 generics_0.1.3 withr_2.5.0 ## [100] pillar_1.8.1 fitdistrplus_1.1-8 abind_1.4-5 ## [103] survival_3.3-1 sp_1.6-0 tibble_3.1.8 ## [106] future.apply_1.10.0 KernSmooth_2.23-20 utf8_1.2.3 ## [109] spatstat.geom_3.0-6 plotly_4.10.1 rmarkdown_2.20 ## [112] grid_4.2.0 data.table_1.14.8 digest_0.6.31 ## [115] xtable_1.8-4 tidyr_1.3.0 httpuv_1.6.9 ## [118] textshaping_0.3.6 munsell_0.5.0 viridisLite_0.4.1 ## [121] bslib_0.4.2

As an alternative, we suggest regressing out the difference between the G2M and S phase scores. This means that signals separating non-cycling cells and cycling cells will be maintained, but differences in cell cycle phase among proliferating cells (which are often uninteresting), will be regressed out of the data marrow$CC.Difference <- marrow$S.Score - marrow$G2M.Score marrow <- ScaleData(marrow, vars.to.regress = "CC.Difference", features = rownames(marrow)) # cell cycle effects strongly mitigated in PCA marrow <- RunPCA(marrow, features = VariableFeatures(marrow), nfeatures.print = 10)## PC_ 1 ## Positive: BLVRB, KLF1, ERMAP, FAM132A, CAR2, RHD, CES2G, SPHK1, AQP1, SLC38A5 ## Negative: TMSB4X, CORO1A, PLAC8, H2AFY, LAPTM5, CD34, LCP1, TMEM176B, IGFBP4, EMB ## PC_ 2 ## Positive: APOE, GATA2, RAB37, ANGPT1, ADGRG1, MEIS1, MPL, F2R, PDZK1IP1, DAPP1 ## Negative: CTSG, ELANE, LY6C2, HP, CLEC12A, ANXA3, IGSF6, TIFAB, SLPI, MPO ## PC_ 3 ## Positive: APOE, GATA2, NKG7, MUC13, ITGA2B, TUBA8, CPA3, RAB44, SLC18A2, CD9 ## Negative: DNTT, FLT3, WFDC17, LSP1, MYL10, LAX1, GIMAP6, IGHM, CD24A, MN1 ## PC_ 4 ## Positive: CSRP3, ST8SIA6, SCIN, LGALS1, APOE, ITGB7, MFSD2B, RGL1, DNTT, IGHV1-23 ## Negative: MPL, MMRN1, PROCR, HLF, SERPINA3G, ESAM, PTGS1, D630039A03RIK, NDN, PPIC ## PC_ 5 ## Positive: HDC, LMO4, CSRP3, IFITM1, FCGR3, HLF, CPA3, PROCR, PGLYRP1, IKZF2 ## Negative: GP1BB, PF4, SDPR, F2RL2, TREML1, RAB27B, SLC14A1, PBX1, PLEK, TUBA8 # when running a PCA on cell cycle genes, actively proliferating cells remain distinct from G1 # cells however, within actively proliferating cells, G2M and S phase cells group together marrow <- RunPCA(marrow, features = c(s.genes, g2m.genes)) DimPlot(marrow)Session Info sessionInfo()## R version 4.2.0 (2022-04-22) ## Platform: x86_64-pc-linux-gnu (64-bit) ## Running under: Ubuntu 20.04.5 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/liblapack.so.3 ## ## locale: ## [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C ## [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8 ## [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 ## ## attached base packages: ## [1] stats graphics grDevices utils datasets methods base ## ## other attached packages: ## [1] ggplot2_3.4.1 SeuratObject_4.1.3 Seurat_4.3.0 ## ## loaded via a namespace (and not attached): ## [1] Rtsne_0.16 colorspace_2.1-0 deldir_1.0-6 ## [4] ellipsis_0.3.2 ggridges_0.5.4 rprojroot_2.0.3 ## [7] fs_1.6.1 spatstat.data_3.0-0 farver_2.1.1 ## [10] leiden_0.4.3 listenv_0.9.0 ggrepel_0.9.3 ## [13] fansi_1.0.4 codetools_0.2-18 splines_4.2.0 ## [16] cachem_1.0.7 knitr_1.42 polyclip_1.10-4 ## [19] jsonlite_1.8.4 ica_1.0-3 cluster_2.1.3 ## [22] png_0.1-8 uwot_0.1.14 spatstat.sparse_3.0-0 ## [25] shiny_1.7.4 sctransform_0.3.5 compiler_4.2.0 ## [28] httr_1.4.5 Matrix_1.5-3 fastmap_1.1.1 ## [31] lazyeval_0.2.2 cli_3.6.0 later_1.3.0 ## [34] formatR_1.14 htmltools_0.5.4 tools_4.2.0 ## [37] igraph_1.4.1 gtable_0.3.1 glue_1.6.2 ## [40] RANN_2.6.1 reshape2_1.4.4 dplyr_1.1.0 ## [43] Rcpp_1.0.10 scattermore_0.8 jquerylib_0.1.4 ## [46] pkgdown_2.0.7 vctrs_0.5.2 nlme_3.1-157 ## [49] spatstat.explore_3.0-6 progressr_0.13.0 lmtest_0.9-40 ## [52] spatstat.random_3.1-3 xfun_0.37 stringr_1.5.0 ## [55] globals_0.16.2 mime_0.12 miniUI_0.1.1.1 ## [58] lifecycle_1.0.3 irlba_2.3.5.1 goftest_1.2-3 ## [61] future_1.31.0 MASS_7.3-56 zoo_1.8-11 ## [64] scales_1.2.1 ragg_1.2.5 promises_1.2.0.1 ## [67] spatstat.utils_3.0-1 parallel_4.2.0 RColorBrewer_1.1-3 ## [70] yaml_2.3.7 memoise_2.0.1 reticulate_1.28 ## [73] pbapply_1.7-0 gridExtra_2.3 sass_0.4.5 ## [76] stringi_1.7.12 highr_0.10 desc_1.4.2 ## [79] rlang_1.0.6 pkgconfig_2.0.3 systemfonts_1.0.4 ## [82] matrixStats_0.63.0 evaluate_0.20 lattice_0.20-45 ## [85] tensor_1.5 ROCR_1.0-11 purrr_1.0.1 ## [88] labeling_0.4.2 patchwork_1.1.2 htmlwidgets_1.6.1 ## [91] cowplot_1.1.1 tidyselect_1.2.0 parallelly_1.34.0 ## [94] RcppAnnoy_0.0.20 plyr_1.8.8 magrittr_2.0.3 ## [97] R6_2.5.1 generics_0.1.3 withr_2.5.0 ## [100] pillar_1.8.1 fitdistrplus_1.1-8 abind_1.4-5 ## [103] survival_3.3-1 sp_1.6-0 tibble_3.1.8 ## [106] future.apply_1.10.0 KernSmooth_2.23-20 utf8_1.2.3 ## [109] spatstat.geom_3.0-6 plotly_4.10.1 rmarkdown_2.20 ## [112] grid_4.2.0 data.table_1.14.8 digest_0.6.31 ## [115] xtable_1.8-4 tidyr_1.3.0 httpuv_1.6.9 ## [118] textshaping_0.3.6 munsell_0.5.0 viridisLite_0.4.1 ## [121] bslib_0.4.2

Session Info sessionInfo()## R version 4.2.0 (2022-04-22) ## Platform: x86_64-pc-linux-gnu (64-bit) ## Running under: Ubuntu 20.04.5 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/liblapack.so.3 ## ## locale: ## [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C ## [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8 ## [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 ## ## attached base packages: ## [1] stats graphics grDevices utils datasets methods base ## ## other attached packages: ## [1] ggplot2_3.4.1 SeuratObject_4.1.3 Seurat_4.3.0 ## ## loaded via a namespace (and not attached): ## [1] Rtsne_0.16 colorspace_2.1-0 deldir_1.0-6 ## [4] ellipsis_0.3.2 ggridges_0.5.4 rprojroot_2.0.3 ## [7] fs_1.6.1 spatstat.data_3.0-0 farver_2.1.1 ## [10] leiden_0.4.3 listenv_0.9.0 ggrepel_0.9.3 ## [13] fansi_1.0.4 codetools_0.2-18 splines_4.2.0 ## [16] cachem_1.0.7 knitr_1.42 polyclip_1.10-4 ## [19] jsonlite_1.8.4 ica_1.0-3 cluster_2.1.3 ## [22] png_0.1-8 uwot_0.1.14 spatstat.sparse_3.0-0 ## [25] shiny_1.7.4 sctransform_0.3.5 compiler_4.2.0 ## [28] httr_1.4.5 Matrix_1.5-3 fastmap_1.1.1 ## [31] lazyeval_0.2.2 cli_3.6.0 later_1.3.0 ## [34] formatR_1.14 htmltools_0.5.4 tools_4.2.0 ## [37] igraph_1.4.1 gtable_0.3.1 glue_1.6.2 ## [40] RANN_2.6.1 reshape2_1.4.4 dplyr_1.1.0 ## [43] Rcpp_1.0.10 scattermore_0.8 jquerylib_0.1.4 ## [46] pkgdown_2.0.7 vctrs_0.5.2 nlme_3.1-157 ## [49] spatstat.explore_3.0-6 progressr_0.13.0 lmtest_0.9-40 ## [52] spatstat.random_3.1-3 xfun_0.37 stringr_1.5.0 ## [55] globals_0.16.2 mime_0.12 miniUI_0.1.1.1 ## [58] lifecycle_1.0.3 irlba_2.3.5.1 goftest_1.2-3 ## [61] future_1.31.0 MASS_7.3-56 zoo_1.8-11 ## [64] scales_1.2.1 ragg_1.2.5 promises_1.2.0.1 ## [67] spatstat.utils_3.0-1 parallel_4.2.0 RColorBrewer_1.1-3 ## [70] yaml_2.3.7 memoise_2.0.1 reticulate_1.28 ## [73] pbapply_1.7-0 gridExtra_2.3 sass_0.4.5 ## [76] stringi_1.7.12 highr_0.10 desc_1.4.2 ## [79] rlang_1.0.6 pkgconfig_2.0.3 systemfonts_1.0.4 ## [82] matrixStats_0.63.0 evaluate_0.20 lattice_0.20-45 ## [85] tensor_1.5 ROCR_1.0-11 purrr_1.0.1 ## [88] labeling_0.4.2 patchwork_1.1.2 htmlwidgets_1.6.1 ## [91] cowplot_1.1.1 tidyselect_1.2.0 parallelly_1.34.0 ## [94] RcppAnnoy_0.0.20 plyr_1.8.8 magrittr_2.0.3 ## [97] R6_2.5.1 generics_0.1.3 withr_2.5.0 ## [100] pillar_1.8.1 fitdistrplus_1.1-8 abind_1.4-5 ## [103] survival_3.3-1 sp_1.6-0 tibble_3.1.8 ## [106] future.apply_1.10.0 KernSmooth_2.23-20 utf8_1.2.3 ## [109] spatstat.geom_3.0-6 plotly_4.10.1 rmarkdown_2.20 ## [112] grid_4.2.0 data.table_1.14.8 digest_0.6.31 ## [115] xtable_1.8-4 tidyr_1.3.0 httpuv_1.6.9 ## [118] textshaping_0.3.6 munsell_0.5.0 viridisLite_0.4.1 ## [121] bslib_0.4.2

sessionInfo()## R version 4.2.0 (2022-04-22) ## Platform: x86_64-pc-linux-gnu (64-bit) ## Running under: Ubuntu 20.04.5 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/liblapack.so.3 ## ## locale: ## [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C ## [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8 ## [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 ## ## attached base packages: ## [1] stats graphics grDevices utils datasets methods base ## ## other attached packages: ## [1] ggplot2_3.4.1 SeuratObject_4.1.3 Seurat_4.3.0 ## ## loaded via a namespace (and not attached): ## [1] Rtsne_0.16 colorspace_2.1-0 deldir_1.0-6 ## [4] ellipsis_0.3.2 ggridges_0.5.4 rprojroot_2.0.3 ## [7] fs_1.6.1 spatstat.data_3.0-0 farver_2.1.1 ## [10] leiden_0.4.3 listenv_0.9.0 ggrepel_0.9.3 ## [13] fansi_1.0.4 codetools_0.2-18 splines_4.2.0 ## [16] cachem_1.0.7 knitr_1.42 polyclip_1.10-4 ## [19] jsonlite_1.8.4 ica_1.0-3 cluster_2.1.3 ## [22] png_0.1-8 uwot_0.1.14 spatstat.sparse_3.0-0 ## [25] shiny_1.7.4 sctransform_0.3.5 compiler_4.2.0 ## [28] httr_1.4.5 Matrix_1.5-3 fastmap_1.1.1 ## [31] lazyeval_0.2.2 cli_3.6.0 later_1.3.0 ## [34] formatR_1.14 htmltools_0.5.4 tools_4.2.0 ## [37] igraph_1.4.1 gtable_0.3.1 glue_1.6.2 ## [40] RANN_2.6.1 reshape2_1.4.4 dplyr_1.1.0 ## [43] Rcpp_1.0.10 scattermore_0.8 jquerylib_0.1.4 ## [46] pkgdown_2.0.7 vctrs_0.5.2 nlme_3.1-157 ## [49] spatstat.explore_3.0-6 progressr_0.13.0 lmtest_0.9-40 ## [52] spatstat.random_3.1-3 xfun_0.37 stringr_1.5.0 ## [55] globals_0.16.2 mime_0.12 miniUI_0.1.1.1 ## [58] lifecycle_1.0.3 irlba_2.3.5.1 goftest_1.2-3 ## [61] future_1.31.0 MASS_7.3-56 zoo_1.8-11 ## [64] scales_1.2.1 ragg_1.2.5 promises_1.2.0.1 ## [67] spatstat.utils_3.0-1 parallel_4.2.0 RColorBrewer_1.1-3 ## [70] yaml_2.3.7 memoise_2.0.1 reticulate_1.28 ## [73] pbapply_1.7-0 gridExtra_2.3 sass_0.4.5 ## [76] stringi_1.7.12 highr_0.10 desc_1.4.2 ## [79] rlang_1.0.6 pkgconfig_2.0.3 systemfonts_1.0.4 ## [82] matrixStats_0.63.0 evaluate_0.20 lattice_0.20-45 ## [85] tensor_1.5 ROCR_1.0-11 purrr_1.0.1 ## [88] labeling_0.4.2 patchwork_1.1.2 htmlwidgets_1.6.1 ## [91] cowplot_1.1.1 tidyselect_1.2.0 parallelly_1.34.0 ## [94] RcppAnnoy_0.0.20 plyr_1.8.8 magrittr_2.0.3 ## [97] R6_2.5.1 generics_0.1.3 withr_2.5.0 ## [100] pillar_1.8.1 fitdistrplus_1.1-8 abind_1.4-5 ## [103] survival_3.3-1 sp_1.6-0 tibble_3.1.8 ## [106] future.apply_1.10.0 KernSmooth_2.23-20 utf8_1.2.3 ## [109] spatstat.geom_3.0-6 plotly_4.10.1 rmarkdown_2.20 ## [112] grid_4.2.0 data.table_1.14.8 digest_0.6.31 ## [115] xtable_1.8-4 tidyr_1.3.0 httpuv_1.6.9 ## [118] textshaping_0.3.6 munsell_0.5.0 viridisLite_0.4.1 ## [121] bslib_0.4.2

Developed by Paul Hoffman, Satija Lab and Collaborators.

Developed by Paul Hoffman, Satija Lab and Collaborators.

Site built with pkgdown 2.0.7.

Site built with pkgdown 2.0.7.

**Examples:**

Example 1 (unknown):
```unknown
vignettes/cell_cycle_vignette.Rmd
```

Example 2 (unknown):
```unknown
cell_cycle_vignette.Rmd
```

Example 3 (python):
```python
library(Seurat)

# Read in the expression matrix The first row is a header row, the first column is rownames
exp.mat <- read.table(file = "../data/nestorawa_forcellcycle_expressionMatrix.txt", header = TRUE,
    as.is = TRUE, row.names = 1)

# A list of cell cycle markers, from Tirosh et al, 2015, is loaded with Seurat.  We can
# segregate this list into markers of G2/M phase and markers of S phase
s.genes <- cc.genes$s.genes
g2m.genes <- cc.genes$g2m.genes

# Create our Seurat object and complete the initalization steps
marrow <- CreateSeuratObject(counts = exp.mat)
marrow <- NormalizeData(marrow)
marrow <- FindVariableFeatures(marrow, selection.method = "vst")
marrow <- ScaleData(marrow, features = rownames(marrow))
```

Example 4 (r):
```r
library(Seurat)

# Read in the expression matrix The first row is a header row, the first column is rownames
exp.mat <- read.table(file = "../data/nestorawa_forcellcycle_expressionMatrix.txt", header = TRUE,
    as.is = TRUE, row.names = 1)

# A list of cell cycle markers, from Tirosh et al, 2015, is loaded with Seurat.  We can
# segregate this list into markers of G2/M phase and markers of S phase
s.genes <- cc.genes$s.genes
g2m.genes <- cc.genes$g2m.genes

# Create our Seurat object and complete the initalization steps
marrow <- CreateSeuratObject(counts = exp.mat)
marrow <- NormalizeData(marrow)
marrow <- FindVariableFeatures(marrow, selection.method = "vst")
marrow <- ScaleData(marrow, features = rownames(marrow))
```

Example 5 (r):
```r
library(Seurat)

# Read in the expression matrix The first row is a header row, the first column is rownames
exp.mat <- read.table(file = "../data/nestorawa_forcellcycle_expressionMatrix.txt", header = TRUE,
    as.is = TRUE, row.names = 1)

# A list of cell cycle markers, from Tirosh et al, 2015, is loaded with Seurat.  We can
# segregate this list into markers of G2/M phase and markers of S phase
s.genes <- cc.genes$s.genes
g2m.genes <- cc.genes$g2m.genes

# Create our Seurat object and complete the initalization steps
marrow <- CreateSeuratObject(counts = exp.mat)
marrow <- NormalizeData(marrow)
marrow <- FindVariableFeatures(marrow, selection.method = "vst")
marrow <- ScaleData(marrow, features = rownames(marrow))
```

Example 6 (unknown):
```unknown
FindVariableFeatures()
```

Example 7 (unknown):
```unknown
marrow <- RunPCA(marrow, features = VariableFeatures(marrow), ndims.print = 6:10, nfeatures.print = 10)
```

Example 8 (r):
```r
marrow <- RunPCA(marrow, features = VariableFeatures(marrow), ndims.print = 6:10, nfeatures.print = 10)
```

Example 9 (r):
```r
marrow <- RunPCA(marrow, features = VariableFeatures(marrow), ndims.print = 6:10, nfeatures.print = 10)
```

Example 10 (unknown):
```unknown
## PC_ 6 
## Positive:  SELL, ARL6IP1, CCL9, CD34, ADGRL4, BPIFC, NUSAP1, FAM64A, CD244, C030034L19RIK 
## Negative:  LY6C2, AA467197, CYBB, MGST2, ITGB2, PF4, CD74, ATP1B1, GP1BB, TREM3 
## PC_ 7 
## Positive:  HDC, CPA3, PGLYRP1, MS4A3, NKG7, UBE2C, CCNB1, NUSAP1, PLK1, FUT8 
## Negative:  F13A1, LY86, CFP, IRF8, CSF1R, TIFAB, IFI209, CCR2, TNS4, MS4A6C 
## PC_ 8 
## Positive:  WFDC17, SLC35D3, ADGRL4, VLDLR, CD33, H2AFY, P2RY14, IFI206, CCL9, CD34 
## Negative:  NUSAP1, UBE2C, KIF23, PLK1, CENPF, FAM64A, CCNB1, H2AFX, ID2, CDC20 
## PC_ 9 
## Positive:  SLC2A6, HBA-A1, HBA-A2, IGHV8-7, FCER1G, F13A1, HBB-BS, PLD4, HBB-BT, IGFBP4 
## Negative:  IGKC, JCHAIN, LY6D, MZB1, CD74, IGLC2, FCRLA, IGKV4-50, IGHM, IGHV9-1 
## PC_ 10 
## Positive:  CTSW, XKRX, PRR5L, RORA, MBOAT4, A630014C17RIK, ZFP105, COL9A3, CLEC2I, TRAT1 
## Negative:  H2AFX, FAM64A, ZFP383, NUSAP1, CDC25B, CENPF, GBP10, TOP2A, GBP6, GFRA1
```

Example 11 (unknown):
```unknown
## PC_ 6 
## Positive:  SELL, ARL6IP1, CCL9, CD34, ADGRL4, BPIFC, NUSAP1, FAM64A, CD244, C030034L19RIK 
## Negative:  LY6C2, AA467197, CYBB, MGST2, ITGB2, PF4, CD74, ATP1B1, GP1BB, TREM3 
## PC_ 7 
## Positive:  HDC, CPA3, PGLYRP1, MS4A3, NKG7, UBE2C, CCNB1, NUSAP1, PLK1, FUT8 
## Negative:  F13A1, LY86, CFP, IRF8, CSF1R, TIFAB, IFI209, CCR2, TNS4, MS4A6C 
## PC_ 8 
## Positive:  WFDC17, SLC35D3, ADGRL4, VLDLR, CD33, H2AFY, P2RY14, IFI206, CCL9, CD34 
## Negative:  NUSAP1, UBE2C, KIF23, PLK1, CENPF, FAM64A, CCNB1, H2AFX, ID2, CDC20 
## PC_ 9 
## Positive:  SLC2A6, HBA-A1, HBA-A2, IGHV8-7, FCER1G, F13A1, HBB-BS, PLD4, HBB-BT, IGFBP4 
## Negative:  IGKC, JCHAIN, LY6D, MZB1, CD74, IGLC2, FCRLA, IGKV4-50, IGHM, IGHV9-1 
## PC_ 10 
## Positive:  CTSW, XKRX, PRR5L, RORA, MBOAT4, A630014C17RIK, ZFP105, COL9A3, CLEC2I, TRAT1 
## Negative:  H2AFX, FAM64A, ZFP383, NUSAP1, CDC25B, CENPF, GBP10, TOP2A, GBP6, GFRA1
```

Example 12 (unknown):
```unknown
DimHeatmap(marrow, dims = c(8, 10))
```

Example 13 (r):
```r
DimHeatmap(marrow, dims = c(8, 10))
```

Example 14 (r):
```r
DimHeatmap(marrow, dims = c(8, 10))
```

Example 15 (unknown):
```unknown
CellCycleScoring()
```

Example 16 (unknown):
```unknown
CellCycleScoring()
```

Example 17 (unknown):
```unknown
set.ident = TRUE
```

Example 18 (unknown):
```unknown
marrow <- CellCycleScoring(marrow, s.features = s.genes, g2m.features = g2m.genes, set.ident = TRUE)

# view cell cycle scores and phase assignments
head(marrow[[]])
```

Example 19 (r):
```r
marrow <- CellCycleScoring(marrow, s.features = s.genes, g2m.features = g2m.genes, set.ident = TRUE)

# view cell cycle scores and phase assignments
head(marrow[[]])
```

Example 20 (r):
```r
marrow <- CellCycleScoring(marrow, s.features = s.genes, g2m.features = g2m.genes, set.ident = TRUE)

# view cell cycle scores and phase assignments
head(marrow[[]])
```

Example 21 (unknown):
```unknown
##          orig.ident nCount_RNA nFeature_RNA     S.Score  G2M.Score Phase
## Prog_013       Prog    2563089        10211 -0.14248691 -0.4680395    G1
## Prog_019       Prog    3030620         9991 -0.16915786  0.5851766   G2M
## Prog_031       Prog    1293487        10192 -0.34627038 -0.3971879    G1
## Prog_037       Prog    1357987         9599 -0.44270212  0.6820229   G2M
## Prog_008       Prog    4079891        10540  0.55854051  0.1284359     S
## Prog_014       Prog    2569783        10788  0.07116218  0.3166073   G2M
##          old.ident
## Prog_013      Prog
## Prog_019      Prog
## Prog_031      Prog
## Prog_037      Prog
## Prog_008      Prog
## Prog_014      Prog
```

Example 22 (unknown):
```unknown
##          orig.ident nCount_RNA nFeature_RNA     S.Score  G2M.Score Phase
## Prog_013       Prog    2563089        10211 -0.14248691 -0.4680395    G1
## Prog_019       Prog    3030620         9991 -0.16915786  0.5851766   G2M
## Prog_031       Prog    1293487        10192 -0.34627038 -0.3971879    G1
## Prog_037       Prog    1357987         9599 -0.44270212  0.6820229   G2M
## Prog_008       Prog    4079891        10540  0.55854051  0.1284359     S
## Prog_014       Prog    2569783        10788  0.07116218  0.3166073   G2M
##          old.ident
## Prog_013      Prog
## Prog_019      Prog
## Prog_031      Prog
## Prog_037      Prog
## Prog_008      Prog
## Prog_014      Prog
```

Example 23 (unknown):
```unknown
# Visualize the distribution of cell cycle markers across
RidgePlot(marrow, features = c("PCNA", "TOP2A", "MCM6", "MKI67"), ncol = 2)
```

Example 24 (r):
```r
# Visualize the distribution of cell cycle markers across
RidgePlot(marrow, features = c("PCNA", "TOP2A", "MCM6", "MKI67"), ncol = 2)
```

Example 25 (r):
```r
# Visualize the distribution of cell cycle markers across
RidgePlot(marrow, features = c("PCNA", "TOP2A", "MCM6", "MKI67"), ncol = 2)
```

Example 26 (unknown):
```unknown
# Running a PCA on cell cycle genes reveals, unsurprisingly, that cells separate entirely by
# phase
marrow <- RunPCA(marrow, features = c(s.genes, g2m.genes))
DimPlot(marrow)
```

Example 27 (r):
```r
# Running a PCA on cell cycle genes reveals, unsurprisingly, that cells separate entirely by
# phase
marrow <- RunPCA(marrow, features = c(s.genes, g2m.genes))
DimPlot(marrow)
```

Example 28 (r):
```r
# Running a PCA on cell cycle genes reveals, unsurprisingly, that cells separate entirely by
# phase
marrow <- RunPCA(marrow, features = c(s.genes, g2m.genes))
DimPlot(marrow)
```

Example 29 (unknown):
```unknown
?AddModuleScore()
```

Example 30 (unknown):
```unknown
ScaleData()
```

Example 31 (unknown):
```unknown
ScaleData()
```

Example 32 (unknown):
```unknown
marrow <- ScaleData(marrow, vars.to.regress = c("S.Score", "G2M.Score"), features = rownames(marrow))
```

Example 33 (r):
```r
marrow <- ScaleData(marrow, vars.to.regress = c("S.Score", "G2M.Score"), features = rownames(marrow))
```

Example 34 (r):
```r
marrow <- ScaleData(marrow, vars.to.regress = c("S.Score", "G2M.Score"), features = rownames(marrow))
```

Example 35 (unknown):
```unknown
# Now, a PCA on the variable genes no longer returns components associated with cell cycle
marrow <- RunPCA(marrow, features = VariableFeatures(marrow), nfeatures.print = 10)
```

Example 36 (r):
```r
# Now, a PCA on the variable genes no longer returns components associated with cell cycle
marrow <- RunPCA(marrow, features = VariableFeatures(marrow), nfeatures.print = 10)
```

Example 37 (r):
```r
# Now, a PCA on the variable genes no longer returns components associated with cell cycle
marrow <- RunPCA(marrow, features = VariableFeatures(marrow), nfeatures.print = 10)
```

Example 38 (unknown):
```unknown
## PC_ 1 
## Positive:  BLVRB, CAR2, KLF1, AQP1, CES2G, ERMAP, CAR1, FAM132A, RHD, SPHK1 
## Negative:  TMSB4X, H2AFY, CORO1A, PLAC8, EMB, MPO, PRTN3, CD34, LCP1, BC035044 
## PC_ 2 
## Positive:  ANGPT1, ADGRG1, MEIS1, ITGA2B, MPL, DAPP1, APOE, RAB37, GATA2, F2R 
## Negative:  LY6C2, ELANE, HP, IGSF6, ANXA3, CTSG, CLEC12A, TIFAB, SLPI, ALAS1 
## PC_ 3 
## Positive:  APOE, GATA2, NKG7, MUC13, MS4A3, RAB44, HDC, CPA3, FCGR3, TUBA8 
## Negative:  FLT3, DNTT, LSP1, WFDC17, MYL10, GIMAP6, LAX1, GPR171, TBXA2R, SATB1 
## PC_ 4 
## Positive:  CSRP3, ST8SIA6, DNTT, MPEG1, SCIN, LGALS1, CMAH, RGL1, APOE, MFSD2B 
## Negative:  PROCR, MPL, HLF, MMRN1, SERPINA3G, ESAM, GSTM1, D630039A03RIK, MYL10, LY6A 
## PC_ 5 
## Positive:  PF4, GP1BB, SDPR, F2RL2, RAB27B, SLC14A1, TREML1, PBX1, F2R, TUBA8 
## Negative:  CPA3, LMO4, IKZF2, IFITM1, FUT8, MS4A2, SIGLECF, CSRP3, HDC, RAB44
```

Example 39 (unknown):
```unknown
## PC_ 1 
## Positive:  BLVRB, CAR2, KLF1, AQP1, CES2G, ERMAP, CAR1, FAM132A, RHD, SPHK1 
## Negative:  TMSB4X, H2AFY, CORO1A, PLAC8, EMB, MPO, PRTN3, CD34, LCP1, BC035044 
## PC_ 2 
## Positive:  ANGPT1, ADGRG1, MEIS1, ITGA2B, MPL, DAPP1, APOE, RAB37, GATA2, F2R 
## Negative:  LY6C2, ELANE, HP, IGSF6, ANXA3, CTSG, CLEC12A, TIFAB, SLPI, ALAS1 
## PC_ 3 
## Positive:  APOE, GATA2, NKG7, MUC13, MS4A3, RAB44, HDC, CPA3, FCGR3, TUBA8 
## Negative:  FLT3, DNTT, LSP1, WFDC17, MYL10, GIMAP6, LAX1, GPR171, TBXA2R, SATB1 
## PC_ 4 
## Positive:  CSRP3, ST8SIA6, DNTT, MPEG1, SCIN, LGALS1, CMAH, RGL1, APOE, MFSD2B 
## Negative:  PROCR, MPL, HLF, MMRN1, SERPINA3G, ESAM, GSTM1, D630039A03RIK, MYL10, LY6A 
## PC_ 5 
## Positive:  PF4, GP1BB, SDPR, F2RL2, RAB27B, SLC14A1, TREML1, PBX1, F2R, TUBA8 
## Negative:  CPA3, LMO4, IKZF2, IFITM1, FUT8, MS4A2, SIGLECF, CSRP3, HDC, RAB44
```

Example 40 (unknown):
```unknown
# When running a PCA on only cell cycle genes, cells no longer separate by cell-cycle phase
marrow <- RunPCA(marrow, features = c(s.genes, g2m.genes))
DimPlot(marrow)
```

Example 41 (r):
```r
# When running a PCA on only cell cycle genes, cells no longer separate by cell-cycle phase
marrow <- RunPCA(marrow, features = c(s.genes, g2m.genes))
DimPlot(marrow)
```

Example 42 (r):
```r
# When running a PCA on only cell cycle genes, cells no longer separate by cell-cycle phase
marrow <- RunPCA(marrow, features = c(s.genes, g2m.genes))
DimPlot(marrow)
```

Example 43 (unknown):
```unknown
marrow$CC.Difference <- marrow$S.Score - marrow$G2M.Score
marrow <- ScaleData(marrow, vars.to.regress = "CC.Difference", features = rownames(marrow))
```

Example 44 (r):
```r
marrow$CC.Difference <- marrow$S.Score - marrow$G2M.Score
marrow <- ScaleData(marrow, vars.to.regress = "CC.Difference", features = rownames(marrow))
```

Example 45 (r):
```r
marrow$CC.Difference <- marrow$S.Score - marrow$G2M.Score
marrow <- ScaleData(marrow, vars.to.regress = "CC.Difference", features = rownames(marrow))
```

Example 46 (unknown):
```unknown
# cell cycle effects strongly mitigated in PCA
marrow <- RunPCA(marrow, features = VariableFeatures(marrow), nfeatures.print = 10)
```

Example 47 (r):
```r
# cell cycle effects strongly mitigated in PCA
marrow <- RunPCA(marrow, features = VariableFeatures(marrow), nfeatures.print = 10)
```

Example 48 (r):
```r
# cell cycle effects strongly mitigated in PCA
marrow <- RunPCA(marrow, features = VariableFeatures(marrow), nfeatures.print = 10)
```

Example 49 (unknown):
```unknown
## PC_ 1 
## Positive:  BLVRB, KLF1, ERMAP, FAM132A, CAR2, RHD, CES2G, SPHK1, AQP1, SLC38A5 
## Negative:  TMSB4X, CORO1A, PLAC8, H2AFY, LAPTM5, CD34, LCP1, TMEM176B, IGFBP4, EMB 
## PC_ 2 
## Positive:  APOE, GATA2, RAB37, ANGPT1, ADGRG1, MEIS1, MPL, F2R, PDZK1IP1, DAPP1 
## Negative:  CTSG, ELANE, LY6C2, HP, CLEC12A, ANXA3, IGSF6, TIFAB, SLPI, MPO 
## PC_ 3 
## Positive:  APOE, GATA2, NKG7, MUC13, ITGA2B, TUBA8, CPA3, RAB44, SLC18A2, CD9 
## Negative:  DNTT, FLT3, WFDC17, LSP1, MYL10, LAX1, GIMAP6, IGHM, CD24A, MN1 
## PC_ 4 
## Positive:  CSRP3, ST8SIA6, SCIN, LGALS1, APOE, ITGB7, MFSD2B, RGL1, DNTT, IGHV1-23 
## Negative:  MPL, MMRN1, PROCR, HLF, SERPINA3G, ESAM, PTGS1, D630039A03RIK, NDN, PPIC 
## PC_ 5 
## Positive:  HDC, LMO4, CSRP3, IFITM1, FCGR3, HLF, CPA3, PROCR, PGLYRP1, IKZF2 
## Negative:  GP1BB, PF4, SDPR, F2RL2, TREML1, RAB27B, SLC14A1, PBX1, PLEK, TUBA8
```

Example 50 (unknown):
```unknown
## PC_ 1 
## Positive:  BLVRB, KLF1, ERMAP, FAM132A, CAR2, RHD, CES2G, SPHK1, AQP1, SLC38A5 
## Negative:  TMSB4X, CORO1A, PLAC8, H2AFY, LAPTM5, CD34, LCP1, TMEM176B, IGFBP4, EMB 
## PC_ 2 
## Positive:  APOE, GATA2, RAB37, ANGPT1, ADGRG1, MEIS1, MPL, F2R, PDZK1IP1, DAPP1 
## Negative:  CTSG, ELANE, LY6C2, HP, CLEC12A, ANXA3, IGSF6, TIFAB, SLPI, MPO 
## PC_ 3 
## Positive:  APOE, GATA2, NKG7, MUC13, ITGA2B, TUBA8, CPA3, RAB44, SLC18A2, CD9 
## Negative:  DNTT, FLT3, WFDC17, LSP1, MYL10, LAX1, GIMAP6, IGHM, CD24A, MN1 
## PC_ 4 
## Positive:  CSRP3, ST8SIA6, SCIN, LGALS1, APOE, ITGB7, MFSD2B, RGL1, DNTT, IGHV1-23 
## Negative:  MPL, MMRN1, PROCR, HLF, SERPINA3G, ESAM, PTGS1, D630039A03RIK, NDN, PPIC 
## PC_ 5 
## Positive:  HDC, LMO4, CSRP3, IFITM1, FCGR3, HLF, CPA3, PROCR, PGLYRP1, IKZF2 
## Negative:  GP1BB, PF4, SDPR, F2RL2, TREML1, RAB27B, SLC14A1, PBX1, PLEK, TUBA8
```

Example 51 (python):
```python
# when running a PCA on cell cycle genes, actively proliferating cells remain distinct from G1
# cells however, within actively proliferating cells, G2M and S phase cells group together
marrow <- RunPCA(marrow, features = c(s.genes, g2m.genes))
DimPlot(marrow)
```

Example 52 (r):
```r
# when running a PCA on cell cycle genes, actively proliferating cells remain distinct from G1
# cells however, within actively proliferating cells, G2M and S phase cells group together
marrow <- RunPCA(marrow, features = c(s.genes, g2m.genes))
DimPlot(marrow)
```

Example 53 (r):
```r
# when running a PCA on cell cycle genes, actively proliferating cells remain distinct from G1
# cells however, within actively proliferating cells, G2M and S phase cells group together
marrow <- RunPCA(marrow, features = c(s.genes, g2m.genes))
DimPlot(marrow)
```

Example 54 (unknown):
```unknown
sessionInfo()
```

Example 55 (r):
```r
sessionInfo()
```

Example 56 (r):
```r
sessionInfo()
```

Example 57 (unknown):
```unknown
## R version 4.2.0 (2022-04-22)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.5 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/liblapack.so.3
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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       
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
## [1] ggplot2_3.4.1      SeuratObject_4.1.3 Seurat_4.3.0      
## 
## loaded via a namespace (and not attached):
##   [1] Rtsne_0.16             colorspace_2.1-0       deldir_1.0-6          
##   [4] ellipsis_0.3.2         ggridges_0.5.4         rprojroot_2.0.3       
##   [7] fs_1.6.1               spatstat.data_3.0-0    farver_2.1.1          
##  [10] leiden_0.4.3           listenv_0.9.0          ggrepel_0.9.3         
##  [13] fansi_1.0.4            codetools_0.2-18       splines_4.2.0         
##  [16] cachem_1.0.7           knitr_1.42             polyclip_1.10-4       
##  [19] jsonlite_1.8.4         ica_1.0-3              cluster_2.1.3         
##  [22] png_0.1-8              uwot_0.1.14            spatstat.sparse_3.0-0 
##  [25] shiny_1.7.4            sctransform_0.3.5      compiler_4.2.0        
##  [28] httr_1.4.5             Matrix_1.5-3           fastmap_1.1.1         
##  [31] lazyeval_0.2.2         cli_3.6.0              later_1.3.0           
##  [34] formatR_1.14           htmltools_0.5.4        tools_4.2.0           
##  [37] igraph_1.4.1           gtable_0.3.1           glue_1.6.2            
##  [40] RANN_2.6.1             reshape2_1.4.4         dplyr_1.1.0           
##  [43] Rcpp_1.0.10            scattermore_0.8        jquerylib_0.1.4       
##  [46] pkgdown_2.0.7          vctrs_0.5.2            nlme_3.1-157          
##  [49] spatstat.explore_3.0-6 progressr_0.13.0       lmtest_0.9-40         
##  [52] spatstat.random_3.1-3  xfun_0.37              stringr_1.5.0         
##  [55] globals_0.16.2         mime_0.12              miniUI_0.1.1.1        
##  [58] lifecycle_1.0.3        irlba_2.3.5.1          goftest_1.2-3         
##  [61] future_1.31.0          MASS_7.3-56            zoo_1.8-11            
##  [64] scales_1.2.1           ragg_1.2.5             promises_1.2.0.1      
##  [67] spatstat.utils_3.0-1   parallel_4.2.0         RColorBrewer_1.1-3    
##  [70] yaml_2.3.7             memoise_2.0.1          reticulate_1.28       
##  [73] pbapply_1.7-0          gridExtra_2.3          sass_0.4.5            
##  [76] stringi_1.7.12         highr_0.10             desc_1.4.2            
##  [79] rlang_1.0.6            pkgconfig_2.0.3        systemfonts_1.0.4     
##  [82] matrixStats_0.63.0     evaluate_0.20          lattice_0.20-45       
##  [85] tensor_1.5             ROCR_1.0-11            purrr_1.0.1           
##  [88] labeling_0.4.2         patchwork_1.1.2        htmlwidgets_1.6.1     
##  [91] cowplot_1.1.1          tidyselect_1.2.0       parallelly_1.34.0     
##  [94] RcppAnnoy_0.0.20       plyr_1.8.8             magrittr_2.0.3        
##  [97] R6_2.5.1               generics_0.1.3         withr_2.5.0           
## [100] pillar_1.8.1           fitdistrplus_1.1-8     abind_1.4-5           
## [103] survival_3.3-1         sp_1.6-0               tibble_3.1.8          
## [106] future.apply_1.10.0    KernSmooth_2.23-20     utf8_1.2.3            
## [109] spatstat.geom_3.0-6    plotly_4.10.1          rmarkdown_2.20        
## [112] grid_4.2.0             data.table_1.14.8      digest_0.6.31         
## [115] xtable_1.8-4           tidyr_1.3.0            httpuv_1.6.9          
## [118] textshaping_0.3.6      munsell_0.5.0          viridisLite_0.4.1     
## [121] bslib_0.4.2
```

Example 58 (unknown):
```unknown
## R version 4.2.0 (2022-04-22)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.5 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/liblapack.so.3
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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       
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
## [1] ggplot2_3.4.1      SeuratObject_4.1.3 Seurat_4.3.0      
## 
## loaded via a namespace (and not attached):
##   [1] Rtsne_0.16             colorspace_2.1-0       deldir_1.0-6          
##   [4] ellipsis_0.3.2         ggridges_0.5.4         rprojroot_2.0.3       
##   [7] fs_1.6.1               spatstat.data_3.0-0    farver_2.1.1          
##  [10] leiden_0.4.3           listenv_0.9.0          ggrepel_0.9.3         
##  [13] fansi_1.0.4            codetools_0.2-18       splines_4.2.0         
##  [16] cachem_1.0.7           knitr_1.42             polyclip_1.10-4       
##  [19] jsonlite_1.8.4         ica_1.0-3              cluster_2.1.3         
##  [22] png_0.1-8              uwot_0.1.14            spatstat.sparse_3.0-0 
##  [25] shiny_1.7.4            sctransform_0.3.5      compiler_4.2.0        
##  [28] httr_1.4.5             Matrix_1.5-3           fastmap_1.1.1         
##  [31] lazyeval_0.2.2         cli_3.6.0              later_1.3.0           
##  [34] formatR_1.14           htmltools_0.5.4        tools_4.2.0           
##  [37] igraph_1.4.1           gtable_0.3.1           glue_1.6.2            
##  [40] RANN_2.6.1             reshape2_1.4.4         dplyr_1.1.0           
##  [43] Rcpp_1.0.10            scattermore_0.8        jquerylib_0.1.4       
##  [46] pkgdown_2.0.7          vctrs_0.5.2            nlme_3.1-157          
##  [49] spatstat.explore_3.0-6 progressr_0.13.0       lmtest_0.9-40         
##  [52] spatstat.random_3.1-3  xfun_0.37              stringr_1.5.0         
##  [55] globals_0.16.2         mime_0.12              miniUI_0.1.1.1        
##  [58] lifecycle_1.0.3        irlba_2.3.5.1          goftest_1.2-3         
##  [61] future_1.31.0          MASS_7.3-56            zoo_1.8-11            
##  [64] scales_1.2.1           ragg_1.2.5             promises_1.2.0.1      
##  [67] spatstat.utils_3.0-1   parallel_4.2.0         RColorBrewer_1.1-3    
##  [70] yaml_2.3.7             memoise_2.0.1          reticulate_1.28       
##  [73] pbapply_1.7-0          gridExtra_2.3          sass_0.4.5            
##  [76] stringi_1.7.12         highr_0.10             desc_1.4.2            
##  [79] rlang_1.0.6            pkgconfig_2.0.3        systemfonts_1.0.4     
##  [82] matrixStats_0.63.0     evaluate_0.20          lattice_0.20-45       
##  [85] tensor_1.5             ROCR_1.0-11            purrr_1.0.1           
##  [88] labeling_0.4.2         patchwork_1.1.2        htmlwidgets_1.6.1     
##  [91] cowplot_1.1.1          tidyselect_1.2.0       parallelly_1.34.0     
##  [94] RcppAnnoy_0.0.20       plyr_1.8.8             magrittr_2.0.3        
##  [97] R6_2.5.1               generics_0.1.3         withr_2.5.0           
## [100] pillar_1.8.1           fitdistrplus_1.1-8     abind_1.4-5           
## [103] survival_3.3-1         sp_1.6-0               tibble_3.1.8          
## [106] future.apply_1.10.0    KernSmooth_2.23-20     utf8_1.2.3            
## [109] spatstat.geom_3.0-6    plotly_4.10.1          rmarkdown_2.20        
## [112] grid_4.2.0             data.table_1.14.8      digest_0.6.31         
## [115] xtable_1.8-4           tidyr_1.3.0            httpuv_1.6.9          
## [118] textshaping_0.3.6      munsell_0.5.0          viridisLite_0.4.1     
## [121] bslib_0.4.2
```

---

## Seurat - Dimensional Reduction Vignette

**URL:** http://127.0.0.1:9173/seurat/archive/v3.0/dim_reduction_vignette/index.html

**Contents:**
- Seurat - Dimensional Reduction Vignette
    - Compiled: June 24, 2019
  - Load in the data
  - Explore the new dimensional reduction structure
  - Storing a custom dimensional reduction calculation

This vignette demonstrates how to store and interact with dimensional reduction information (such as the output from RunPCA) in Seurat v3.0. For demonstration purposes, we will be using the 2,700 PBMC object that is created in the first guided tutorial. You can download the pre-computed object here.

In Seurat v3.0, storing and interacting with dimensional reduction information has been generalized and formalized into the DimReduc object. Each dimensional reduction procedure is stored as a DimReduc object in the object@reductions slot as an element of a named list. Accessing these reductions can be done with the [[ operator, calling the name of the reduction desired. For example, after running a principle component analysis with RunPCA, object[['pca']] will contain the results of the PCA. By adding new elements to the list, users can add additional, and custom, dimensional reductions. Each stored dimensional reduction contains the following slots:

To access these slots, we provide the Embeddings,Loadings, and Stdev functions

Seurat provides RunPCA (pca), and RunTSNE (tsne), and representing dimensional reduction techniques commonly applied to scRNA-seq data. When using these functions, all slots are filled automatically.

We also allow users to add the results of a custom dimensional reduction technique (for example, multi-dimensional scaling (MDS), or zero-inflated factor analysis), that is computed separately. All you need is a matrix with each cell’s coordinates in low-dimensional space, as shown below.

Though not incorporated as part of the Seurat package, its easy to run multidimensional scaling (MDS) in R. If you were interested in running MDS and storing the output in your Seurat object:

**Examples:**

Example 1 (r):
```r
library(Seurat)
pbmc <- readRDS(file = "../data/pbmc3k_final.rds")
```

Example 2 (r):
```r
library(Seurat)
pbmc <- readRDS(file = "../data/pbmc3k_final.rds")
```

Example 3 (unknown):
```unknown
object@reductions
```

Example 4 (unknown):
```unknown
object[['pca']]
```

Example 5 (r):
```r
pbmc[["pca"]]
```

Example 6 (r):
```r
pbmc[["pca"]]
```

Example 7 (unknown):
```unknown
## A dimensional reduction object with key PC_ 
##  Number of dimensions: 50 
##  Projected dimensional reduction calculated:  FALSE 
##  Jackstraw run: TRUE 
##  Computed using assay: RNA
```

Example 8 (unknown):
```unknown
## A dimensional reduction object with key PC_ 
##  Number of dimensions: 50 
##  Projected dimensional reduction calculated:  FALSE 
##  Jackstraw run: TRUE 
##  Computed using assay: RNA
```

Example 9 (r):
```r
head(Embeddings(pbmc, reduction = "pca")[, 1:5])
```

Example 10 (r):
```r
head(Embeddings(pbmc, reduction = "pca")[, 1:5])
```

Example 11 (unknown):
```unknown
##                      PC_1       PC_2       PC_3       PC_4        PC_5
## AAACATACAACCAC -4.7296855 -0.5184265 -0.7623220 -2.3156790 -0.07160006
## AAACATTGAGCTAC -0.5174029  4.5918957  5.9091921  6.9118856 -1.96243034
## AAACATTGATCAGC -3.1891063 -3.4695154 -0.8313710 -2.0019985 -5.10442765
## AAACCGTGCTTCCG 12.7933021  0.1007166  0.6310221 -0.3687338  0.21838204
## AAACCGTGTATGCG -3.1288078 -6.3481412  1.2507776  3.0191026  7.84739502
## AAACGCACTGGTAC -3.1088963  0.9262125 -0.6482331 -2.3244378 -2.00526763
```

Example 12 (unknown):
```unknown
##                      PC_1       PC_2       PC_3       PC_4        PC_5
## AAACATACAACCAC -4.7296855 -0.5184265 -0.7623220 -2.3156790 -0.07160006
## AAACATTGAGCTAC -0.5174029  4.5918957  5.9091921  6.9118856 -1.96243034
## AAACATTGATCAGC -3.1891063 -3.4695154 -0.8313710 -2.0019985 -5.10442765
## AAACCGTGCTTCCG 12.7933021  0.1007166  0.6310221 -0.3687338  0.21838204
## AAACCGTGTATGCG -3.1288078 -6.3481412  1.2507776  3.0191026  7.84739502
## AAACGCACTGGTAC -3.1088963  0.9262125 -0.6482331 -2.3244378 -2.00526763
```

Example 13 (r):
```r
head(Loadings(pbmc, reduction = "pca")[, 1:5])
```

Example 14 (r):
```r
head(Loadings(pbmc, reduction = "pca")[, 1:5])
```

Example 15 (unknown):
```unknown
##                PC_1        PC_2        PC_3        PC_4        PC_5
## PPBP    0.010990202  0.01148426 -0.15176092  0.10403737 0.003299077
## LYZ     0.116231706  0.01472515 -0.01280613 -0.04414540 0.049906881
## S100A9  0.115414362  0.01895146 -0.02368853 -0.05787777 0.085382309
## IGLL5  -0.007987473  0.05454239  0.04901533  0.06694722 0.004603231
## GNLY   -0.015238762 -0.13375626  0.04101340  0.06912322 0.104558611
## FTL     0.118292572  0.01871142 -0.00984755 -0.01555269 0.038743505
```

Example 16 (unknown):
```unknown
##                PC_1        PC_2        PC_3        PC_4        PC_5
## PPBP    0.010990202  0.01148426 -0.15176092  0.10403737 0.003299077
## LYZ     0.116231706  0.01472515 -0.01280613 -0.04414540 0.049906881
## S100A9  0.115414362  0.01895146 -0.02368853 -0.05787777 0.085382309
## IGLL5  -0.007987473  0.05454239  0.04901533  0.06694722 0.004603231
## GNLY   -0.015238762 -0.13375626  0.04101340  0.06912322 0.104558611
## FTL     0.118292572  0.01871142 -0.00984755 -0.01555269 0.038743505
```

Example 17 (r):
```r
head(Stdev(pbmc, reduction = "pca"))
```

Example 18 (r):
```r
head(Stdev(pbmc, reduction = "pca"))
```

Example 19 (unknown):
```unknown
## [1] 7.098420 4.495493 3.872592 3.748859 3.171755 2.545292
```

Example 20 (unknown):
```unknown
## [1] 7.098420 4.495493 3.872592 3.748859 3.171755 2.545292
```

Example 21 (r):
```r
# Before running MDS, we first calculate a distance matrix between all pairs of cells.  Here we
# use a simple euclidean distance metric on all genes, using scale.data as input
d <- dist(t(GetAssayData(pbmc, slot = "scale.data")))
# Run the MDS procedure, k determines the number of dimensions
mds <- cmdscale(d = d, k = 2)
# cmdscale returns the cell embeddings, we first label the columns to ensure downstream
# consistency
colnames(mds) <- paste0("MDS_", 1:2)
# We will now store this as a custom dimensional reduction called 'mds'
pbmc[["mds"]] <- CreateDimReducObject(embeddings = mds, key = "MDS_", assay = DefaultAssay(pbmc))

# We can now use this as you would any other dimensional reduction in all downstream functions
DimPlot(pbmc, reduction = "mds", pt.size = 0.5)
```

Example 22 (r):
```r
# Before running MDS, we first calculate a distance matrix between all pairs of cells.  Here we
# use a simple euclidean distance metric on all genes, using scale.data as input
d <- dist(t(GetAssayData(pbmc, slot = "scale.data")))
# Run the MDS procedure, k determines the number of dimensions
mds <- cmdscale(d = d, k = 2)
# cmdscale returns the cell embeddings, we first label the columns to ensure downstream
# consistency
colnames(mds) <- paste0("MDS_", 1:2)
# We will now store this as a custom dimensional reduction called 'mds'
pbmc[["mds"]] <- CreateDimReducObject(embeddings = mds, key = "MDS_", assay = DefaultAssay(pbmc))

# We can now use this as you would any other dimensional reduction in all downstream functions
DimPlot(pbmc, reduction = "mds", pt.size = 0.5)
```

Example 23 (r):
```r
# If you wold like to observe genes that are strongly correlated with the first MDS coordinate
pbmc <- ProjectDim(pbmc, reduction = "mds")
```

Example 24 (r):
```r
# If you wold like to observe genes that are strongly correlated with the first MDS coordinate
pbmc <- ProjectDim(pbmc, reduction = "mds")
```

Example 25 (unknown):
```unknown
## MDS_ 1 
## Positive:  CST3, TYROBP, FCER1G, LST1, FTL, AIF1, FTH1, TYMP, FCN1, LYZ 
##     LGALS1, S100A9, CFD, CD68, SERPINA1, CTSS, IFITM3, SPI1, S100A8, LGALS2 
## Negative:  MALAT1, RPS27A, RPS27, RPL3, RPL23A, RPL21, RPL13A, RPS6, RPS3A, RPS3 
##     RPL9, LTB, RPSA, CD3D, RPS25, RPS18, PTPRCAP, RPS12, RPL30, RPL31 
## MDS_ 2 
## Positive:  NKG7, PRF1, CST7, GZMA, GZMB, B2M, FGFBP2, CTSW, GNLY, HLA-C 
##     GZMH, SPON2, CD247, FCGR3A, CCL5, HLA-A, CCL4, GZMM, KLRD1, CLIC3 
## Negative:  RPL32, RPL18A, HLA-DRA, CD79A, RPL13, MS4A1, RPL11, TCL1A, RPS9, RPL12 
##     LINC00926, HLA-DQB1, HLA-DQA1, HLA-DRB1, RPL28, RPS2, S100A8, HLA-DMA, RPL8, RPLP1
```

Example 26 (unknown):
```unknown
## MDS_ 1 
## Positive:  CST3, TYROBP, FCER1G, LST1, FTL, AIF1, FTH1, TYMP, FCN1, LYZ 
##     LGALS1, S100A9, CFD, CD68, SERPINA1, CTSS, IFITM3, SPI1, S100A8, LGALS2 
## Negative:  MALAT1, RPS27A, RPS27, RPL3, RPL23A, RPL21, RPL13A, RPS6, RPS3A, RPS3 
##     RPL9, LTB, RPSA, CD3D, RPS25, RPS18, PTPRCAP, RPS12, RPL30, RPL31 
## MDS_ 2 
## Positive:  NKG7, PRF1, CST7, GZMA, GZMB, B2M, FGFBP2, CTSW, GNLY, HLA-C 
##     GZMH, SPON2, CD247, FCGR3A, CCL5, HLA-A, CCL4, GZMM, KLRD1, CLIC3 
## Negative:  RPL32, RPL18A, HLA-DRA, CD79A, RPL13, MS4A1, RPL11, TCL1A, RPS9, RPL12 
##     LINC00926, HLA-DQB1, HLA-DQA1, HLA-DRB1, RPL28, RPS2, S100A8, HLA-DMA, RPL8, RPLP1
```

Example 27 (r):
```r
# Display the results as a heatmap
DimHeatmap(pbmc, reduction = "mds", dims = 1, cells = 500, projected = TRUE, balanced = TRUE)
```

Example 28 (r):
```r
# Display the results as a heatmap
DimHeatmap(pbmc, reduction = "mds", dims = 1, cells = 500, projected = TRUE, balanced = TRUE)
```

Example 29 (r):
```r
# Explore how the first MDS dimension is distributed across clusters
VlnPlot(pbmc, features = "MDS_1")
```

Example 30 (r):
```r
# Explore how the first MDS dimension is distributed across clusters
VlnPlot(pbmc, features = "MDS_1")
```

Example 31 (r):
```r
# See how the first MDS dimension is correlated with the first PC dimension
FeatureScatter(pbmc, feature1 = "MDS_1", feature2 = "PC_1")
```

Example 32 (r):
```r
# See how the first MDS dimension is correlated with the first PC dimension
FeatureScatter(pbmc, feature1 = "MDS_1", feature2 = "PC_1")
```

---

## Analysis, visualization, and integration of Visium HD spatial datasets with Seurat • Seurat

**URL:** http://127.0.0.1:9173/seurat/articles/covid_sctmapping/index.html

**Contents:**
- Map COVID PBMC datasets to a healthy reference
    - Compiled: 2023-11-15
- Introduction: Reference mapping analysis in Seurat v5
- Load the PBMC Reference Dataset and Query Datasets
- Mapping
- Explore the mapping results
- Differential composition analysis
- Differential expression analysis
- Contents

In Seurat v5, we introduce a scalable approach for reference mapping datasets from separate studies or individuals. Reference mapping is a powerful approach to identify consistent labels across studies and perform cross-dataset analysis. We emphasize that while individual datasets are manageable in size, the aggregate of many datasets often amounts to millions of cell which do not fit in-memory. Furthermore, cross-dataset analysis is often challenged by disparate or unique cell type labels. Through reference mapping, we annotate all cells with a common reference for consistent cell type labels. Importantly, we never simultaneously load all of the cells in-memory to maintain low memory usage.

In this vignette, we reference map three publicly available datasets totaling 1,498,064 cells and 277 donors which are available through CZI cellxgene collections: Ahern, et al., Nature 2022, Jin, et al., Science 2021, and Yoshida, et al., Nature 2022. Each dataset consists of PBMCs from both healthy donors and donors diagnosed with COVID-19. Using the harmonized annotations, we demonstrate how to prepare a pseudobulk object to perform differential expression analysis across disease within cell types.

Prior to running this vignette, please install Seurat v5 and see the BPCells vignette to construct the on-disk object used in this vignette. Additionally, we map to our annotated CITE-seq reference containing 162,000 cells and 228 antibodies (Hao, Hao, et al., Cell 2021) which is available for download here.

We first load the reference (available here) and normalize the query Seurat object prepared in the BPCells interaction vignette. The query object consists of datasets from three different studies constructed using the CreateSeuratObject function, which accepts a list of BPCells matrices as input. Within the Seurat object, the three datasets reside in the RNA assay in three separate layers on-disk.

Using the same code from the v4 reference mapping vignette, we find anchors between the reference and query in the precomputed supervised PCA. We recommend the use of supervised PCA for CITE-seq reference datasets, and demonstrate how to compute this transformation in v4 reference mapping vignette. In Seurat v5, we only need to call FindTransferAnchors and MapQuery once to map all three datasets as they are all contained within the query object. Furthermore, utilizing the on-disk capabilities of BPCells, we map 1.5 million cells without ever loading them all into memory.

Next, we visualize all cells from the three studies which have been projected into a UMAP-space defined by the reference. Each cell is annotated at two levels of granularity (predicted.celltype.l1 and predicted.celltype.l2). We can compare the differing ontologies used in the original annotations (cell_type) to the now harmonized annotations (predicted.celltype.l2, for example) that were predicted from reference-mapping. Previously, the lack of standardization prevented us from directly performing integrative analysis across studies, but now we can easily compare.

We utilize our harmonized annotations to identify differences in the proportion of different cell types between healthy individuals and COVID-19 patients. For example, we noticed a reduction in MAIT cells as well as an increase in plasmablasts among COVID-19 patients.

In addition to composition analysis, we use an aggregation-based (pseudobulk) workflow to explore differential genes between healthy individuals and COVID-19 donors. We aggregate all cells within the same cell type and donor using the AggregateExpression function. This returns a Seurat object where each ‘cell’ represents the pseudobulk profile of one cell type in one individual.

Once a pseudobulk object is created, we can perform cell type-specific differential expression analysis between healthy individuals and COVID-19 donors. Here, we only visualize certain interferon-stimulated genes which are often upregulated during viral infection.

Developed by Rahul Satija, Satija Lab and Collaborators.

Site built with pkgdown 2.0.7.

**Examples:**

Example 1 (unknown):
```unknown
vignettes/COVID_SCTMapping.Rmd
```

Example 2 (unknown):
```unknown
COVID_SCTMapping.Rmd
```

Example 3 (unknown):
```unknown
library(Seurat)
library(BPCells)
library(dplyr)
library(patchwork)
library(ggplot2)
options(future.globals.maxSize = 1e9)
```

Example 4 (r):
```r
library(Seurat)
library(BPCells)
library(dplyr)
library(patchwork)
library(ggplot2)
options(future.globals.maxSize = 1e9)
```

Example 5 (unknown):
```unknown
CreateSeuratObject
```

Example 6 (unknown):
```unknown
reference <- readRDS("/brahms/hartmana/vignette_data/pbmc_multimodal_2023.rds")
object <- readRDS("/brahms/mollag/seurat_v5/vignette_data/merged_covid_object.rds")
object <- NormalizeData(object, verbose = FALSE)
```

Example 7 (r):
```r
reference <- readRDS("/brahms/hartmana/vignette_data/pbmc_multimodal_2023.rds")
object <- readRDS("/brahms/mollag/seurat_v5/vignette_data/merged_covid_object.rds")
object <- NormalizeData(object, verbose = FALSE)
```

Example 8 (r):
```r
reference <- readRDS("/brahms/hartmana/vignette_data/pbmc_multimodal_2023.rds")
object <- readRDS("/brahms/mollag/seurat_v5/vignette_data/merged_covid_object.rds")
object <- NormalizeData(object, verbose = FALSE)
```

Example 9 (unknown):
```unknown
FindTransferAnchors
```

Example 10 (unknown):
```unknown
anchor <- FindTransferAnchors(
  reference = reference,
  query = object,
  reference.reduction = "spca",
  normalization.method = "SCT",
  dims = 1:50
)
object <- MapQuery(
  anchorset = anchor,
  query = object,
  reference = reference,
  refdata = list(
    celltype.l1 = "celltype.l1",
    celltype.l2 = "celltype.l2"
  ),
  reduction.model = "wnn.umap"
)
```

Example 11 (r):
```r
anchor <- FindTransferAnchors(
  reference = reference,
  query = object,
  reference.reduction = "spca",
  normalization.method = "SCT",
  dims = 1:50
)
object <- MapQuery(
  anchorset = anchor,
  query = object,
  reference = reference,
  refdata = list(
    celltype.l1 = "celltype.l1",
    celltype.l2 = "celltype.l2"
  ),
  reduction.model = "wnn.umap"
)
```

Example 12 (r):
```r
anchor <- FindTransferAnchors(
  reference = reference,
  query = object,
  reference.reduction = "spca",
  normalization.method = "SCT",
  dims = 1:50
)
object <- MapQuery(
  anchorset = anchor,
  query = object,
  reference = reference,
  refdata = list(
    celltype.l1 = "celltype.l1",
    celltype.l2 = "celltype.l2"
  ),
  reduction.model = "wnn.umap"
)
```

Example 13 (unknown):
```unknown
predicted.celltype.l1
```

Example 14 (unknown):
```unknown
predicted.celltype.l2
```

Example 15 (unknown):
```unknown
predicted.celltype.l2
```

Example 16 (unknown):
```unknown
DimPlot(object, reduction = "ref.umap", group.by = "cell_type", alpha = 0.1, label = TRUE, split.by = "publication", ncol = 3, label.size = 3) + NoLegend()
```

Example 17 (r):
```r
DimPlot(object, reduction = "ref.umap", group.by = "cell_type", alpha = 0.1, label = TRUE, split.by = "publication", ncol = 3, label.size = 3) + NoLegend()
```

Example 18 (r):
```r
DimPlot(object, reduction = "ref.umap", group.by = "cell_type", alpha = 0.1, label = TRUE, split.by = "publication", ncol = 3, label.size = 3) + NoLegend()
```

Example 19 (unknown):
```unknown
DimPlot(object, reduction = "ref.umap", group.by = "predicted.celltype.l2", alpha = 0.1, label = TRUE, split.by = "publication", ncol = 3, label.size = 3) + NoLegend()
```

Example 20 (r):
```r
DimPlot(object, reduction = "ref.umap", group.by = "predicted.celltype.l2", alpha = 0.1, label = TRUE, split.by = "publication", ncol = 3, label.size = 3) + NoLegend()
```

Example 21 (r):
```r
DimPlot(object, reduction = "ref.umap", group.by = "predicted.celltype.l2", alpha = 0.1, label = TRUE, split.by = "publication", ncol = 3, label.size = 3) + NoLegend()
```

Example 22 (unknown):
```unknown
df_comp <- as.data.frame.matrix(table(object$donor_id, object$predicted.celltype.l2))
select.donors <- rownames(df_comp)[rowSums(df_comp) > 50]
df_comp <- df_comp[select.donors, ]
df_comp_relative <- sweep(x = df_comp, MARGIN = 1, STATS = rowSums(df_comp), FUN = "/")

df_disease <- as.data.frame.matrix(table(object$donor_id, object$disease))[select.donors, ]

df_comp_relative$disease <- "other"
df_comp_relative$disease[df_disease$normal != 0] <- "normal"
df_comp_relative$disease[df_disease$`COVID-19` != 0] <- "COVID-19"
df_comp_relative$disease <- factor(df_comp_relative$disease, levels = c("normal", "COVID-19", "other"))
df_comp_relative <- df_comp_relative[df_comp_relative$disease %in% c("normal", "COVID-19"), ]
```

Example 23 (r):
```r
df_comp <- as.data.frame.matrix(table(object$donor_id, object$predicted.celltype.l2))
select.donors <- rownames(df_comp)[rowSums(df_comp) > 50]
df_comp <- df_comp[select.donors, ]
df_comp_relative <- sweep(x = df_comp, MARGIN = 1, STATS = rowSums(df_comp), FUN = "/")

df_disease <- as.data.frame.matrix(table(object$donor_id, object$disease))[select.donors, ]

df_comp_relative$disease <- "other"
df_comp_relative$disease[df_disease$normal != 0] <- "normal"
df_comp_relative$disease[df_disease$`COVID-19` != 0] <- "COVID-19"
df_comp_relative$disease <- factor(df_comp_relative$disease, levels = c("normal", "COVID-19", "other"))
df_comp_relative <- df_comp_relative[df_comp_relative$disease %in% c("normal", "COVID-19"), ]
```

Example 24 (r):
```r
df_comp <- as.data.frame.matrix(table(object$donor_id, object$predicted.celltype.l2))
select.donors <- rownames(df_comp)[rowSums(df_comp) > 50]
df_comp <- df_comp[select.donors, ]
df_comp_relative <- sweep(x = df_comp, MARGIN = 1, STATS = rowSums(df_comp), FUN = "/")

df_disease <- as.data.frame.matrix(table(object$donor_id, object$disease))[select.donors, ]

df_comp_relative$disease <- "other"
df_comp_relative$disease[df_disease$normal != 0] <- "normal"
df_comp_relative$disease[df_disease$`COVID-19` != 0] <- "COVID-19"
df_comp_relative$disease <- factor(df_comp_relative$disease, levels = c("normal", "COVID-19", "other"))
df_comp_relative <- df_comp_relative[df_comp_relative$disease %in% c("normal", "COVID-19"), ]
```

Example 25 (python):
```python
p1 <- ggplot(data = df_comp_relative, mapping = aes(x = disease, y = MAIT, fill = disease)) +
  geom_boxplot(outlier.shape = NA) +
  scale_fill_manual(values = c("#377eb8", "#e41a1c")) +
  xlab("") +
  ylab("relative abundance") +
  ggtitle("MAIT") +
  geom_jitter(color = "black", size = 0.4, alpha = 0.9) +
  theme_bw() +
  theme(
    axis.title = element_text(size = 12),
    axis.text = element_text(size = 12),
    plot.title = element_text(size = 15, hjust = 0.5, face = "bold")
  )

p2 <- ggplot(data = df_comp_relative, mapping = aes(x = disease, y = Plasmablast, fill = disease)) +
  geom_boxplot(outlier.shape = NA) +
  scale_fill_manual(values = c("#377eb8", "#e41a1c")) +
  xlab("") +
  ylab("relative abundance") +
  ggtitle("Plasmablast") +
  geom_jitter(color = "black", size = 0.4, alpha = 0.9) +
  theme_bw() +
  theme(
    axis.title = element_text(size = 12),
    axis.text = element_text(size = 12),
    plot.title = element_text(size = 15, hjust = 0.5, face = "bold")
  )

p1 + p2 + plot_layout(ncol = 2)
```

Example 26 (r):
```r
p1 <- ggplot(data = df_comp_relative, mapping = aes(x = disease, y = MAIT, fill = disease)) +
  geom_boxplot(outlier.shape = NA) +
  scale_fill_manual(values = c("#377eb8", "#e41a1c")) +
  xlab("") +
  ylab("relative abundance") +
  ggtitle("MAIT") +
  geom_jitter(color = "black", size = 0.4, alpha = 0.9) +
  theme_bw() +
  theme(
    axis.title = element_text(size = 12),
    axis.text = element_text(size = 12),
    plot.title = element_text(size = 15, hjust = 0.5, face = "bold")
  )

p2 <- ggplot(data = df_comp_relative, mapping = aes(x = disease, y = Plasmablast, fill = disease)) +
  geom_boxplot(outlier.shape = NA) +
  scale_fill_manual(values = c("#377eb8", "#e41a1c")) +
  xlab("") +
  ylab("relative abundance") +
  ggtitle("Plasmablast") +
  geom_jitter(color = "black", size = 0.4, alpha = 0.9) +
  theme_bw() +
  theme(
    axis.title = element_text(size = 12),
    axis.text = element_text(size = 12),
    plot.title = element_text(size = 15, hjust = 0.5, face = "bold")
  )

p1 + p2 + plot_layout(ncol = 2)
```

Example 27 (r):
```r
p1 <- ggplot(data = df_comp_relative, mapping = aes(x = disease, y = MAIT, fill = disease)) +
  geom_boxplot(outlier.shape = NA) +
  scale_fill_manual(values = c("#377eb8", "#e41a1c")) +
  xlab("") +
  ylab("relative abundance") +
  ggtitle("MAIT") +
  geom_jitter(color = "black", size = 0.4, alpha = 0.9) +
  theme_bw() +
  theme(
    axis.title = element_text(size = 12),
    axis.text = element_text(size = 12),
    plot.title = element_text(size = 15, hjust = 0.5, face = "bold")
  )

p2 <- ggplot(data = df_comp_relative, mapping = aes(x = disease, y = Plasmablast, fill = disease)) +
  geom_boxplot(outlier.shape = NA) +
  scale_fill_manual(values = c("#377eb8", "#e41a1c")) +
  xlab("") +
  ylab("relative abundance") +
  ggtitle("Plasmablast") +
  geom_jitter(color = "black", size = 0.4, alpha = 0.9) +
  theme_bw() +
  theme(
    axis.title = element_text(size = 12),
    axis.text = element_text(size = 12),
    plot.title = element_text(size = 15, hjust = 0.5, face = "bold")
  )

p1 + p2 + plot_layout(ncol = 2)
```

Example 28 (unknown):
```unknown
AggregateExpression
```

Example 29 (unknown):
```unknown
bulk <- AggregateExpression(object,
  return.seurat = TRUE,
  assays = "RNA",
  group.by = c("predicted.celltype.l2", "donor_id", "disease")
)
```

Example 30 (r):
```r
bulk <- AggregateExpression(object,
  return.seurat = TRUE,
  assays = "RNA",
  group.by = c("predicted.celltype.l2", "donor_id", "disease")
)
```

Example 31 (r):
```r
bulk <- AggregateExpression(object,
  return.seurat = TRUE,
  assays = "RNA",
  group.by = c("predicted.celltype.l2", "donor_id", "disease")
)
```

Example 32 (unknown):
```unknown
bulk <- subset(bulk, subset = disease %in% c("normal", "COVID-19"))
bulk <- subset(bulk, subset = predicted.celltype.l2 != "Doublet")
bulk$disease <- factor(bulk$disease, levels = c("normal", "COVID-19"))
```

Example 33 (r):
```r
bulk <- subset(bulk, subset = disease %in% c("normal", "COVID-19"))
bulk <- subset(bulk, subset = predicted.celltype.l2 != "Doublet")
bulk$disease <- factor(bulk$disease, levels = c("normal", "COVID-19"))
```

Example 34 (r):
```r
bulk <- subset(bulk, subset = disease %in% c("normal", "COVID-19"))
bulk <- subset(bulk, subset = predicted.celltype.l2 != "Doublet")
bulk$disease <- factor(bulk$disease, levels = c("normal", "COVID-19"))
```

Example 35 (unknown):
```unknown
p1 <- VlnPlot(
  object = bulk, features = "IFI6", group.by = "predicted.celltype.l2",
  split.by = "disease", cols = c("#377eb8", "#e41a1c")
)
p2 <- VlnPlot(
  object = bulk, features = c("ISG15"), group.by = "predicted.celltype.l2",
  split.by = "disease", cols = c("#377eb8", "#e41a1c")
)
p3 <- VlnPlot(
  object = bulk, features = c("IFIT5"), group.by = "predicted.celltype.l2",
  split.by = "disease", cols = c("#377eb8", "#e41a1c")
)
p1 + p2 + p3 + plot_layout(ncol = 1)
```

Example 36 (r):
```r
p1 <- VlnPlot(
  object = bulk, features = "IFI6", group.by = "predicted.celltype.l2",
  split.by = "disease", cols = c("#377eb8", "#e41a1c")
)
p2 <- VlnPlot(
  object = bulk, features = c("ISG15"), group.by = "predicted.celltype.l2",
  split.by = "disease", cols = c("#377eb8", "#e41a1c")
)
p3 <- VlnPlot(
  object = bulk, features = c("IFIT5"), group.by = "predicted.celltype.l2",
  split.by = "disease", cols = c("#377eb8", "#e41a1c")
)
p1 + p2 + p3 + plot_layout(ncol = 1)
```

Example 37 (r):
```r
p1 <- VlnPlot(
  object = bulk, features = "IFI6", group.by = "predicted.celltype.l2",
  split.by = "disease", cols = c("#377eb8", "#e41a1c")
)
p2 <- VlnPlot(
  object = bulk, features = c("ISG15"), group.by = "predicted.celltype.l2",
  split.by = "disease", cols = c("#377eb8", "#e41a1c")
)
p3 <- VlnPlot(
  object = bulk, features = c("IFIT5"), group.by = "predicted.celltype.l2",
  split.by = "disease", cols = c("#377eb8", "#e41a1c")
)
p1 + p2 + p3 + plot_layout(ncol = 1)
```

Example 38 (unknown):
```unknown
sessionInfo()
```

Example 39 (r):
```r
sessionInfo()
```

Example 40 (r):
```r
sessionInfo()
```

Example 41 (unknown):
```unknown
## R version 4.2.2 Patched (2022-11-10 r83330)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.6 LTS
## 
## Matrix products: default
## BLAS:   /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.9.0
## LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.9.0
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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       
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
## [1] ggplot2_3.4.4      patchwork_1.1.3    dplyr_1.1.3        BPCells_0.1.0     
## [5] Seurat_5.0.1  testthat_3.2.0     SeuratObject_5.0.1 sp_2.1-1          
## 
## loaded via a namespace (and not attached):
##   [1] utf8_1.2.4             spatstat.explore_3.2-5 reticulate_1.34.0     
##   [4] R.utils_2.12.2         tidyselect_1.2.0       htmlwidgets_1.6.2     
##   [7] grid_4.2.2             Rtsne_0.16             devtools_2.4.5        
##  [10] munsell_0.5.0          codetools_0.2-19       ragg_1.2.5            
##  [13] ica_1.0-3              future_1.33.0          miniUI_0.1.1.1        
##  [16] withr_2.5.2            spatstat.random_3.2-1  colorspace_2.1-0      
##  [19] progressr_0.14.0       highr_0.10             knitr_1.45            
##  [22] rstudioapi_0.14        stats4_4.2.2           ROCR_1.0-11           
##  [25] tensor_1.5             listenv_0.9.0          labeling_0.4.3        
##  [28] GenomeInfoDbData_1.2.9 polyclip_1.10-6        farver_2.1.1          
##  [31] rprojroot_2.0.4        parallelly_1.36.0      vctrs_0.6.4           
##  [34] generics_0.1.3         xfun_0.40              R6_2.5.1              
##  [37] GenomeInfoDb_1.34.9    ggbeeswarm_0.7.1       bitops_1.0-7          
##  [40] spatstat.utils_3.0-4   cachem_1.0.8           promises_1.2.1        
##  [43] scales_1.2.1           beeswarm_0.4.0         gtable_0.3.4          
##  [46] globals_0.16.2         processx_3.8.2         goftest_1.2-3         
##  [49] spam_2.10-0            rlang_1.1.1            systemfonts_1.0.4     
##  [52] splines_4.2.2          lazyeval_0.2.2         spatstat.geom_3.2-7   
##  [55] yaml_2.3.7             reshape2_1.4.4         abind_1.4-5           
##  [58] httpuv_1.6.12          tools_4.2.2            usethis_2.1.6         
##  [61] ellipsis_0.3.2         jquerylib_0.1.4        RColorBrewer_1.1-3    
##  [64] BiocGenerics_0.44.0    sessioninfo_1.2.2      ggridges_0.5.4        
##  [67] Rcpp_1.0.11            plyr_1.8.9             zlibbioc_1.44.0       
##  [70] purrr_1.0.2            RCurl_1.98-1.12        ps_1.7.5              
##  [73] prettyunits_1.2.0      deldir_1.0-9           pbapply_1.7-2         
##  [76] cowplot_1.1.1          urlchecker_1.0.1       S4Vectors_0.36.2      
##  [79] zoo_1.8-12             ggrepel_0.9.4          cluster_2.1.4         
##  [82] fs_1.6.3               magrittr_2.0.3         data.table_1.14.8     
##  [85] RSpectra_0.16-1        scattermore_1.2        lmtest_0.9-40         
##  [88] RANN_2.6.1             fitdistrplus_1.1-11    R.cache_0.16.0        
##  [91] matrixStats_1.0.0      pkgload_1.3.3          mime_0.12             
##  [94] evaluate_0.22          xtable_1.8-4           fastDummies_1.7.3     
##  [97] IRanges_2.32.0         gridExtra_2.3          compiler_4.2.2        
## [100] tibble_3.2.1           KernSmooth_2.23-22     crayon_1.5.2          
## [103] R.oo_1.25.0            htmltools_0.5.6.1      later_1.3.1           
## [106] tidyr_1.3.0            MASS_7.3-58.2          Matrix_1.6-1.1        
## [109] brio_1.1.3             cli_3.6.1              R.methodsS3_1.8.2     
## [112] parallel_4.2.2         dotCall64_1.1-0        igraph_1.5.1          
## [115] GenomicRanges_1.50.2   pkgconfig_2.0.3        pkgdown_2.0.7         
## [118] plotly_4.10.3          spatstat.sparse_3.0-3  vipor_0.4.5           
## [121] bslib_0.5.1            XVector_0.38.0         stringr_1.5.0         
## [124] callr_3.7.3            digest_0.6.33          sctransform_0.4.1     
## [127] RcppAnnoy_0.0.21       spatstat.data_3.0-3    rmarkdown_2.25        
## [130] leiden_0.4.3           uwot_0.1.16            shiny_1.7.5.1         
## [133] lifecycle_1.0.4        nlme_3.1-162           jsonlite_1.8.7        
## [136] desc_1.4.2             viridisLite_0.4.2      fansi_1.0.5           
## [139] pillar_1.9.0           lattice_0.21-9         ggrastr_1.0.1         
## [142] fastmap_1.1.1          httr_1.4.7             pkgbuild_1.4.2        
## [145] survival_3.5-7         glue_1.6.2             remotes_2.4.2.1       
## [148] png_0.1-8              stringi_1.7.12         sass_0.4.7            
## [151] profvis_0.3.7          textshaping_0.3.6      RcppHNSW_0.5.0        
## [154] memoise_2.0.1          styler_1.10.2          irlba_2.3.5.1         
## [157] future.apply_1.11.0
```

Example 42 (unknown):
```unknown
## R version 4.2.2 Patched (2022-11-10 r83330)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.6 LTS
## 
## Matrix products: default
## BLAS:   /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.9.0
## LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.9.0
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [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       
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
## [1] ggplot2_3.4.4      patchwork_1.1.3    dplyr_1.1.3        BPCells_0.1.0     
## [5] Seurat_5.0.1  testthat_3.2.0     SeuratObject_5.0.1 sp_2.1-1          
## 
## loaded via a namespace (and not attached):
##   [1] utf8_1.2.4             spatstat.explore_3.2-5 reticulate_1.34.0     
##   [4] R.utils_2.12.2         tidyselect_1.2.0       htmlwidgets_1.6.2     
##   [7] grid_4.2.2             Rtsne_0.16             devtools_2.4.5        
##  [10] munsell_0.5.0          codetools_0.2-19       ragg_1.2.5            
##  [13] ica_1.0-3              future_1.33.0          miniUI_0.1.1.1        
##  [16] withr_2.5.2            spatstat.random_3.2-1  colorspace_2.1-0      
##  [19] progressr_0.14.0       highr_0.10             knitr_1.45            
##  [22] rstudioapi_0.14        stats4_4.2.2           ROCR_1.0-11           
##  [25] tensor_1.5             listenv_0.9.0          labeling_0.4.3        
##  [28] GenomeInfoDbData_1.2.9 polyclip_1.10-6        farver_2.1.1          
##  [31] rprojroot_2.0.4        parallelly_1.36.0      vctrs_0.6.4           
##  [34] generics_0.1.3         xfun_0.40              R6_2.5.1              
##  [37] GenomeInfoDb_1.34.9    ggbeeswarm_0.7.1       bitops_1.0-7          
##  [40] spatstat.utils_3.0-4   cachem_1.0.8           promises_1.2.1        
##  [43] scales_1.2.1           beeswarm_0.4.0         gtable_0.3.4          
##  [46] globals_0.16.2         processx_3.8.2         goftest_1.2-3         
##  [49] spam_2.10-0            rlang_1.1.1            systemfonts_1.0.4     
##  [52] splines_4.2.2          lazyeval_0.2.2         spatstat.geom_3.2-7   
##  [55] yaml_2.3.7             reshape2_1.4.4         abind_1.4-5           
##  [58] httpuv_1.6.12          tools_4.2.2            usethis_2.1.6         
##  [61] ellipsis_0.3.2         jquerylib_0.1.4        RColorBrewer_1.1-3    
##  [64] BiocGenerics_0.44.0    sessioninfo_1.2.2      ggridges_0.5.4        
##  [67] Rcpp_1.0.11            plyr_1.8.9             zlibbioc_1.44.0       
##  [70] purrr_1.0.2            RCurl_1.98-1.12        ps_1.7.5              
##  [73] prettyunits_1.2.0      deldir_1.0-9           pbapply_1.7-2         
##  [76] cowplot_1.1.1          urlchecker_1.0.1       S4Vectors_0.36.2      
##  [79] zoo_1.8-12             ggrepel_0.9.4          cluster_2.1.4         
##  [82] fs_1.6.3               magrittr_2.0.3         data.table_1.14.8     
##  [85] RSpectra_0.16-1        scattermore_1.2        lmtest_0.9-40         
##  [88] RANN_2.6.1             fitdistrplus_1.1-11    R.cache_0.16.0        
##  [91] matrixStats_1.0.0      pkgload_1.3.3          mime_0.12             
##  [94] evaluate_0.22          xtable_1.8-4           fastDummies_1.7.3     
##  [97] IRanges_2.32.0         gridExtra_2.3          compiler_4.2.2        
## [100] tibble_3.2.1           KernSmooth_2.23-22     crayon_1.5.2          
## [103] R.oo_1.25.0            htmltools_0.5.6.1      later_1.3.1           
## [106] tidyr_1.3.0            MASS_7.3-58.2          Matrix_1.6-1.1        
## [109] brio_1.1.3             cli_3.6.1              R.methodsS3_1.8.2     
## [112] parallel_4.2.2         dotCall64_1.1-0        igraph_1.5.1          
## [115] GenomicRanges_1.50.2   pkgconfig_2.0.3        pkgdown_2.0.7         
## [118] plotly_4.10.3          spatstat.sparse_3.0-3  vipor_0.4.5           
## [121] bslib_0.5.1            XVector_0.38.0         stringr_1.5.0         
## [124] callr_3.7.3            digest_0.6.33          sctransform_0.4.1     
## [127] RcppAnnoy_0.0.21       spatstat.data_3.0-3    rmarkdown_2.25        
## [130] leiden_0.4.3           uwot_0.1.16            shiny_1.7.5.1         
## [133] lifecycle_1.0.4        nlme_3.1-162           jsonlite_1.8.7        
## [136] desc_1.4.2             viridisLite_0.4.2      fansi_1.0.5           
## [139] pillar_1.9.0           lattice_0.21-9         ggrastr_1.0.1         
## [142] fastmap_1.1.1          httr_1.4.7             pkgbuild_1.4.2        
## [145] survival_3.5-7         glue_1.6.2             remotes_2.4.2.1       
## [148] png_0.1-8              stringi_1.7.12         sass_0.4.7            
## [151] profvis_0.3.7          textshaping_0.3.6      RcppHNSW_0.5.0        
## [154] memoise_2.0.1          styler_1.10.2          irlba_2.3.5.1         
## [157] future.apply_1.11.0
```

---

## Seurat - Interaction Tips

**URL:** http://127.0.0.1:9173/seurat/archive/v2.4/interaction_vignette/index.html

**Contents:**
- Seurat - Interaction Tips
    - Compiled: March 24, 2018
  - Load in the data
  - Switch identity class between cluster ID and replicate
  - Tabulate cells by cluster ID, replicate, or both
  - Selecting particular cells and subsetting the Seurat object
  - Calculating the average gene expression within a cluster

This vignette demonstrates some useful features for interacting with the Seurat object. For demonstration purposes, we will be using the 2,700 PBMC object that is created in the first guided tutorial. You can download the pre-computed object here. To simulate the scenario where we have two replicates, we will randomly assign half the cells in each cluster to be from “rep1” and other half from “rep2”.

**Examples:**

Example 1 (r):
```r
library(Seurat)
library(dplyr)
pbmc <- readRDS(file = "~/Projects/datasets/pbmc3k_final.rds")

# pretend that cells were originally assigned to one of two replicates (we
# assign randomly here) if your cells do belong to multiple replicates, and
# you want to add this info to the Seurat object create a data frame with
# this information (similar to replicate.info below)
set.seed(seed = 42)
replicate.info <- data.frame(replicate = sample(x = c("rep1", "rep2"), size = length(x = pbmc@cell.names), 
    replace = TRUE), row.names = pbmc@cell.names)
pbmc <- AddMetaData(object = pbmc, metadata = replicate.info)
```

Example 2 (r):
```r
library(Seurat)
library(dplyr)
pbmc <- readRDS(file = "~/Projects/datasets/pbmc3k_final.rds")

# pretend that cells were originally assigned to one of two replicates (we
# assign randomly here) if your cells do belong to multiple replicates, and
# you want to add this info to the Seurat object create a data frame with
# this information (similar to replicate.info below)
set.seed(seed = 42)
replicate.info <- data.frame(replicate = sample(x = c("rep1", "rep2"), size = length(x = pbmc@cell.names), 
    replace = TRUE), row.names = pbmc@cell.names)
pbmc <- AddMetaData(object = pbmc, metadata = replicate.info)
```

Example 3 (r):
```r
# Plot tSNE, coloring cells by cell type (currently stored in object@ident)
TSNEPlot(object = pbmc)
```

Example 4 (r):
```r
# Plot tSNE, coloring cells by cell type (currently stored in object@ident)
TSNEPlot(object = pbmc)
```

Example 5 (r):
```r
# How do I create a tSNE plot where cells are colored by replicate?  First,
# store the current identities in a new column of meta.data called CellType
pbmc <- StashIdent(object = pbmc, save.name = "CellType")
# Next, switch the identity class of all cells to reflect replicate ID
pbmc <- SetAllIdent(object = pbmc, id = "replicate")
TSNEPlot(object = pbmc)
```

Example 6 (r):
```r
# How do I create a tSNE plot where cells are colored by replicate?  First,
# store the current identities in a new column of meta.data called CellType
pbmc <- StashIdent(object = pbmc, save.name = "CellType")
# Next, switch the identity class of all cells to reflect replicate ID
pbmc <- SetAllIdent(object = pbmc, id = "replicate")
TSNEPlot(object = pbmc)
```

Example 7 (r):
```r
# alternately : TSNEPlot(pbmc, group.by = 'replicate') you can pass the
# pt.shape to label points by both replicate and cell type

# Switch back to cell type labels
pbmc <- SetAllIdent(object = pbmc, id = "CellType")
```

Example 8 (r):
```r
# alternately : TSNEPlot(pbmc, group.by = 'replicate') you can pass the
# pt.shape to label points by both replicate and cell type

# Switch back to cell type labels
pbmc <- SetAllIdent(object = pbmc, id = "CellType")
```

Example 9 (r):
```r
# How many cells are in each cluster
table(pbmc@ident)
```

Example 10 (r):
```r
# How many cells are in each cluster
table(pbmc@ident)
```

Example 11 (unknown):
```unknown
## 
##           B cells       CD4 T cells       CD8 T cells   CD14+ Monocytes 
##               342              1151               308               479 
##   Dendritic cells FCGR3A+ Monocytes    Megakaryocytes          NK cells 
##                32               157                14               155
```

Example 12 (unknown):
```unknown
## 
##           B cells       CD4 T cells       CD8 T cells   CD14+ Monocytes 
##               342              1151               308               479 
##   Dendritic cells FCGR3A+ Monocytes    Megakaryocytes          NK cells 
##                32               157                14               155
```

Example 13 (r):
```r
# How many cells are in each replicate?
table(pbmc@meta.data$replicate)
```

Example 14 (r):
```r
# How many cells are in each replicate?
table(pbmc@meta.data$replicate)
```

Example 15 (unknown):
```unknown
## 
## rep1 rep2 
## 1327 1311
```

Example 16 (unknown):
```unknown
## 
## rep1 rep2 
## 1327 1311
```

Example 17 (r):
```r
# restore cluster ID
pbmc <- SetAllIdent(object = pbmc, id = "CellType")

# What proportion of cells are in each cluster?
prop.table(x = table(pbmc@ident))
```

Example 18 (r):
```r
# restore cluster ID
pbmc <- SetAllIdent(object = pbmc, id = "CellType")

# What proportion of cells are in each cluster?
prop.table(x = table(pbmc@ident))
```

Example 19 (unknown):
```unknown
## 
##           B cells       CD4 T cells       CD8 T cells   CD14+ Monocytes 
##       0.129643669       0.436315390       0.116755118       0.181576952 
##   Dendritic cells FCGR3A+ Monocytes    Megakaryocytes          NK cells 
##       0.012130402       0.059514784       0.005307051       0.058756634
```

Example 20 (unknown):
```unknown
## 
##           B cells       CD4 T cells       CD8 T cells   CD14+ Monocytes 
##       0.129643669       0.436315390       0.116755118       0.181576952 
##   Dendritic cells FCGR3A+ Monocytes    Megakaryocytes          NK cells 
##       0.012130402       0.059514784       0.005307051       0.058756634
```

Example 21 (r):
```r
# How does cluster membership vary by replicate?
table(pbmc@ident, pbmc@meta.data$replicate)
```

Example 22 (r):
```r
# How does cluster membership vary by replicate?
table(pbmc@ident, pbmc@meta.data$replicate)
```

Example 23 (unknown):
```unknown
##                    
##                     rep1 rep2
##   B cells            164  178
##   CD4 T cells        563  588
##   CD8 T cells        176  132
##   CD14+ Monocytes    240  239
##   Dendritic cells     19   13
##   FCGR3A+ Monocytes   80   77
##   Megakaryocytes       4   10
##   NK cells            81   74
```

Example 24 (unknown):
```unknown
##                    
##                     rep1 rep2
##   B cells            164  178
##   CD4 T cells        563  588
##   CD8 T cells        176  132
##   CD14+ Monocytes    240  239
##   Dendritic cells     19   13
##   FCGR3A+ Monocytes   80   77
##   Megakaryocytes       4   10
##   NK cells            81   74
```

Example 25 (r):
```r
prop.table(x = table(pbmc@ident, pbmc@meta.data$replicate), margin = 2)
```

Example 26 (r):
```r
prop.table(x = table(pbmc@ident, pbmc@meta.data$replicate), margin = 2)
```

Example 27 (unknown):
```unknown
##                    
##                            rep1        rep2
##   B cells           0.123587038 0.135774218
##   CD4 T cells       0.424265260 0.448512586
##   CD8 T cells       0.132629992 0.100686499
##   CD14+ Monocytes   0.180859081 0.182303585
##   Dendritic cells   0.014318011 0.009916095
##   FCGR3A+ Monocytes 0.060286360 0.058733791
##   Megakaryocytes    0.003014318 0.007627765
##   NK cells          0.061039940 0.056445461
```

Example 28 (unknown):
```unknown
##                    
##                            rep1        rep2
##   B cells           0.123587038 0.135774218
##   CD4 T cells       0.424265260 0.448512586
##   CD8 T cells       0.132629992 0.100686499
##   CD14+ Monocytes   0.180859081 0.182303585
##   Dendritic cells   0.014318011 0.009916095
##   FCGR3A+ Monocytes 0.060286360 0.058733791
##   Megakaryocytes    0.003014318 0.007627765
##   NK cells          0.061039940 0.056445461
```

Example 29 (r):
```r
# What are the cell names of all NK cells?
WhichCells(object = pbmc, ident = "NK cells")
```

Example 30 (r):
```r
# What are the cell names of all NK cells?
WhichCells(object = pbmc, ident = "NK cells")
```

Example 31 (unknown):
```unknown
##   [1] "AAACCGTGTATGCG" "AAATTCGATTCTCA" "AACCTTACGCGAGA" "AACGCCCTCGTACA"
##   [5] "AACGTCGAGTATCG" "AAGATTACCTCAAG" "AAGCAAGAGGTGTT" "AAGTAGGATACAGC"
##   [9] "AATACTGAATTGGC" "AATCCTTGGTGAGG" "AATCTCTGCTTTAC" "ACAAATTGTTGCGA"
##  [13] "ACAACCGAGGGATG" "ACAATTGATGACTG" "ACACCCTGGTGTTG" "ACAGGTACTGGTGT"
##  [17] "ACCTGGCTAAGTAG" "ACGAACACCTTGTT" "ACGATCGAGGACTT" "ACGCAATGGTTCAG"
##  [21] "ACGCTGCTGTTCTT" "ACGGAACTCAGATC" "ACGTGATGTGACAC" "ACGTTGGAGCCAAT"
##  [25] "ACTGCCACTCCGTC" "ACTGGCCTTCAGTG" "ACTTCAACGTAGGG" "AGAACAGAAATGCC"
##  [29] "AGATATACCCGTAA" "AGATTCCTGTTCAG" "AGCCTCTGCCAATG" "AGCGATTGAGATCC"
##  [33] "AGGATGCTTTAGGC" "AGGGACGAGTCAAC" "AGTAATACATCACG" "AGTCACGATGAGCT"
##  [37] "AGTTTGCTACTGGT" "ATACCACTGCCAAT" "ATACTCTGGTATGC" "ATCCCGTGCAGTCA"
##  [41] "ATCTTTCTTGTCCC" "ATGAAGGACTTGCC" "ATGATAACTTCACT" "ATGATATGGTGCTA"
##  [45] "ATGGACACGCATCA" "ATGGGTACATCGGT" "ATTAACGATGAGAA" "ATTCCAACTTAGGC"
##  [49] "CAAGGTTGTCTGGA" "CAATCTACTGACTG" "CACCACTGGCGAAG" "CACGGGTGGAGGAC"
##  [53] "CAGATGACATTCTC" "CAGCAATGGAGGGT" "CAGCGGACCTTTAC" "CAGCTCTGTGTGGT"
##  [57] "CAGTTTACACACGT" "CATCAGGACTTCCG" "CATCAGGATAGCCA" "CATGAGACGTTGAC"
##  [61] "CATTACACCAACTG" "CATTTCGAGATACC" "CCTCGAACACTTTC" "CGACCACTAAAGTG"
##  [65] "CGACCACTGCCAAT" "CGAGGCTGACGCTA" "CGCCGAGAGCTTAG" "CGGCGAACGACAAA"
##  [69] "CGGCGAACTACTTC" "CGGGCATGTCTCTA" "CGTACCTGGCATCA" "CGTGTAGACGATAC"
##  [73] "CGTGTAGAGTTACG" "CGTGTAGATTCGGA" "CTAAACCTCTGACA" "CTAACGGAACCGAT"
##  [77] "CTACGCACTGGTCA" "CTACTCCTATGTCG" "CTAGTTACGAAACA" "CTATACTGCTACGA"
##  [81] "CTATACTGTCTCAT" "CTCGACTGGTTGAC" "CTGAGAACGTAAAG" "CTTTAGTGACGGGA"
##  [85] "GAACCAACTTCCGC" "GAAGTGCTAAACGA" "GAATGCACCTTCGC" "GAATTAACGTCGTA"
##  [89] "GACGGCACACGGGA" "GAGCGCTGAAGATG" "GAGGTACTGACACT" "GAGGTGGATCCTCG"
##  [93] "GATAGAGAAGGGTG" "GATCCCTGACCTTT" "GCACACCTGTGCTA" "GCACCACTTCCTTA"
##  [97] "GCACTAGAGTCGTA" "GCAGGGCTATCGAC" "GCCGGAACGTTCTT" "GCCTACACAGTTCG"
## [101] "GCGCATCTTGCTCC" "GCGCGATGGTGCAT" "GGAAGGTGGCGAGA" "GGACGCTGTCCTCG"
## [105] "GGAGGCCTCGTTGA" "GGCAAGGAAAAAGC" "GGCATATGCTTATC" "GGCCGAACTCTAGG"
## [109] "GGCTAAACACCTGA" "GGGTTAACGTGCAT" "GGTGGAGAAACGGG" "GGTGGAGACAGATC"
## [113] "GTAGTGTGAGCGGA" "GTCGACCTGAATGA" "GTGATTCTGGTTCA" "GTTAAAACCGAGAG"
## [117] "GTTCAACTGGGACA" "GTTGACGAGCCCTT" "GTTGACGATATCGG" "TAACTCACTCTACT"
## [121] "TAAGAGGACTTGTT" "TAATGCCTCGTCTC" "TACGCAGAGAATCC" "TACGGCCTGGGACA"
## [125] "TACTCTGAATCGAC" "TACTGTTGAGGCGA" "TAGCATCTCAGCTA" "TAGCCCACAGCTAC"
## [129] "TAGTGGTGAAGTGA" "TAGTTAGAACCACA" "TATCGACTACTAGC" "TATGAATGGAGGAC"
## [133] "TATGGGTGCATCAG" "TATTTCCTGGAGGT" "TCAACACTGTTTGG" "TCAGACGACGTTAG"
## [137] "TCCCGAACACAGTC" "TCCTAAACCGCATA" "TCGATTTGCAGCTA" "TCTAACACCAGTTG"
## [141] "TGATAAACTCCGTC" "TGCACAGACGACAT" "TGCCACTGCGATAC" "TGCTGAGAGAGCAG"
## [145] "TGGAACACAAACAG" "TGGTAGACCCTCAC" "TGTAATGACACAAC" "TGTAATGAGGTAAA"
## [149] "TTACTCGATCTACT" "TTAGTCTGCCAACA" "TTCCAAACTCCCAC" "TTCCCACTTGAGGG"
## [153] "TTCTAGTGGAGAGC" "TTCTGATGGAGACG" "TTGTCATGGACGGA"
```

Example 32 (unknown):
```unknown
##   [1] "AAACCGTGTATGCG" "AAATTCGATTCTCA" "AACCTTACGCGAGA" "AACGCCCTCGTACA"
##   [5] "AACGTCGAGTATCG" "AAGATTACCTCAAG" "AAGCAAGAGGTGTT" "AAGTAGGATACAGC"
##   [9] "AATACTGAATTGGC" "AATCCTTGGTGAGG" "AATCTCTGCTTTAC" "ACAAATTGTTGCGA"
##  [13] "ACAACCGAGGGATG" "ACAATTGATGACTG" "ACACCCTGGTGTTG" "ACAGGTACTGGTGT"
##  [17] "ACCTGGCTAAGTAG" "ACGAACACCTTGTT" "ACGATCGAGGACTT" "ACGCAATGGTTCAG"
##  [21] "ACGCTGCTGTTCTT" "ACGGAACTCAGATC" "ACGTGATGTGACAC" "ACGTTGGAGCCAAT"
##  [25] "ACTGCCACTCCGTC" "ACTGGCCTTCAGTG" "ACTTCAACGTAGGG" "AGAACAGAAATGCC"
##  [29] "AGATATACCCGTAA" "AGATTCCTGTTCAG" "AGCCTCTGCCAATG" "AGCGATTGAGATCC"
##  [33] "AGGATGCTTTAGGC" "AGGGACGAGTCAAC" "AGTAATACATCACG" "AGTCACGATGAGCT"
##  [37] "AGTTTGCTACTGGT" "ATACCACTGCCAAT" "ATACTCTGGTATGC" "ATCCCGTGCAGTCA"
##  [41] "ATCTTTCTTGTCCC" "ATGAAGGACTTGCC" "ATGATAACTTCACT" "ATGATATGGTGCTA"
##  [45] "ATGGACACGCATCA" "ATGGGTACATCGGT" "ATTAACGATGAGAA" "ATTCCAACTTAGGC"
##  [49] "CAAGGTTGTCTGGA" "CAATCTACTGACTG" "CACCACTGGCGAAG" "CACGGGTGGAGGAC"
##  [53] "CAGATGACATTCTC" "CAGCAATGGAGGGT" "CAGCGGACCTTTAC" "CAGCTCTGTGTGGT"
##  [57] "CAGTTTACACACGT" "CATCAGGACTTCCG" "CATCAGGATAGCCA" "CATGAGACGTTGAC"
##  [61] "CATTACACCAACTG" "CATTTCGAGATACC" "CCTCGAACACTTTC" "CGACCACTAAAGTG"
##  [65] "CGACCACTGCCAAT" "CGAGGCTGACGCTA" "CGCCGAGAGCTTAG" "CGGCGAACGACAAA"
##  [69] "CGGCGAACTACTTC" "CGGGCATGTCTCTA" "CGTACCTGGCATCA" "CGTGTAGACGATAC"
##  [73] "CGTGTAGAGTTACG" "CGTGTAGATTCGGA" "CTAAACCTCTGACA" "CTAACGGAACCGAT"
##  [77] "CTACGCACTGGTCA" "CTACTCCTATGTCG" "CTAGTTACGAAACA" "CTATACTGCTACGA"
##  [81] "CTATACTGTCTCAT" "CTCGACTGGTTGAC" "CTGAGAACGTAAAG" "CTTTAGTGACGGGA"
##  [85] "GAACCAACTTCCGC" "GAAGTGCTAAACGA" "GAATGCACCTTCGC" "GAATTAACGTCGTA"
##  [89] "GACGGCACACGGGA" "GAGCGCTGAAGATG" "GAGGTACTGACACT" "GAGGTGGATCCTCG"
##  [93] "GATAGAGAAGGGTG" "GATCCCTGACCTTT" "GCACACCTGTGCTA" "GCACCACTTCCTTA"
##  [97] "GCACTAGAGTCGTA" "GCAGGGCTATCGAC" "GCCGGAACGTTCTT" "GCCTACACAGTTCG"
## [101] "GCGCATCTTGCTCC" "GCGCGATGGTGCAT" "GGAAGGTGGCGAGA" "GGACGCTGTCCTCG"
## [105] "GGAGGCCTCGTTGA" "GGCAAGGAAAAAGC" "GGCATATGCTTATC" "GGCCGAACTCTAGG"
## [109] "GGCTAAACACCTGA" "GGGTTAACGTGCAT" "GGTGGAGAAACGGG" "GGTGGAGACAGATC"
## [113] "GTAGTGTGAGCGGA" "GTCGACCTGAATGA" "GTGATTCTGGTTCA" "GTTAAAACCGAGAG"
## [117] "GTTCAACTGGGACA" "GTTGACGAGCCCTT" "GTTGACGATATCGG" "TAACTCACTCTACT"
## [121] "TAAGAGGACTTGTT" "TAATGCCTCGTCTC" "TACGCAGAGAATCC" "TACGGCCTGGGACA"
## [125] "TACTCTGAATCGAC" "TACTGTTGAGGCGA" "TAGCATCTCAGCTA" "TAGCCCACAGCTAC"
## [129] "TAGTGGTGAAGTGA" "TAGTTAGAACCACA" "TATCGACTACTAGC" "TATGAATGGAGGAC"
## [133] "TATGGGTGCATCAG" "TATTTCCTGGAGGT" "TCAACACTGTTTGG" "TCAGACGACGTTAG"
## [137] "TCCCGAACACAGTC" "TCCTAAACCGCATA" "TCGATTTGCAGCTA" "TCTAACACCAGTTG"
## [141] "TGATAAACTCCGTC" "TGCACAGACGACAT" "TGCCACTGCGATAC" "TGCTGAGAGAGCAG"
## [145] "TGGAACACAAACAG" "TGGTAGACCCTCAC" "TGTAATGACACAAC" "TGTAATGAGGTAAA"
## [149] "TTACTCGATCTACT" "TTAGTCTGCCAACA" "TTCCAAACTCCCAC" "TTCCCACTTGAGGG"
## [153] "TTCTAGTGGAGAGC" "TTCTGATGGAGACG" "TTGTCATGGACGGA"
```

Example 33 (r):
```r
# How can I extract expression matrix for all NK cells (perhaps, to load
# into another package)
nk.raw.data <- as.matrix(x = pbmc@raw.data[, WhichCells(object = pbmc, ident = "NK cells")])

# Can I create a Seurat object of just the NK cells and B cells?
nk.subset <- SubsetData(object = pbmc, ident.use = c("NK cells", "B cells"))

# Can I create a Seurat object of all cells except the NK cells and B cells?
other.subset <- SubsetData(object = pbmc, ident.remove = c("NK cells", "B cells"))

# note that if you wish to perform additional rounds of clustering after
# SubsetData we recommend re-running FindVariableGenes() and ScaleData()
```

Example 34 (r):
```r
# How can I extract expression matrix for all NK cells (perhaps, to load
# into another package)
nk.raw.data <- as.matrix(x = pbmc@raw.data[, WhichCells(object = pbmc, ident = "NK cells")])

# Can I create a Seurat object of just the NK cells and B cells?
nk.subset <- SubsetData(object = pbmc, ident.use = c("NK cells", "B cells"))

# Can I create a Seurat object of all cells except the NK cells and B cells?
other.subset <- SubsetData(object = pbmc, ident.remove = c("NK cells", "B cells"))

# note that if you wish to perform additional rounds of clustering after
# SubsetData we recommend re-running FindVariableGenes() and ScaleData()
```

Example 35 (r):
```r
# How can I calculate the average expression of all cells within a cluster?
cluster.averages <- AverageExpression(object = pbmc)
```

Example 36 (r):
```r
# How can I calculate the average expression of all cells within a cluster?
cluster.averages <- AverageExpression(object = pbmc)
```

Example 37 (unknown):
```unknown
## [1] "Finished averaging RNA for cluster B cells"
## [1] "Finished averaging RNA for cluster CD4 T cells"
## [1] "Finished averaging RNA for cluster CD8 T cells"
## [1] "Finished averaging RNA for cluster CD14+ Monocytes"
## [1] "Finished averaging RNA for cluster Dendritic cells"
## [1] "Finished averaging RNA for cluster FCGR3A+ Monocytes"
## [1] "Finished averaging RNA for cluster Megakaryocytes"
## [1] "Finished averaging RNA for cluster NK cells"
```

Example 38 (unknown):
```unknown
## [1] "Finished averaging RNA for cluster B cells"
## [1] "Finished averaging RNA for cluster CD4 T cells"
## [1] "Finished averaging RNA for cluster CD8 T cells"
## [1] "Finished averaging RNA for cluster CD14+ Monocytes"
## [1] "Finished averaging RNA for cluster Dendritic cells"
## [1] "Finished averaging RNA for cluster FCGR3A+ Monocytes"
## [1] "Finished averaging RNA for cluster Megakaryocytes"
## [1] "Finished averaging RNA for cluster NK cells"
```

Example 39 (r):
```r
head(x = cluster.averages[, 1:5])
```

Example 40 (r):
```r
head(x = cluster.averages[, 1:5])
```

Example 41 (unknown):
```unknown
##                  B cells CD4 T cells CD8 T cells CD14+ Monocytes
## AL627309.1    0.00000000 0.006198564  0.01807769      0.04864473
## AP006222.2    0.00000000 0.003443558  0.01048354      0.01090743
## RP11-206L10.2 0.02077107 0.004513297  0.00000000      0.00000000
## RP11-206L10.9 0.00000000 0.000000000  0.00000000      0.01052309
## LINC00115     0.03911281 0.018897675  0.02850651      0.03761574
## NOC2L         0.55560804 0.457757658  0.49811901      0.27827017
##               Dendritic cells
## AL627309.1         0.00000000
## AP006222.2         0.00000000
## RP11-206L10.2      0.08462847
## RP11-206L10.9      0.00000000
## LINC00115          0.00000000
## NOC2L              0.27913384
```

Example 42 (unknown):
```unknown
##                  B cells CD4 T cells CD8 T cells CD14+ Monocytes
## AL627309.1    0.00000000 0.006198564  0.01807769      0.04864473
## AP006222.2    0.00000000 0.003443558  0.01048354      0.01090743
## RP11-206L10.2 0.02077107 0.004513297  0.00000000      0.00000000
## RP11-206L10.9 0.00000000 0.000000000  0.00000000      0.01052309
## LINC00115     0.03911281 0.018897675  0.02850651      0.03761574
## NOC2L         0.55560804 0.457757658  0.49811901      0.27827017
##               Dendritic cells
## AL627309.1         0.00000000
## AP006222.2         0.00000000
## RP11-206L10.2      0.08462847
## RP11-206L10.9      0.00000000
## LINC00115          0.00000000
## NOC2L              0.27913384
```

Example 43 (r):
```r
# Return this information as a Seurat object (enables downstream plotting
# and analysis)
cluster.averages <- AverageExpression(object = pbmc, return.seurat = TRUE, show.progress = FALSE)

# How can I plot the average expression of NK cells vs. CD8 T cells?  Pass
# do.hover = T for an interactive plot to identify gene outliers
CellPlot(object = cluster.averages, cell1 = "NK cells", cell2 = "CD8 T cells")
```

Example 44 (r):
```r
# Return this information as a Seurat object (enables downstream plotting
# and analysis)
cluster.averages <- AverageExpression(object = pbmc, return.seurat = TRUE, show.progress = FALSE)

# How can I plot the average expression of NK cells vs. CD8 T cells?  Pass
# do.hover = T for an interactive plot to identify gene outliers
CellPlot(object = cluster.averages, cell1 = "NK cells", cell2 = "CD8 T cells")
```

Example 45 (r):
```r
# How can I calculate expression averages separately for each replicate?
cluster.averages <- AverageExpression(object = pbmc, return.seurat = TRUE, add.ident = "replicate", 
    show.progress = FALSE)
CellPlot(object = cluster.averages, cell1 = "CD14+ Monocytes_rep1", cell2 = "CD14+ Monocytes_rep2")
```

Example 46 (r):
```r
# How can I calculate expression averages separately for each replicate?
cluster.averages <- AverageExpression(object = pbmc, return.seurat = TRUE, add.ident = "replicate", 
    show.progress = FALSE)
CellPlot(object = cluster.averages, cell1 = "CD14+ Monocytes_rep1", cell2 = "CD14+ Monocytes_rep2")
```

Example 47 (r):
```r
# You can also plot heatmaps of these 'in silico' bulk datasets to visualize
# agreement between replicates
DoHeatmap(object = cluster.averages, genes.use = PCTopGenes(object = pbmc, pc.use = 1, 
    do.balanced = TRUE), group.label.rot = TRUE, group.cex = 0)
```

Example 48 (r):
```r
# You can also plot heatmaps of these 'in silico' bulk datasets to visualize
# agreement between replicates
DoHeatmap(object = cluster.averages, genes.use = PCTopGenes(object = pbmc, pc.use = 1, 
    do.balanced = TRUE), group.label.rot = TRUE, group.cex = 0)
```

---

## Using sctransform in Seurat

**URL:** http://127.0.0.1:9173/seurat/archive/v3.2/sctransform_vignette/index.html

**Contents:**
- Using sctransform in Seurat
    - Christoph Hafemeister & Rahul Satija
    - Compiled: 2020-10-02

This vignette shows how to use the sctransform wrapper in Seurat.

Install sctransform and Seurat v3.

Load data and create Seurat object

Apply sctransform normalization

Perform dimensionality reduction by PCA and UMAP embedding

Why can we choose more PCs when using sctransform?

In the standard Seurat workflow we focus on 10 PCs for this dataset, though we highlight that the results are similar with higher settings for this parameter. Interestingtly, we've found that when using sctransform, we often benefit by pushing this parameter even higher. We believe this is because the sctransform workflow performs more effective normalization, strongly removing technical effects from the data.

Even after standard log-normalization, variation in sequencing depth is still a confounding factor (see Figure 1), and this effect can subtly influence higher PCs. In sctransform, this effect is substantially mitigated (see Figure 3). This means that higher PCs are more likely to represent subtle, but biologically relevant, sources of heterogeneity -- so including them may improve downstream analysis.

In addition, sctransform returns 3,000 variable features by default, instead of 2,000. The rationale is similar, the additional variable features are less likely to be driven by technical differences across cells, and instead may represent more subtle biological fluctuations. In general, we find that results produced with sctransform are less dependent on these parameters (indeed, we achieve nearly identical results when using all genes in the transcriptome, though this does reduce computational efficiency). This can help users generate more robust results, and in addition, enables the application of standard anlaysis pipelines with identical parameter settings that can quickly be applied to new datasets:

For example, the following code replicates the full end-to-end workflow, in a single command:

Where are normalized values stored for sctransform?

As described in our preprint, sctransform calculates a model of technical noise in scRNA-seq data using 'regularized negative binomial regression'. The residuals for this model are normalized values, and can be positive or negative. Positive residuals for a given gene in a given cell indicate that we observed more UMIs than expected given the gene’s average expression in the population and cellular sequencing depth, while negative residuals indicate the converse.

The results of sctransfrom are stored in the "SCT" assay. You can learn more about multi-assay data and commands in Seurat in our vignette, command cheat sheet, or developer guide.

Users can individually annotate clusters based on canonical markers. However, the sctransform normalization reveals sharper biological distinctions compared to the standard Seurat workflow, in a few ways:

**Examples:**

Example 1 (r):
```r
install.packages("Seurat")
```

Example 2 (r):
```r
install.packages("Seurat")
```

Example 3 (r):
```r
library(Seurat)
library(ggplot2)
library(sctransform)
```

Example 4 (r):
```r
library(Seurat)
library(ggplot2)
library(sctransform)
```

Example 5 (r):
```r
pbmc_data <- Read10X(data.dir = "../data/pbmc3k/filtered_gene_bc_matrices/hg19/")
pbmc <- CreateSeuratObject(counts = pbmc_data)
```

Example 6 (r):
```r
pbmc_data <- Read10X(data.dir = "../data/pbmc3k/filtered_gene_bc_matrices/hg19/")
pbmc <- CreateSeuratObject(counts = pbmc_data)
```

Example 7 (unknown):
```unknown
NormalizeData
```

Example 8 (unknown):
```unknown
FindVariableFeatures
```

Example 9 (r):
```r
# store mitochondrial percentage in object meta data
pbmc <- PercentageFeatureSet(pbmc, pattern = "^MT-", col.name = "percent.mt")

# run sctransform
pbmc <- SCTransform(pbmc, vars.to.regress = "percent.mt", verbose = FALSE)
```

Example 10 (r):
```r
# store mitochondrial percentage in object meta data
pbmc <- PercentageFeatureSet(pbmc, pattern = "^MT-", col.name = "percent.mt")

# run sctransform
pbmc <- SCTransform(pbmc, vars.to.regress = "percent.mt", verbose = FALSE)
```

Example 11 (r):
```r
# These are now standard steps in the Seurat workflow for visualization and clustering
pbmc <- RunPCA(pbmc, verbose = FALSE)
pbmc <- RunUMAP(pbmc, dims = 1:30, verbose = FALSE)

pbmc <- FindNeighbors(pbmc, dims = 1:30, verbose = FALSE)
pbmc <- FindClusters(pbmc, verbose = FALSE)
DimPlot(pbmc, label = TRUE) + NoLegend()
```

Example 12 (r):
```r
# These are now standard steps in the Seurat workflow for visualization and clustering
pbmc <- RunPCA(pbmc, verbose = FALSE)
pbmc <- RunUMAP(pbmc, dims = 1:30, verbose = FALSE)

pbmc <- FindNeighbors(pbmc, dims = 1:30, verbose = FALSE)
pbmc <- FindClusters(pbmc, verbose = FALSE)
DimPlot(pbmc, label = TRUE) + NoLegend()
```

Example 13 (r):
```r
pbmc <- CreateSeuratObject(pbmc_data) %>% PercentageFeatureSet(pattern = "^MT-", col.name = "percent.mt") %>% 
    SCTransform(vars.to.regress = "percent.mt") %>% RunPCA() %>% FindNeighbors(dims = 1:30) %>% 
    RunUMAP(dims = 1:30) %>% FindClusters()
```

Example 14 (r):
```r
pbmc <- CreateSeuratObject(pbmc_data) %>% PercentageFeatureSet(pattern = "^MT-", col.name = "percent.mt") %>% 
    SCTransform(vars.to.regress = "percent.mt") %>% RunPCA() %>% FindNeighbors(dims = 1:30) %>% 
    RunUMAP(dims = 1:30) %>% FindClusters()
```

Example 15 (unknown):
```unknown
pbmc[["SCT"]]@scale.data
```

Example 16 (unknown):
```unknown
SCTransform
```

Example 17 (unknown):
```unknown
pbmc[["SCT"]]@counts
```

Example 18 (unknown):
```unknown
pbmc[["SCT"]]@data
```

Example 19 (r):
```r
# These are now standard steps in the Seurat workflow for visualization and clustering Visualize
# canonical marker genes as violin plots.
VlnPlot(pbmc, features = c("CD8A", "GZMK", "CCL5", "S100A4", "ANXA1", "CCR7", "ISG15", "CD3D"), 
    pt.size = 0.2, ncol = 4)
```

Example 20 (r):
```r
# These are now standard steps in the Seurat workflow for visualization and clustering Visualize
# canonical marker genes as violin plots.
VlnPlot(pbmc, features = c("CD8A", "GZMK", "CCL5", "S100A4", "ANXA1", "CCR7", "ISG15", "CD3D"), 
    pt.size = 0.2, ncol = 4)
```

Example 21 (r):
```r
# Visualize canonical marker genes on the sctransform embedding.
FeaturePlot(pbmc, features = c("CD8A", "GZMK", "CCL5", "S100A4", "ANXA1", "CCR7"), pt.size = 0.2, 
    ncol = 3)
```

Example 22 (r):
```r
# Visualize canonical marker genes on the sctransform embedding.
FeaturePlot(pbmc, features = c("CD8A", "GZMK", "CCL5", "S100A4", "ANXA1", "CCR7"), pt.size = 0.2, 
    ncol = 3)
```

Example 23 (r):
```r
FeaturePlot(pbmc, features = c("CD3D", "ISG15", "TCL1A", "FCER2", "XCL1", "FCGR3A"), pt.size = 0.2, 
    ncol = 3)
```

Example 24 (r):
```r
FeaturePlot(pbmc, features = c("CD3D", "ISG15", "TCL1A", "FCER2", "XCL1", "FCGR3A"), pt.size = 0.2, 
    ncol = 3)
```

---
