### Installing JOINTLY R Package Source: https://github.com/madsen-lab/rjointly/blob/main/README.md This snippet demonstrates how to install the JOINTLY R package directly from GitHub using the `remotes` package. It first installs `remotes` from CRAN, then uses it to install `rJOINTLY` from the `madsen-lab` repository. This is the recommended method for obtaining the latest development version of JOINTLY. ```R install.packages("remotes") remotes::install_github("madsen-lab/rJOINTLY") ``` -------------------------------- ### Installing and Loading Libraries (R) Source: https://github.com/madsen-lab/rjointly/blob/main/README.md This snippet installs and loads necessary R packages for the JOINTLY analysis. It includes `presto` for single-cell analysis and `expm` for matrix exponentiation, which are prerequisites for the subsequent steps. ```R remotes::install_github("immunogenomics/presto") install.packages("expm") library("expm") library("presto") ``` -------------------------------- ### Performing Joint Clustering and Interpretation with JOINTLY in R Source: https://github.com/madsen-lab/rjointly/blob/main/README.md This comprehensive example demonstrates the full workflow for using JOINTLY. It covers setting up the R environment by installing and loading necessary libraries (Seurat, aricode, UCell, JOINTLY), loading a test dataset, running the `jointly` function for clustering, importing and adding cell type labels, subsetting the data, performing Seurat-based clustering, evaluating results with ARI and NMI, embedding data with UMAP, and finally interpreting results by calculating and visualizing module scores. The `jointly` function processes a Seurat object and returns a list containing the processed Seurat object and identified modules. ```R ### How to setup the environment for testing JOINTLY ## Install libraries from CRAN install.packages("remotes") install.packages("Seurat") install.packages("aricode") ## Install libraries from GitHub remotes::install_github("madsen-lab/rJOINTLY") remotes::install_github("carmonalab/UCell") ## Load libraries library(Seurat) library(aricode) library(UCell) library(JOINTLY) ## Load the liver dataset # Datasets, labels, embeddings and results used for testing JOINTLY can be downloaded here: https://zenodo.org/record/8298157 liver <- readRDS("Human_Liver.rds") ### Joint clustering and evaluation with JOINTLY ## Run JOINTLY # To run in parallel pass the option: bpparam = BiocParallel::MulticoreParam() # The resulting object is a list that holds a Seurat object as the first entry and module as the second entry liver <- jointly(liver, batch.var = "batch_label") ## Import labels and add to the object labels <- read.delim("Human_Liver_labels.tsv") labels <- labels[ match(colnames(liver$object), labels$X),] liver$object$celltype <- labels$Transferred_labels ## Subset the object to only named cell types with more than 10 cells liver$object <- subset(liver$object, celltype %in% names(which(table(liver$object$celltype) >= 10))) liver$object <- subset(liver$object, celltype != "") ## Run clustering liver$object <- FindNeighbors(liver$object, reduction = "JOINTLY", dims = 1:15) liver$object <- FindClusters(liver$object, res = 0.05) ## Calculate ARI and NMI aricode::ARI(liver$object$celltype, liver$object$seurat_clusters) # 0.7415981 aricode::NMI(liver$object$celltype, liver$object$seurat_clusters) # 0.6325386 ## Embed using UMAP liver$object <- RunUMAP(liver$object, reduction = "JOINTLY", dims = 1:15) ## Plot by cluster, cell type and batch # Setting a seed and re-running produces a different result. Sometimes it is worth running JOINTLY up to 5 times and choosing the best solution. DimPlot(liver$object, group.by = "seurat_clusters", label = TRUE) + DimPlot(liver$object, group.by = "celltype", label = TRUE) + DimPlot(liver$object, group.by = "batch_label", label = FALSE) & NoLegend() ### Interpretation of JOINTLY ## Calculate module scores liver$object <- AddModuleScore_UCell(liver$object, features = liver$modules) ## Visualize module scores on the UMAP FeaturePlot(liver$object, features = "factor_1_UCell") ``` -------------------------------- ### Loading Liver Dataset (R) Source: https://github.com/madsen-lab/rjointly/blob/main/README.md This code loads the 'Human_Liver.rds' dataset into the `liver` R object. It provides two example paths, demonstrating how to load the Seurat object from a local file or a specific user directory. ```R liver <- readRDS("Human_Liver.rds") liver <- readRDS("C:/Users/jgsm/OneDrive - Syddansk Universitet/Human_Liver.rds") ``` -------------------------------- ### Running JOINTLY Preprocessing and Solving (R) Source: https://github.com/madsen-lab/rjointly/blob/main/README.md This snippet executes the core JOINTLY workflow without the convenience wrapper. It preprocesses the `liver` dataset by `batch_label`, performs cPCA, prepares data inputs, and then solves the JOINTLY model to obtain `Hmat` and `Fmat`. ```R proc <- preprocess(liver, "batch_label") cpca <- cpca(proc) inputs <- prepareData(cpca$cpca) solved <- JOINTLYsolve(inputs$kernels, inputs$snn, inputs$rareity, cpca) ``` -------------------------------- ### Calculating Batch-Aware Smoothed Expression (R) Source: https://github.com/madsen-lab/rjointly/blob/main/README.md This loop calculates batch-aware smoothed expression values for each dataset using the learned F and H matrices, similar to MAGIC. It constructs a transition matrix `T` from the reconstructed kernel and applies it for `n_steps` to smooth the normalized expression data, storing results in `recon_expression_list`. ```R n_steps = 1 recon_expression_list <- list() for (idx in 1:length(proc)){ recon_kernel = solved$Fmat[[idx]] %*% solved$Hmat[[idx]] recon_kernel = 0.5 * (recon_kernel + t(recon_kernel)) D = 1 / rowSums(recon_kernel) T = matrix(diag(D),ncol=length(D)) %*% recon_kernel T_steps = T %^% n_steps recon_expression = as.data.frame(T_steps %*% t(cpca$normalized[[idx]])) rownames(recon_expression) = colnames(cpca$normalized[[idx]]) recon_expression_list[[idx]] = recon_expression } ``` -------------------------------- ### Importing Labels and Subsetting Seurat Object (R) Source: https://github.com/madsen-lab/rjointly/blob/main/README.md This snippet imports cell type labels and applies them to the `liver$object` Seurat object. It then subsets the object to include only cell types with at least 10 cells and non-empty cell type labels, preparing the data for further analysis. ```R labels <- read.delim("Human_Liver_labels.tsv") labels <- labels[ match(colnames(liver$object), labels$X),] liver$object$celltype <- labels$Transferred_labels liver$object <- subset(liver$object, celltype %in% names(which(table(liver$object$celltype) >= 10))) liver$object <- subset(liver$object, celltype != "") ``` -------------------------------- ### Identifying Marker Genes with Presto (R) Source: https://github.com/madsen-lab/rjointly/blob/main/README.md This snippet uses the `wilcoxauc` function from the `presto` package to identify marker genes for each cell type. It performs this analysis separately for both the raw 'RNA' assay and the 'imputed' assay, creating unique IDs for each marker. ```R res.raw <- wilcoxauc(liver, group_by = "celltype", seurat_assay = "RNA") res.raw$id <- paste(res.raw$group, res.raw$feature, sep="_") res.imputed <- wilcoxauc(liver, group_by = "celltype", seurat_assay = "imputed") res.imputed$id <- paste(res.imputed$group, res.imputed$feature, sep="_") ``` -------------------------------- ### Calculating Pseudo-bulk Expression (R) Source: https://github.com/madsen-lab/rjointly/blob/main/README.md This snippet calculates pseudo-bulk expression values for each cell type and batch combination. It creates a `group` metadata field and then uses `AverageExpression` to compute average expression for both imputed and raw RNA assays. ```R liver$group <- paste(liver$celltype, liver$batch_label, sep="_") psb_imputed <- AverageExpression(liver, assays = "imputed", group.by = "group")$imputed psb_raw <- AverageExpression(liver, assays = "RNA", group.by = "group")$RNA ``` -------------------------------- ### Performing UMAP Embedding with JOINTLY Reduction (R) Source: https://github.com/madsen-lab/rjointly/blob/main/README.md This snippet performs Uniform Manifold Approximation and Projection (UMAP) on the Seurat object. It uses the 'JOINTLY' dimensional reduction (derived from the H matrix) and the first 15 dimensions for the embedding. ```R liver <- RunUMAP(liver, reduction = "JOINTLY", dims = 1:15) ``` -------------------------------- ### Calculating IGF1 Coefficient of Variation (R) Source: https://github.com/madsen-lab/rjointly/blob/main/README.md This code calculates and compares the coefficient of variation (CV) for IGF1 expression specifically in hepatocytes, using both raw and imputed pseudo-bulk values. It demonstrates that imputed values have a lower CV, suggesting reduced batch effects. ```R igf1_hep_imputed <- psb_imputed[ rownames(psb_imputed) == "ENSG00000017427", grep("Hepatocytes", colnames(psb_imputed))] igf1_hep_raw <- psb_raw[ rownames(psb_raw) == "ENSG00000017427", grep("Hepatocytes", colnames(psb_raw))] sd(igf1_hep_raw) / mean(igf1_hep_raw) # 1.045458 sd(igf1_hep_imputed) / mean(igf1_hep_imputed) # 0.5184951 ``` -------------------------------- ### Calculating Global Coefficient of Variation (R) Source: https://github.com/madsen-lab/rjointly/blob/main/README.md This code iterates through all unique cell types to calculate the coefficient of variation (CV) for all genes using both raw and imputed pseudo-bulk expression values. It then reports the median CV for both sets, demonstrating the overall reduction in variability after imputation. ```R cov.raw <- c() cov.imputed <- c() for (ct in unique(liver$celltype)) { imputed <- psb_imputed[ , grep(ct, colnames(psb_imputed))] cov.imputed <- c(cov.imputed, apply(imputed,1,FUN="sd") / apply(imputed,1,FUN="mean")) raw <- psb_raw[, grep(ct, colnames(psb_raw))] cov.raw <- c(cov.raw, apply(raw,1,FUN="sd") / apply(raw,1,FUN="mean")) } median(cov.raw, na.rm=TRUE) # 1.38173 median(cov.imputed, na.rm=TRUE) # 0.513786 ``` -------------------------------- ### Integrating JOINTLY H Matrix into Seurat (R) Source: https://github.com/madsen-lab/rjointly/blob/main/README.md This code integrates the scaled H matrix (`Hmat`) obtained from JOINTLY into the original Seurat object as a `DimReduc` object named 'JOINTLY'. It ensures the H matrix rows are matched to the Seurat object's column names (cells) before creation. ```R Hmat <- solved$Hmat.scaled Hmat <- Hmat[ match(colnames(liver), rownames(Hmat)),] liver[["JOINTLY"]] <- Seurat::CreateDimReducObject(Hmat, assay = "RNA") ``` -------------------------------- ### Importing and Assigning Cell Type Labels (R) Source: https://github.com/madsen-lab/rjointly/blob/main/README.md This code imports cell type labels from 'Human_Liver_labels.tsv' and adds them to the Seurat object. It matches the labels to the cell barcodes in the `liver` object and assigns them to the `celltype` metadata slot. ```R labels <- read.delim("Human_Liver_labels.tsv") labels <- labels[ match(colnames(liver), labels$X),] liver$celltype <- labels$Transferred_labels ``` -------------------------------- ### Combining Smoothed Expression Across Batches (R) Source: https://github.com/madsen-lab/rjointly/blob/main/README.md This snippet combines the smoothed expression data from individual batches (stored in `recon_expression_list`) into a single data frame. It uses `do.call` and `rbind` to vertically concatenate the data frames. ```R recon_expression = as.data.frame(do.call("rbind", recon_expression_list)) ``` -------------------------------- ### Adding Imputed Expression as Seurat Assay (R) Source: https://github.com/madsen-lab/rjointly/blob/main/README.md This code creates a new assay named 'imputed' within the Seurat object, populating it with the calculated smoothed (imputed) expression values. It transposes the `recon_expression` data and matches cell names to ensure correct alignment. ```R liver[["imputed"]] <- CreateAssayObject(data = t(recon_expression[match(colnames(liver), rownames(recon_expression)),])) ``` -------------------------------- ### Visualizing IGF1 Expression on UMAP (R) Source: https://github.com/madsen-lab/rjointly/blob/main/README.md This snippet visualizes the expression of IGF1 (gene ENSG00000017427) on the UMAP embedding using both raw and imputed values. It generates two feature plots and combines them to compare the effect of smoothing on gene expression visualization. ```R fp_raw <- FeaturePlot(liver, "ENSG00000017427", reduction = "umap") DefaultAssay(liver) <- "imputed" fp_imputed <- FeaturePlot(liver, "ENSG00000017427", reduction = "umap") fp_raw + fp_imputed ``` -------------------------------- ### Filtering Marker Genes from Raw Data (R) Source: https://github.com/madsen-lab/rjointly/blob/main/README.md This code filters the results from the raw marker gene analysis (`res.raw`) to define a list of significant markers. It selects genes with a log2 fold change (logFC) greater than or equal to log2(1.1), an adjusted p-value (padj) less than or equal to 0.05, and an AUC greater than or equal to 0.6. ```R markers.raw <- res.raw[ res.raw$logFC >= log2(1.1) & res.raw$padj <= 0.05 & res.raw$auc >= 0.6,"id"] ``` -------------------------------- ### Calculating Average AUC for Marker Genes in R Source: https://github.com/madsen-lab/rjointly/blob/main/README.md This R code snippet calculates the mean Area Under the Curve (AUC) for a set of marker genes, first from raw data and then from imputed data. It highlights the improvement in AUC values after imputation, indicating enhanced cell type separation. The `res.raw` and `res.imputed` objects are expected to contain AUC results, and `markers.raw` identifies the specific marker genes. ```R mean(res.raw[ res.raw$id %in% markers.raw,"auc"]) # 0.6866768 mean(res.imputed[ res.imputed$id %in% markers.raw,"auc"]) # 0.8296886 ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.