### Install scRepertoire from Bioconductor Source: https://github.com/borchlab/screpertoire/blob/devel/index.md Installs the stable version of scRepertoire from Bioconductor. Ensure BiocManager is installed first. ```R if (!require("BiocManager", quietly = TRUE)) install.packages("BiocManager") BiocManager::install("scRepertoire") ``` -------------------------------- ### Install scRepertoire from GitHub (Development) Source: https://github.com/borchlab/screpertoire/blob/devel/index.md Installs the development version of scRepertoire and its dependency immApex directly from GitHub. Use this for the latest features or if Bioconductor is not preferred. ```R remotes::install_github(c("BorchLab/immApex", "BorchLab/scRepertoire@devel")) ``` -------------------------------- ### Install Legacy Version 1 of scRepertoire Source: https://github.com/borchlab/screpertoire/blob/devel/index.md Installs version 1 of the scRepertoire package from GitHub. This is for users who require compatibility with older workflows. ```R devtools::install_github("BorchLab/scRepertoire@v1") ``` -------------------------------- ### Visualize Clonal Homeostasis (Custom Bins) Source: https://context7.com/borchlab/screpertoire/llms.txt Generates a stacked bar chart with custom clone size bins, focusing on lower frequency clones. Use when specific frequency ranges are of interest. ```r clonalHomeostasis(combined, clone.call = "aa", clone.size = c(Rare = 0.001, Common = 0.01, Dominant = 1), palette = "Sunset") ``` -------------------------------- ### Visualize Clonal Homeostasis (Default Bins) Source: https://context7.com/borchlab/screpertoire/llms.txt Renders a stacked bar chart showing clonal proportion per sample using default bins (Rare, Small, Medium, Large, Hyperexpanded). Use for a general overview of clonal size distribution. ```r library(scRepertoire) combined <- combineTCR( contig_list, samples = c("P17B", "P17L", "P18B", "P18L", "P19B", "P19L", "P20B", "P20L") ) # Default bins: Rare (0–0.0001), Small, Medium, Large, Hyperexpanded (≤1) clonalHomeostasis(combined, clone.call = "gene") ``` -------------------------------- ### Return Bootstrap Values for Diversity Metrics Source: https://context7.com/borchlab/screpertoire/llms.txt Returns all bootstrap values for a specified diversity metric, suitable for statistical testing. Use when detailed bootstrap results are needed for further analysis. ```r # Return all 100 bootstrap values for statistical testing boot_df <- clonalDiversity(combined, clone.call = "strict", metric = "norm.entropy", return.boots = TRUE, export.table = TRUE) head(boot_df) # columns: Group, value, metric ``` -------------------------------- ### Highlight Specific Clones with clonalCompare Source: https://context7.com/borchlab/screpertoire/llms.txt Use clonalCompare to highlight specific clones in a comparison. The `highlight.clones` argument takes a vector of clone identifiers. `relabel.clones` simplifies legend labels, and `graph = "area"` is used for visualization. Set `proportion = FALSE` to show raw counts. ```R clonalCompare(combined, clone.call = "aa", samples = c("P17B", "P17L"), top.clones = 10, highlight.clones = c("CVVSDNTGGFKTIF_CASSVRRERANTGELFF"), relabel.clones = TRUE, # simplify legend labels graph = "area", proportion = FALSE) # show raw counts ``` ```R # Export underlying clone proportion table df <- clonalCompare(combined, clone.call = "aa", top.clones = 5, export.table = TRUE) ``` -------------------------------- ### Compare Clonal Sharing (Morisita Overlap) Source: https://context7.com/borchlab/screpertoire/llms.txt Computes pairwise Morisita overlap, which accounts for clone abundance, and renders a heatmap. Use when clone abundance should influence overlap calculation. ```r # Morisita overlap (accounts for clone abundance) clonalOverlap(combined, clone.call = "strict", method = "morisita", palette = "Viridis") ``` -------------------------------- ### Visualize Normalized Clone Distributions Source: https://context7.com/borchlab/screpertoire/llms.txt Generates a density plot of normalized clone distributions, colored by tissue type. Use when normalized distributions and group comparisons are needed. ```r clonalAbundance(combined, clone.call = "aa", scale = TRUE, group.by = "Tissue", palette = "Zissou 1") ``` -------------------------------- ### Load and Combine TCR Contigs Source: https://github.com/borchlab/screpertoire/blob/devel/index.md Loads and combines TCR contig data from multiple samples. Ensure 'contig_list' contains the necessary data and 'samples' are correctly named. ```R library(scRepertoire) # Load and combine contigs into clones combined.TCR <- combineTCR(contig_list, samples = c("P17B", "P17L", "P18B", "P18L", "P19B", "P19L", "P20B", "P20L")) ``` -------------------------------- ### Visualize Clone Abundance by Rank Source: https://context7.com/borchlab/screpertoire/llms.txt Generates a line plot of raw clone counts by abundance rank. Use when raw counts are desired. ```r clonalAbundance(combined, clone.call = "gene", scale = FALSE) ``` -------------------------------- ### Export Clonal Homeostasis Proportion Matrix Source: https://context7.com/borchlab/screpertoire/llms.txt Exports the proportion matrix for clonal homeostasis analysis. Use when only the data matrix is required. ```r # Export the proportion matrix mat <- clonalHomeostasis(combined, clone.call = "strict", export.table = TRUE) # Returns numeric matrix: rows = samples, cols = size bins ``` -------------------------------- ### Track Clone Abundance (Alluvial Plot) Source: https://context7.com/borchlab/screpertoire/llms.txt Visualizes the relative proportion of selected top clones across samples using an alluvial plot. Use for tracking clone dynamics between specific samples. ```r library(scRepertoire) combined <- combineTCR( contig_list, samples = c("P17B", "P17L", "P18B", "P18L", "P19B", "P19L", "P20B", "P20L") ) # Top-5 clones across two samples, alluvial plot clonalCompare(combined, clone.call = "aa", samples = c("P17B", "P17L"), top.clones = 5, graph = "alluvial") ``` -------------------------------- ### Compare Clonal Sharing (Jaccard Index Heatmap) Source: https://context7.com/borchlab/screpertoire/llms.txt Generates a heatmap of pairwise Jaccard index to visualize clonal overlap between samples. Use for assessing similarity in clone composition. ```r library(scRepertoire) combined <- combineTCR( contig_list, samples = c("P17B", "P17L", "P18B", "P18L", "P19B", "P19L", "P20B", "P20L") ) # Jaccard index heatmap clonalOverlap(combined, clone.call = "aa", method = "jaccard") ``` -------------------------------- ### clonalAbundance Source: https://context7.com/borchlab/screpertoire/llms.txt Displays clonal frequency distributions (number of clones at each abundance level) as line or density plots on a log10-scaled x-axis, highlighting differences in repertoire structure between samples. ```APIDOC ## clonalAbundance — Plot Clone Frequency Distributions ### Description Displays clonal frequency distributions (number of clones at each abundance level) as line or density plots on a log10-scaled x-axis, highlighting differences in repertoire structure between samples. ### Parameters - **combined**: A named list of contig data frames, typically the output of `combineTCR()` or `combineBCR()`. - **clone.call**: Character string specifying the clone definition method. Options include "strict", "gene", "aa", "nt". Defaults to "strict". - **chain**: Character string specifying the T-cell receptor chain to consider. Options are "TRA", "TRB", or "both". Defaults to "both". - **group.by**: Character string specifying a metadata variable to group the plots by (e.g., "Tissue", "Patient"). - **plot.type**: Character string specifying the type of plot. Options are "line" or "density". Defaults to "line". - **export.table**: Logical. If TRUE, returns the underlying data as a data frame instead of a ggplot object. Defaults to FALSE. ### Request Example ```r library(scRepertoire) combined <- combineTCR( contig_list, samples = c("P17B", "P17L", "P18B", "P18L", "P19B", "P19L", "P20B", "P20L") ) combined <- addVariable(combined, "Tissue", rep(c("Blood","Liver"), 4)) # Plot clonal abundance distributions by sample p1 <- clonalAbundance(combined, clone.call = "strict", chain = "both") # Plot clonal abundance distributions grouped by Tissue p2 <- clonalAbundance(combined, clone.call = "aa", group.by = "Tissue", plot.type = "density") # Get underlying data as a data frame df <- clonalAbundance(combined, export.table = TRUE) ``` ### Response - **plot**: A ggplot object representing the clonal abundance distribution plot. - **df**: A data frame containing the clonal abundance data if `export.table = TRUE`. ``` -------------------------------- ### Tag Specific Clones in a Single-Cell Object with highlightClones Source: https://context7.com/borchlab/screpertoire/llms.txt The `highlightClones` function adds a `highlight` metadata column to Seurat/SCE objects, marking cells with specified clonal sequences. This facilitates UMAP/tSNE overlays. Multiple sequences can be provided for highlighting. ```R library(scRepertoire) library(Seurat) combined <- combineTCR( contig_list, samples = c("P17B", "P17L", "P18B", "P18L", "P19B", "P19L", "P20B", "P20L") ) scRep_example <- get(data("scRep_example")) scRep_example <- combineExpression(combined, scRep_example) # Mark cells carrying a specific TRA+TRB amino acid clone scRep_example <- highlightClones( scRep_example, clone.call = "aa", sequence = c("CVVSDNTGGFKTIF_CASSVRRERANTGELFF", "CASSPPRSGNTGELFF") # multiple sequences supported ) # Visualize on UMAP — highlighted cells show sequence, others are NA DimPlot(scRep_example, group.by = "highlight", na.value = "grey90") + ggtitle("Clonal Highlight on UMAP") ``` -------------------------------- ### loadContigs Source: https://context7.com/borchlab/screpertoire/llms.txt Loads immune receptor contigs from various single-cell sequencing data formats into a standardized structure. It supports automatic format detection or explicit specification of formats like 10X, AIRR, BD, Dandelion, Immcantation, JSON, MiXCR, ParseBio, TRUST4, and WAT3R. ```APIDOC ## loadContigs — Load Immune Receptor Contigs from Multiple Formats Reads contig files or pre-loaded data frames from any supported single-cell immune receptor format and normalizes them into a common structure ready for `combineTCR()` or `combineBCR()`. ### Parameters * **input**: Path to directory or a data frame containing contig data. * **format**: Character string specifying the input format. Accepts: `"10X"`, `"AIRR"`, `"BD"`, `"Dandelion"`, `"Immcantation"`, `"JSON"`, `"MiXCR"`, `"ParseBio"`, `"TRUST4"`, `"WAT3R"`, or `"auto"` for automatic detection. ### Request Example ```r # Load from a directory (auto-detects format from filenames) contig.list <- loadContigs("/path/to/cellranger/outs/", format = "auto") # Load TRUST4 output that was pre-read into R TRUST4 <- read.csv("https://www.borch.dev/uploads/contigs/TRUST4_contigs.csv") contig.list <- loadContigs(TRUST4, format = "TRUST4") # Load BD Rhapsody Contigs_AIRR.tsv output BD <- read.csv("https://www.borch.dev/uploads/contigs/BD_contigs.csv") bd.list <- loadContigs(BD, format = "BD") # Load WAT3R output WAT3R <- read.csv("https://www.borch.dev/uploads/contigs/WAT3R_contigs.csv") wat3r.list <- loadContigs(WAT3R, format = "WAT3R") ``` ### Response Returns a named list of data frames, where each data frame contains normalized contig information with columns: `barcode`, `chain`, `v_gene`, `d_gene`, `j_gene`, `c_gene`, `cdr3_nt`, `cdr3`, `reads`. ``` -------------------------------- ### clonalQuant Source: https://context7.com/borchlab/screpertoire/llms.txt Counts the number of unique clones per sample and visualizes the result as a bar chart. Setting scale = TRUE converts to percentage of unique clones relative to total detected clones. ```APIDOC ## clonalQuant — Quantify Unique or Scaled Clone Counts ### Description Counts the number of unique clones per sample and visualizes the result as a bar chart. Setting `scale = TRUE` converts to percentage of unique clones relative to total detected clones. ### Parameters - **combined**: A named list of contig data frames, typically the output of `combineTCR()` or `combineBCR()`. - **clone.call**: Character string specifying the clone definition method. Options include "strict", "gene", "aa", "nt". Defaults to "strict". - **chain**: Character string specifying the T-cell receptor chain to consider. Options are "TRA", "TRB", or "both". Defaults to "both". - **scale**: Logical. If TRUE, returns the proportion of unique clones relative to the total number of clones. Defaults to FALSE. - **palette**: A character string specifying the color palette for the plot. Defaults to NULL. - **export.table**: Logical. If TRUE, returns the underlying data as a data frame instead of a ggplot object. Defaults to FALSE. ### Request Example ```r library(scRepertoire) combined <- combineTCR( contig_list, samples = c("P17B", "P17L", "P18B", "P18L", "P19B", "P19L", "P20B", "P20L") ) # Raw unique clone counts per sample p1 <- clonalQuant(combined, clone.call = "strict", # CTstrict definition chain = "both", scale = FALSE) # returns ggplot bar chart # Proportional unique clones (accounts for different library depths) p2 <- clonalQuant(combined, clone.call = "aa", scale = TRUE, palette = "Blues 3") # Get underlying data as a data frame df <- clonalQuant(combined, clone.call = "gene", export.table = TRUE) ``` ### Response - **plot**: A ggplot object representing the bar chart of unique clone counts or proportions. - **df**: A data frame containing the clone count data if `export.table = TRUE`. ### Response Example ```r # Returns: contigs (unique), values (sample), total (all clones), scaled (%) head(df) ``` ``` -------------------------------- ### Quantify Unique or Scaled Clone Counts Source: https://context7.com/borchlab/screpertoire/llms.txt Counts unique clones per sample and visualizes as a bar chart. Setting `scale = TRUE` converts counts to percentages relative to total detected clones, accounting for library depth differences. ```r library(scRepertoire) combined <- combineTCR( contig_list, samples = c("P17B", "P17L", "P18B", "P18L", "P19B", "P19L", "P20B", "P20L") ) # Raw unique clone counts per sample p1 <- clonalQuant( combined, clone.call = "strict", # CTstrict definition chain = "both", scale = FALSE) # returns ggplot bar chart # Proportional unique clones (accounts for different library depths) p2 <- clonalQuant( combined, clone.call = "aa", scale = TRUE, palette = "Blues 3") # Get underlying data as a data frame df <- clonalQuant( combined, clone.call = "gene", export.table = TRUE) # Returns: contigs (unique), values (sample), total (all clones), scaled (%) head(df) ``` -------------------------------- ### Calculate Repertoire Diversity (Shannon Entropy) Source: https://context7.com/borchlab/screpertoire/llms.txt Computes Shannon entropy with bootstrap downsampling to equalize library sizes. Use for comparing diversity across groups when library sizes may vary. ```r library(scRepertoire) combined <- combineTCR( contig_list, samples = c("P17B", "P17L", "P18B", "P18L", "P19B", "P19L", "P20B", "P20L") ) combined <- addVariable(combined, "Tissue", rep(c("Blood","Liver"), 4)) # Shannon entropy with 100 bootstrap iterations (downsampling to smallest group) clonalDiversity(combined, clone.call = "gene", metric = "shannon", group.by = "Tissue", n.boots = 100) ``` -------------------------------- ### Calculate Repertoire Diversity (Inverse Simpson, No Bootstrap) Source: https://context7.com/borchlab/screpertoire/llms.txt Computes Inverse Simpson diversity without bootstrapping, using the full dataset. Use for diversity calculation on the complete data. ```r # Inverse Simpson without bootstrapping (full dataset) clonalDiversity(combined, clone.call = "aa", metric = "inv.simpson", skip.boots = TRUE) ``` -------------------------------- ### Visualize Clonal Frequency Source: https://github.com/borchlab/screpertoire/blob/devel/index.md Visualizes the frequency of immune cell clones. Specify 'clone.call' and 'chain' for detailed filtering. ```R # Visualize clonal frequency clonalQuant(combined.TCR, clone.call = "strict", chain = "both") ``` -------------------------------- ### Plot Clone Frequency Distributions Source: https://context7.com/borchlab/screpertoire/llms.txt Displays clonal frequency distributions using line or density plots on a log10-scaled x-axis. Useful for highlighting differences in repertoire structure between samples. ```r library(scRepertoire) combined <- combineTCR( contig_list, samples = c("P17B", "P17L", "P18B", "P18L", "P19B", "P19L", "P20B", "P20L") ) combined <- addVariable(combined, "Tissue", rep(c("Blood","Liver"), 4)) ``` -------------------------------- ### highlightClones Source: https://context7.com/borchlab/screpertoire/llms.txt Adds a 'highlight' metadata column to a Seurat or SingleCellExperiment object, marking cells that contain specific clonal sequences. This is useful for visualizing these cells on dimensionality reduction plots like UMAP or tSNE. ```APIDOC ## highlightClones ### Description Adds a `highlight` metadata column to a Seurat/SCE object marking cells that carry one or more user-specified clonal sequences, enabling UMAP/tSNE overlays. ### Parameters - `scExp`: A Seurat or SingleCellExperiment object. - `clone.call`: The name of the clone call to use (e.g., 'aa' for amino acid, 'nt' for nucleotide). - `sequence`: A character vector of clonal sequences to highlight. ### Example Usage ```r # Mark cells carrying a specific TRA+TRB amino acid clone scRep_example <- highlightClones( scRep_example, clone.call = "aa", sequence = c("CVVSDNTGGFKTIF_CASSVRRERANTGELFF", "CASSPPRSGNTGELFF") ) # Visualize on UMAP — highlighted cells show sequence, others are NA # Assuming DimPlot is available from Seurat or similar package # DimPlot(scRep_example, group.by = "highlight", na.value = "grey90") + ggtitle("Clonal Highlight on UMAP") ``` ``` -------------------------------- ### Analyze V/D/J Gene Usage with percentGeneUsage and related functions Source: https://context7.com/borchlab/screpertoire/llms.txt Functions like `percentGeneUsage`, `vizGenes`, `percentGenes`, and `percentVJ` quantify and visualize V, D, J gene segment usage. They support various plot types (heatmap, bar plot) and can group data by sample. `export.table = TRUE` can be used to export raw usage matrices. ```R library(scRepertoire) combined <- combineTCR( contig_list, samples = c("P17B", "P17L", "P18B", "P18L", "P19B", "P19L", "P20B", "P20L") ) # TRBV usage heatmap colored by percentage, grouped by sample percentGeneUsage(combined, genes = "TRBV", group.by = "sample", summary.fun = "percent", plot.type = "heatmap") ``` ```R # Paired TRBV–TRBJ usage heatmap (co-occurrence) percentGeneUsage(combined[1:2], genes = c("TRBV", "TRBJ"), group.by = "sample", summary.fun = "count") ``` ```R # Simplified wrapper: vizGenes for TRAV vs TRAJ pairing vizGenes(combined[1:2], x.axis = "TRAV", y.axis = "TRAJ", group.by = "sample", summary.fun = "percent") ``` ```R # percentVJ: always computes V-J pairing for the given chain percentVJ(combined, chain = "TRB", group.by = "sample", summary.fun = "proportion") ``` ```R # Export raw usage matrix trbv_table <- percentGenes(combined, chain = "TRB", gene = "Vgene", group.by = "sample", summary.fun = "count", export.table = TRUE) # Returns matrix: rows = gene names, columns = sample groups ``` -------------------------------- ### Export Underlying Abundance Table Source: https://context7.com/borchlab/screpertoire/llms.txt Exports the underlying abundance table for further analysis. Use when only the data table is required. ```r df <- clonalAbundance(combined, clone.call = "strict", export.table = TRUE) ``` -------------------------------- ### Load Immune Receptor Contigs with loadContigs Source: https://context7.com/borchlab/screpertoire/llms.txt Reads contig files or data frames from supported immune receptor formats and normalizes them. Use 'auto' for automatic detection or specify the format like 'TRUST4', 'BD', or 'WAT3R'. ```r library(scRepertoire) # Load from a directory (auto-detects format from filenames) contig.list <- loadContigs("/path/to/cellranger/outs/", format = "auto") ``` ```r # Load TRUST4 output that was pre-read into R TRUST4 <- read.csv("https://www.borch.dev/uploads/contigs/TRUST4_contigs.csv") contig.list <- loadContigs(TRUST4, format = "TRUST4") ``` ```r # Load BD Rhapsody Contigs_AIRR.tsv output BD <- read.csv("https://www.borch.dev/uploads/contigs/BD_contigs.csv") bd.list <- loadContigs(BD, format = "BD") ``` ```r # Load WAT3R output WAT3R <- read.csv("https://www.borch.dev/uploads/contigs/WAT3R_contigs.csv") wat3r.list <- loadContigs(WAT3R, format = "WAT3R") # Each element is a data frame with columns: barcode, chain, v_gene, d_gene, # j_gene, c_gene, cdr3_nt, cdr3, reads — ready for combineTCR()/combineBCR() ``` -------------------------------- ### Combine TCR Data and Export Clones Source: https://context7.com/borchlab/screpertoire/llms.txt Combines TCR contig data and exports it in multiple formats. Requires the scRepertoire library and a contig list. The 'paired' format saves to CSV, while 'airr', 'TCRMatch', and 'immunarch' formats return data frames or lists for further R processing. ```r library(scRepertoire) combined <- combineTCR( contig_list, samples = c("P17B", "P17L", "P18B", "P18L", "P19B", "P19L", "P20B", "P20L") ) # Paired format: one row per barcode, chain1/chain2 columns exportClones(combined, format = "paired", write.file = TRUE, file.name = "paired_clones.csv") # AIRR Community format: one row per chain, standard column names airr_df <- exportClones(combined, format = "airr", write.file = FALSE) # columns: cell_id, locus, v_call, d_call, j_call, c_call, junction, junction_aa # TCRMatch format: TRB CDR3 amino acid + clonal frequency tcrm_df <- exportClones(combined, format = "TCRMatch", write.file = FALSE) # columns: chain2_aa (CDR3 without leading C), group, clonalFrequency # immunarch format: returns list with $data (per-sample data frames) and $meta im <- exportClones(combined, format = "immunarch", write.file = FALSE) names(im) # "data", "meta" names(im$data) # sample names head(im$data[[1]]) # Clones Proportion CDR3.nt CDR3.aa V.name D.name J.name C.name Barcode ``` -------------------------------- ### Cluster Clones by Sequence Similarity with clonalCluster Source: https://context7.com/borchlab/screpertoire/llms.txt The `clonalCluster` function builds a sequence-similarity network for TCR/BCR clones. It supports various distance metrics and similarity thresholds. The function can export the network as an igraph object or an adjacency matrix. ```R library(scRepertoire) combined <- combineTCR( contig_list, samples = c("P17B", "P17L", "P18B", "P18L", "P19B", "P19L", "P20B", "P20L") ) # Default: Levenshtein on TRB amino acid sequences, 85% similarity combined_clustered <- clonalCluster( combined[c(1, 2)], chain = "TRB", sequence = "aa", threshold = 0.85, # < 1 → normalized similarity; ≥ 1 → raw edit distance use.V = TRUE # sequences must share same V gene ) # Adds column "TRB.Cluster" (e.g., "cluster.1", NA for singletons) ``` ```R # Alignment-based clustering with BLOSUM80 substitution matrix combined_nw <- clonalCluster( combined[c(1, 2)], chain = "TRA", dist.type = "nw", dist.mat = "BLOSUM80", threshold = 0.85 ) ``` ```R # Export the igraph network object for custom visualization g <- clonalCluster(combined[c(1, 2)], chain = "TRB", export.graph = TRUE) # g is an igraph object with vertex attributes: barcode, cdr3_aa, v, j, cluster ``` ```R # Export sparse adjacency matrix adj <- clonalCluster(combined[c(1, 2)], chain = "TRB", export.adj.matrix = TRUE) class(adj) # "dgCMatrix" ``` -------------------------------- ### Export Pairwise Overlap Matrix Source: https://context7.com/borchlab/screpertoire/llms.txt Exports the pairwise overlap matrix for clonal sharing analysis. Use when only the overlap data is required. ```r # Export the pairwise overlap matrix mat <- clonalOverlap(combined, clone.call = "aa", method = "jaccard", export.table = TRUE) # Returns: symmetric numeric matrix, samples × samples; NA on diagonal ``` -------------------------------- ### Subset Combined Contig List by Metadata Source: https://context7.com/borchlab/screpertoire/llms.txt Filters a combined contig list to include only samples matching specified metadata variables. Useful for targeted downstream analyses on specific experimental groups. ```r library(scRepertoire) combined <- combineTCR( contig_list, samples = c("P17B", "P17L", "P18B", "P18L", "P19B", "P19L", "P20B", "P20L") ) # Keep only blood samples (those whose "sample" column starts with P17) blood_only <- subsetClones(combined, name = "sample", variables = c("P17B", "P18B", "P19B", "P20B")) length(blood_only) # 4 names(blood_only) # "P17B" "P18B" "P19B" "P20B" ``` -------------------------------- ### Annotate Combined List with Custom Metadata Source: https://context7.com/borchlab/screpertoire/llms.txt Appends a new column to every data frame in a combined list, enabling grouping by experimental variables like treatment, tissue, or timepoint. ```r library(scRepertoire) combined <- combineTCR( contig_list, samples = c("P17B", "P17L", "P18B", "P18L", "P19B", "P19L", "P20B", "P20L") ) # Add tissue type (B = blood, L = liver) combined <- addVariable(combined, variable.name = "Tissue", variables = rep(c("Blood", "Liver"), 4)) # Add patient identifier combined <- addVariable(combined, variable.name = "Patient", variables = c("P17","P17","P18","P18", "P19","P19","P20","P20")) # Now group.by = "Tissue" or "Patient" is available in all analysis functions ``` -------------------------------- ### Combine B Cell Receptor Contigs with combineBCR Source: https://context7.com/borchlab/screpertoire/llms.txt Consolidates BCR contig annotations to the cell barcode level, performing sequence-similarity clustering on the heavy chain CDR3 for clonotyping. Use 'call.related.clones = TRUE' to enable clustering. Specify 'chain', 'sequence', 'threshold', 'dist.type', 'normalize', and 'use.V' to control the clustering parameters. ```r library(scRepertoire) # Download example NSCLC B-cell contigs BCR <- read.csv("https://www.borch.dev/uploads/contigs/b_contigs.csv") combined.BCR <- combineBCR( BCR, samples = "Patient1", call.related.clones = TRUE, # use Levenshtein clustering for CTstrict chain = "IGH", # cluster on heavy chain sequence = "nt", # use nucleotide sequences threshold = 0.85, # 85% similarity required dist.type = "levenshtein", normalize = "length", use.V = TRUE, # must share V gene filter.nonproductive= TRUE ) # Inspect result str(combined.BCR[["Patient1"]]) # 'data.frame': N obs. of 11 variables: # $ barcode : chr ... # $ IGH : chr ... (heavy chain, CTaa) # $ IGLC : chr ... (light chain) # $ CTgene : chr ... # $ CTnt : chr ... # $ CTaa : chr ... ``` -------------------------------- ### combineBCR Source: https://context7.com/borchlab/screpertoire/llms.txt Combines B cell receptor (BCR) contig annotations to the cell barcode level, similar to `combineTCR()`. It additionally performs sequence-similarity clustering on the heavy chain CDR3 to define related clones, supporting somatic-hypermutation-aware clonotyping. ```APIDOC ## combineBCR — Combine B Cell Receptor Contigs per Cell Barcode Like `combineTCR()` but for BCR data; additionally performs sequence-similarity clustering on the heavy chain CDR3 to define related clones. The `CTstrict` column encodes cluster membership (e.g., `cluster.1_IGKV3-15.CQQYSN...`) enabling somatic-hypermutation-aware clonotyping. ### Parameters * **contig_list**: A list of data frames, where each data frame contains BCR contig annotations for a sample, typically generated by `loadContigs()`. * **samples**: A character vector of sample names to be used as prefixes for cell barcodes. * **call.related.clones**: Logical, whether to use Levenshtein clustering for `CTstrict` (default: `FALSE`). * **chain**: Character string specifying the chain to use for clustering (default: `"IGH"`). * **sequence**: Character string specifying the sequence type for clustering (`"nt"` for nucleotide or `"aa"` for amino acid). * **threshold**: Numeric, the similarity threshold for clustering (default: `0.85`). * **dist.type**: Character string specifying the distance metric for clustering (e.g., `"levenshtein"`). * **normalize**: Character string specifying the normalization method for distance calculation (e.g., `"length"`). * **use.V**: Logical, whether V gene must be shared for clustering (default: `TRUE`). * **filter.nonproductive**: Logical, whether to remove non-productive contigs (default: `TRUE`). ### Request Example ```r # Download example NSCLC B-cell contigs BCR <- read.csv("https://www.borch.dev/uploads/contigs/b_contigs.csv") combined.BCR <- combineBCR( BCR, samples = "Patient1", call.related.clones = TRUE, # use Levenshtein clustering for CTstrict chain = "IGH", # cluster on heavy chain sequence = "nt", # use nucleotide sequences threshold = 0.85, # 85% similarity required dist.type = "levenshtein", normalize = "length", use.V = TRUE, # must share V gene filter.nonproductive= TRUE ) ``` ### Response Returns a named list of data frames, one per sample. Each row represents a unique cell barcode with columns including `barcode`, `IGH` (heavy chain, CTaa), `IGLC` (light chain), `CTgene`, `CTnt`, `CTaa`, and `CTstrict` (cluster membership). ``` -------------------------------- ### combineExpression Source: https://context7.com/borchlab/screpertoire/llms.txt Merges the output of combineTCR() or combineBCR() with a Seurat or SingleCellExperiment object. It calculates per-clone frequency and proportion and bins cells into homeostatic clonal size categories. ```APIDOC ## combineExpression — Attach Clonal Data to a Single-Cell Object ### Description Merges the output of `combineTCR()` or `combineBCR()` with a Seurat or SingleCellExperiment object. Calculates per-clone frequency and proportion and bins cells into homeostatic clonal size categories (Rare → Hyperexpanded) stored as a factor in metadata. ### Parameters - **combined**: The output of `combineTCR()` or `combineBCR()`. - **scRep**: A Seurat or SingleCellExperiment object. - **clone.call**: Character string specifying the clone definition method. Options include "strict", "gene", "aa", "nt". Defaults to "strict". - **chain**: Character string specifying the T-cell receptor chain to consider. Options are "TRA", "TRB", or "both". Defaults to "both". - **proportion**: Logical. If TRUE, compute proportions (not raw counts) of clones. Defaults to TRUE. - **clone.size**: A named numeric vector defining the size bins for clones. Defaults to c(Rare = 1e-4, Small = 0.001, Medium = 0.01, Large = 0.1, Hyperexpanded = 1). - **filter.na**: Logical. If TRUE, remove cells without clone information. Defaults to FALSE. ### Request Example ```r library(scRepertoire) library(Seurat) # Prepare combined TCR data combined <- combineTCR( contig_list, samples = c("P17B", "P17L", "P18B", "P18L", "P19B", "P19L", "P20B", "P20L") ) # Load example Seurat object (barcodes must match combined object) scRep_example <- get(data("scRep_example")) # Attach clonal information — frequencies computed per list element (sample) scRep_example <- combineExpression( combined, scRep_example, clone.call = "strict", # use VDJC gene + CDR3-nt for clone definition chain = "both", # include both TRA and TRB proportion = TRUE, # compute proportions (not raw counts) clone.size = c(Rare = 1e-4, Small = 0.001, Medium = 0.01, Large = 0.1, Hyperexpanded = 1), filter.na = FALSE # keep cells without clone info ) ``` ### Response - **scRep**: The modified Seurat or SingleCellExperiment object with new metadata columns added: CTgene, CTnt, CTaa, CTstrict, clonalProportion, clonalFrequency, cloneSize (factor). ### Response Example ```r table(scRep_example$cloneSize) # Hyperexpanded Large Medium Small Rare None # 42 150 273 312 895 10542 ``` ``` -------------------------------- ### percentGeneUsage / vizGenes / percentGenes / percentVJ Source: https://context7.com/borchlab/screpertoire/llms.txt A family of functions for quantifying and visualizing V, D, J gene segment usage (single gene or paired) across samples. These functions can generate heatmaps or bar plots to represent gene segment frequencies. ```APIDOC ## percentGeneUsage / vizGenes / percentGenes / percentVJ ### Description A family of functions for quantifying and visualizing V, D, J gene segment usage (single gene or paired) across samples as heatmaps or bar plots. ### Parameters - `combined`: Combined TCR/BCR data object. - `genes`: Gene(s) to analyze ('Vgene', 'Dgene', 'Jgene', 'V-J', 'V-D', 'D-J'). - `group.by`: Column name to group the data by (e.g., 'sample', 'cell.type'). - `summary.fun`: Function to summarize gene usage ('count', 'proportion', 'percent'). - `plot.type`: Type of plot to generate ('heatmap', 'bar'). - `chain`: The immune chain to analyze ('TRB', 'TRA', 'IGH', 'IGL', 'IGK'). - `x.axis`: For `vizGenes`, the gene to plot on the x-axis. - `y.axis`: For `vizGenes`, the gene to plot on the y-axis. - `export.table`: Logical, if TRUE, exports the raw usage matrix. ### Example Usage ```r # TRBV usage heatmap colored by percentage, grouped by sample percentGeneUsage(combined, genes = "TRBV", group.by = "sample", summary.fun = "percent", plot.type = "heatmap") # Paired TRBV–TRBJ usage heatmap (co-occurrence) percentGeneUsage(combined[1:2], genes = c("TRBV", "TRBJ"), group.by = "sample", summary.fun = "count") # Simplified wrapper: vizGenes for TRAV vs TRAJ pairing vizGenes(combined[1:2], x.axis = "TRAV", y.axis = "TRAJ", group.by = "sample", summary.fun = "percent") # percentVJ: always computes V-J pairing for the given chain percentVJ(combined, chain = "TRB", group.by = "sample", summary.fun = "proportion") # Export raw usage matrix trbv_table <- percentGenes(combined, chain = "TRB", gene = "Vgene", group.by = "sample", summary.fun = "count", export.table = TRUE) ``` ``` -------------------------------- ### subsetClones Source: https://context7.com/borchlab/screpertoire/llms.txt Filters the named list produced by combineTCR() or combineBCR() to only those samples matching specified variable values, enabling targeted downstream analyses. ```APIDOC ## subsetClones — Subset Combined Contig List by Metadata Variable ### Description Filters the named list produced by `combineTCR()` or `combineBCR()` to only those samples matching specified variable values, enabling targeted downstream analyses. ### Parameters - **combined**: A named list of contig data frames, typically the output of `combineTCR()` or `combineBCR()`. - **name**: The name of the metadata variable to filter by (e.g., "sample", "Tissue"). - **variables**: A character vector of variable values to keep. ### Request Example ```r library(scRepertoire) combined <- combineTCR( contig_list, samples = c("P17B", "P17L", "P18B", "P18L", "P19B", "P19L", "P20B", "P20L") ) # Keep only blood samples (those whose "sample" column starts with P17) blood_only <- subsetClones(combined, name = "sample", variables = c("P17B", "P18B", "P19B", "P20B")) ``` ### Response - **subsetted_list**: A named list containing only the contig data frames that match the specified filter criteria. ### Response Example ```r length(blood_only) # 4 names(blood_only) # "P17B" "P18B" "P19B" "P20B" ``` ``` -------------------------------- ### Combine TCR Data with Single-Cell Object Source: https://context7.com/borchlab/screpertoire/llms.txt Merges TCR contig data with Seurat or SingleCellExperiment objects. Computes per-clone frequencies, proportions, and bins cells into clonal size categories. Ensure barcodes in the contig data match the single-cell object. ```r library(scRepertoire) library(Seurat) # Prepare combined TCR data combined <- combineTCR( contig_list, samples = c("P17B", "P17L", "P18B", "P18L", "P19B", "P19L", "P20B", "P20L") ) # Load example Seurat object (barcodes must match combined object) scRep_example <- get(data("scRep_example")) # Attach clonal information — frequencies computed per list element (sample) scRep_example <- combineExpression( combined, scRep_example, clone.call = "strict", # use VDJC gene + CDR3-nt for clone definition chain = "both", # include both TRA and TRB proportion = TRUE, # compute proportions (not raw counts) clone.size = c(Rare = 1e-4, Small = 0.001, Medium = 0.01, Large = 0.1, Hyperexpanded = 1), filter.na = FALSE # keep cells without clone info ) # New metadata columns added: CTgene, CTnt, CTaa, CTstrict, # clonalProportion, clonalFrequency, cloneSize (factor) table(scRep_example$cloneSize) # Hyperexpanded Large Medium Small Rare None # 42 150 273 312 895 10542 ``` -------------------------------- ### Attach Clonal Data to Single-Cell Object Source: https://github.com/borchlab/screpertoire/blob/devel/index.md Attaches combined clonal data to a single-cell object. This function is crucial for integrating immune receptor data with other single-cell modalities. ```R # Attach clonal data to a single-cell object scRep_example <- combineExpression(combined.TCR, scRep_example) ```