Package {immunarch}


Type: Package
Title: Multi-Modal Immune Repertoire Analytics for Immunotherapy and Vaccine Design in R
Version: 0.11.0
Contact: support@immunomind.com
Description: A comprehensive analytics framework for building reproducible pipelines on T-cell and B-cell immune receptor repertoire data. Delivers multi-modal immune profiling (bulk, single-cell, CITE-seq/AbSeq, spatial, immunogenicity data), feature engineering (ML-ready feature tables and matrices), and biomarker discovery workflows (cohort comparisons, longitudinal tracking, repertoire similarity, enrichment). Provides a user-friendly interface to widely used AIRR methods — clonality/diversity, V(D)J usage, similarity, annotation, tracking, and many more. Think Scanpy or Seurat, but for AIRR data, a.k.a. Adaptive Immune Receptor Repertoire, VDJ-seq, RepSeq, or VDJ sequencing data. A successor to our previously published "tcR" R package (Nazarov 2015).
License: Apache License (≥ 2.0)
URL: https://immunomind.github.io/docs/, https://github.com/immunomind/immunarch/, https://immunarch.com/
BugReports: https://github.com/immunomind/immunarch/issues
Depends: R (≥ 4.2.0), ggplot2 (≥ 3.1.0), immundata (> 0.1.0), patchwork
Imports: DBI, glue, dplyr (≥ 1.2.0), dtplyr (≥ 1.0.0), data.table (≥ 1.12.6), cli, magrittr, methods, scales, rlang, readr, stringr, tibble, tidyselect, tidyr (≥ 1.3.0), utils, checkmate, duckplyr (≥ 1.2.0), dbplyr, lifecycle, purrr, stats, vctrs, ggthemes, ggsci, ggrepel (≥ 0.9.0)
Suggests: knitr (≥ 1.8), roxygen2 (≥ 3.0.0), testthat (≥ 3.0.0), pkgdown (≥ 0.1.0), rmarkdown, pheatmap (≥ 1.0.12), circlize, airr, ape, stringdist, factoextra (≥ 1.0.4), fpc, ggpubr (≥ 0.2), ggraph, ggseqlogo, igraph, phangorn, withr, ggalluvial (≥ 0.10.0), UpSetR (≥ 1.4.0), shiny (≥ 1.4.0), shinythemes, quarto, MASS (≥ 7.3), Rtsne (≥ 0.15)
VignetteBuilder: knitr, quarto
Encoding: UTF-8
LazyData: true
LazyDataCompression: xz
Config/Needs/website: rmarkdown
Config/testthat/edition: 3
Config/testthat/parallel: false
Config/roxygen2/version: 8.1.0
NeedsCompilation: no
Packaged: 2026-11-26 17:50:34 UTC; vdn
Author: Vadim I. Nazarov ORCID iD [aut, cre], Vasily O. Tsvetkov [aut], Aleksandr A. Popov [aut], Ivan Balashov [aut]
Maintainer: Vadim I. Nazarov <support@immunomind.com>
Repository: CRAN
Date/Publication: 2026-11-26 19:00:08 UTC

Get a column's name using the input alias

Description

Get a column's name using the input alias

Usage

.quant_column_choice(x)

Arguments

x

Character vector of length 1.

Value

A string with the column name.

Developer Examples

immunarch:::.quant_column_choice("count") immunarch:::.quant_column_choice("freq")


Tables with amino acid properties

Description

Tables with amino acid properties


Amino acid / codon table

Description

Amino acid / codon table

Usage

AA_TABLE

Add a new class attribute

Description

Add a new class attribute

Usage

add_class(.obj, .class)

Arguments

.obj

R object.

.class

String with the desired class name.

Value

Input object with additional class .class.

Developer Examples

tmp <- "abc" class(tmp) tmp <- immunarch:::add_class(tmp, "new_class") class(tmp)


Clonality - receptor overabundance statistics for immune repertoires

Description

[Experimental]

A family of functions to quantify receptor overabundance per repertoire. It helps in deciphering the structure and partition the repertoire. Higher clonality means that one or several receptors are over-expanded. Such effects is usually associated with the ongoing immune system response or anomalous behaviour, e.g., in blood cancers.

Available functions

The following methods are available.

1) Rank-abundance lines (airr_clonality_line). Prepare a plot for each repertoire. It orders receptors from most to least abundant and keeps the top limit receptors. Use it to see whether a small number of receptors dominate the repertoire: a steep line suggests strong clonal expansion.

2) Rank-bin statistics (airr_clonality_rank). Summarise how much of a repertoire is occupied by receptors in different rank ranges. Receptors are ordered by proportion and grouped using rank thresholds such as the top 10, top 100, or top 1,000 receptors. Use it to compare whether expansion is concentrated in the highest-ranked receptors across repertoires.

3) Proportion-bin statistics (airr_clonality_prop). Summarise how much of a repertoire is occupied by receptors at different abundance levels. It assigns each receptor to a proportion-based group, such as "Hyperexpanded", "Large", or "Ultra-rare". Each bin contains receptors with the proportion in the specified limits – just like in a histogram. Use it to compare the balance of expanded and rare receptors across repertoires.

Usage

airr_clonality_line(
  idata,
  limit = 1e+05,
  autojoin = getOption(IMMUNARCH_AUTOJOIN_OPTION, IMMUNARCH_AUTOJOIN_DEFAULT),
  format = c("long", "wide")
)

airr_clonality_rank(
  idata,
  bins = c(10, 30, 100, 300, 1000, 10000, 1e+05),
  autojoin = getOption(IMMUNARCH_AUTOJOIN_OPTION, IMMUNARCH_AUTOJOIN_DEFAULT),
  format = c("long", "wide")
)

airr_clonality_prop(
  idata,
  bins = c(Hyperexpanded = 0.01, Large = 0.001, Medium = 1e-04, Small = 1e-05, Rare =
    1e-06),
  autojoin = getOption(IMMUNARCH_AUTOJOIN_OPTION, IMMUNARCH_AUTOJOIN_DEFAULT),
  format = c("long", "wide")
)

Arguments

idata

An immundata::ImmunData object.

limit

A single whole number greater than or equal to 10, giving the maximum number of top receptors to keep per repertoire (default 100000).

autojoin

Logical. If TRUE, join repertoire metadata by the schema repertoire id. Change the default behaviour by calling options(immunarch.autojoin = FALSE).

format

String. One of "long" ("long" tibble with imd_repertoire_id, facet columns, and value; useful for visualizations) or "wide" (wide/unmelted table of features, with each row corresponding to a specific repertoire / pair of repertoires; useful for Machine Learning).

bins

A named numeric vector of thresholds (e.g., c(Hyperexpanded = 1e-2, Large = 1e-3, ...)). Names become bin labels and must be non-empty. Internally sorted in descending order for assignment. Result rows follow the supplied bin order, with "Ultra-rare" last.

Value

1) Rank-abundance lines (airr_clonality_line)

A tibble with columns:

2) Rank-bin statistics (airr_clonality_rank)

A tibble with

3) Proportion-bin statistics (airr_clonality_prop)

A tibble with

Visualisation

All three ⁠airr_clonality_*()⁠ results can be passed directly to vis(). With autojoin = TRUE (the default), repertoire metadata is included in the result and can be selected by the plotting arguments.

1) Rank-abundance lines (airr_clonality_line)

vis() plots receptor rank (index) against imd_proportion on a logarithmic y-axis by default. The line plot accepts:

2) Rank-bin statistics (airr_clonality_rank)

vis() produces a stacked column plot of occupied_prop per repertoire, filled by clonal_rank_bin. Receptors beyond the largest requested rank have a missing bin and are not drawn, so the total bar height shows the repertoire space occupied by the displayed ranks.

3) Proportion-bin statistics (airr_clonality_prop)

vis() produces a stacked column plot of occupied_prop per repertoire, filled by clonal_prop_bin. The "Ultra-rare" bin is included, so each complete repertoire normally sums to 100%.

Both stacked plots accept xval, yval, and fill to remap columns, plus facet, dir, and title for layout and labeling.

See Also

Examples

# Limit the number of threads used by the underlying DB for this example.
# Generally, you should NOT do this in your session.
db_exec("SET threads TO 1")

# Load example data.
immdata <- get_test_idata()

#
# Analyse receptor abundance by rank.
top_line <- airr_clonality_line(immdata, limit = 1000)

# Visualise the depth-normalised rank-abundance curve.
vis(top_line)


# Or visualise raw receptor counts.
vis(top_line, yval = "imd_count")


#
# Analyse the repertoire space occupied by different rank ranges.
rank_stat <- airr_clonality_rank(immdata, bins = c(10, 100))

# Visualise the rank-bin summary.
vis(rank_stat)


#
# Analyse the repertoire space occupied by abundance groups.
prop_stat <- airr_clonality_prop(immdata)

# Visualise the abundance-group summary.
vis(prop_stat)


Descriptive immune repertoire statistics

Description

[Experimental]

A family of functions that summarise the basic structure of immune repertoires. These summaries help you check data quality, compare samples, and describe chain counts, sequence lengths, and gene usage before more detailed analyses.

Available functions

The following methods are available.

1) Chain counts (airr_desc_chains). Count V(D)J chains in each repertoire, optionally grouped by locus. Use this method to check capture depth, compare library sizes, examine TRA/TRB/IGH balance, and identify locus-specific loss or over-representation.

2) Sequence-length distribution (airr_desc_lengths). Count sequences of each length per repertoire, optionally grouped by annotation columns. Use this method to describe CDR3 length distributions, detect possible library preparation bias, compare groups, and create length-based features.

3) Gene usage (airr_desc_genes). Count V(D)J gene segments per repertoire, optionally grouped by locus. The method can count unique receptors or sum barcode/UMI counts. Use it to compare gene usage between groups, identify unusual gene patterns, and create repertoire-level features.

Usage

airr_desc_chains(
  idata,
  locus_col = NA,
  autojoin = getOption(IMMUNARCH_AUTOJOIN_OPTION, IMMUNARCH_AUTOJOIN_DEFAULT),
  format = c("long", "wide")
)

airr_desc_lengths(
  idata,
  seq_col = "cdr3_aa",
  by = NA_character_,
  autojoin = getOption(IMMUNARCH_AUTOJOIN_OPTION, IMMUNARCH_AUTOJOIN_DEFAULT),
  format = c("long", "wide")
)

airr_desc_genes(
  idata,
  gene_col = "v_call",
  level = c("receptor", "barcode"),
  by = NA_character_,
  autojoin = getOption(IMMUNARCH_AUTOJOIN_OPTION, IMMUNARCH_AUTOJOIN_DEFAULT),
  format = c("long", "wide")
)

Arguments

idata

An immundata::ImmunData object.

locus_col

A single character string, NA, or NULL. The default, NA, uses the canonical locus column when it is available. Supply NULL to combine loci, or a column name to group by that column.

autojoin

Logical. If TRUE, join repertoire metadata by the schema repertoire id. Change the default behaviour by calling options(immunarch.autojoin = FALSE).

format

String. One of "long" ("long" tibble with imd_repertoire_id, facet columns, and value; useful for visualizations) or "wide" (wide/unmelted table of features, with each row corresponding to a specific repertoire / pair of repertoires; useful for Machine Learning).

seq_col

A single character string naming the sequence column.

by

A character vector, NA, or NULL. The default NA automatically groups by the canonical locus column when it is available. Supply NULL to pool loci, or a character vector to group by and return those columns explicitly.

gene_col

A single character string naming a gene-segment column calls (e.g., "v_call", "d_call", "j_call", "c_call"). Default is "v_call".

level

A single character string: "receptor" or "barcode". If "receptor" (default), the function counts unique receptors (one per receptor ID) that carry a given gene segment. If "barcode", the function sums counts (e.g., cells/UMIs) per gene segment using the column defined by immundata::imd_schema("count").

Value

1) Chain counts (airr_desc_chains)

A tibble with columns:

2) Sequence-length distribution (airr_desc_lengths)

A tibble with columns:

3) Gene usage (airr_desc_genes)

A tibble with columns:

Visualisation

All three ⁠airr_desc_*()⁠ results can be passed directly to vis(). With autojoin = TRUE (the default), repertoire summaries and user metadata are included in the result and can be selected by the plotting arguments.

1) Chain counts (airr_desc_chains)

vis() plots one point per repertoire, with n_barcodes on the x-axis and n_receptors on the y-axis. Both axes use log scales. Dashed lines mark overall receptor-to-barcode ratios of 100%, 50%, and 25%. Locus-specific rows share the same repertoire totals, so they appear as one point. The plot accepts:

For single-cell data, n_barcodes is the observed cell count; for bulk data, it is total abundance. The ratio shows repertoire-level richness, not how many receptors occur within each barcode.

2) Sequence-length distribution (airr_desc_lengths)

vis() plots seq_len on the x-axis and prop on the y-axis, filled by repertoire. Set fill to a metadata or grouping column to compare groups with box-and-violin distributions. facet accepts one column for a wrapped layout or two columns for a facet grid; dir = "h" or dir = "v" controls the wrapping direction.

3) Gene usage (airr_desc_genes)

vis() produces a dot plot with gene segments as rows, repertoires as columns, and n mapped to dot size and colour. Use row to select the gene column, col to select repertoire or metadata columns, and value to select the numeric measure. size_max_mm controls the largest dot; row_order and col_order set the display order.

See Also

immundata::ImmunData

Examples

# Limit the number of threads used by the underlying DB for this example.
# Generally, you should NOT do this in your session.
db_exec("SET threads TO 1")

# Load example data.
immdata <- get_test_idata()

#
# Count chains in each repertoire.
chain_stats <- airr_desc_chains(immdata)

# Repertoire size versus distinct receptor count
vis(chain_stats)

# Label and colour by repertoire metadata when those columns are available.
# vis(chain_stats, label = "Sample", colour = "Tissue")


#
# Calculate CDR3 length distributions.
length_stats <- airr_desc_lengths(immdata)

# Default: CDR3 length proportions by repertoire
vis(length_stats)

# Compare distributions between repertoires and split them by locus.
vis(length_stats, fill = "imd_filename", facet = "locus")

airr_desc_lengths(immdata, by = "locus")
airr_desc_lengths(immdata, by = NULL)


#
# Calculate V gene usage from receptor counts.
gene_stats <- airr_desc_genes(
  immdata,
  gene_col = "v_call",
  level = "receptor"
)

# Default: genes by repertoire, with counts mapped to dot size and colour
vis(gene_stats)

# Compare gene usage across repertoires and loci.
vis(
  gene_stats,
  row = "v_call",
  col = c("imd_filename", "locus"),
  value = "n",
  size_max_mm = 5
)

# V gene usage by summed cell/UMI counts (if a count column is present)
airr_desc_genes(immdata, gene_col = "v_call", level = "barcode")

# Split by locus (TRA/TRB/... if locus column exists)
airr_desc_genes(immdata, gene_col = "v_call", level = "receptor", by = "locus")

# Pool loci explicitly
airr_desc_genes(immdata, gene_col = "v_call", by = NULL)


Diversity - estimating the heterogeneity of immune repertoires

Description

[Experimental]

A family of functions to quantify receptor diversity in each repertoire. Diversity describes how many different receptors are present and how evenly their abundances are distributed. These methods help you compare repertoire structure, detect clonal expansion, and assess sampling depth.

Available functions

The following methods are available.

1) Coverage diversity (airr_diversity_dxx). Calculate the minimum number of the most abundant receptors needed to cover ⁠perc%⁠ of a repertoire. For example, D50 is the number of receptors that cover half of the repertoire. Use it to identify repertoires dominated by expanded receptors.

2) Chao1 richness (airr_diversity_chao1). Estimate the total number of receptors, including receptors that may be missing because of limited sampling. Use this non-parametric estimator when rare receptors suggest that the observed repertoire is incomplete.

3) Rarefaction and extrapolation (airr_diversity_rarefaction). Estimate how receptor richness changes with sample size. Use interpolation to compare repertoires at a common sampling depth and extrapolation to estimate how many additional receptors may be found with deeper sampling.

Computation is done in RAM after one database query that fetches only the repertoire identifier and receptor counts. Interpolation uses the exact hypergeometric expectation for sampling without replacement. Extrapolation uses the finite-sample Chao estimator, and confidence bounds use bootstrap standard errors from an estimated abundance distribution. Clonotype counts must be positive integers.

4) Shannon entropy (airr_diversity_shannon). Calculate Shannon entropy from receptor proportions in each repertoire. The value increases when a repertoire contains more receptors or has a more even abundance distribution. Use it as one summary that reflects both richness and evenness.

5) Pielou evenness (airr_diversity_pielou). Calculate how evenly receptor abundance is distributed within each repertoire. The method divides Shannon entropy by the maximum entropy for the observed richness. Use it to compare evenness between repertoires with different numbers of receptors.

6) Diversity index (airr_diversity_index). Calculate the Hill number at q = 1, which is the exponential of Shannon entropy calculated with natural logarithms. Use it as an effective number of receptors that is easy to compare between repertoires.

7) Hill numbers (airr_diversity_hill). Calculate a diversity profile for one or more orders q. At q = 0, the result is receptor richness; at q = 1, it is the exponential of Shannon entropy; higher values of q give more weight to abundant receptors. Use several orders to compare the influence of rare and abundant receptors.

Usage

airr_diversity_dxx(
  idata,
  perc = 50,
  autojoin = getOption(IMMUNARCH_AUTOJOIN_OPTION, IMMUNARCH_AUTOJOIN_DEFAULT),
  format = c("long", "wide")
)

airr_diversity_chao1(
  idata,
  autojoin = getOption(IMMUNARCH_AUTOJOIN_OPTION, IMMUNARCH_AUTOJOIN_DEFAULT),
  format = c("long", "wide")
)

airr_diversity_rarefaction(
  idata,
  step = NA,
  quantile = c(0.025, 0.975),
  extrapolation = NA,
  nboot = 50,
  norm = TRUE,
  verbose = TRUE,
  autojoin = getOption(IMMUNARCH_AUTOJOIN_OPTION, IMMUNARCH_AUTOJOIN_DEFAULT),
  format = c("long", "wide")
)

airr_diversity_shannon(
  idata,
  autojoin = getOption(IMMUNARCH_AUTOJOIN_OPTION, IMMUNARCH_AUTOJOIN_DEFAULT),
  format = c("long", "wide")
)

airr_diversity_pielou(
  idata,
  autojoin = getOption(IMMUNARCH_AUTOJOIN_OPTION, IMMUNARCH_AUTOJOIN_DEFAULT),
  format = c("long", "wide")
)

airr_diversity_index(
  idata,
  autojoin = getOption(IMMUNARCH_AUTOJOIN_OPTION, IMMUNARCH_AUTOJOIN_DEFAULT),
  format = c("long", "wide")
)

airr_diversity_hill(
  idata,
  q = 0:5,
  autojoin = getOption(IMMUNARCH_AUTOJOIN_OPTION, IMMUNARCH_AUTOJOIN_DEFAULT),
  format = c("long", "wide")
)

Arguments

idata

An immundata::ImmunData object.

perc

A number or numeric vector in ⁠(0, 100]⁠ (default 50), e.g. 50 for D50, 20 for D20.

autojoin

Logical. If TRUE, join repertoire metadata by the schema repertoire id. Change the default behaviour by calling options(immunarch.autojoin = FALSE).

format

String. One of "long" ("long" tibble with imd_repertoire_id, facet columns, and value; useful for visualizations) or "wide" (wide/unmelted table of features, with each row corresponding to a specific repertoire / pair of repertoires; useful for Machine Learning).

step

A whole number greater than or equal to 1, or NA. The default, NA, uses up to 50 evenly spaced points through the smallest observed depth. Each repertoire gets up to 50 points for each remaining interpolation and extrapolation interval.

quantile

A numeric vector of length 2 containing confidence probabilities strictly between 0 and 1.

extrapolation

A nonnegative whole number or NA giving the upper size limit for extrapolation. Use 0 to disable extrapolation. The default, NA, uses twice each repertoire's observed clone count.

nboot

A nonnegative whole number that is either 0 or at least 2. It gives the number of bootstrap replicates used to estimate confidence bounds. Defaults to 50; use 0 to return NA confidence bounds.

norm

A single logical value; if TRUE, size is divided by total repertoire size and richness estimates are divided by observed richness.

verbose

A single logical value controlling whether a concise progress message is shown.

q

A numeric scalar or vector of nonnegative orders. Defaults to 0:5.

Value

1) Coverage diversity (airr_diversity_dxx)

A tibble with:

2) Chao1 richness (airr_diversity_chao1)

A tibble with:

3) Rarefaction and extrapolation (airr_diversity_rarefaction)

A tibble with:

4) Shannon entropy (airr_diversity_shannon)

A tibble with:

5) Pielou evenness (airr_diversity_pielou)

A tibble with:

6) Diversity index (airr_diversity_index)

A tibble with:

7) Hill numbers (airr_diversity_hill)

A tibble with:

Visualisation

Most ⁠airr_diversity_*()⁠ results can be passed directly to vis(). With autojoin = TRUE (the default), repertoire metadata is included in the result and can be selected by the plotting arguments.

1) Coverage diversity (airr_diversity_dxx)

vis() plots dxx for each repertoire. When several perc values are present, use fill = "perc" to show a separate column for each coverage threshold.

2) Chao1 richness (airr_diversity_chao1)

vis() produces a column plot of the estimated richness (Estimator) for each repertoire.

3) Rarefaction and extrapolation (airr_diversity_rarefaction)

vis() plots estimated richness (mean) against sample size (size). Use color to group curves, show_ci = FALSE to hide confidence intervals, and log = TRUE to use a logarithmic x-axis.

4) Shannon entropy (airr_diversity_shannon)

vis() produces a column plot of shannon for each repertoire.

5) Pielou evenness (airr_diversity_pielou)

vis() produces a column plot of pielou for each repertoire.

6) Diversity index (airr_diversity_index)

vis() produces a column plot of hill_number at q = 1 for each repertoire.

7) Hill numbers (airr_diversity_hill)

This result does not currently have a dedicated vis() method. Use the returned q and hill_number columns to create a diversity profile.

References

Chao, A. et al. (2014). Rarefaction and extrapolation with Hill numbers: a framework for sampling and estimation in species diversity studies. Ecological Monographs, 84, 45-67. doi:10.1890/13-0133.1

See Also

immundata::ImmunData

Examples

# Limit the number of threads used by the underlying DB for this example.
# Generally, you should NOT do this in your session.
db_exec("SET threads TO 1")

# Load example data.
immdata <- get_test_idata()

#
# Calculate D50 and several coverage thresholds.
d50 <- airr_diversity_dxx(immdata, perc = 50)


d_multi <- airr_diversity_dxx(immdata, perc = c(20, 50, 80))

# Visualise the coverage diversity.
vis(d_multi)


#
# Estimate receptor richness.
chao <- airr_diversity_chao1(immdata)

# Visualise the richness estimates.
vis(chao)


#
# Calculate a rarefaction curve without extrapolation.
raref <- airr_diversity_rarefaction(immdata, step = 2000)

# Visualise the rarefaction curve.
vis(raref)


#
# Calculate Shannon entropy.
sh <- airr_diversity_shannon(immdata)
vis(sh)


#
# Calculate Pielou evenness.
pj <- airr_diversity_pielou(immdata)
vis(pj)


#
# Calculate the default diversity index.
idx <- airr_diversity_index(immdata)
vis(idx)


#
# Calculate a diversity profile for three Hill orders.
hill <- airr_diversity_hill(immdata, q = c(0, 1, 2))


Summarize immunoglobulin somatic hypermutation per repertoire

Description

Summarize the mutation counts and frequencies produced by annotate_ig_shm(). Aggregation runs in DuckDB on the duckplyr-backed input.

Usage

airr_ig_shm(
  idata,
  by = NA_character_,
  clone_col = "clone_id",
  autojoin = getOption(IMMUNARCH_AUTOJOIN_OPTION, IMMUNARCH_AUTOJOIN_DEFAULT),
  format = c("long", "wide")
)

Arguments

idata

An immundata::ImmunData object with SHM annotations and clones.

by

Character vector, NA, or NULL. The default uses the canonical locus column when available. Use NULL to pool loci. Repertoires are always summarized separately; clone IDs cannot be included in by.

clone_col

Column containing clone assignments. Missing clone IDs are included in sequence summaries but excluded from clone summaries.

autojoin

Logical. If TRUE, join repertoire metadata by the schema repertoire id. Change the default behaviour by calling options(immunarch.autojoin = FALSE).

format

Inherited from the common AIRR interface. This method always returns long-format summaries.

Details

This function uses the mutation counts and frequencies already calculated by annotate_ig_shm(). Here, a sequence means one immunoglobulin chain sequence in the input.

The function summarizes these counts and frequencies in two ways:

These calculations do not use read counts or UMI counts as weights.

Value

A long-format table of repertoire statistics. Each row contains the repertoire ID, any by columns, region, mutation, measure, and the 24 statistics listed above. Repertoire metadata is added by default.

Output statistics

Each repertoire has several output rows. The columns region, mutation, and measure tell you which mutation counts or frequencies the row describes:

Column Meaning
region The region being analyzed: overall for all available annotated regions; v for FWR1 through FWR3; cdr for all available CDRs; fwr for all available framework regions; or one region such as cdr3.
mutation replacement for mutations that change the amino acid, silent for mutations that do not change the amino acid, or total for replacement plus silent mutations. See annotate_ig_shm() for counting rules.
measure count for the number of mutations, or freq for mutation frequency. Frequencies are fractions: 0.05 means 5%.

The other columns contain the statistics for that row. For example, consider four sequences in one repertoire. Clone A has total CDR3 mutation counts of 0, 0, and 9. Clone B has one sequence with 6 total CDR3 mutations. Part of the output would be:

imd_repertoire_id region mutation measure sequence_mean clone_mean_mean clone_median_mean
1 cdr3 total count 3.75 4.5 3

All three statistics in this row describe total CDR3 mutation counts:

A row with measure = "freq" contains the same kinds of statistics for mutation frequencies instead of mutation counts. Results are calculated separately for each repertoire and each group selected with by, such as locus. Repertoire metadata is added when autojoin = TRUE.

The full list of 24 statistics is below. In every description, the mutation count or frequency is the one specified by region, mutation, and measure in that row. q25 and q75 are the lower and upper quartiles (25th and 75th percentiles).

Column Meaning
n_sequences Number of input sequences, including those with a missing mutation count or frequency, or a missing clone ID.
n_valid Number of sequences with an available mutation count or frequency.
n_missing Number of sequences whose mutation count or frequency is NA: n_sequences - n_valid.
n_valid_without_clone Number of sequences with an available mutation count or frequency but no clone ID.
n_zero Number of sequences with a mutation count or frequency of zero.
zero_prop Proportion of sequences with zero mutations of this type in this region, among sequences with an available count or frequency: n_zero / n_valid.
sequence_mean Mean mutation count or frequency across sequences. Each sequence has equal weight.
sequence_median Median mutation count or frequency across sequences.
sequence_q25 Lower quartile of mutation counts or frequencies across sequences.
sequence_q75 Upper quartile of mutation counts or frequencies across sequences.
n_clones Number of clones with a known clone ID, including clones for which all mutation counts or frequencies are missing.
n_valid_clones Number of clones with at least one sequence whose mutation count or frequency is available.
n_valid_with_clone Number of sequences with both an available mutation count or frequency and a clone ID.
clone_mean_weighted_mean Mean mutation count or frequency across sequences with a clone ID. This is also the mean of clone means weighted by the number of sequences with available counts or frequencies in each clone.
clone_mean_mean Calculate the mean mutation count or frequency in each clone, then take the mean of these clone means. Each clone has equal weight.
clone_mean_median Calculate the mean mutation count or frequency in each clone, then take the median of these clone means.
clone_mean_q25 Lower quartile of the clone means.
clone_mean_q75 Upper quartile of the clone means.
clone_median_mean Calculate the median mutation count or frequency in each clone, then take the mean of these clone medians. Each clone has equal weight.
clone_median_median Calculate the median mutation count or frequency in each clone, then take the median of these clone medians.
clone_median_q25 Lower quartile of the clone medians.
clone_median_q75 Upper quartile of the clone medians.
n_zero_clone_means Number of clones whose mean mutation count or frequency is zero.
n_zero_clone_medians Number of clones whose median mutation count or frequency is zero.

Missing mutation counts or frequencies (NA) are excluded from means, medians, quartiles, and the denominator of zero_prop. Zero is included. Sequences without clone IDs are included in sequence statistics but excluded from clone statistics. Clones with no available mutation counts or frequencies are included in n_clones but excluded from the clone means, medians, and quartiles. If none of the required counts or frequencies are available, the mean, median, quartiles, and zero_prop are NA. Quartiles use linear interpolation.

Combined region frequencies come from annotate_ig_shm(), which divides the total mutation count by the total number of comparable bases in those regions. This function does not average the frequencies of different regions to obtain a combined frequency. Regions without the required input columns are skipped.


Annotate clonality - per-receptor labels for overabundance

Description

[Experimental]

A small family of helpers that add clonality labels to each receptor in an immundata::ImmunData object.

Available functions

annotate_clonality_rank() - for each repertoire, receptors are ordered by within-repertoire abundance (proportion) and assigned a rank bin label.

annotate_clonality_prop() - label each receptor by proportion bin using named thresholds (matched in descending order; else "Ultra-rare").

Usage

annotate_clonality_rank(idata, bins = c(10, 30, 100, 300, 1000, 10000, 1e+05))

annotate_clonality_prop(
  idata,
  bins = c(Hyperexpanded = 0.01, Large = 0.001, Medium = 1e-04, Small = 1e-05, Rare =
    1e-06)
)

Arguments

idata

An immundata::ImmunData object.

bins

A named numeric vector of thresholds (e.g., c(Hyperexpanded = 1e-2, Large = 1e-3, ...)). Names become bin labels and must be non-empty. Internally sorted in descending order for assignment. Result rows follow the supplied bin order, with "Ultra-rare" last.

Value

An immundata::ImmunData whose ⁠$annotations⁠ gains:

An immundata::ImmunData whose ⁠$annotations⁠ gains:

See Also

Examples

## Not run: 
idata <- get_test_idata() |> agg_repertoires("Therapy")
idata_rank <- annotate_clonality_rank(idata)
idata_prop <- annotate_clonality_prop(idata)

## End(Not run)


Analyse and annotate immunoglobulin receptors

Description

[Experimental]

A family of functions for analysing and adding biologically useful immunoglobulin annotations to receptors. These annotations help connect receptor sequence variation with clonal expansion and B-cell evolution.

Each function has its own dedicated help page, so click on the function names to open corresponding pages.

Available functions

  1. Clonal family inference (annotate_ig_clones()). Usually the very first step in any of the Ig analysis workflows. The function clusters Ig receptors to clonal families using heavy-chain or paired heavy-light junction similarity by Hamming distance.

  2. Germline annotation (annotate_ig_germlines()). The first step in the somatic hypermutation (SHM) analysis workflows. This function annotates the Ig receptors with information about germline genes for the subsequent SHM analysis.

  3. Somatic hypermutation computation (annotate_ig_shm()). The second and the final step in the SHM analysis workflows. This function computes the SHM per-receptor and aggregated statistics and annotates the receptors with them. After that you can use airr_ig_shm() to explore and analyse the repertoire-wide and family-wide statistics in a more convenient form.

See Also

annotate_ig_clones(), annotate_ig_germlines(), annotate_ig_shm()


Build and annotate immunoglobulin clonal families

Description

[Experimental]

Build clonal families from B-cell receptors and assign them to receptors.

Receptors are compared within a subject or repertoire. A heavy-chain edge requires a shared V/J union group, equal junction length, and normalized junction Hamming distance at or below heavy_threshold. Paired mode independently builds the corresponding light-chain graph and keeps receptors together only when they share both heavy- and light-chain families.

Usage

annotate_ig_clones(
  idata,
  heavy_threshold,
  light_threshold = NULL,
  mode = c("auto", "heavy", "paired"),
  by_scope = "<auto>",
  junction_col = "junction",
  v_col = "v_call",
  j_col = "j_call",
  heavy_locus = "IGH",
  clone_col = "clone_id"
)

Arguments

idata

immundata::ImmunData. Paired or heavy-chain IG receptor data.

heavy_threshold, light_threshold

Numeric scalar or data frame. Normalized Hamming-distance threshold strictly between 0 and 1, or a complete table containing the by_scope column and a numeric threshold column. light_threshold defaults to heavy_threshold.

mode

Character scalar. Annotation strategy: "heavy" uses only the heavy chain, "paired" combines independently inferred heavy- and light-chain families, and "auto" selects paired mode for a paired IG receptor schema and heavy mode otherwise.

by_scope

Character scalar. Column that prevents clonal families from crossing biological subjects or repertoires. "<auto>" uses the first available subject-like column and otherwise the repertoire identifier.

junction_col, v_col, j_col

Character scalar. Columns containing the nucleotide junction, V call, and J call. V and J calls are grouped at gene level, allowing overlapping ambiguous assignments.

heavy_locus

Character scalar. Value identifying the heavy-chain locus. The default is "IGH"; all other loci declared by the receptor schema are treated as light chains in paired mode.

clone_col

Character scalar. Name of the combined clone annotation. The default is "clone_id".

Details

Connected components use single linkage: when A connects to B and B connects to C, all three receptors belong to one chain family even if A and C are farther apart than the threshold. Hamming distance compares only junctions of equal length, so it does not represent insertions or deletions.

Junction nucleotides are converted to uppercase. Junctions containing characters other than A, C, G, and T cannot create edges and remain isolated.

For grouping, V/J calls are split on commas or |, whitespace and allele suffixes are removed, and duplicate calls are ignored. Calls sharing both a V candidate and a J candidate are connected transitively within each scope and locus, before splitting by junction length or applying distance thresholds. Missing or empty gene calls cannot connect groups. Original calls and receptor IDs are preserved. The second example separately shows preprocessing when normalized calls should also define receptor identity.

Value

immundata::ImmunData. The original rows and columns plus clone_id (or the name supplied through clone_col), heavy_family_id, and light_family_id. Both chain rows of a paired receptor receive the same labels. In heavy mode, clone_id equals heavy_family_id and light_family_id is missing.

Examples




# Limit the number of threads used by the underlying DB for this example.
# Generally, you should NOT do this in your session.
db_exec("SET threads TO 1")

# Six chain observations representing three paired B-cell receptors.
ig_chains <- tibble::tribble(
  ~sample, ~cell, ~subject, ~locus, ~junction, ~v_call, ~j_call, ~umi,
  "S1", "c1", "P1", "IGH", "AAAA", "IGHV1", "IGHJ1", 10L,
  "S1", "c1", "P1", "IGK", "CCCC", "IGKV1", "IGKJ1", 8L,
  "S1", "c2", "P1", "IGH", "AAAT", "IGHV1", "IGHJ1", 10L,
  "S1", "c2", "P1", "IGK", "CCCT", "IGKV1", "IGKJ1", 8L,
  "S1", "c3", "P1", "IGH", "GGGG", "IGHV2", "IGHJ2", 10L,
  "S1", "c3", "P1", "IGL", "TTTT", "IGLV1", "IGLJ1", 8L
)
input_file <- tempfile(fileext = ".tsv")
output_folder <- tempfile("ig-clones-")
readr::write_tsv(ig_chains, input_file)

ig_schema <- make_receptor_schema(
  features = c("junction", "v_call", "j_call"),
  chains = c("IGH", "IGK|IGL")
)

idata <- read_repertoires(
  path = input_file,
  schema = ig_schema,
  barcode_col = "cell",
  locus_col = "locus",
  umi_col = "umi",
  repertoire_schema = "sample",
  rename_columns = NULL,
  output_folder = output_folder,
  verbose = FALSE
)

# c1 and c2 form one family; c3 remains separate.
annotated <- annotate_ig_clones(idata, heavy_threshold = 0.25)

annotated

# Use heavy-chain similarity alone when the scientific question requires it.
annotate_ig_clones(
  idata,
  heavy_threshold = 0.25,
  mode = "heavy"
)

# Canonicalize ambiguous V/J calls lazily before receptors are constructed.
# For example, "IGHV2*01, IGHV1*02" becomes "IGHV1|IGHV2".
canonicalize_vj <- function(data, ...) {
  data |>
    dplyr::mutate(dplyr::across(
      c(v_call, j_call),
      ~ dd$array_to_string(
        dd$list_sort(dd$list_distinct(dd$string_split(
          dd$regexp_replace(
            dd$regexp_replace(.x, "\\*[0-9]+", "", "g"),
            "\\s+", "", "g"
          ),
          ","
        ))),
        "|"
      )
    ))
}

messy_chains <- ig_chains |>
  dplyr::mutate(
    v_call = dplyr::case_when(
      cell == "c2" & locus == "IGH" ~ " IGHV1*02, IGHV1*01 ",
      TRUE ~ paste0(v_call, "*01")
    ),
    j_call = paste0(j_call, "*01")
  )
messy_file <- tempfile(fileext = ".tsv")
canonical_folder <- tempfile("ig-clones-canonical-")
readr::write_tsv(messy_chains, messy_file)

canonical_idata <- read_repertoires(
  path = messy_file,
  schema = ig_schema,
  barcode_col = "cell",
  locus_col = "locus",
  umi_col = "umi",
  repertoire_schema = "sample",
  rename_columns = NULL,
  preprocess = list(canonicalize_vj = canonicalize_vj),
  output_folder = canonical_folder,
  verbose = FALSE
)

annotate_ig_clones(canonical_idata, heavy_threshold = 0.25)

unlink(messy_file)
unlink(canonical_folder, recursive = TRUE)

unlink(input_file)
unlink(output_folder, recursive = TRUE)


Reconstruct clone-level immunoglobulin germlines

Description

[Experimental]

B cells in the same clone come from one starting cell, but their antibody sequences can gain different mutations over time. To study these mutations, we need a shared sequence to compare them with.

The method annotates each clone and locus with a representative germline sequence from references – usually IMGT germline table.

The result can be used as the reference for somatic hypermutation analysis with annotate_ig_shm().

Usage

annotate_ig_germlines(
  idata,
  references,
  species = NULL,
  by = "<auto>",
  sequence_id_col = "sequence_id",
  sequence_col = "sequence_alignment",
  v_col = "v_call",
  j_col = "j_call",
  v_start_col = "v_germline_start",
  v_end_col = "v_germline_end",
  j_start_col = "j_germline_start",
  j_end_col = "j_germline_end",
  germline_col = "germline_alignment"
)

Arguments

idata

immundata::ImmunData. AIRR data to annotate.

references

A table returned by read_germline_references() containing IMGT-gapped reconstruction references. These are not the ungapped reference files used to build an IgBLAST database; see Assumptions and reference compatibility.

species

Character scalar, or NULL to use the sole reference species.

by

Character vector or "<auto>". Clone grouping columns. Automatic grouping uses clone_id, with subject_id when available. Locus is always added.

sequence_id_col, sequence_col, v_col, j_col

Character scalars selecting the sequence ID, IMGT-gapped aligned sequence, V-call, and J-call columns.

v_start_col, v_end_col, j_start_col, j_end_col

Character scalars selecting the closed, IMGT-gapped germline-coordinate columns.

germline_col

Character scalar naming the reconstructed output column.

Value

immundata::ImmunData with one clone/locus germline assigned to each input row. Groups which cannot be reconstructed receive NA.

Assumptions and reference compatibility

This function reconstructs germlines by indexing directly into the supplied reference strings. It does not insert IMGT numbering gaps, convert coordinates, or otherwise align the input sequences and references. Consequently, all of the following assumptions must hold:

An Immcantation-style workflow normally maintains two representations of the same reference release: ungapped sequences for the IgBLAST database and IMGT-gapped sequences for germline reconstruction. This function requires the latter. Matching references therefore means the same allele set and release, not the literal ungapped FASTA passed to IgBLAST.

read_germline_references() preserves gaps that are already present in a FASTA file, but neither it nor this function converts ungapped references to IMGT-gapped references. Supplying incompatible ungapped data can produce a plausible-length but incorrectly shifted germline without an error.

The reconstructed value corresponds conceptually to Dowser's germline_alignment_d_mask: the retained V and J portions surround an N-masked middle region. This function does not reconstruct a full V(D)J germline or infer a D segment.

Preparing the input

To create the BCR repertoire, first you need to run IgBlast either standalone or through immundapter::tool_igblast() with an IMGT database on your FASTQ files or 10XGenomics contigs files. immundapter automatically prepares the alignment and V positions for IMGT-gapped references. Then, read V and J references from the same IMGT release with read_germline_references(). See the "Ig tutorial" on the website for the detailed workflow – it is a bit complicated, as per usual with BCR analysis.

Other AIRR data can be used when its alignment and V/J positions match the supplied IMGT-gapped references. But please mind that raw IgBlast AIRR output has not been prepared this way. This function does not convert positions or add gaps, so mismatched input can give an incorrect sequence without an error.

Output

This is a D-masked germline, not a complete ancestral receptor sequence. By default, it replaces an existing germline_alignment column. Use germline_col to keep that column.


Annotate immunoglobulin somatic hypermutation

Description

[Experimental]

Calculate overall, V-region, and AIRR-region somatic-hypermutation counts and frequencies from aligned observed and reconstructed germline sequences.

The input must contain the columns selected by sequence_col and germline_col, v_sequence_start, v_alignment_start, and the canonical AIRR ⁠*_start⁠ and ⁠*_end⁠ columns for FWR1, CDR1, FWR2, CDR2, FWR3, CDR3, and FWR4. The default germline column is normally created with annotate_ig_germlines().

Usage

annotate_ig_shm(
  idata,
  sequence_col = "sequence_alignment",
  germline_col = "germline_alignment",
  by = "<auto>"
)

Arguments

idata

immundata::ImmunData. IgBLAST AIRR data to annotate.

sequence_col

Character scalar. Aligned observed-sequence column.

germline_col

Character scalar. Aligned reconstructed germline column. sequence_col and germline_col may select alternative alignment columns, but those columns must use the same alignment and coordinate system as the canonical AIRR region-coordinate columns.

by

Character vector, "<auto>", or NULL. Columns used to calculate group-level mu_freq summaries. The default uses clone_id, with subject_id when available; locus is added when available. NULL skips grouped summaries.

Details

AIRR region coordinates are interpreted as 1-based closed intervals on the unaligned query sequence. v_alignment_start identifies the aligned position corresponding to v_sequence_start. While mapping query positions, N consumes a query coordinate, whereas . and - do not.

A position is comparable only when both aligned characters are unambiguous A, C, G, or T nucleotides. Thus N, ., and - positions contribute to neither mutation counts nor frequency denominators. mu_count is the sum of classifiable replacement and silent mutations across all available regions; mu_freq divides that count by the number of comparable positions in those regions. Overall and combined CDR/FWR replacement and silent frequencies use the sum of comparable positions across their selected regions, not aggregated regional frequencies. Individual-region frequencies use the comparable positions in that region as their denominator.

Replacement and silent consequences are classified independently for each mutation against the germline codon. Stop-producing substitutions are not counted as either class. If one boundary of a region is missing, all four outputs for that region are missing while other regions and overall outputs remain available. A valid region with no comparable positions has zero counts and missing frequencies. Combined CDR and framework metrics use the available regions in their respective sets. If no region in a set has both boundaries, all combined outputs for that set are missing.

When grouping is enabled, mu_freq_median and mu_freq_mean summarize non-missing mu_freq values without weighting, and mu_freq_n counts their contributors. Rows missing any grouping key receive missing median and mean values and a zero count. Explicit by columns are used exactly as supplied; include locus explicitly to keep heavy and light chains separate. Use dplyr::distinct() on the grouping columns and summaries when a group-level rather than row-level result is needed.

Value

immundata::ImmunData. The input rows with combined mu_count and mu_freq columns plus replacement and silent counts and frequencies overall, across the V region (FWR1 through FWR3), across all CDRs, across all framework regions, and for each individual region. When grouping is enabled, the result also includes mu_freq_median, mu_freq_mean, and mu_freq_n on every row.

Why SHM results may differ between tools

Results can differ between SHM tools, even for the same sequences. This function counts a mutation only when its codon (a group of three bases) is complete and has no alignment gap. Other tools may count mutations in codons with gaps. Removing . characters from an IMGT alignment can also shift codon boundaries and change which mutations are counted, including mutations that create a stop codon. For a fair comparison, use matching alignments and region positions, and check how each tool handles gaps and stop codons.


Annotate receptors with publicness statistics

Description

[Experimental]

Usage

annotate_public(idata)

Arguments

idata

An immundata::ImmunData object with aggregated repertoires.

Details

Adds per-receptor publicness metrics to an immundata::ImmunData object. Global metrics are always computed. If ⁠$repertoires⁠ contains imd_strata_id (created by immundata::agg_strata()), strata-specific metrics are added as well. If strata is missing, the function reports that only global metrics are produced.

For large datasets, this can be a computationally heavy operation. After annotation, consider persisting the result as a snapshot with immundata::write_immundata() to avoid recomputation.

Value

An immundata::ImmunData with added annotation columns:

Visualisation

Use vis(annotated, plot = "incidence") to show how many receptor identities occur in exactly one, two, or more repertoires. With strata, the plot stacks their within-stratum incidence distributions. A receptor observed in several strata contributes once to each; the stack heights sum within-stratum counts rather than globally distinct identities. Without strata, the plot shows a single unstacked distribution across all repertoires and omits the stratum legend. Long stratum labels wrap in a vertical legend on the right; their underlying names are unchanged. title = NULL omits the plot title.

Incidence annotations describe the population at the time of annotation. Rerun annotate_public() after filtering or changing repertoires or strata before plotting the new population.

See Also

vis(), vdj_public()

Examples

## Not run: 
idata_global <- get_test_idata() |>
  agg_repertoires(c("Response", "Therapy")) |>
  annotate_public()
vis(idata_global, plot = "incidence")

idata_strata <- get_test_idata() |>
  agg_repertoires(c("Response", "Therapy")) |>
  agg_strata(schema = "Response") |>
  annotate_public()
vis(idata_strata, plot = "incidence")

write_immundata(idata_global, "snapshots/public-annotated-global")
write_immundata(idata_strata, "snapshots/public-annotated-strata")

## End(Not run)


Annotate ImmunData with an external sequence database (e.g. VDJdb)

Description

Add annotations to ImmunData from an external database such as VDJdb.

Usage

annotate_with_database(idata, db, by, label_col = "species", ...)

Arguments

idata

An immundata::ImmunData object.

db

A data frame, tibble, duckplyr_df, or a single character string containing a path to a delimited or Parquet file. Files are read via duckplyr.

by

A named character vector of join columns, of the form c(idata_col = "db_col").

label_col

A single character string naming the column from db to add to idata (for VDJdb, this could be "species").

...

Optional dplyr or duckplyr filter expressions evaluated on db before joining (e.g. species == "HomoSapiens", gene == "TRB").

Value

A new immundata::ImmunData object with the selected database label added as an annotation column.


Apply function to each pair of data frames from a list.

Description

Apply the given function to every pair in the given datalist. Function either symmetrical (i.e. fun(x,y) == fun(y,x)) or assymmetrical (i.e. fun(x,y) != fun(y,x)).

Usage

apply_symm(.datalist, .fun, ..., .diag = NA, .verbose = TRUE)

apply_asymm(.datalist, .fun, ..., .diag = NA, .verbose = TRUE)

Arguments

.datalist

List with some data.frames.

.fun

Function to apply, which return basic class value.

...

Arguments passsed to .fun.

.diag

Either NA for NA or something else != NULL for .fun(x,x).

.verbose

if TRUE then output a progress bar.

Value

Matrix with values M(i,j) = fun(datalist(i), datalist(j))

Examples

## Not run: 
data(immdata)
apply_symm(immdata$data, function(x, y) {
  nrow(x) + nrow(y)
})

## End(Not run)

BCR dataset

Description

A dataset with BCR data for testing and examplatory purposes.

Usage

bcrdata

Format

A list of two elements. The first element ("data") is a list of 1 element named "full_clones" that contains immune repertoire data frame. The second element ("meta") is empty metadata table.

data

List of immune repertoire data frames.

meta

Metadata

...


Nucleotide to amino acid sequence translation

Description

Nucleotide to amino acid sequence translation

Usage

bunch_translate(.seq, .two.way = TRUE, .ignore.n = FALSE)

Arguments

.seq

Vector or list of strings.

.two.way

Logical. If TRUE (default) then translate from the both ends (like MIXCR).

.ignore.n

Logical. If FALSE (default) then return NA for sequences that have N, else parse triplets with N as ~

Value

Character vector of translated input sequences.

Examples

## Not run: 
data(immdata)
head(bunch_translate(immdata$data[[1]]$CDR3.nt))

## End(Not run)

Check and normalise distributions

Description

Check if the given .data is a distribution and normalise it if necessary with an optional Laplace correction.

Usage

check_distribution(
  .data,
  .do.norm = NA,
  .laplace = 1,
  .na.val = 0,
  .warn.zero = FALSE,
  .warn.sum = TRUE
)

Arguments

.data

Numeric vector of values.

.do.norm

One of the three values - NA, TRUE or FALSE. If NA then checks for distrubution (sum(.data) == 1) and normalises if needed with the given laplace correction value. if TRUE then does the normalisation and laplace correction. If FALSE then doesn't do either normalisaton or laplace correction.

.laplace

Value for the laplace correction.

.na.val

Replace all NAs with this value.

.warn.zero

if TRUE then the function checks if in the resulted vector (after normalisation) are any zeros, and prints a warning message if there are some.

.warn.sum

if TRUE then the function checks if the sum of resulted vector (after normalisation) is equal to one, and prints a warning message if not.

Value

Numeric vector.

Developer Examples

immunarch:::check_distribution(c(1, 2, 3)) immunarch:::check_distribution(c(1, 2, 3), TRUE) immunarch:::check_distribution(c(1, 2, 3), FALSE)


Connected-component clustering for receptor graphs

Description

[Experimental]

A family of functions for clustering sparse receptor graphs represented by an ImmunData object and an immunarch_sequence_graph.

clust_cc() finds receptor-level connected components from the contracted sequence graph returned by dist_hamm() with mode = "graph".

Usage

clust_cc(
  idata,
  edges,
  by = NULL,
  cluster_col = "cluster_id",
  size_col = "cluster_size"
)

Arguments

idata

An immundata::ImmunData object. Its receptor annotations provide the graph nodes through the canonical receptor-ID column and, when requested, repertoire metadata.

edges

An immunarch_sequence_graph returned by dist_hamm() with mode = "graph". Ordinary receptor edge tables are not accepted.

by

A character vector of column names or NULL. These columns come from the receptor annotations in idata; each distinct combination is an independent clustering scope. The scope may be broader than the comparison groups used by dist_hamm(). The canonical receptor-ID column cannot also be used in by.

cluster_col

A single character string giving the output component-identifier column name. Within each by group, the identifier is the minimum original receptor identifier in that component. Defaults to "cluster_id".

size_col

A single character string giving the output component-size column name. The size is the number of distinct original receptors in the component. Defaults to "cluster_size".

Details

Sequence-node distances are applied only where both nodes participate in the same clustering scope. If one receptor belongs to several sequence nodes in a scope, those nodes are joined by identity edges before components are computed. Receptors without a usable sequence remain singleton components.

Value

A lazy duckplyr table with one row per distinct, non-missing receptor ID per clustering scope and the following columns:

Call dplyr::collect() when an in-memory tibble is needed.

Examples


# Limit the number of threads used by the underlying DB for this example.
# Generally, you should NOT do this in your session.
db_exec("SET threads TO 1")

idata <- immundata::get_test_idata()

# Connect receptors whose CDR3 amino-acid sequences differ by at most one
# residue. Request the contracted graph used by clust_cc().
graph <- dist_hamm(idata, max_dist = 1, mode = "graph")
res <- clust_cc(
  idata = idata,
  edges = graph
)
res
res <- res |> collect()


# Build independent graphs within each repertoire and V-gene group. The
# same columns must be supplied to by in both functions.
group_cols <- c("imd_repertoire_id", "v_call")
graph_by_group <- dist_hamm(
  idata,
  by = group_cols,
  min_sim = 0.8,
  mode = "graph"
)

res_by_group <- clust_cc(
  idata = idata,
  edges = graph_by_group,
  by = group_cols
)

res_by_group |>
  dplyr::filter(cluster_size > 1L) |>
  dplyr::arrange(dplyr::desc(cluster_size)) |>
  dplyr::collect()


Filter out coding and non-coding clonotype sequences

Description

Filter out clonotypes with non-coding, coding, in-frame or out-of-frame CDR3 sequences:

coding() - remove all non-coding sequences (i.e., remove all sequences with stop codons and frame shifts);

noncoding() - remove all coding sequences (i.e., leave sequences with stop codons and frame shifts only);

inframes() - remove all out-of-frame sequences (i.e., remove all sequences with frame shifts);

outofframes() - remove all in-frame sequences (i.e., leave sequences with frame shifts only).

Note: the function will remove all clonotypes sequences with NAs in the CDR3 amino acid column.

Usage

coding(.data)

noncoding(.data)

inframes(.data)

outofframes(.data)

Arguments

.data

The data to be processed. Can be data.frame, data.table::data.table, or a list of these objects.

Every object must have columns in the immunarch compatible format. immunarch_data_format

Competent users may provide advanced data representations: DBI database connections, Apache Spark DataFrame from "copy_to" or a list of these objects. They are supported with the same limitations as basic objects.

Note: each connection must represent a separate repertoire.

Value

Filtered data frame.

Examples

## Not run: 
data(immdata)
immdata_cod <- coding(immdata$data)
immdata_cod1 <- coding(immdata$data[[1]])

## End(Not run)

Annotate clonotypes in immune repertoires using clonotype databases (e.g., VDJDB, McPAS)

Description

[Deprecated]

Annotate clonotypes by matching them to known condition-associated immune receptors in a database. Before using this function, you must download or load the relevant database files. For more information, see the online tutorial.

Usage

dbAnnotate(.data, .db, .data.col, .db.col)

Arguments

.data

The data to process. It can be a data.frame, a data.table::data.table, or a list of these objects.

Every object must have columns in the immunarch compatible format. immunarch_data_format

Competent users may provide advanced data representations: DBI database connections, or a list of these objects. They are supported with the same limitations as basic objects.

Note: each connection must represent a separate repertoire.

.db

A data frame or a data table with an immune receptor database. See dbLoad on how to load databases into R.

.data.col

Character vector. Vector of columns in the input repertoires to use for clonotype search. E.g., "CDR3.aa" or c("CDR3.aa", "V.name").

.db.col

Character vector. Vector of columns in the database to use for clonotype search. The order must match the order of ".data.col". E.g., if ".data.col" is c("CDR3.aa", "V.name"), then ".db.col" must have the exact order of columns. i.e., the first column must correspond to CDR3 amino acid sequences, and the second column must correspond to V gene segment names.

Value

Data frame with input sequences and counts or proportions for each of the input repertoire.

Examples

## Not run: 
data(immdata)

#' # Example file path
file_path <- paste0(system.file(package = "immunarch"), "/extdata/db/vdjdb.example.txt")

# Load the database with human-only TRB-only receptors for all known antigens
db <- dbLoad(file_path, "vdjdb", "HomoSapiens", "TRB")

res <- dbAnnotate(immdata$data, db, "CDR3.aa", "cdr3")
res

## End(Not run)

Load clonotype databases such as VDJDB and McPAS into the R workspace

Description

[Deprecated]

The function automatically detects the database format and loads it into R. Additionally, the function provides a general query interface to databases that allows filtering by species, chain types (i.e., locus) and pathology (i.e., antigen species).

Currently we support three popular databases:

VDJDB - https://github.com/antigenomics/vdjdb-db

McPAS-TCR - https://friedmanlab.weizmann.ac.il/McPAS-TCR/

TBAdb from PIRD - https://db.cngb.org/pird/

Usage

dbLoad(.path, .db, .species = NA, .chain = NA, .pathology = NA)

Arguments

.path

Character. A path to the database file, e.g., "/Users/researcher/Downloads/McPAS-TCR.csv".

.db

Character. A database type: either "vdjdb", "vdjdb-search", "mcpas" or "tbadb".

"vdjdb" for VDJDB; "vdjdb-search" for search table obtained from the web interface of VDJDB; "mcpas" for McPAS-TCR; "tbadb" for PIRD TBAdb.

.species

Character. A string or a vector of strings specifying which species need to be in the database, e.g., "HomoSapiens". Pass NA (by default) to load all available species.

.chain

Character. A string or a vector of strings specifying which chains need to be in the database, e.g., "TRB". Pass NA (by default) to load all available chains.

.pathology

Character. A string or a vector of strings specifying which disease, virus, bacteria or any condition needs to be in the database, e.g., "CMV". Pass NA (by default) to load all available conditions.

Value

Data frame with the input database records.

Examples

## Not run: 
# Example file path
file_path <- paste0(system.file(package = "immunarch"), "/extdata/db/vdjdb.example.txt")

# Load the database with human-only TRB-only receptors for all known antigens
db <- dbLoad(file_path, "vdjdb", "HomoSapiens", "TRB")
db

## End(Not run)

Immune receptor distances

Description

[Experimental]

A family of functions to calculate sequence distances between immune receptors. These methods help you explore receptor similarity, select thresholds for Immunoglobulin clone assignment, and construct sparse receptor-similarity graphs.

Available functions

The following methods are available.

1) Hamming distances (dist_hamm). Compute an upper-triangular sparse edge table of Hamming distances between receptor IDs represented in the receptor annotations in idata. Comparisons are restricted to equal sequence lengths and equal values of by. The data are not grouped by repertoire automatically. For paired-chain receptor schemas, the canonical locus column is added to by automatically, so distances are computed separately per locus. Add it explicitly if you have a non-AIRR-C standard locus column name.

Usage

dist_hamm(
  idata,
  seq_col = "cdr3_aa",
  by = NULL,
  max_dist = NULL,
  min_sim = NULL,
  sample_n = 0L,
  sample_by = "<auto>",
  mode = c("pairs", "graph")
)

Arguments

idata

An immundata::ImmunData object.

seq_col

A single character string naming a sequence feature in the receptor schema.

by

A character vector or NULL. These optional annotation columns must be equal within a receptor pair. For B-cell clone assignment, a typical choice is c("v_call", "j_call"); add imd_repertoire_id when comparisons must stay within repertoires, or subject_id if your data has such a dedicated column for subject-specific metadata. Locus grouping is also always applied for paired-chain receptor schemas.

max_dist

A single nonnegative number, a keyed threshold table, or NULL. Scalar values in ⁠(0, 1)⁠ bound normalized Hamming distance; integer values which are ⁠>=1⁠ bound raw Hamming distance. NULL (the default) and the legacy scalar value 0 disable bounding. A threshold table must contain one or more key columns plus a numeric threshold column strictly inside ⁠(0, 1)⁠. Its key columns must be included in by and must exactly cover the corresponding input key combinations. Mutually exclusive with min_sim.

min_sim

A single number in ⁠[0, 1]⁠ or NULL, giving the minimum normalized Hamming similarity. It is mutually exclusive with max_dist.

sample_n

A nonnegative whole number giving the maximum number of distinct receptor IDs to sample before distance calculation within each sample_by group. 0 (the default) disables sampling.

sample_by

A single character string or NULL selecting the column to sample by. The default, "<auto>", uses the first available column among subject_id, donor, donor_id, patient_id, patient, subject, and imd_repertoire_id. The resolved column must also be supplied through by. Set to NULL to sample from the whole dataset without accounting for groups. This argument is ignored when sample_n = 0.

mode

Output representation. "pairs" (the default) returns the receptor-pair table described below. "graph" returns contracted sequence-node edges and receptor-to-node membership. Grouping columns cannot use names reserved for structural columns in the selected output.

Value

1) Hamming distances (dist_hamm)

With mode = "pairs", a lazy duckplyr table with:

With mode = "graph", an immunarch_sequence_graph object containing two lazy duckplyr tables. edges contains the effective grouping columns, globally unique from and to node IDs, and seq_len, dist, norm_dist, and sim. membership contains the effective grouping columns, the canonical receptor ID, and node_id. A receptor can have multiple membership rows, and membership includes nodes without edges. Nodes represent distinct combinations of the full effective comparison group and a non-missing, non-empty sequence; sequences themselves are not returned.

Call dplyr::collect() only when a returned table is small enough for memory.

Visualisation

Distance results can be passed directly to vis().

1) Hamming distances (dist_hamm)

vis() plots the normalized distance to the nearest non-identical neighbor for each receptor by default. This is the distribution used for manual IG clone-threshold selection. When a subject column can be inferred using the same priority as sample_by = "<auto>", one panel is drawn per subject; otherwise, a single pooled distribution is drawn.

Use mode = "all" to plot every pairwise distance instead of nearest neighbors. Pass one of the following values to xval to change what will be plotted: "norm_dist" (the default), "dist" (non-normalised distnaces), or "sim" (similarity). Set facet = NULL to have one plot per all input samples, or name a result column to facet by it. binwidth and title customize the histogram.

See Also

immundata::ImmunData

Examples


idata <- get_test_idata()


# Build the computing query
res <- dist_hamm(idata)
# Check how results would look like
res
# Run the computation query and upload the results to the memory
res <- res |> collect()

# Bound Hamming distance.
# Non-normalised -- no receptors with more than 1 mismatch in the output
res <- dist_hamm(idata, max_dist = 1) |> collect()
res


# Normalised -- no receptors with more than .2 normalised distance in the output
res <- dist_hamm(idata, max_dist = .2) |> collect()
res

# Similarity, inverse to normalised distance -- no receptors with
# less than 0.9 similarity in the output
# The results are the same as for the previous normalised run
res <- dist_hamm(idata, min_sim = .8) |> collect()
res

# Plot normalized nearest-non-identical-neighbor distances.
vis(dist_hamm(idata))
# Plot all raw pairwise distances instead.
vis(dist_hamm(idata), mode = "all", xval = "dist")

## Not run: 
#
# Typical use case for BCR data
#

# BCR-style V/J/length blocking with at most three mismatches, inside patients
clone_edges <- dist_hamm(
  idata_bcr,
  seq_col = "junction",
  by = c("patient", "v_call", "j_call"),
  max_dist = 3
)

## End(Not run)


Information measures

Description

[Deprecated]

Compute information-based estimates and distances.

Usage

entropy(.data, .base = 2, .norm = FALSE, .do.norm = NA, .laplace = 1e-12)

kl_div(.alpha, .beta, .base = 2, .do.norm = NA, .laplace = 1e-12)

js_div(.alpha, .beta, .base = 2, .do.norm = NA, .laplace = 1e-12, .norm.entropy = FALSE)

cross_entropy(.alpha, .beta, .base = 2, .do.norm = NA,
              .laplace = 1e-12, .norm.entropy = FALSE)

Arguments

.data

Numeric vector. Any distribution.

.base

Numeric. A base of logarithm.

.norm

Logical. If TRUE then normalises the entropy by the maximal value of the entropy.

.do.norm

If TRUE then normalises the input distributions to make them sum up to 1.

.laplace

Numeric. A value for the laplace correction.

.alpha

Numeric vector. A distribution of some random value.

.beta

Numeric vector. A distribution of some random value.

.norm.entropy

Logical. If TRUE then normalises the resulting value by the average entropy of input distributions.

Value

A numeric value.

Examples

## Not run: 
P <- abs(rnorm(10))
Q <- abs(rnorm(10))
entropy(P)
kl_div(P, Q)
js_div(P, Q)
cross_entropy(P, Q)

## End(Not run)

Manipulate ggplot plots and create publication-ready plots

Description

[Deprecated]

The fixVis is a built-in software tool for the manipulation of plots, such as adjusting title text font and size, axes, and more. It is a powerful tool designed to produce publication-ready plots with minimal amount of coding.

Usage

fixVis(.plot = NA)

Arguments

.plot

A ggplot2 plot.

Value

No return value because it is an application.

Examples

## Not run: 
if (interactive()) {
  # Compute gene usage, visualise it and tweak via fixVis
  data(immdata) # load test data
  gu <- geneUsage(immdata$data)
  p <- vis(gu)
  fixVis(p)
}

## End(Not run)

Main function for estimation of V-gene and J-gene statistics

Description

[Deprecated]

An utility function to analyse the immune receptor gene usage (IGHD, IGHJ, IDHV, IGIJ, IGKJ, IGKV, IGLJ, IGLV, TRAJ, TRAV, TRBD, etc.) and statistics. For gene details run gene_stats().

Usage

geneUsage(
  .data,
  .gene = c("hs.trbv", "HomoSapiens.TRBJ", "macmul.IGHV"),
  .quant = c(NA, "count"),
  .ambig = c("inc", "exc", "maj"),
  .type = c("segment", "allele", "family"),
  .norm = FALSE
)

Arguments

.data

The data to be processed. Can be data.frame, data.table::data.table, or a list of these objects.

Every object must have columns in the immunarch compatible format. immunarch_data_format

Competent users may provide advanced data representations: DBI database connections,or a list of these objects. They are supported with the same limitations as basic objects.

Note: each connection must represent a separate repertoire.

.gene

A character vector of length one with the name of the gene you want to analyse of the specific species. If you provide a vector of different length, only the first element will be used. The string should also contain the species of interest, for example, valid ".gene" arguments are "hs.trbv", "HomoSapiens.TRBJ" or "macmul.IGHV". For details run gene_stats().

.quant

Selects the column with data to evaluate. Pass NA if you want to compute gene statistics at the clonotype level without re-weighting. Pass "count" to use the "Clones" column to weight genes by abundance of their corresponding clonotypes.

.ambig

An option to handle ambiguous gene assigments, e.g., "TRAV1,TRAV2".

  • Pass "inc" to include all possible gene segments, so "TRAV1,TRAV2" is counted as a different gene segment.

  • Pass "exc" to exclude all ambiguous gene assignments, so "TRAV1,TRAV2" is excluded from the resultant gene table.

We recommend to turn it on by passing "inc" (turned on by default). You can exclude data for the cases where there is no clear match for gene, include it for every supplied gene, or pick only first from the set. Set it to "exc", "inc" or "maj", respectively.

.type

Set the type of data to evaluate: "segment", "allele", or "family".

.norm

If TRUE then return proportions of genes. If FALSE then return counts of genes.

Value

A data frame with rows corresponding to gene segments and columns corresponding to the input samples.

Examples

## Not run: 
data(immdata)
gu <- geneUsage(immdata$data)
vis(gu)

## End(Not run)

Post-analysis of V-gene and J-gene statistics: PCA, clustering, etc.

Description

[Deprecated]

The geneUsageAnalysis() function deploys several data analysis methods, including PCA, multidimensional scaling, Jensen-Shannon divergence, k-means, hierarchical clustering, DBscan, and different correlation coefficients.

Usage

geneUsageAnalysis(
  .data,
  .method = c("js+hclust", "pca+kmeans", "anova", "js+pca+kmeans"),
  .base = 2,
  .norm.entropy = FALSE,
  .cor = c("pearson", "kendall", "spearman"),
  .do.norm = TRUE,
  .laplace = 1e-12,
  .verbose = TRUE,
  .k = 2,
  .eps = 0.01,
  .perp = 1,
  .theta = 0.1
)

Arguments

.data

The geneUsageAnalysis() function runs on the output from geneUsage().

.method

A string that defines the type of analysis to perform. Can be "pca", "mds", "js", "kmeans", "hclust", "dbscan" or "cor" if you want to calculate correlation coefficient. In the latter case you have to provide .cor argument.

.base

A numerical value that defines the logarithm base for Jensen-Shannon divergence.

.norm.entropy

A logical value. Set TRUE to normalise your data if you haven't done it already.

.cor

A string that defines the correlation coefficient for analysis. Can be "pearson", "kendall" or "spearman".

.do.norm

A logical value. If TRUE it forces Laplace smoothing, if NA it checks if smoothing is necessary, if FALSE does nothing.

.laplace

The numeric value, which is used as a pseudocount for Laplace smoothing.

.verbose

A logical value.

.k

The number of clusters to create, passed as k to hcut or as centers to kmeans.

.eps

A numerical value, DBscan epsylon parameter, see immunr_dbscan().

.perp

A numerical value, t-SNE perplexity, see immunr_tsne().

.theta

A numerical value, t-SNE theta parameter, see immunr_tsne().

Value

Depends on the last element in the .method string. See immunr_tsne for more info.

Examples

## Not run: 
data(immdata)
gu <- geneUsage(immdata$data, .norm = TRUE)
geneUsageAnalysis(gu, "js+hclust", .verbose = FALSE) %>% vis()

## End(Not run)

Gene segments table

Description

Gene segments table


WIP

Description

WIP

Usage

gene_stats()

Value

gene_stats returns all segment gene statistics

Examples

## Not run: 
gene_stats()
get_genes("hs.trbv", "segment")

## End(Not run)

Calculate the k-mer statistics of immune repertoires

Description

[Deprecated]

Usage

getKmers(.data, .k, .col = c("aa", "nt"), .coding = TRUE)

Arguments

.data

The data to be processed. Can be data.frame, data.table::data.table, or a list of these objects.

Every object must have columns in the immunarch compatible format. immunarch_data_format

Competent users may provide advanced data representations: DBI database connections,or a list of these objects. They are supported with the same limitations as basic objects.

Note: each connection must represent a separate repertoire.

.k

Integer. Length of k-mers.

.col

Character. Which column to use, pass "aa" (by default) for CDR3 amino acid sequence, pass "nt" for CDR3 nucleotide sequences.

.coding

Logical. If TRUE (by default) then removes all non-coding sequences from input data first.

Value

Data frame with two columns (k-mers and their counts).

Examples

## Not run: 
data(immdata)
kmers <- getKmers(immdata$data[[1]], 5)
kmers %>% vis()

## End(Not run)

Get the Latest immunarch Update

Description

Retrieves an update message for immunarch.

Usage

get_immunarch_news(datepoint = "latest")

Arguments

datepoint

A single character string specifying the update date. Use "latest" for the most recent update or supply a valid date key (e.g., "Apr 2025").

Details

If datepoint is set to "latest", the function returns the most recent update. Otherwise, specify the update date key (e.g., "Apr 2025") to retrieve that particular update. If no matching update is found, a warning is issued along with available update keys.

Value

A character string with the update details or a warning if the key is not found.

See Also

list_immunarch_news()


Get a character vector of samples' groups from the input metadata file

Description

Get a character vector of samples' groups from the input metadata file

Usage

group_from_metadata(.by, .metadata, .sep = "; ")

Arguments

.by

Character vector. Specify a column or columns in the input metadata to group by.

.metadata

Metadata object.

.sep

Character vector. Defines a separator between groups if more than one group passed in .by.

Value

Character vector with group names.

Developer Examples

immunarch:::group_from_metadata("Status", data.frame(Status = c("A", "A", "B", "B", "C")))


Check for the specific class

Description

A function to check if an input object has a specific class name.

Usage

has_class(.data, .class)

Arguments

.data

Any R object.

.class

Character vector. Specifies a class name to check against.

Value

Logical value.

Developer Examples

tmp <- "abc" immunarch:::has_class(tmp, "new_class") tmp <- immunarch:::add_class(tmp, "new_class") immunarch:::has_class(tmp, "new_class")


Single chain immune repertoire dataset

Description

A dataset with single chain TCR data for testing and examplatory purposes.

Usage

immdata

Format

A list of two elements. The first element ("data") is a list with data frames with clonotype tables. The second element ("meta") is a metadata table.

data

List of immune repertoire data frames.

meta

Metadata

...


Get a list of package updates

Description

Get a list of package updates

Usage

immunarch_v1_updates

Specification of the data format used by immunarch dataframes

Description


Clustering of objects or distance matrices

Description

[Deprecated]

Clusters the data with one of the following methods:

Usage

immunr_hclust(.data, .k = 2, .k.max = nrow(.data) - 1, .method = "complete", .dist = TRUE)

immunr_kmeans(.data, .k = 2, .k.max = as.integer(sqrt(nrow(.data))) + 1,
.method = c("silhouette", "gap_stat"))

immunr_dbscan(.data, .eps, .dist = TRUE)

Arguments

.data

Matrix or data frame with features, distance matrix or output from repOverlapAnalysis or geneUsageAnalysis functions.

.k

The number of clusters to create, defined as k to hcut or as centers to kmeans.

.k.max

Limits the maximum number of clusters. It is passed as k.max to factoextra::fviz_nbclust for immunr_hclust and immunr_kmeans.

.method

Passed to factoextra::hcut or as factoextra::fviz_nbclust.

In case of factoextra::hcut the agglomeration method is going to be used (argument hc_method).

In case of factoextra::fviz_nbclust it is the method to be used for estimating the optimal number of clusters (argument method).

.dist

If TRUE then ".data" is expected to be a distance matrix. If FALSE then the euclidean distance is computed for the input objects.

.eps

Local radius for expanding clusters, minimal distance between points to expand clusters. Passed as eps to dbscan.

Value

immunr_hclust - list with two elements. The first element is an output from factoextra::hcut. The second element is an output from factoextra::fviz_nbclust

immunr_kmeans - list with three elements. The first element is an output from kmeans. The second element is an output from factoextra::fviz_nbclust. The third element is the input dataset .data.

immunr_dbscan - list with two elements. The first element is an output from fpc::dbscan. The second element is the input dataset .data.

Examples

## Not run: 
data(immdata)
gu <- geneUsage(immdata$data, .norm = TRUE)
immunr_hclust(t(as.matrix(gu[, -1])), .dist = FALSE)

gu[is.na(gu)] <- 0
immunr_kmeans(t(as.matrix(gu[, -1])))

## End(Not run)

Dimensionality reduction

Description

[Deprecated]

Collects a set of principal variables, reducing the number of not important variables to analyse. Dimensionality reduction makes data analysis algorithms work faster and sometimes more accurate, since it also reduces noise in the data. Currently available methods are:

Usage

immunr_pca(.data, .scale = default_scale_fun, .raw = TRUE, .orig = FALSE, .dist = FALSE)

immunr_mds(.data, .scale = default_scale_fun, .raw = TRUE, .orig = FALSE, .dist = TRUE)

immunr_tsne(.data, .perp = 1, .dist = TRUE, ...)

Arguments

.data

A matrix or a data frame with features, distance matrix or output from repOverlapAnalysis or geneUsageAnalysis functions.

.scale

A function to apply to your data before passing it to any of dimensionality reduction algorithms. There is no scaling by default.

.raw

If TRUE then returns the non-processed output from dimensionality reduction algorithms. Pass FALSE if you want to visualise results.

.orig

If TRUE then returns the original result from algorithms. Pass FALSE if you want to visualise results.

.dist

If TRUE then assumes that ".data" is a distance matrix.

.perp

The perplexity parameter for Rtsne. Specifies the number of neighbors each data point must have in the resulting plot.

...

Other parameters passed to Rtsne.

Value

immunr_pca - an output from prcomp.

immunr_mds - an output from isoMDS.

immunr_tsne - an output from Rtsne.

See Also

vis.immunr_pca for visualisations.

Examples

## Not run: 
data(immdata)
gu <- geneUsage(immdata$data)
gu[is.na(gu)] <- 0
gu <- t(as.matrix(gu[, -1]))
immunr_pca(gu)
immunr_mds(dist(gu))
immunr_tsne(dist(gu))

## End(Not run)

Incremental counting of repertoire similarity

Description

[Deprecated]

For reference please look up https://www.pnas.org/content/111/16/5980 (Fig. 4).

Usage

inc_overlap(
  .data,
  .fun,
  .step = 1000,
  .n.steps = 10,
  .downsample = FALSE,
  .bootstrap = NA,
  .verbose.inc = TRUE,
  ...
)

Arguments

.data

The data to be processed. Can be data.frame, data.table::data.table, or a list of these objects.

Every object must have columns in the immunarch compatible format. immunarch_data_format

Competent users may provide advanced data representations: DBI database connections, or a list of these objects. They are supported with the same limitations as basic objects.

Note: each connection must represent a separate repertoire.

.fun

Function to compute overlaps. e.g., morisita_index.

.step

Either an integer or a numeric vector.

In the first case, the integer defines the step of incremental overlap.

In the second case, the vector encodes all repertoire sampling depths.

.n.steps

Integer. Number of steps if .step is a single integer. Skipped if ".step" is a numeric vector.

.downsample

If TRUE then performs downsampling to N clonotypes at each step instead of choosing the top N clonotypes.

.bootstrap

Set NA to turn off any bootstrapping, set a number to perform bootstrapping with this number of tries.

.verbose.inc

Logical. If TRUE then shows the output from the computation process.

...

Other arguments passed to .fun.

Value

List with overlap matrices.

Examples

## Not run: 
data(immdata)
ov <- repOverlap(immdata$data, "inc+overlap", .step = 100, .verbose.inc = FALSE, .verbose = FALSE)
vis(ov)

## End(Not run)

List Available immunarch Updates

Description

Prints each available update date and its command. Click the command to run it in consoles that support clickable R commands.

Usage

list_immunarch_news()

Value

Invisibly returns NULL.

See Also

get_immunarch_news()


Describe one publicness selection rule

Description

Define a comparison population and inclusive incidence and abundance bounds for vdj_public(). The constructor stores a rule without evaluating data.

Usage

make_public_filter(
  repertoires = NULL,
  strata = NULL,
  incidence_by = c("repertoire", "strata"),
  min_incidence = NULL,
  max_incidence = NULL,
  min_count = NULL,
  max_count = NULL,
  min_proportion = NULL,
  max_proportion = NULL
)

Arguments

repertoires

A numeric vector of repertoire IDs, or NULL for all.

strata

Numeric strata IDs or existing strata_name labels, or NULL for all. When both selectors are supplied, use their intersection.

incidence_by

A character scalar: "repertoire" counts distinct repertoires; "strata" counts existing strata.

min_incidence, max_incidence

Non-negative whole-number bounds, or NULL. Without either bound, the minimum is one. An explicit maximum alone imposes no minimum, so zero incidence can pass.

min_count, max_count

Numeric count bounds, or NULL.

min_proportion, max_proportion

Numeric within-repertoire proportion bounds, or NULL.

Details

Abundance bounds qualify individual receptor occurrences before incidence is counted. Repeated chain/cell abundance values are deduplicated, never summed. For example, ⁠max_count = 10, min_incidence = 2⁠ requires qualifying occurrences in two repertoires, allowing larger occurrences elsewhere. ⁠min_count = 5, max_incidence = 0⁠ allows observed counts below five. Unknown selectors and empty comparison populations are errors during evaluation. Selectors do not match arbitrary metadata values.

Value

A list describing one rule for vdj_public().

See Also

vdj_public() for strata preparation and applying several rules.

Examples

# Count >= 5 in at least one repertoire.
abundant <- make_public_filter(min_count = 5)


idata <- get_test_idata() |>
  agg_repertoires(c("Response", "Therapy"))

vdj_public(idata, abundant, output = "df") |>
  dplyr::select(cdr3_aa, v_call, Therapy, imd_orig_count) |>
  head()

# At least one occurrence with count <= 10. Larger occurrences are allowed.
low_count <- make_public_filter(max_count = 10)

# No occurrence with count >= 5. Smaller counts are allowed.
below_threshold <- make_public_filter(min_count = 5, max_incidence = 0L)


Copy the upper matrix triangle to the lower one

Description

Copy the upper matrix triangle to the lower one

Usage

matrixdiagcopy(.mat)

Arguments

.mat

Matrix.

Value

Matrix with its upper tri part copied to the lower tri part.

Developer Examples

mat <- matrix(0, 3, 3) mat mat(1, 3) <- 1 mat <- immunarch:::matrixdiagcopy(mat) mat


Common arguments for immunarch helpers

Description

Common arguments for immunarch helpers

Usage

method_args_airr(
  autojoin = getOption(IMMUNARCH_AUTOJOIN_OPTION, IMMUNARCH_AUTOJOIN_DEFAULT),
  format = c("long", "wide")
)

Arguments

autojoin

Logical. If TRUE, join repertoire metadata by the schema repertoire id. Change the default behaviour by calling options(immunarch.autojoin = FALSE).

format

String. One of "long" ("long" tibble with imd_repertoire_id, facet columns, and value; useful for visualizations) or "wide" (wide/unmelted table of features, with each row corresponding to a specific repertoire / pair of repertoires; useful for Machine Learning).


Create a repertoire of public clonotypes

Description

[Deprecated]

Usage

pubRep(
  .data,
  .col = "aa+v",
  .quant = c("count", "prop"),
  .coding = TRUE,
  .min.samples = 1,
  .max.samples = NA,
  .verbose = TRUE
)

Arguments

.data

The data to be processed. Can be data.frame, data.table::data.table, or a list of these objects.

Every object must have columns in the immunarch compatible format. immunarch_data_format

Competent users may provide advanced data representations: DBI database connections, or a list of these objects. They are supported with the same limitations as basic objects.

Note: each connection must represent a separate repertoire.

.col

A string that specifies the column(s) to be processed. Outputs one of the following strings, separated by the plus sign: "nt" for nucleotide sequences, "aa" for amino acid sequences, "v" for V gene segments, "j" for J gene segments. E.g., pass "aa+v" to compute overlaps on CDR3 amino acid sequences paired with V gene segments, i.e., in this case a unique clonotype is a pair of CDR3 amino acid and V gene segment.

.quant

A string that specifies the column to be processed. Set "count" to see public clonotype sharing with the number of clones, set "prop" to see proportions.

.coding

Logical. If TRUE then preprocesses the data to filter out non-coding sequences.

.min.samples

Integer. A minimal number of samples a clonotype must have to be included in the public repertoire table.

.max.samples

Integer. A maxminal number of samples a clonotype must have to be included in the public repertoire table. Set NA (by default) to have the maximal amount of samples.

.verbose

Logical. If TRUE then outputs the progress.

Value

Data table with columns for:

Examples

## Not run: 
# Subset the data to make the example faster to run
immdata$data <- lapply(immdata$data, head, 2000)
pr <- pubRep(immdata$data, .verbose = FALSE)
vis(pr, "clonotypes", 1, 2)

## End(Not run)

Apply transformations to public repertoires

Description

[Deprecated]

Usage

pubRepApply(.pr1, .pr2, .fun = function(x) log10(x[1])/log10(x[2]))

Arguments

.pr1

First public repertoire.

.pr2

Second public repertoire.

.fun

A function to apply to pairs of frequencies of same clonotypes from "pr1" and "pr2". By default - log(X) / log(Y) where ⁠X,Y⁠ - frequencies of the same clonotype, found in both public repertoires.

Value

Work in progress.

Examples

## Not run: 
data(immdata)
immdata$data <- lapply(immdata$data, head, 2000)
pr <- pubRep(immdata$data, .verbose = FALSE)
pr1 <- pubRepFilter(pr, immdata$meta, .by = c(Status = "MS"))
pr2 <- pubRepFilter(pr, immdata$meta, .by = c(Status = "C"))
prapp <- pubRepApply(pr1, pr2)
head(prapp)

## End(Not run)

Filter out clonotypes from public repertoires

Description

[Deprecated]

Filter our clonotypes with low incidence in a specific group.

Usage

pubRepFilter(.pr, .meta, .by, .min.samples = 1)

Arguments

.pr

Public repertoires, an output from pubRep.

.meta

Metadata file.

.by

Named character vector. Names of the group to filter by.

.min.samples

Integer. Filters out clonotypes with the number of samples below than this number.

Value

Data frame with filtered clonotypes.

Examples

## Not run: 
data(immdata)
immdata$data <- lapply(immdata$data, head, 2000)
pr <- pubRep(immdata$data, .verbose = FALSE)
pr1 <- pubRepFilter(pr, immdata$meta, .by = c(Status = "MS"))
head(pr1)

## End(Not run)

Statistics of number of public clonotypes for each possible combinations of repertoires

Description

[Deprecated]

Usage

pubRepStatistics(.data, .by = NA, .meta = NA)

Arguments

.data

Public repertoire, an output from the pubRep function.

.by

Work in Progress.

.meta

Work in Progress.

Value

Data frame with incidence statistics per sample.

Examples

## Not run: 
data(immdata)
immdata$data <- lapply(immdata$data, head, 2000)
pr <- pubRep(immdata$data, .verbose = FALSE)
pubRepStatistics(pr) %>% vis()

## End(Not run)

Get a matrix with public clonotype frequencies

Description

[Deprecated]

Usage

public_matrix(.data)

Arguments

.data

Public repertoire, an output from pubRep.

Value

Matrix with per-sample clonotype counts / proportions only.

Examples

## Not run: 
data(immdata)
immdata$data <- lapply(immdata$data, head, 2000)
pr <- pubRep(immdata$data, .verbose = FALSE)
pr.mat <- public_matrix(pr)
dim(pr.mat)
head(pr.mat)

## End(Not run)

Read IMGT immunoglobulin germline references

Description

[Experimental]

V and J genes provide parts of an antibody sequence. To measure mutations in a B-cell clone, we need to compare its sequences with reference versions of those genes before somatic hypermutation.

This function reads nucleotide V and J genes from an IMGT FASTA file for use by annotate_ig_germlines(). It keeps the IMGT gaps (.) in the reference sequences.

Usage

read_germline_references(path)

Arguments

path

Character scalar. Path to an IMGT FASTA file.

Value

A tibble with species, locus, segment, allele_id, and sequence columns.

Choosing files

Use IMGT-gapped V and J FASTA files from the same IMGT release used for your IgBlast run. Read each needed file and combine the resulting tables. Do not use the ungapped FASTA from the searchable IgBlast database: this function does not add gaps or convert positions.


Register an Immunarch method (developer)

Description

[Experimental]

Usage

register_method_impl(
  core,
  family,
  name,
  register_family = TRUE,
  required_cols = NULL,
  need_repertoires = TRUE,
  airr_args = FALSE,
  result_class = TRUE,
  vdj_args = FALSE
)

Arguments

core

A function with signature ⁠function(idata, ...)⁠. This is your core implementation; it must accept an ImmunData as the first argument and must not declare autojoin or format.

family

String. Method family name used for dispatch (e.g., "airr_stats").

name

String. Method name within the family (e.g., "lengths").

register_family

Logical (default TRUE). If TRUE, attempts to create/ensure the family environment by calling register_method_family() when available.

required_cols

Character vector of column names that must be present in idata$annotations. Use this to declare the minimal input schema your core needs.

need_repertoires

Logical. Use this to declare the necessity of having aggregated repertoires.

vdj_args

Logical scalar. If TRUE, add the VDJ output argument unless the core declares it, and collect ImmunData results when output = "df". A core declaring output may return its own summary tibble directly. The default is FALSE.

Details

Wrap a core implementation into a user-facing function and (optionally) register it in the in-memory method registry. Domain-specific registrars add the appropriate arguments and post-processing while sharing the same safety checks.

What your core must look like

What the wrapper adds

Value

A function - the user-facing wrapper around core. Typical usage is to assign it to the exported symbol of the method, e.g.: airr_stats_lengths <- register_method_airr(...).

Examples

## Not run: 
# Minimal core implementation (must accept `idata`)
airr_stats_lengths_impl <- function(idata, seq_col = "cdr3_aa") {
  repertoire_col <- immundata::imd_schema("repertoire")
  idata$annotations |>
    dplyr::distinct(!!rlang::sym(repertoire_col), !!rlang::sym(seq_col)) |>
    dplyr::mutate(seq_len = nchar(!!rlang::sym(seq_col))) |>
    dplyr::count(!!rlang::sym(repertoire_col), seq_len, name = "n")
}

# Register and expose a user-facing function
airr_stats_lengths <- register_method_airr(
  core = airr_stats_lengths_impl,
  family = "airr_stats",
  name = "lengths",
  required_cols = c("cdr3_aa", immundata::imd_schema("repertoire"))
)

# Optional: call via dispatcher
# make_airr_dispatcher("airr_stats")(idata = immdata, method = "lengths")

## End(Not run)


Aligns all sequences incliding germline within each clonal lineage within each cluster

Description

[Deprecated]

This function aligns all sequences (incliding germline) that belong to one clonal lineage and one cluster. After clustering and building the clonal lineage and germline, the next step is to analyze the degree of mutation and maturity of each clonal lineage. This allows for finding high mature cells and cells with a large number of offspring. The phylogenetic analysis will find mutations that increase the affinity of BCR. Making alignment of the sequence is the first step towards sequence analysis including BCR.

Usage

repAlignLineage(.data, .min_lineage_sequences, .prepare_threads, .align_threads, .nofail)

Arguments

.data

The data to be processed. Can be data.frame, data.table::data.table or a list of these objects.

.min_lineage_sequences

If number of sequences in the same clonal lineage and the same cluster (not including germline) is lower than this threshold, this group of sequences will be filtered out from the dataframe; so only large enough lineages will be included.

.prepare_threads

Number of threads to prepare results table. Please note that high number can cause heavy memory usage!

.align_threads

Number of threads for lineage alignment.

It must have columns in the immunarch compatible format immunarch_data_format, and also must contain 'Cluster' column, which is added by seqCluster() function, and 'Germline.sequence' column, which is added by repGermline() function.

.nofail

Will return NA instead of stopping if Clustal W is not installed. Used to avoid raising errors in examples on computers where Clustal W is not installed.

Value

Dataframe or list of dataframes (if input is a list with multiple samples). The dataframe has these columns:

Examples

## Not run: 

data(bcrdata)
bcr_data <- bcrdata$data

bcr_data %>%
  seqCluster(seqDist(bcr_data), .fixed_threshold = 3) %>%
  repGermline(.threads = 1) %>%
  repAlignLineage(.min_lineage_sequences = 2, .align_threads = 2, .nofail = TRUE)

## End(Not run)

Builds a phylogenetic tree using the sequences of a clonal lineage

Description

[Deprecated]

This function uses the PHYLIP package to make phylogenetic analysis. For making trees it uses maximum parsimony methods.

Usage

repClonalFamily(.data, .vis_groups, .threads, .nofail)

Arguments

.data

The data to be processed, output of repAlignLineage() function.

.vis_groups

Groups for visualization, used to annotate specific clones on chart and display them in different colors. This is a named list, where names are for the chart legend, and list items are clone IDs that belong to the groups. It's not necessary to assign groups to all clonotypes; unassigned ones will be displayed on the chart as "Clonotype" category. It's also possible to assign multiple clonotypes to the same group by providing nested lists or vectors of clone IDs instead of single clone IDs. Example: .vis_groups = list(A = 817, B = 201, C = list(303, 42))

.threads

Number of threads to use.

.nofail

Returns NA instead of stopping if PHYLIP is not installed. Used to avoid raising errors in examples on computers where PHYLIP is not installed.

Value

Dataframe or list of dataframes (if input is a list with multiple samples). The dataframe has these columns:

Examples

## Not run: 

data(bcrdata)
bcr_data <- bcrdata$data

bcr_data %>%
  seqCluster(seqDist(bcr_data), .fixed_threshold = 3) %>%
  repGermline(.threads = 1) %>%
  repAlignLineage(.min_lineage_sequences = 2, .align_threads = 2, .nofail = TRUE) %>%
  repClonalFamily(.threads = 1, .nofail = TRUE)

## End(Not run)

Clonality analysis of immune repertoires

Description

[Deprecated]

repClonality function encompasses several methods to measure clonal proportions in a given repertoire.

Usage

repClonality(
  .data,
  .method = c("clonal.prop", "homeo", "top", "rare"),
  .perc = 10,
  .clone.types = c(Rare = 1e-05, Small = 1e-04, Medium = 0.001, Large = 0.01,
    Hyperexpanded = 1),
  .head = c(10, 100, 1000, 3000, 10000, 30000, 1e+05),
  .bound = c(1, 3, 10, 30, 100)
)

Arguments

.data

The data to be processed. Can be data.frame, data.table::data.table, or a list of these objects.

Every object must have columns in the immunarch compatible format. immunarch_data_format

Competent users may provide advanced data representations: DBI database connections, or a list of these objects. They are supported with the same limitations as basic objects.

Note: each connection must represent a separate repertoire.

.method

A String with one of the following options: "clonal.prop", "homeo", "top" or "rare".

Set "clonal.prop" to compute clonal proportions or in other words percentage of clonotypes required to occupy specified by .perc percent of the total immune repertoire.

Set "homeo" to analyse relative abundance (also known as clonal space homeostasis), which is defined as the proportion of repertoire occupied by clonal groups with specific abundances..

Set "top" to estimate relative abundance for the groups of top clonotypes in repertoire, e.g., ten most abundant clonotypes. Use ".head" to define index intervals, such as 10, 100 and so on.

Set "rare" to estimate relative abundance for the groups of rare clonotypes with low counts. Use ".bound" to define the threshold of clonotype groups.

.perc

A single numerical value ranging from 0 to 100.

.clone.types

A named numerical vector with the threshold of the half-closed intervals that mark off clonal groups.

.head

A numerical vector with ranges of the top clonotypes.

.bound

A numerical vector with ranges of abundance for the rare clonotypes in the dataset.

Details

Clonal proportion assessment is a different approach to estimate repertoire diversity. When visualised, it allows for thorough examination of immune repertoire structure and composition.

In its core this type of analysis is similar to the relative species abundance concept in ecology. Relative abundance is the percent composition of an organism of a particular kind relative to the total number of organisms in the area.

A stacked barplot of relative clonotype abundances can be therefore viewed as a non-parametric approach to comparing their underlying distributions.

Value

If input data is a single immune repertoire, then the function returns a numeric vector with clonality statistics.

Otherwise, it returns a numeric matrix with clonality statistics for all input repertoires.

See Also

repDiversity

Examples

## Not run: 
# Load the data
data(immdata)

imm_pr <- repClonality(immdata$data, .method = "clonal.prop")
vis(imm_pr)

imm_top <- repClonality(immdata$data, .method = "top", .head = c(10, 100, 1000, 3000, 10000))
vis(imm_top)

imm_rare <- repClonality(immdata$data, .method = "rare")
vis(imm_rare)

imm_hom <- repClonality(immdata$data, .method = "homeo")
vis(imm_hom)

## End(Not run)

The main function for immune repertoire diversity estimation

Description

[Deprecated]

This is a utility function to estimate the diversity of species or objects in the given distribution.

Note: functions will check if .data is a distribution of a random variable (sum == 1) or not. To force normalisation and / or to prevent this, set .do.norm to TRUE (do normalisation) or FALSE (don't do normalisation), respectively.

Usage

repDiversity(
  .data,
  .method = "chao1",
  .col = "aa",
  .max.q = 6,
  .min.q = 1,
  .q = 5,
  .step = NA,
  .quantile = c(0.025, 0.975),
  .extrapolation = NA,
  .perc = 50,
  .norm = TRUE,
  .verbose = TRUE,
  .do.norm = NA,
  .laplace = 0
)

Arguments

.data

The data to be processed. Can be data.frame, data.table::data.table, or a list of these objects.

Every object must have columns in the immunarch compatible format. immunarch_data_format

Competent users may provide advanced data representations: DBI database connections, or a list of these objects. They are supported with the same limitations as basic objects.

Note: each connection must represent a separate repertoire.

.method

Picks a method used for estimation out of a following list: chao1, hill, div, gini.simp, inv.simp, gini, raref, d50, dxx.

.col

A string that specifies the column(s) to be processed. Pass one of the following strings, separated by the plus sign: "nt" for nucleotide sequences, "aa" for amino acid sequences, "v" for V gene segments, "j" for J gene segments. E.g., pass "aa+v" to compute diversity estimations on CDR3 amino acid sequences paired with V gene segments, i.e., in this case a unique clonotype is a pair of CDR3 amino acid and V gene segment. Clonal counts of equal clonotypes will be summed up.

.max.q

The max hill number to calculate (default: 5).

.min.q

Function calculates several hill numbers. Set the min (default: 1).

.q

q-parameter for the Diversity index.

.step

Rarefaction step's size.

.quantile

Numeric vector with quantiles for confidence intervals.

.extrapolation

An integer. An upper limit for the number of clones to extrapolate to. Pass 0 (zero) to turn extrapolation subroutines off.

.perc

Set the percent to dXX index measurement.

.norm

Normalises rarefaction curves.

.verbose

If TRUE then outputs progress.

.do.norm

One of the three values - NA, TRUE or FALSE. If NA then checks for distrubution (sum(.data) == 1) and normalises if needed with the given laplace correction value. if TRUE then does normalisation and laplace correction. If FALSE then doesn't do neither normalisaton nor laplace correction.

.laplace

A numeric value, which is used as a pseudocount for Laplace smoothing.

Details

Value

div, gini, gini.simp, inv.simp, raref return numeric vector of length 1 with value.

chao1 returns 4 values: estimated number of species, standart deviation of this number and two 95% confidence intervals for the species number.

hill returns a vector of specified length .max.q - .min.q

For most methods, if input data is a single immune repertoire, then the function returns a numeric vector with diversity statistics.

Otherwise, it returns a numeric matrix with diversity statistics for all input repertoires.

For Chao1 the function returns a matrix with diversity estimations.

For rarefaction the function returns either a matrix with diversity estimatinos on different step of the simulaiton process or a list with such matrices.

See Also

repOverlap, entropy, repClonality Rarefaction wiki https://en.wikipedia.org/wiki/Rarefaction_(ecology) Hill numbers paper https://www.uvm.edu/~ngotelli/manuscriptpdfs/ChaoHill.pdf Diversity wiki https://en.wikipedia.org/wiki/Measurement_of_biodiversity

Examples

## Not run: 
data(immdata)

# Make data smaller for testing purposes
immdata$data <- top(immdata$data, 4000)

# chao1
repDiversity(.data = immdata$data, .method = "chao1") %>% vis()

# Hill numbers
repDiversity(
  .data = immdata$data, .method = "hill", .max.q = 6,
  .min.q = 1, .do.norm = NA, .laplace = 0
) %>% vis()

# diversity
repDiversity(.data = immdata$data, .method = "div", .q = 5, .do.norm = NA, .laplace = 0) %>%
  vis()

# Gini-Simpson
repDiversity(.data = immdata$data, .method = "gini.simp", .q = 5, .do.norm = NA, .laplace = 0) %>%
  vis()

# inverse Simpson
repDiversity(.data = immdata$data, .method = "inv.simp", .do.norm = NA, .laplace = 0) %>% vis()

# Gini coefficient
repDiversity(.data = immdata$data, .method = "gini", .do.norm = NA, .laplace = 0)

# d50
repDiversity(.data = immdata$data, .method = "d50") %>% vis()

## End(Not run)

Main function for exploratory data analysis: compute the distribution of lengths, clones, etc.

Description

[Deprecated]

The repExplore function calculates the basic statistics of repertoire: the number of unique immune receptor clonotypes, their relative abundances, and sequence length distribution across the input dataset.

Usage

repExplore(
  .data,
  .method = c("volume", "count", "len", "clones"),
  .col = c("nt", "aa"),
  .coding = TRUE
)

Arguments

.data

The data to be processed. Can be data.frame, data.table::data.table, or a list of these objects.

Every object must have columns in the immunarch compatible format. immunarch_data_format

Competent users may provide advanced data representations: DBI database connections, or a list of these objects. They are supported with the same limitations as basic objects.

Note: each connection must represent a separate repertoire.

.method

A string that specifies the method of analysis. It can be either "volume", "count", "len" or "clones".

When .method is set to "volume" the repExplore calculates the number of unique clonotypes in the input data.

When .method is set to "count" the repExplore calculates the distribution of clonotype abundances, i.e., how frequent receptors with different abundances are.

When .method is set to "len" the repExplore calculates the distribution of CDR3 sequence lengths.

When .method is set to "clones" the repExplore returns the number of clones (i.e., cells) per input repertoire.

.col

A string that specifies the column to be processed. Pass "nt" for nucleotide sequence or "aa" for amino acid sequence.

.coding

If TRUE, then only coding sequences will be analysed.

Value

If input data is a single immune repertoire, then the function returns a numeric vector with exploratory analysis statistics.

Otherwise, it returns a numeric matrix with exploratory analysis statistics for all input repertoires.

See Also

vis.immunr_exp_vol

Examples

## Not run: 
data(immdata)

# Calculate statistics and generate a visual output with vis()
repExplore(immdata$data, .method = "volume") %>% vis()

repExplore(immdata$data, .method = "count") %>% vis()

repExplore(immdata$data, .method = "len") %>% vis()

## End(Not run)

Main function for data filtering

Description

[Deprecated]

Usage

repFilter(
  .data,
  .method = "by.clonotype",
  .query = list(CDR3.aa = exclude("partial", "out_of_frame")),
  .match = "exact"
)

Arguments

.data

The data to be processed. Must be the list of 2 elements: a data table and a metadata table.

.method

Method of filtering. Implemented methods: by.meta, by.repertoire (by.rep), by.clonotype (by.cl) Default value: 'by.clonotype'.

.query

Filtering query. It's a named list of filters that will be applied to data. Possible values for names in this list are dependent on filter methods:

  • by.meta: filters by metadata. Names in the named list are metadata column headers.

  • by.repertoire: filters by the number of clonotypes or total number of clones in sample. Possible names in the named list are "n_clonotypes" and "n_clones".

  • by.clonotype: filters by data in all samples. Names in the named list are data column headers. Elements of the named list for each of the filters are filtering options. Possible values for filtering options:

  • include("STR1", "STR2", ...): keeps only rows with matching values. Available for methods: "by.meta", "by.clonotype".

  • exclude("STR1", "STR2", ...): removes rows with matching values. Available for methods: "by.meta", "by.clonotype".

  • lessthan(value): keeps rows/samples with numeric values less than specified. Available for methods: "by.meta", "by.repertoire", "by.clonotype".

  • morethan(value): keeps rows/samples with numeric values more than specified. Available for methods: "by.meta", "by.repertoire", "by.clonotype".

  • interval(from, to): keeps rows/samples with numeric values that fits in this interval. from is inclusive, to is exclusive. Available for methods: "by.meta", "by.repertoire", "by.clonotype". Default value: 'list(CDR3.aa = exclude("partial", "out_of_frame"))'.

.match

Matching method for "include" and "exclude" options in query. Possible values:

  • exact: matches only the exact specified string;

  • startswith: matches all strings starting with the specified substring;

  • substring: matches all strings containing the specified substring. Default value: 'exact'.


Creates germlines for clonal lineages

Description

[Deprecated]

This function creates germlines for clonal lineages. B cell clonal lineage represents a set of B cells that presumably have a common origin (arising from the same VDJ rearrangement event) and a common ancestor. Each clonal lineage has its own germline sequence that represents the ancestral sequence for each BCR in clonal lineage. In other words, germline sequence is a sequence of B-cells immediately after VDJ recombination, before B-cell maturation and hypermutation process. Germline sequence is useful for assessing the degree of mutation and maturity of the repertoire.

Usage

repGermline(.data, .species, .min_nuc_outside_cdr3, .threads)

Arguments

.data

The data to be processed. Can be data.frame, data.table::data.table or a list of these objects.

It must have columns in the immunarch compatible format immunarch_data_format.

.species

Species from which the data was acquired. Available options: "HomoSapiens" (default), "MusMusculus", "BosTaurus", "CamelusDromedarius", "CanisLupusFamiliaris", "DanioRerio", "MacacaMulatta", "MusMusculusDomesticus", "MusMusculusCastaneus", "MusMusculusMolossinus", "MusMusculusMusculus", "MusSpretus", "OncorhynchusMykiss", "OrnithorhynchusAnatinus", "OryctolagusCuniculus", "RattusNorvegicus", "SusScrofa".

.min_nuc_outside_cdr3

This parameter sets how many nucleotides should have V or J chain outside of CDR3 to be considered good for further alignment.

.threads

Number of threads to use.

Value

Data with added columns:

Examples

## Not run: 

data(bcrdata)

bcrdata$data %>%
  top(5) %>%
  repGermline()

## End(Not run)

Load immune repertoire files into the R workspace

Description

[Deprecated]

The repLoad function loads repertoire files into R workspace in the immunarch format where you can immediately use them for the analysis. repLoad automatically detects the right format for your files, so all you need is simply provide the path to your files.

See "Details" for more information on supported formats. See "Examples" for diving right into it.

Usage

repLoad(.path, .mode = "paired", .coding = TRUE, ...)

Arguments

.path

A character string specifying the path to the input data. Input data can be one of the following:

  • a single repertoire file. In this case repLoad returns an R data.frame;

  • a vector of paths to repertoire files. Same as in the case with no metadata file presented in the next section below;

  • a path to the folder with repertoire files and, if available, metadata file "metadata.txt". If the metadata file if presented, then the repLoad returns a list with two elements "data" and "meta". "data" is an another list with repertoire R data.frames. "meta" is a data frame with the metadata. If the metadata file "metadata.txt" is not presented, then the repLoad creates a dummy metadata file with sample names and returns a list with two elements "data" and "meta". If input data has multiple chains or cell types stored in the same file (for example, like in 10xGenomics repertoire files), such repertoire files will be splitted to different R data frames with only one type of chain and cell presented. The metadata file will have additional columns specifying cell and chain types for different samples.

.mode

Either "single" for single chain data or "paired" for paired chain data.

Currently "single" works for every format, and "paired" works only for 10X Genomics data.

By default, 10X Genomics data will be loaded as paired chain data, and other files will be loaded as single chain data.

.coding

A logical value. Set TRUE to get coding-only clonotypes (by defaul). Set FALSE to get all clonotypes.

...

Extra arguments for parsing functions

Details

The metadata has to be a tab delimited file with first column named "Sample". It can have any number of additional columns with arbitrary names. The first column should contain base names of files without extensions in your folder. Example:

Sample Sex Age Status
immunoseq_1 M 1 C
immunoseq_2 M 2 C
immunoseq_3 FALSE 3 A

Currently, Immunarch support the following formats:

Value

A list with two named elements:

See Also

immunr_data_format for immunarch data format; repSave for file saving; repOverlap, geneUsage and repDiversity for starting with immune repertoires basic statistics.

Examples

## Not run: 
# To load the data from a single file (note that you don't need to specify the data format):
file_path <- paste0(system.file(package = "immunarch"), "/extdata/io/Sample1.tsv.gz")
immdata <- repLoad(file_path)

# Suppose you have a following structure in your folder:
# >_ ls
# immunoseq1.txt
# immunoseq2.txt
# immunoseq3.txt
# metadata.txt

# To load the whole folder with every file in it type:
file_path <- paste0(system.file(package = "immunarch"), "/extdata/io/")
immdata <- repLoad(file_path)
print(names(immdata))

# We recommend creating a metadata file named "metadata.txt" in the folder.

# In that case, when you load your data you will see:
# > immdata <- repLoad("path/to/your/folder/")
# > names(immdata)
# [1] "data" "meta"

# If you do not have "metadata.txt", you will see the same output,
# but your metadata will be almost empty:
# > immdata <- repLoad("path/to/your/folder/")
# > names(immdata)
# [1] "data" "meta"

## End(Not run)

Main function for public clonotype statistics calculations

Description

[Deprecated]

The repOverlap function is designed to analyse the overlap between two or more repertoires. It contains a number of methods to compare immune receptor sequences that are shared between individuals.

Usage

repOverlap(
  .data,
  .method = c("public", "overlap", "jaccard", "tversky", "cosine", "morisita",
    "inc+public", "inc+morisita"),
  .col = "aa",
  .a = 0.5,
  .b = 0.5,
  .verbose = TRUE,
  .step = 1000,
  .n.steps = 10,
  .downsample = FALSE,
  .bootstrap = NA,
  .verbose.inc = NA,
  .force.matrix = FALSE
)

Arguments

.data

The data to be processed. Can be data.frame, data.table::data.table, or a list of these objects.

Every object must have columns in the immunarch compatible format. immunarch_data_format

Competent users may provide advanced data representations: DBI database connections, or a list of these objects. They are supported with the same limitations as basic objects.

Note: each connection must represent a separate repertoire.

.method

A string that specifies the method of analysis or a combination of methods. The repOverlap function supports following basic methods: "public", "overlap", "jaccard", "tversky", "cosine", "morisita". If vector of multiple methods is given for this parameter, the first method will be used.

.col

A string that specifies the column(s) to be processed. Pass one of the following strings, separated by the plus sign: "nt" for nucleotide sequences, "aa" for amino acid sequences, "v" for V gene segments, "j" for J gene segments. E.g., pass "aa+v" to compute overlaps on CDR3 amino acid sequences paired with V gene segments, i.e., in this case a unique clonotype is a pair of CDR3 amino acid and V gene segment. Clonal counts of equal clonotypes will be summed up.

.a, .b

Alpha and beta parameters for Tversky Index. Default values give the Jaccard index measure.

.verbose

if TRUE then output the progress.

.step

Either an integer or a numeric vector.

In the first case, the integer defines the step of incremental overlap.

In the second case, the vector encodes all repertoire sampling depths.

.n.steps

Skipped if ".step" is a numeric vector.

.downsample

If TRUE then performs downsampling to N clonotypes at each step instead of choosing the top N clonotypes in incremental overlaps. Change nothing of you are using conventional methods.

.bootstrap

Set NA to turn off any bootstrapping, set a number to perform bootstrapping with this number of tries.

.verbose.inc

Logical. If TRUE then shows output from the computation process.

.force.matrix

Logical. If TRUE then always forces the matrix output even in case of two input repertoires.

Details

"public" and "shared" are synonyms that exist for the convenience of researchers.

The "overlap" coefficient is a similarity measure that measures the overlap between two finite sets.

The "jaccard" index is conceptually a percentage of how many objects two sets have in common out of how many objects they have total.

The "tversky" index is an asymmetric similarity measure on sets that compares a variant to a prototype.

The "cosine" index is a measure of similarity between two non-zero vectors of an inner product space that measures the cosine of the angle between them.

The "morisita" index measures how many times it is more likely to randomly select two sampled points from the same quadrat (the dataset is covered by a regular grid of changing size) then it would be in the case of a random distribution generated from a Poisson process. Duplicate objects are merged with their counts are summed up.

Value

In most cases the return value is a matrix with overlap values for each pair of repertoires.

If only two repertoires were provided, return value is single numeric value.

If one of the incremental method is chosen, return list of overlap matrix.

See Also

inc_overlap, vis

Examples

## Not run: 
data(immdata)

# Make data smaller for testing purposes
immdata$data <- top(immdata$data, 4000)

ov <- repOverlap(immdata$data, .verbose = FALSE)
vis(ov)

ov <- repOverlap(immdata$data, "jaccard", .verbose = FALSE)
vis(ov, "heatmap2")

## End(Not run)

Post-analysis of public clonotype statistics: PCA, clustering, etc.

Description

[Deprecated]

The repOverlapAnalysis() function contains advanced data analysis methods. You can use several clustering and dimensionality reduction techniques in order to investigate further the difference between repertoires provided.

To cluster a subset of similar data with repOverlapAnalysis() you can perform hierarchical clustering, k-means or dbscan ('hclust', 'kmeans', 'dbscan' respectively).

To reduce dimensions, for example, to select features for subsequent analysis, you can execute the multidimensional scaling or t-sne algorithms ('mds' and 'tsne' respectively).

Usage

repOverlapAnalysis(
  .data,
  .method = ("hclust"),
  .scale = default_scale_fun,
  .raw = TRUE,
  .perp = 1,
  .theta = 0.1,
  .eps = 0.01,
  .k = 2
)

Arguments

.data

Any distance matrix between pairs of repertoires. You can also pass your output from repOverlap().

.method

A string that defines the type of analysis to perform.

.scale

A function to scale the data before passing it to the MDS algorithm.

.raw

A logical value. Set TRUE if you want to receive raw output of clustering or dimensionality reduction function of choice. Set FALSE if you want to receive processed output that can be subjected to visualisation with vis() function.

.perp

A numerical value, t-SNE parameter, see immunr_tsne().

.theta

A numerical value, t-SNE parameter, see immunr_tsne().

.eps

A numerical value, DBscan epsylon parameter, see immunr_dbscan().

.k

The number of clusters to create, passed as k to hcut or as centers to kmeans.

Value

Depends on the last element in the .method string. See immunr_tsne for more info.

Examples

## Not run: 
data(immdata)
ov <- repOverlap(immdata$data)
repOverlapAnalysis(ov, "mds+hclust") %>% vis()

## End(Not run)

Downsampling and resampling of immune repertoires

Description

[Deprecated]

Sample (downsample) repertoires using different approches.

Usage

repSample(
  .data,
  .method = c("downsample", "resample", "sample"),
  .n = NA,
  .prob = TRUE
)

Arguments

.data

The data to be processed. Can be data.frame, data.table::data.table, or a list of these objects.

Every object must have columns in the immunarch compatible format. immunarch_data_format

Competent users may provide advanced data representations: DBI database connections, or a list of these objects. They are supported with the same limitations as basic objects.

Note: each connection must represent a separate repertoire.

.method

Character. Name of a sampling method. See "Details" for more details. Default value is "downsample" that downsamples the repertoires to the number of clones (i.e., reads / UMIs) that the smallest repertoire has, if user doesn't set any value to the ".n" argument.

.n

Integer. Number of clones / clonotypes / reads / UMIs to choose, depending on the method. Set NA to sample repertoires to the size of the smallest repertoire in the ".data".

.prob

Logical. If TRUE then samples the clonotypes with probability weights equal to their number of clones. Used only if ".method" is "sample".

Details

If .method is "downsample" then repSample chooses .n clones (not clonotypes!) from the input repertoires without any probabilistic simulation, but exactly computing each choosed clones. Such approach is is more consistent and biologically pleasant than an output from the function if .method is "resample".

If .method is "resample" then repSample uses multinomial distribution to compute the number of occurences for each cloneset. then it removes zero-number clonotypes and return the resulting data frame. Probabilities for rmultinom for each cloneset is a percentage of this cloneset in the "Proportion" column. It's a some sort of simulation of how clonotypes are chosen from the organisms.

if .method is "sample" then repSample chooses .n clonotypes (not clones!) randomly. Depending on the .prob argument, the function chooses clonotypes either according to their size (if .prob is TRUE, by default), or each clonotype has an equal chance to be choosed (if .prob is FALSE). Note that sampling is done without replacing.

Value

Subsampled immune repertoire or a list of subsampled immune repertoires.

See Also

rmultinom, clonal_proportion

Examples

## Not run: 
data(immdata)
# Downsampling to 1000 clones (not clonotypes!)
tmp <- repSample(immdata$data[[1]], .n = 1000)
sum(tmp$Clones)

# Downsampling to 1000 clonotypes
tmp <- repSample(immdata$data[[1]], "sample", .n = 1000)
nrow(tmp)

# Downsampling to the smallest repertoire by clones (not clonotypes!)
tmp <- repSample(immdata$data[c(1, 2)])
sum(tmp[[1]]$Clones)
sum(tmp[[2]]$Clones)

# Downsampling to the smallest repertoire by clonotypes
tmp <- repSample(immdata$data[c(1, 2)], "sample")
nrow(tmp[[1]]$Clones)
nrow(tmp[[2]]$Clones)

## End(Not run)

Save immune repertoires to the disk

Description

[Deprecated]

The repSave function is deigned to save your data to the disk in desirable format. Currently supports "immunarch" and "vdjtools" file formats.

Usage

repSave(.data, .path, .format = c("immunarch", "vdjtools"), .compress = TRUE)

Arguments

.data

An R dataframe, a list of R dataframes or a list with data and meta where first element is a list of dataframes and the latter is a dataframe with metadata.

.path

A string with the path to the output directory. It should include file name if a single dataframe is provided to .data argument.

.format

A string with desirable format specification. Current options are "immunarch" and "vdjtools".

.compress

A boolean value. Defines whether the output will be compressed or not.

Details

It is not necessary to create directories beforehand. If the provided directory does not exist it will be created automatically.

Value

No return value.

Examples

## Not run: 
data(immdata)
# Reduce data to save time on examples
immdata$data <- map(immdata$data, ~ .x %>% head(10))
dirpath <- tempdir()
# Save the list of repertoires
repSave(immdata, dirpath)
# Load it and check if it is the same
new_immdata <- repLoad(dirpath)
# sum(immdata$data[[1]] != new_immdata$data[[1]], na.rm = TRUE)
# sum(immdata$data[[2]] != new_immdata$data[[2]], na.rm = TRUE)
# sum(immdata$meta != new_immdata$meta, na.rm = TRUE)

## End(Not run)

Calculates number of mutations against the germline for each clonotype

Description

[Deprecated]

This function aligns V and J genes from the germline in each cluster with corresponding genes in each clonotype, saves the alignments for purpose of visualization, and calculates number of mutations for each clonotype.

Usage

repSomaticHypermutation(.data, .threads, .nofail)

Arguments

.data

The data to be processed: an output of repClonalFamily(); variants with one sample and list of samples are both supported.

.threads

Number of threads to use.

.nofail

Will return NA instead of stopping if Clustal W is not installed. Used to avoid raising errors in examples on computers where Clustal W is not installed.

Value

Dataframe or list of dataframes (if input is a list with multiple samples). The dataframe has all the columns from repClonalFamily() output dataframe, with Sequence column unnested: the resulting dataframe has one line per clonotype. Clone.ID column contains original IDs for clonotypes, and can be used as dataframe key. New columns are added:

Examples

## Not run: 

data(bcrdata)
bcr_data <- bcrdata$data

bcr_data %>%
  seqCluster(seqDist(bcr_data), .fixed_threshold = 3) %>%
  repGermline(.threads = 1) %>%
  repAlignLineage(.min_lineage_sequences = 2, .align_threads = 2, .nofail = TRUE) %>%
  repClonalFamily(.threads = 1, .nofail = TRUE) %>%
  repSomaticHypermutation(.threads = 1, .nofail = TRUE)

## End(Not run)

Immune repertoire similarity

Description

[Experimental]

A family of functions to compare shared receptors between repertoires. These methods help you measure repertoire similarity, identify public receptors, compare biological groups, and check whether replicate samples have similar receptor composition.

Available functions

The following methods are available.

1) Shared-receptor counts (repsim_intersection). Count the unique receptors shared by each pair of repertoires. Use this method to find related samples, check replicate similarity, or identify receptors shared across many repertoires.

2) Jaccard similarity (repsim_jaccard). Compare the sets of unique receptors in each pair of repertoires. The score accounts for the total number of unique receptors in both repertoires. Use it to compare receptor overlap when repertoire sizes differ.

J(A, B) = \frac{|A \cap B|}{|A \cup B|}

3) Chao-Jaccard similarity (repsim_chao_jaccard). Compare receptor overlap using receptor counts. The method estimates similarity after allowing for shared receptors that may be missing because one or both repertoires were sampled at limited depth. Use it when sampling depth may affect the observed overlap.

4) Morisita-Horn similarity (repsim_morisita_horn). Compare receptor abundance profiles. Abundant receptors have more influence on the score than rare receptors. Use it to determine whether the same expanded receptors dominate two repertoires. The method uses imd_proportion as the abundance measure.

C_{MH} = \frac{2 \sum_k x_{ik} x_{jk}} {(\lambda_i + \lambda_j) N_i N_j}

5) Bray-Curtis similarity (repsim_bray). Measure how similar two receptor abundance profiles are. This is one minus Bray-Curtis dissimilarity: 0 means no overlap, and 1 means identical abundance composition. The method uses imd_proportion as the abundance measure.

Set transform = "log1p" to reduce the influence of the most abundant receptors and give lower-abundance receptors more influence on the result. This can reveal broader repertoire similarity when a few expanded receptors would otherwise dominate the comparison. The transformation is applied inside the database query and does not modify idata.

Immune-repertoire studies commonly calculate Bray-Curtis measures from clonotype proportions without an additional transformation. Therefore, transform = "none" remains the default. The "log1p" option is an exploratory sensitivity analysis based on a common ecological pre-treatment for reducing the effect of dominant taxa. After transformation, the values no longer sum to one, and the result no longer has the simple interpretation of the fraction of original repertoire abundance that overlaps.

Usage

repsim_intersection(idata)

repsim_jaccard(idata)

repsim_chao_jaccard(idata)

repsim_morisita_horn(idata)

repsim_bray(idata, transform = c("none", "log1p"))

Arguments

idata

An immundata::ImmunData object.

transform

A single character string selecting the transformation applied to imd_proportion before calculating similarity. Use "none" (the default) for the original proportions or "log1p" for log(1 + imd_proportion).

S_{BC,ij} = 1 - \frac{\sum_k |a_{ik} - a_{jk}|} {\sum_k (a_{ik} + a_{jk})} = \frac{2\sum_k \min(a_{ik}, a_{jk})}{\sum_k (a_{ik} + a_{jk})}

where a_{ik} is the original or transformed abundance of receptor k in repertoire i.

Value

1) Shared-receptor counts (repsim_intersection)

A symmetric numeric matrix where rows/columns are repertoire labels derived from schema_repertoire. Each cell is the count of shared unique receptors. The diagonal contains per-repertoire richness (total unique receptors).

2) Jaccard similarity (repsim_jaccard)

A symmetric numeric matrix where rows/columns are repertoire labels derived from schema_repertoire. Each cell is the Jaccard similarity in ⁠[0, 1]⁠. The diagonal is 1.

3) Chao-Jaccard similarity (repsim_chao_jaccard)

A symmetric numeric matrix where rows/columns are repertoire labels derived from schema_repertoire. Each cell is the Chao-Jaccard similarity in ⁠[0, 1]⁠ (1 = maximum estimated overlap, 0 = no observed shared receptors). The diagonal is 1.

4) Morisita-Horn similarity (repsim_morisita_horn)

A symmetric numeric matrix whose rows/columns are repertoire labels derived from schema_repertoire, with values in ⁠[0, 1]⁠ (0 = no shared abundance, 1 = identical abundance composition). The diagonal is 1. Comparisons involving an empty repertoire are NA.

5) Bray-Curtis similarity (repsim_bray)

A symmetric numeric matrix where rows/columns are repertoire labels derived from schema_repertoire. Each cell is Bray-Curtis similarity in ⁠[0, 1]⁠ (0 = no overlap, 1 = identical). The diagonal is 1.

Visualisation

All five ⁠repsim_*()⁠ results can be passed directly to vis(). vis() displays the result as a dot plot, with repertoire labels on both axes. Each dot represents one pair of repertoires; its size and fill show the value for that pair.

1) Shared-receptor counts (repsim_intersection)

Larger and brighter dots mean that the repertoires share more unique receptors. The matrix diagonal contains repertoire richness; the plot omits self-comparisons.

2) Jaccard similarity (repsim_jaccard)

Larger and brighter dots mean greater similarity between the sets of unique receptors. Values range from 0 (no shared receptors) to 1 (identical receptor sets).

3) Chao-Jaccard similarity (repsim_chao_jaccard)

Larger and brighter dots mean greater estimated similarity after correction for receptors that may be missing because of limited sampling. Values range from 0 (no observed shared receptors) to 1 (maximum estimated similarity).

4) Morisita-Horn similarity (repsim_morisita_horn)

Larger and brighter dots mean greater similarity between receptor abundance profiles. Values range from 0 (no overlap) to 1 (identical abundance composition).

5) Bray-Curtis similarity (repsim_bray)

Larger and brighter dots mean greater similarity between receptor abundance profiles. Values range from 0 (no overlap) to 1 (identical abundance composition).

All plots omit self-comparisons. Their color legends mark the smallest, midpoint, and largest plotted pairwise values.

All repertoire-similarity plots accept:

References

Chao A, Chazdon RL, Colwell RK, Shen TJ (2005). A new statistical approach for assessing similarity of species composition with incidence and abundance data. Ecology Letters, 8(2), 148-159. doi:10.1111/j.1461-0248.2004.00707.x

Horn HS (1966). Measurement of overlap in comparative ecological studies. The American Naturalist, 100(914), 419-424. doi:10.1086/282436

Clarke KR, Chapman MG, Somerfield PJ, Needham HR (2006). Dispersion-based weighting of species counts in assemblage analyses. Marine Ecology Progress Series, 320, 11-27. doi:10.3354/meps320011

The TCR assigns naive T cells to a preferred lymph node (2024). Science Advances. doi:10.1126/sciadv.adl0796

*On the feasibility of using TCR sequencing to follow a vaccination response

See Also

immundata::ImmunData

Examples

# Limit the number of threads used by the underlying DB for this example.
# Generally, you should NOT do this in your session.
db_exec("SET threads TO 1")

# Load example data.
immdata <- get_test_idata()

#
# Count receptors shared by each pair of repertoires.
m_pub <- repsim_intersection(immdata)

# Visualise the shared-receptor counts.
vis(m_pub)


#
# Calculate Jaccard similarity.
m_jac <- repsim_jaccard(immdata)
vis(m_jac)


#
# Calculate sampling-corrected Jaccard similarity.
m_chao_jac <- repsim_chao_jaccard(immdata)
vis(m_chao_jac)


#
# Calculate Morisita-Horn similarity.
m_mh <- repsim_morisita_horn(immdata)
vis(m_mh)


#
# Calculate Bray-Curtis similarity.
m_bray <- repsim_bray(immdata)
vis(m_bray)

# Reduce the influence of highly expanded receptors.
m_bray_log <- repsim_bray(
  immdata,
  transform = "log1p"
)
vis(m_bray_log)


Select specific clonotypes using barcodes from single-cell metadata

Description

[Deprecated]

Subsets the input immune repertoire by barcodes. Creates a vector of barcodes to subset or a vector cluster IDs and corresponding barcodes to get a list of immune repertoires corresponding to cluster IDs. Columns with clonotype counts and proportions are changed accordingly to the filtered barcodes.

Usage

select_barcodes(.data, .barcodes, .force.list = FALSE)

Arguments

.data

The data to be processed. Can be data.frame, data.table::data.table, or a list of these objects.

Every object must have columns in the immunarch compatible format. immunarch_data_format

Competent users may provide advanced data representations: DBI database connections, or a list of these objects. They are supported with the same limitations as basic objects.

Note: each connection must represent a separate repertoire.

.barcodes

Either a character vector with barcodes or a named character/factor vector with barcodes as names and cluster IDs a vector elements. The output of Seurat's Idents function works.

.force.list

Logical. If TRUE then always returns a list, even if the result is one data frame.

Value

An immune repertoire (if ".barcodes" is a barcode vector) or a list of immune repertoires (if ".barcodes" is named vector or an output from Seurat::Idents()). Each element is an immune repertoire with clonotype barcodes corresponding to the input barcodes. The output list names are cluster names in the ".barcode" argument (Seurat::Idents() case only).

See Also

select_clusters

Examples

## Not run: 
data(immdata)
# Create a fake single-cell data
df <- immdata$data[[1]]
df$Barcode <- "AAAAACCCCC"
df$Barcode[51:nrow(df)] <- "GGGGGCCCCC"
barcodes <- "AAAAACCCCC"
df <- select_barcodes(df, barcodes)
nrow(df)

## End(Not run)

Split the immune repertoire data to clusters from single-cell barcodes

Description

[Deprecated]

Given the vector of barcodes from Seurat, splits the input repertoires to separate subsets following the barcodes' assigned IDs. Useful in case you want to split immune repertoires by patients or clusters.

Usage

select_clusters(.data, .clusters, .field = "Cluster")

Arguments

.data

List of two elements "data" and "meta", with "data" being a list of immune repertoires, and "meta" being a metadata table.

.clusters

Factor vector with barcodes as vector names and cluster IDs as vector elements. The output of the Seurat Idents function works.

.field

A string specifying the name of the field in the input metadata. New immune repertoire subsets will have cluster IDs in this field.

Value

A list with two elements "data" and "meta" with updated immune repertoire tables and metadata.

See Also

select_barcodes

Examples

## Not run: 
library(Seurat)
Idents(pbmc_small)
new_cluster_ids <- c("A", "B", "C")
new_cluster_ids <- levels(pbmc_small)
new_cluster_ids
pbmc_small <- RenameIdents(pbmc_small, new_cluster_ids)

## End(Not run)

Function for assigning clusters based on sequences similarity

Description

[Deprecated]

Graph clustering based on distances between sequences

Usage

seqCluster(.data, .dist, .perc_similarity, .nt_similarity, .fixed_threshold)

Arguments

.data

The data which was used to caluculate .dist object. Can be data.frame, data.table::data.table, or a list of these objects.

Every object must have columns in the immunarch compatible format immunarch_data_format

.dist

List of distance objects produced with seqDist function.

.perc_similarity

Numeric value between 0 and 1 specifying the maximum acceptable weight of an edge in a graph. This threshold depends on the length of sequences.

.nt_similarity

Numeric between 0-sequence length specifying the threshold of allowing a 1 in n nucleotides mismatch in sequencies.

.fixed_threshold

Numeric specifying the threshold on the maximum weight of an edge in a graph.

Value

Immdata data format object. Same as .data, but with extra 'Cluster' column with clusters assigned.

Examples

## Not run: 
data(immdata)
# In this example, we will use only 2 samples with 500 clonotypes in each for time saving
input_data <- lapply(immdata$data[1:2], head, 500)
dist_result <- seqDist(input_data)
cluster_result <- seqCluster(input_data, dist_result, .fixed_threshold = 1)

## End(Not run)

Function for computing distance for sequences

Description

[Deprecated]

Computing sequential distances between clonotypes from two repertoires:

Usage

seqDist(.data, .col = 'CDR3.nt', .method = 'hamming',
 .group_by = c("V.name", "J.name"), .group_by_seqLength = TRUE, .trim_genes = TRUE, ...)

Arguments

.data

The data to be processed. Can be data.frame, data.table::data.table, or a list of these objects.

Every object must have columns in the immunarch compatible format immunarch_data_format

.col

A string that specifies the column name to be processed. The default value is 'CDR3.nt'.

.method

Character value or user-defined function.

.group_by

Character vector of column names to group sequence by. The default value is c("V.first", "J.first"). Columns "V.first" and "J.first" containing first genes without allele suffixes are calculated automatically from "V.name" and "J.name" if absent in the data. Pass NA for no grouping options.

.group_by_seqLength

If TRUE - adds grouping by sequence length of .col argument

.trim_genes

If TRUE - use only general gene values (e.g. "IGHV1-18") of .group_by columns for clustering; if FALSE - can cause very small clusters in case of high resolution genotyping

...

Extra arguments for user-defined function.

The default value is 'hamming' for Hamming distance which counts the number of character substitutions that turns b into a. If a and b have different number of characters the distance is Inf.

Other possible values are:

'lv' for Levenshtein distance which counts the number of deletions, insertions and substitutions necessary to turn b into a.

'lcs' for longest common substring is defined as the longest string can be obtained by pairing characters from a and b while keeping the order of characters intact.

In case of user-defined function, it should take x and y parameters as input and return dist object.

Value

Named list of list with dist objects for given repertoires for each combination of .group_by variable(s) and/or sequence length of .col.

Examples

## Not run: 
data(immdata)
# Reducing data to save time on examples
immdata$data <- map(immdata$data, ~ .x %>% head(10))
# Computing hamming distance for the first two repertoires in `'immdata'`
seqDist(immdata$data[1:2])

# Here we define a custom distance function
# that will count the difference in number of characters in sequences.

f <- function(x, y) {
  res <- matrix(nrow = length(x), ncol = length(y))
  for (i in 1:length(x)) {
    res[i, ] <- abs(nchar(x[i]) - nchar(y))
  }
  dimnames(res) <- list(x, y)
  return(as.dist(res))
}

seqDist(immdata$data[1:2], .method = f, .group_by_seqLength = FALSE)

## End(Not run)


Set and update progress bars

Description

Set and update progress bars

Usage

set_pb(.max)

add_pb(.pb, .value = 1)

Arguments

.max

Integer. Maximal value of the progress bar.

.pb

Progress bar object from set_pb.

.value

Numeric. Value to add to the progress bar at each step.

Value

An updated progress bar.

Developer Examples

pb <- immunarch:::set_pb(100) immunarch:::add_pb(pb, 25) immunarch:::add_pb(pb, 25) immunarch:::add_pb(pb, 25) immunarch:::add_pb(pb, 25) close(pb)


Immune repertoire spectratyping

Description

[Deprecated]

Usage

spectratype(.data, .quant = c("id", "count"), .col = "nt")

Arguments

.data

The data to be processed. Can be data.frame, data.table::data.table, or a list of these objects.

Every object must have columns in the immunarch compatible format. immunarch_data_format

Competent users may provide advanced data representations: DBI database connections, or a list of these objects. They are supported with the same limitations as basic objects.

Note: each connection must represent a separate repertoire.

.quant

Select the column with clonal counts to evaluate. Set to "id" to count every clonotype once. Set to "count" to take into the account number of clones per clonotype.

.col

A string that specifies the column(s) to be processed. The output is one of the following strings, separated by the plus sign: "nt" for nucleotide sequences, "aa" for amino acid sequences, "v" for V gene segments, "j" for J gene segments. E.g., pass "aa+v" for spectratyping on CDR3 amino acid sequences paired with V gene segments, i.e., in this case a unique clonotype is a pair of CDR3 amino acid and V gene segment. Clonal counts of equal clonotypes will be summed up.

Value

Data frame with distributions of clonotypes per CDR3 length.

Examples

## Not run: 
# Load the data
data(immdata)
sp <- spectratype(immdata$data[[1]], .col = "aa+v")
vis(sp)

## End(Not run)

Analysis immune repertoire kmer statistics: sequence profiles, etc.

Description

[Deprecated]

Usage

split_to_kmers(.data, .k)

kmer_profile(.data, .method = c("freq", "prob", "wei", "self"), .remove.stop = TRUE)

Arguments

.data

Character vector or the output from getKmers.

.k

Integer. Size of k-mers.

.method

Character vector of length one. If "freq" then returns a position frequency matrix (PFM) - a matrix with occurences of each amino acid in each position.

If "prob" then returns a position probability matrix (PPM) - a matrix with probabilities of occurences of each amino acid in each position. This is a traditional representation of sequence motifs.

If "wei" then returns a position weight matrix (PWM) - a matrix with log likelihoods of PPM elements.

If "self" then returns a matrix with self-information of elements in PWM.

For more information see https://en.wikipedia.org/wiki/Position_weight_matrix.

.remove.stop

Logical. If TRUE (by default) remove stop codons.

Value

split_to_kmers - Data frame with two columns (k-mers and their counts).

kmer_profile - a matrix with per-position amino acid statistics.

Examples

## Not run: 
data(immdata)
kmers <- getKmers(immdata$data[[1]], 5)
kmer_profile(kmers) %>% vis()

## End(Not run)

Return a column's name

Description

Return a column's name

Usage

switch_type(type)

process_col_argument(.col)

Arguments

type

Character. Specifies the column to choose: "nt" chooses the CDR3 nucleotide column, "aa" chooses the CDR3 amino acid column, "v" chooses the V gene segment column, "j" chooses the J gene segment column.

.col

A string that specifies the column(s) to be processed. Select one of the following strings, separated by the plus sign: "nt" for nucleotide sequences, "aa" for amino acid sequences, "v" for V gene segments, "j" for J gene segments.

Value

A column's name.

Developer Examples

immunarch:::switch_type("nuc") immunarch:::switch_type("v")


Get the N most abundant clonotypes

Description

Get the N most abundant clonotypes

Usage

top(.data, .n = 10)

Arguments

.data

The data to be processed. Can be data.frame, data.table::data.table, or a list of these objects.

Every object must have columns in the immunarch compatible format. immunarch_data_format

Competent users may provide advanced data representations: DBI database connections, or a list of these objects. They are supported with the same limitations as basic objects.

Note: each connection must represent a separate repertoire.

.n

Numeric. Number of the most abundant clonotypes to return.

Value

Data frame with the .n most abundant clonotypes only.

Examples

## Not run: 
data(immdata)
top(immdata$data)
top(immdata$data[[1]])

## End(Not run)

Track clonotypes across time and data points

Description

[Deprecated]

Tracks the temporal dynamics of clonotypes in repertoires. For example, tracking across multiple time points after vaccination.

Note: duplicated clonotypes are merged and their counts are summed up.

Usage

trackClonotypes(.data, .which = list(1, 15), .col = "aa", .norm = TRUE)

Arguments

.data

The data to process. It can be a data.frame, a data.table::data.table, or a list of these objects.

Every object must have columns in the immunarch compatible format. immunarch_data_format

Competent users may provide advanced data representations: DBI database connections, or a list of these objects. They are supported with the same limitations as basic objects.

Note: each connection must represent a separate repertoire.

.which

An argument that regulates which clonotypes to choose for tracking. There are three options for this argument:

  1. passes a list with two elements list(X, Y), where X is the name or the index of a target repertoire from ".data", and Y is the number of the most abundant clonotypes to take from X.

  2. passes a character vector of sequences to take from all data frames;

  3. passes a data frame (data table, database) with one or more columns - first for sequences, and other for gene segments (if applicable).

See the "Examples" below with examples for each option.

.col

A character vector of length 1. Specifies an identifier for a column, from which the function chooses clonotype sequences. Specify "nt" for nucleotide sequences, "aa" for amino acid sequences, "aa+v" for amino acid sequences and Variable genes, "nt+j" for nucleotide sequences with Joining genes, or any combination of the above. Used only if ".which" has option 1) or option 2).

.norm

Logical. If TRUE then uses Proportion instead of the number of Clones per clonotype to store in the function output.

Value

Data frame with input sequences and counts or proportions for each of the input repertoire.

Examples

## Not run: 
# Load an example data that comes with immunarch
data(immdata)

# Make the data smaller in order to speed up the examples
immdata$data <- immdata$data[c(1, 2, 3, 7, 8, 9)]
immdata$meta <- immdata$meta[c(1, 2, 3, 7, 8, 9), ]

# Option 1
# Choose the first 10 amino acid clonotype sequences
# from the first repertoire to track
tc <- trackClonotypes(immdata$data, list(1, 10), .col = "aa")
# Choose the first 20 nucleotide clonotype sequences
# and their V genes from the "MS1" repertoire to track
tc <- trackClonotypes(immdata$data, list("MS1", 20), .col = "nt+v")

# Option 2
# Choose clonotypes with amino acid sequences "CASRGLITDTQYF" or "CSASRGSPNEQYF"
tc <- trackClonotypes(immdata$data, c("CASRGLITDTQYF", "CSASRGSPNEQYF"), .col = "aa")

# Option 3
# Choose the first 10 clonotypes from the first repertoire
# with amino acid sequences and V segments
target <- immdata$data[[1]] %>%
  select(CDR3.aa, V.name) %>%
  head(10)
tc <- trackClonotypes(immdata$data, target)

# Visualise the output regardless of the chosen option
# Therea are three way to visualise it, regulated by the .plot argument
vis(tc, .plot = "smooth")
vis(tc, .plot = "area")
vis(tc, .plot = "line")

# Visualising timepoints
# First, we create an additional column in the metadata with randomly choosen timepoints:
immdata$meta$Timepoint <- sample(1:length(immdata$data))
immdata$meta
# Next, we create a vector with samples in the right order,
# according to the "Timepoint" column (from smallest to greatest):
sample_order <- order(immdata$meta$Timepoint)
# Sanity check: timepoints are following the right order:
immdata$meta$Timepoint[sample_order]
# Samples, sorted by the timepoints:
immdata$meta$Sample[sample_order]
# And finally, we visualise the data:
vis(tc, .order = sample_order)

## End(Not run)

Select receptors by their incidence across repertoires or strata

Description

Select shared receptors, receptors private to a strata, or receptors absent above an abundance threshold. Define one or more rules to select receptors by their sharing and abundance in comparison populations using make_public_filter().

Usage

vdj_public(idata, ..., output = c("immundata", "df"))

Arguments

idata

An immundata::ImmunData object with defined repertoires.

...

One or more rules created by make_public_filter(). With no rules, require presence in at least two input repertoires.

output

A character scalar: "immundata" returns a new ImmunData, "df" returns a data frame convenient to immediately pass to vis().

Details

Input counts and proportions are saved as imd_orig_count and imd_orig_proportion. The input is unchanged. No per-rule incidence columns or custom attributes are added.

Value

A new ImmunData or collected observation table.

Repeated calls

Warning: Applying vdj_public() to an already filtered result overwrites imd_orig_count and imd_orig_proportion with abundances from its immediate input. Since proportions are recalculated after filtering, the saved proportions no longer refer to the repertoire before the first call. Keep the original ImmunData as a reference when calculating percentages relative to the original repertoires. To apply several rules to the same original input, pass them together in one vdj_public() call.

Visualisation

Plot the selected receptors with vis(selected, plot = "public", reference = idata), where idata is the original input to vdj_public(). Alternatively, pipe vdj_public(idata, output = "df") to vis(reference = idata); its result class selects this plot automatically. The ordinary observation rows in the collected output are unchanged.

Bars show abundance, the sum of the selected identities' saved original repertoire proportions, read against the left percentage axis. Dots show coverage, the number of selected identities detected in each repertoire, read against the right receptor-count axis. Dot labels give the detected/selected counts; bar labels give abundance percentages. Observed occurrences below selection thresholds still contribute to both measures. Coverage describes the selected set, not the fraction of all receptor identities in a repertoire. Individual receptor trajectories can be visualised with vdj_track().

The required reference defines the complete input repertoire population, retaining repertoires with no selected receptors at zero. Use the selected result and its own original reference: repertoire metadata is matched using the reference repertoire schema because filtering can rebuild repertoire IDs. The reference does not restore abundances overwritten by repeated vdj_public() calls; the saved original proportions must refer to this baseline. An empty selection cannot be plotted.

xval selects a repertoire ID or metadata column for the x-axis; each value must identify one repertoire. fill selects a repertoire metadata column for colour and defaults to the defined strata when available. Repertoires are ordered by colour group and x value; factor levels control their order. title changes the title or removes it with NULL.

See Also

make_public_filter(), annotate_public()

Examples

idata <- get_test_idata() |> agg_repertoires("Therapy")

# Keep receptors shared across at least two repertoires.
shared <- vdj_public(idata)
shared$repertoires


vis(shared, plot = "public", reference = idata)

# Work with repertoire and strata rules.
idata <- get_test_idata() |>
  agg_repertoires(c("Response", "Therapy")) |>
  agg_strata("Therapy")

vdj_public(idata, output = "df") |>
  vis(reference = idata, fill = "Therapy")

# Inspect strata and find the IDs for the two therapies.
groups <- idata$strata
groups
ici <- groups$imd_strata_id[groups$Therapy == "ICI"]
car_t <- groups$imd_strata_id[groups$Therapy == "CAR-T"]

# The test data has one repertoire per therapy, so use incidence >= 1.
in_ici <- vdj_public(idata, make_public_filter(
  strata = ici, min_incidence = 1L
))

# Count distinct strata instead of repertoires.
across_therapies <- vdj_public(idata, make_public_filter(
  incidence_by = "strata", min_incidence = 2L
))

# Present in ICI and absent in CAR-T. Collect the retained observations.
ici_only <- vdj_public(
  idata,
  make_public_filter(strata = ici, min_incidence = 1L),
  make_public_filter(strata = car_t, max_incidence = 0L),
  output = "df"
)
ici_only |>
  dplyr::select(
    cdr3_aa, v_call, Therapy, imd_orig_count,
    imd_orig_proportion
  ) |>
  head()

# Select by repertoire IDs and require count >= 5 in an ICI repertoire.
ids <- idata$repertoires |>
  dplyr::filter(Therapy == "ICI") |>
  dplyr::pull(imd_repertoire_id)
abundant <- vdj_public(idata, make_public_filter(
  repertoires = ids, min_count = 5
))
# All observations of passing receptors are retained throughout idata.


Track selected immune receptors across time and space

Description

Use vdj_track() to follow receptors across samples, time points, tissues, or cell populations. For example, select abundant receptors before treatment and find their abundances in later samples. You can also follow a set of sequences identified in another experiment.

Select receptors with the argument from, or use n to select the most abundant receptors in each source repertoire. Follow them throughout the target idata, including repertoires where they are rare or unobserved. The input ImmunData object is not changed.

Usage

vdj_track(idata, from = NULL, n = NULL, output = c("immundata", "df"))

Arguments

idata

An immundata::ImmunData object with defined repertoires. These are the repertoires through which receptors will be followed.

from

NULL, a numeric vector of repertoire IDs, an immundata::ImmunData object, or a data frame.

NULL, the default, uses every target repertoire as a source. Numeric values select source imd_repertoire_id values in idata.

An ImmunData source supplies its observed receptor identities.

A data frame supplies exact column combinations to match, such as junction alone or junction together with v_call. Tibbles and duckplyr tables are also accepted. tibble::tibble is recommended.

n

A non-negative whole number or NULL. Select up to n receptors with the highest counts in each source repertoire, then follow their combined set of identities. Equal counts are resolved by receptor ID, as in immundata::top_n(). NULL, the default, selects all source receptors. This argument applies only when from is NULL or contains repertoire IDs.

output

A character scalar. "immundata", the default, returns a new ImmunData object containing the selected receptors' observed cells and chains. "df" returns an abundance-summary tibble with one row per selected receptor and input repertoire, including explicit zeros where unobserved. Both outputs preserve the original target abundances. The summary retains input receptor and repertoire IDs, receptor identity features, and repertoire metadata as columns, and ready for plotting with vis().

Details

An ImmunData source must use the same receptor features and chain schema as the target. Complete feature combinations, including both chains of a paired receptor, are matched

Column names same as in the idata must exist in the target observations in the from argument. Matching is exact and case-sensitive, with no sequence or gene-call normalization. Missing query values in from are not allowed. Unmatched queries, empty query tables, and n = 0 produce an empty result.

Value

With output = "immundata", a new immundata::ImmunData object containing the selected receptors' observed rows, with imd_orig_count and imd_orig_proportion.

With output = "df", an immunarch result tibble containing:

Each selected receptor has exactly one row in every input repertoire. Receptor features sharing a name with repertoire metadata receive the suffix ⁠_receptor⁠. Barcode, chain-observation, and other row-level fields are excluded. The tibble is recognised by vis() and needs no attached repertoire metadata. Empty selections produce a zero-row summary with the same column structure.

Common use cases

Original abundances

imd_orig_count and imd_orig_proportion columns in the output store the target receptors counts and proportions before vdj_track filters the data. Use these columns to compare abundances across the original samples. The ordinary imd_count and imd_proportion describe the filtered object, following normal immundata behavior, i.e., normalising the proportions. Please be careful - another vdj_track call replaces the original-abundance columns imd_orig_count and imd_orig_proportion.

The ImmunData result contains observed chains only and follows normal immundata filtering, including rebuilding IDs for the remaining repertoires. In other words, the repertoire ID could change after calling vdj_track with output = "immundata". This is temporary inconvenience, sorry for that. The good news is that no repertoire metadata is missing so you still analyse the data. The "df" summary uses the input IDs and contains zero-count rows for unobserved combinations. These are abundance rows, without barcode or observation-specific fields. A receptor not observed in a sample is not necessarily biologically absent.

Visualisation

Pass vdj_track(..., output = "df") directly to vis(). The summary tibble carries a result class that selects the tracking plot. The default ImmunData output is intended for further analysis, so pass output = "df" whenever you want to plot the results.

vis() draws an alluvial plot of imd_orig_proportion by imd_repertoire_id by default. Receptors are distinguished by colour and labelled by their receptor features in the legend, for example ⁠AAA V01⁠. For paired receptors, each chain's locus and features are combined, for example ⁠IGH AAA V01 + IGL BBB V02⁠. Receptor IDs remain the grouping keys, so pairs sharing one chain remain separate trajectories. The plot accepts:

The summary already contains zero abundances for unobserved receptor-repertoire combinations. Every original target repertoire remains on the plot, including samples with no tracked observations.

Repertoire metadata is returned in regular columns for every target sample, including samples with no tracked observations. Use those columns for xval and facet, or prepare additional display columns in the summary.

See Also

Examples

library(immundata)

# A small bulk dataset sampled at four time points.
# At T3, only TTT is observed; neither AAA nor CCC is observed.
rows <- tibble::tibble(
  sample = c(rep(c("T0", "T1", "T2"), each = 3), "T3"),
  junction = c(
    "AAA", "CCC", "GGG", "AAA", "CCC", "TTT",
    "AAA", "GGG", "ACG", "TTT"
  ),
  v_call = c("V1", "V2", "V1", "V1", "V2", "V3", "V1", "V1", "V4", "V3"),
  abundance = c(8L, 2L, 1L, 1L, 9L, 4L, 2L, 3L, 5L, 5L)
)
input <- tempfile(fileext = ".tsv")
readr::write_tsv(rows, input)
idata <- read_repertoires(
  input,
  schema = c("junction", "v_call"), count_col = "abundance",
  repertoire_schema = "sample", output_folder = tempfile("vdj-track-"),
  preprocess = NULL, postprocess = NULL, rename_columns = NULL,
  verbose = FALSE
)
source_id <- idata$repertoires |>
  dplyr::filter(sample == "T0") |>
  dplyr::pull(imd_repertoire_id)

# Follow every receptor observed at T0, or only its two most abundant ones.
from_t0 <- vdj_track(idata, from = source_id)


top_from_t0 <- vdj_track(idata, from = source_id, n = 2L)

# Follow any receptor that is the most abundant in at least one repertoire.
top_from_each <- vdj_track(idata, n = 1L)

# An upstream selection can also supply the receptors to follow.
selected <- immundata::top_n(idata, n = 1L)
from_selected <- vdj_track(idata, from = selected)

# Match sequences alone, or exact sequence/gene combinations.
from_sequences <- vdj_track(idata, from = tibble::tibble(
  junction = c("AAA", "GGG")
))
from_panel <- vdj_track(idata, from = tibble::tibble(
  junction = c("AAA", "CCC"), v_call = c("V1", "V2")
), output = "df")

# The summary already has one row per receptor and repertoire: 2 x 4 rows.
from_panel

# Both selected receptors have explicit zero counts and proportions at T3.
from_panel |>
  dplyr::filter(sample == "T3") |>
  dplyr::select(sample, junction, imd_orig_count, imd_orig_proportion)

# Select baseline receptors, then visualise their original abundances.
tracked <- vdj_track(idata, from = source_id, n = 2L, output = "df")
tracked$sample <- factor(tracked$sample, levels = c("T0", "T1", "T2", "T3"))
# T3 remains on each plot, with both receptor abundances at zero.
# Legend labels combine receptor features automatically, for example AAA V1.
vis(tracked, xval = "sample")
vis(tracked, xval = "sample", plot = "area")
vis(tracked, xval = "sample", plot = "line")

# Plot original counts instead of proportions.
vis(tracked, xval = "sample", plot = "line", yval = "imd_orig_count")


One function to visualise them all

Description

[Experimental]

vis() is a lightweight, quick-look plotting helper. It's designed to help you visualise results fast with sensible defaults. It automatically detects the input type and chooses an appropriate visualisation (e.g., output from airr_stats_genes() is recognised as gene usage values and plotted without extra arguments).

vis() is not intended for publication-quality figures. For serious, highly customised, or publication-ready plots, I recommend building your graphics directly with ggplot2.

Information on how visualise a specific result from a domain, e.g., clonality or diversity, is available at each domain's help page in the visualisation section. Take a look at the "See also" section down below to see links to the domains, which support visualisations.

Usage

vis(.data, ...)

Arguments

.data

The output from any immunarch analysis function. The function automatically resolves to a correct visualisation.

...

Any other arguments, see the "Details" section for specific visualisation functions.

Details

vis() chooses a plot based on the analysis result. Start with vis(result), then consult the documentation for the analysis that created it to see its plotting defaults and supported arguments.

E.g., for clonality results, see airr_clonality by running ?airr_clonality. Or see repsim For repertoire similarity by running ?repsim.

Value

A ggplot2 object.

See Also

Examples

## Not run: 
immdata <- get_test_idata() |> agg_repertoires("Therapy")
airr_stats_genes(immdata, gene_col = "v_call") |> vis()
airr_public_jaccard(immdata) |> vis()
airr_diversity_pielou(immdata) |> vis()
airr_diversity_chao1(immdata) |> vis()
# Tracking summaries include explicit zeros for unobserved combinations.
vdj_track(immdata, n = 5, output = "df") |> vis()
vdj_public(immdata, output = "df") |> vis(reference = immdata)
annotate_public(immdata) |> vis(plot = "incidence")

## End(Not run)

Visualise public receptor selection, incidence, or pairwise frequencies

Description

Visualise selected receptor coverage and abundance with plot = "public", or receptor frequencies shared between two repertoires with the default plot = "pairwise". For annotate_public() results, plot = "incidence" shows receptor counts by the number of repertoires in which they occur.

In pairwise plots, receptor proportions are shown on log-scaled axes. Point fill shows the log proportion ratio between the x and y repertoires.

Usage

## S3 method for class 'ImmunData'
vis(
  .data,
  x = 1,
  y = 2,
  density = TRUE,
  lm = TRUE,
  plot = c("pairwise", "public", "incidence"),
  reference = NULL,
  xval = "imd_repertoire_id",
  fill = NULL,
  title = "Selected immune receptors across repertoires",
  ...
)

Arguments

.data

An immundata::ImmunData object with aggregated repertoires.

x

Repertoire for the x-axis. Either a numeric repertoire index, repertoire ID, or a repertoire schema value.

y

Repertoire for the y-axis. Either a numeric repertoire index, repertoire ID, or a repertoire schema value.

density

Logical. If TRUE, show marginal distributions of unique and public receptor proportions.

lm

Logical. If TRUE, add a linear model fit and adjusted R-squared.

plot

One of "pairwise" (the default), "public", or "incidence".

reference

For plot = "public", the original ImmunData supplied to vdj_public(). It defines the complete repertoire axis, including repertoires without selected receptors. Required for this plot.

xval

For plot = "public", the repertoire ID or metadata column used for x-axis labels. Each value must identify one repertoire.

fill

For plot = "public", a repertoire metadata column used for colour. NULL uses strata_name when strata are defined; otherwise the plot uses a single colour.

title

For plot = "public" or "incidence", the plot title, or NULL to omit it. Each view has its own default title.

...

Must be empty.

Details

The incidence view stacks within-stratum receptor counts when strata are defined. An identity observed in several strata contributes once to each stratum's distribution; stack totals are not globally distinct receptor counts. Without strata, one unstacked global distribution is shown and every identity contributes once. This view uses statistics from the last annotate_public() call; rerun annotation after changing the population. Both publicness views use vertical legends on the right and wrap long colour labels for display without changing the underlying names.

Value

A ggplot2 or patchwork object.

Examples

## Not run: 
idata |> vis()
idata |> vis(x = 1, y = 2)
idata |> vis(x = "Blood", y = "Tumor")
idata |> vis(x = 1, y = 2, density = FALSE)
selected <- vdj_public(idata)
vis(selected, plot = "public", reference = idata)
annotate_public(idata) |> vis(plot = "incidence")

## End(Not run)


Visualise clonal family tree: wrapper for calling on the entire repClonalFamily output

Description

[Deprecated]

Usage

## S3 method for class 'clonal_family'
vis(.data, ...)

Arguments

.data

Clonal families from 1 or multiple samples: repClonalFamily() output.

...

Not used here.

Value

A ggraph object.

Examples

## Not run: 
data(bcrdata)
bcr_data <- bcrdata$data

clonal_family <- bcr_data %>%
  seqCluster(seqDist(bcr_data), .fixed_threshold = 3) %>%
  repGermline(.threads = 1) %>%
  repAlignLineage(.min_lineage_sequences = 2, .align_threads = 2, .nofail = TRUE) %>%
  repClonalFamily(.threads = 1, .nofail = TRUE) %>%
  vis()

## End(Not run)

Visualise clonal family tree

Description

[Deprecated]

Usage

## S3 method for class 'clonal_family_tree'
vis(.data, ...)

Arguments

.data

Single clonal family tree data from 1 cluster: 1 element from TreeStats column from repClonalFamily() output.

...

Not used here.

Value

A ggraph object.

Examples

## Not run: 
data(bcrdata)
bcr_data <- bcrdata$data

clonal_family <- bcr_data %>%
  seqCluster(seqDist(bcr_data), .fixed_threshold = 3) %>%
  repGermline(.threads = 1) %>%
  repAlignLineage(.min_lineage_sequences = 2, .align_threads = 2, .nofail = TRUE) %>%
  repClonalFamily(.threads = 1, .nofail = TRUE)

# This condition can be omitted; it prevents the example from crashing
# when ClustalW or PHYLIP are not installed
if (!("step_failure_ignored" %in% class(clonal_family))) {
  vis(clonal_family[["full_clones"]][["TreeStats"]][[2]])
}

## End(Not run)

Visualise diversity.

Description

[Deprecated]

An utility function to visualise the output from repDiversity().

Usage

## S3 method for class 'immunr_chao1'
vis(
  .data,
  .by = NA,
  .meta = NA,
  .errorbars = c(0.025, 0.975),
  .errorbars.off = FALSE,
  .points = TRUE,
  .test = TRUE,
  .signif.label.size = 3.5,
  ...
)

Arguments

.data

Output from repDiversity().

.by

Pass NA if you want to plot samples without grouping.

You can pass a character vector with one or several column names from ".meta" to group your data before plotting. In this case you should provide ".meta".

You can pass a character vector that exactly matches the number of samples in your data, each value should correspond to a sample's property. It will be used to group data based on the values provided. Note that in this case you should pass NA to ".meta".

.meta

A metadata object. An R dataframe with sample names and their properties, such as age, serostatus or hla.

.errorbars

A numeric vector of length two with quantiles for error bars on sectors. Disabled if ".errorbars.off" is TRUE.

.errorbars.off

If TRUE then plot CI bars for distances between each group. Disabled if no group passed to the ".by" argument.

.points

A logical value defining whether points will be visualised or not.

.test

A logical vector whether statistical tests should be applied. See "Details" for more information.

.signif.label.size

An integer value defining the size of text for p-value.

...

Not used here.

Details

If data is grouped, then statistical tests for comparing means of groups will be performed, unless .test = FALSE is supplied. In case there are only two groups, the Wilcoxon rank sum test (https://en.wikipedia.org/wiki/Wilcoxon_signed-rank_test) is performed (R function wilcox.test() with an argument exact = FALSE) for testing if there is a difference in mean rank values between two groups. In case there more than two groups, the Kruskal-Wallis test (https://en.wikipedia.org/wiki/Kruskal%E2%80%93Wallis_one-way_analysis_of_variance) is performed (R function kruskal.test()), that is equivalent to ANOVA for ranks and it tests whether samples from different groups originated from the same distribution. A significant Kruskal-Wallis test indicates that at least one sample stochastically dominates one other sample. Adjusted for multiple comparisons P-values are plotted on the top of groups. P-value adjusting is done using the Holm method (https://en.wikipedia.org/wiki/Holm%E2%80%93Bonferroni_method) (also known as Holm-Bonferroni correction). You can execute the command ?p.adjust in the R console to see more.

Value

A ggplot2 object.

See Also

repDiversity vis

Examples

## Not run: 
data(immdata)
dv <- repDiversity(immdata$data, "chao1")
vis(dv)

## End(Not run)

Visualise results of the clonality analysis

Description

[Deprecated]

An utility function to visualise the output from repClonality().

Usage

## S3 method for class 'immunr_clonal_prop'
vis(
  .data,
  .by = NA,
  .meta = NA,
  .errorbars = c(0.025, 0.975),
  .errorbars.off = FALSE,
  .points = TRUE,
  .test = TRUE,
  .signif.label.size = 3.5,
  ...
)

Arguments

.data

Output from repClonality().

.by

Pass NA if you want to plot samples without grouping.

You can pass a character vector with one or several column names from ".meta" to group your data before plotting. In this case you should provide ".meta".

You can pass a character vector that exactly matches the number of samples in your data, each value should correspond to a sample's property. It will be used to group data based on the values provided. Note that in this case you should pass NA to ".meta".

.meta

A metadata object. An R dataframe with sample names and their properties, such as age, serostatus or hla.

.errorbars

A numeric vector of length two with quantiles for error bars on sectors. Disabled if ".errorbars.off" is TRUE.

.errorbars.off

If TRUE then plot CI bars for distances between each group. Disabled if no group passed to the ".by" argument.

.points

A logical value defining whether points will be visualised or not.

.test

A logical vector whether statistical tests should be applied. See "Details" for more information.

.signif.label.size

An integer value defining the size of text for p-value.

...

Not used here.

Details

If data is grouped, then statistical tests for comparing means of groups will be performed, unless .test = FALSE is supplied. In case there are only two groups, the Wilcoxon rank sum test (https://en.wikipedia.org/wiki/Wilcoxon_signed-rank_test) is performed (R function wilcox.test() with an argument exact = FALSE) for testing if there is a difference in mean rank values between two groups. In case there more than two groups, the Kruskal-Wallis test (https://en.wikipedia.org/wiki/Kruskal%E2%80%93Wallis_one-way_analysis_of_variance) is performed (R function kruskal.test()), that is equivalent to ANOVA for ranks and it tests whether samples from different groups originated from the same distribution. A significant Kruskal-Wallis test indicates that at least one sample stochastically dominates one other sample. Adjusted for multiple comparisons P-values are plotted on the top of groups. P-value adjusting is done using the Holm method (https://en.wikipedia.org/wiki/Holm%E2%80%93Bonferroni_method) (also known as Holm-Bonferroni correction). You can execute the command ?p.adjust in the R console to see more.

Value

A ggplot2 object.

See Also

repClonality vis

Examples

## Not run: 
data(immdata)
clp <- repClonality(immdata$data, "clonal.prop")
vis(clp)

hom <- repClonality(immdata$data, "homeo")
# Remove p values and points from the plot
vis(hom, .by = "Status", .meta = immdata$meta, .test = FALSE, .points = FALSE)

## End(Not run)

Visualise clonotype dynamics

Description

[Deprecated]

Usage

## S3 method for class 'immunr_dynamics'
vis(.data, .plot = c("smooth", "area", "line"), .order = NA, .log = FALSE, ...)

Arguments

.data

Output from the trackClonotypes function.

.plot

Character. Either "smooth", "area" or "line". Each specifies a type of plot for visualisation of clonotype dynamics.

.order

Numeric or character vector. Specifies the order to samples, e.g., it used for ordering samples by timepoints. Either See "Examples" below for more details.

.log

Logical. If TRUE then use log-scale for the frequency axis.

...

Not used here.

Value

A ggplot2 object.

Examples

## Not run: 
# Load an example data that comes with immunarch
data(immdata)

# Make the data smaller in order to speed up the examples
immdata$data <- immdata$data[c(1, 2, 3, 7, 8, 9)]
immdata$meta <- immdata$meta[c(1, 2, 3, 7, 8, 9), ]

# Option 1
# Choose the first 10 amino acid clonotype sequences
# from the first repertoire to track
tc <- trackClonotypes(immdata$data, list(1, 10), .col = "aa")
# Choose the first 20 nucleotide clonotype sequences
# and their V genes from the "MS1" repertoire to track
tc <- trackClonotypes(immdata$data, list("MS1", 20), .col = "nt+v")

# Option 2
# Choose clonotypes with amino acid sequences "CASRGLITDTQYF" or "CSASRGSPNEQYF"
tc <- trackClonotypes(immdata$data, c("CASRGLITDTQYF", "CSASRGSPNEQYF"), .col = "aa")

# Option 3
# Choose the first 10 clonotypes from the first repertoire
# with amino acid sequences and V segments
target <- immdata$data[[1]] %>%
  select(CDR3.aa, V.name) %>%
  head(10)
tc <- trackClonotypes(immdata$data, target)

# Visualise the output regardless of the chosen option
# Therea are three way to visualise it, regulated by the .plot argument
vis(tc, .plot = "smooth")
vis(tc, .plot = "area")
vis(tc, .plot = "line")

# Visualising timepoints
# First, we create an additional column in the metadata with randomly choosen timepoints:
immdata$meta$Timepoint <- sample(1:length(immdata$data))
immdata$meta
# Next, we create a vector with samples in the right order,
# according to the "Timepoint" column (from smallest to greatest):
sample_order <- order(immdata$meta$Timepoint)
# Sanity check: timepoints are following the right order:
immdata$meta$Timepoint[sample_order]
# Samples, sorted by the timepoints:
immdata$meta$Sample[sample_order]
# And finally, we visualise the data:
vis(tc, .order = sample_order)

## End(Not run)

Visualise results of the exploratory analysis

Description

[Deprecated]

An utility function to visualise the output from repExplore().

Usage

## S3 method for class 'immunr_exp_vol'
vis(
  .data,
  .by = NA,
  .meta = NA,
  .errorbars = c(0.025, 0.975),
  .errorbars.off = FALSE,
  .points = TRUE,
  .test = TRUE,
  .signif.label.size = 3.5,
  ...
)

Arguments

.data

Output from repExplore().

.by

Pass NA if you want to plot samples without grouping.

You can pass a character vector with one or several column names from ".meta" to group your data before plotting. In this case you should provide ".meta".

You can pass a character vector that exactly matches the number of samples in your data, each value should correspond to a sample's property. It will be used to group data based on the values provided. Note that in this case you should pass NA to ".meta".

.meta

A metadata object. An R dataframe with sample names and their properties, such as age, serostatus or hla.

.errorbars

A numeric vector of length two with quantiles for error bars on sectors. Disabled if ".errorbars.off" is TRUE.

.errorbars.off

If TRUE then plot CI bars for distances between each group. Disabled if no group passed to the ".by" argument.

.points

A logical value defining whether points will be visualised or not.

.test

A logical vector whether statistical tests should be applied. See "Details" for more information.

.signif.label.size

An integer value defining the size of text for p-value.

...

Not used here.

Details

If data is grouped, then statistical tests for comparing means of groups will be performed, unless .test = FALSE is supplied. In case there are only two groups, the Wilcoxon rank sum test (https://en.wikipedia.org/wiki/Wilcoxon_signed-rank_test) is performed (R function wilcox.test() with an argument exact = FALSE) for testing if there is a difference in mean rank values between two groups. In case there more than two groups, the Kruskal-Wallis test (https://en.wikipedia.org/wiki/Kruskal%E2%80%93Wallis_one-way_analysis_of_variance) is performed (R function kruskal.test()), that is equivalent to ANOVA for ranks and it tests whether samples from different groups originated from the same distribution. A significant Kruskal-Wallis test indicates that at least one sample stochastically dominates one other sample. Adjusted for multiple comparisons P-values are plotted on the top of groups. P-value adjusting is done using the Holm method (https://en.wikipedia.org/wiki/Holm%E2%80%93Bonferroni_method) (also known as Holm-Bonferroni correction). You can execute the command ?p.adjust in the R console to see more.

Value

A ggplot2 object.

See Also

repExplore vis

Examples

## Not run: 
data(immdata)
repExplore(immdata$data, "volume") %>% vis()
repExplore(immdata$data, "count") %>% vis()
repExplore(immdata$data, "len") %>% vis()
repExplore(immdata$data, "clones") %>% vis()

## End(Not run)

Histograms and boxplots (general case / gene usage)

Description

[Deprecated]

Visualise distributions of genes using heatmaps or other plots.

Usage

## S3 method for class 'immunr_gene_usage'
vis(.data, .plot = c("hist", "box", "heatmap", "heatmap2", "circos"), ...)

Arguments

.data

Output from the geneUsage function.

.plot

String specifying the plot type:

...

Other arguments passed to corresponding functions depending on the plot type:

Value

A ggplot2 object, pheatmap or circlize object.

See Also

geneUsage

Examples

## Not run: 
data(immdata)

gu <- geneUsage(immdata$data[[1]])
vis(gu)

gu <- geneUsage(immdata$data)
vis(gu, .by = "Status", .meta = immdata$meta)
vis(gu, "box", .by = "Status", .meta = immdata$meta)

## End(Not run)

Visualisation of hierarchical clustering

Description

[Deprecated]

Visualisation of the results of hierarchical clustering. For other clustering visualisations see vis.immunr_kmeans.

Usage

## S3 method for class 'immunr_hclust'
vis(.data, .rect = FALSE, .plot = c("clust", "best"), ...)

Arguments

.data

Clustering results from repOverlapAnalysis or geneUsageAnalysis.

.rect

Passed to factoextra::fviz_dend - whether to add a rectangle around groups.

.plot

A character vector of length one or two specifying which plots to visualise. If "clust" then plot only the clustering. If "best" then plot the number of optimal clusters. If both then plot both.

...

Not used here.

Value

Ggplot2 objects inside the patchwork container.

See Also

vis, repOverlapAnalysis, geneUsageAnalysis

Examples

## Not run: 
data(immdata)
ov <- repOverlap(immdata$data)
repOverlapAnalysis(ov, "mds+hclust") %>% vis()

## End(Not run)

Visualise incremental overlaps

Description

[Deprecated]

Usage

## S3 method for class 'immunr_inc_overlap'
vis(.data, .target = 1, .grid = FALSE, .ncol = 2, ...)

Arguments

.data

Output from the repOverlap function that uses "top" methods.

.target

Index of a repertoire to plot. Omitted if .grid is TRUE.

.grid

Logical. If TRUE then plot all similarities in a grid.

.ncol

Numeric. Number of columns in the resulting grid.

...

Not used here.

Value

A ggplot2 object.

See Also

repOverlap

Examples

## Not run: 
data(immdata)
tmp <- repOverlap(immdata$data[1:4], "inc+overlap", .verbose.inc = FALSE, .verbose = FALSE)
vis(tmp, .target = 1)
vis(tmp, .grid = TRUE)

## End(Not run)

Visualisation of K-means and DBSCAN clustering

Description

[Deprecated]

Visualisation of the results of K-means and DBSCAN clustering. For hierarhical clustering visualisations see vis.immunr_hclust.

Usage

## S3 method for class 'immunr_kmeans'
vis(
  .data,
  .point = TRUE,
  .text = TRUE,
  .ellipse = TRUE,
  .point.size = 2,
  .text.size = 10,
  .plot = c("clust", "best"),
  ...
)

Arguments

.data

Clustering results from repOverlapAnalysis or geneUsageAnalysis.

.point

If TRUE then plot sample points. Passed to factoextra::fviz_cluster.

.text

If TRUE then plot text labels. Passed to factoextra::fviz_cluster.

.ellipse

If TRUE then plot ellipses around all samples. Passed to "ellipse" from factoextra::fviz_cluster.

.point.size

Size of points, passed to "pointsize" from factoextra::fviz_cluster.

.text.size

Size of text labels, passed to labelsize from factoextra::fviz_cluster.

.plot

A character vector of length one or two specifying which plots to visualise. If "clust" then plot only the clustering. If "best" then plot the number of optimal clusters. If both then plot both.

...

Not used here.

Value

Ggplot2 objects inside the pathwork container.

See Also

vis, repOverlapAnalysis, geneUsageAnalysis

Examples

## Not run: 
data(immdata)
ov <- repOverlap(immdata$data)
repOverlapAnalysis(ov, "mds+kmeans") %>% vis()

## End(Not run)

Most frequent kmers visualisation.

Description

[Deprecated]

Plot a distribution (bar plot) of the most frequent kmers in a data.

Usage

## S3 method for class 'immunr_kmer_table'
vis(
  .data,
  .head = 100,
  .position = c("stack", "dodge", "fill"),
  .log = FALSE,
  ...
)

Arguments

.data

Data frame with two columns "Kmers" and "Count" or a list with such data frames. See Examples.

.head

Number of the most frequent kmers to choose for plotting from each data frame.

.position

Character vector of length 1. Position of bars for each kmers. Value for the ggplot2 argument position.

.log

Logical. If TRUE then plot log-scaled plots.

...

Not used here.

Value

A ggplot2 object.

See Also

get.kmers

Examples

## Not run: 
# Load necessary data and package.
data(immdata)
# Get 5-mers.
imm.km <- getKmers(immdata$data[[1]], 5)
# Plots for kmer proportions in each data frame in immdata.
p1 <- vis(imm.km, .position = "stack")
p2 <- vis(imm.km, .position = "fill")
p1 + p2

## End(Not run)

PCA / MDS / tSNE visualisation (mainly overlap / gene usage)

Description

[Deprecated]

Usage

## S3 method for class 'immunr_mds'
vis(
  .data,
  .by = NA,
  .meta = NA,
  .point = TRUE,
  .text = TRUE,
  .ellipse = TRUE,
  .point.size = 2,
  .text.size = 4,
  ...
)

Arguments

.data

Output from analysis functions such as geneUsageAnalysis or immunr_pca, immunr_mds or immunr_tsne.

.by

Pass NA if you want to plot samples without grouping.

You can pass a character vector with one or several column names from ".meta" to group your data before plotting. In this case you should provide ".meta".

You can pass a character vector that exactly matches the number of samples in your data, each value should correspond to a sample's property. It will be used to group data based on the values provided. Note that in this case you should pass NA to ".meta".

.meta

A metadata object. An R dataframe with sample names and their properties, such as age, serostatus or hla.

.point

Logical. If TRUE then plot points corresponding to objects.

.text

Logical. If TRUE then plot sample names.

.ellipse

Logical. If TRUE then plot ellipses around clusters of grouped samples.

.point.size

Numeric. A size of points to plot.

.text.size

Numeric. A size of sample names' labels.

...

Not used here.

Details

Other visualisation methods:

Value

A ggplot2 object.

Examples

## Not run: 
data(immdata)
ov <- repOverlap(immdata$data)
repOverlapAnalysis(ov, "mds") %>% vis()

## End(Not run)

Repertoire overlap and gene usage visualisations

Description

[Deprecated]

Visualises matrices with overlap values or gene usage distances among samples. For details see the links below.

Usage

## S3 method for class 'immunr_ov_matrix'
vis(.data, .plot = c("heatmap", "heatmap2", "circos"), ...)

Arguments

.data

Output from repOverlap or geneUsageAnalysis.

.plot

A string specifying the plot type:

...

Other arguments are passed through to the underlying plotting function:

Value

A ggplot2, pheatmap or circlize object.

Examples

## Not run: 
data(immdata)
ov <- repOverlap(immdata$data)
vis(ov)
vis(ov, "heatmap")
vis(ov, "heatmap2")
vis(ov, "circos")

## End(Not run)

Public repertoire visualisation

Description

[Deprecated]

Usage

## S3 method for class 'immunr_public_repertoire'
vis(.data, .plot = c("freq", "clonotypes"), ...)

Arguments

.data

Public repertoire, an output from pubRep.

.plot

A string specifying the plot type:

  • "freq" for visualisation of the distribution of occurrences of clonotypes and their frequencies using vis_public_frequencies.

  • "clonotypes" for visualisation of public clonotype frequenciy correlations between pairs of samples using vis_public_clonotypes

...

Further arguments passed vis_public_frequencies or vis_public_clonotypes, depending on the ".plot" argument.

Value

A ggplot2 object.

Examples

## Not run: 
data(immdata)
immdata$data <- lapply(immdata$data, head, 300)
pr <- pubRep(immdata$data, .verbose = FALSE)
vis(pr, "freq")
vis(pr, "freq", .type = "none")

vis(pr, "clonotypes", 1, 2)

## End(Not run)

Visualise sharing of clonotypes among samples

Description

[Deprecated]

Visualise public clonotype frequencies.

Usage

## S3 method for class 'immunr_public_statistics'
vis(.data, ...)

Arguments

.data

Public repertoire - an output from the pubRep function.

...

Other arguments passsed directly to UpSetR::upset.

Value

A ggplot2 object.

Examples

## Not run: 
data(immdata)
immdata$data <- lapply(immdata$data, head, 2000)
pr <- pubRep(immdata$data, .verbose = FALSE)
pubRepStatistics(pr) %>% vis()

## End(Not run)

Handler for .nofail argument of pipeline steps that prevents examples from crashing on computers where certain dependencies are not installed

Description

[Deprecated]

Usage

## S3 method for class 'step_failure_ignored'
vis(.data, ...)

Arguments

.data

Not used here.

...

Not used here.

Value

An empty object with "step_failure_ignored" class.


Bar plots

Description

[Deprecated]

Usage

vis_bar(
  .data,
  .by = NA,
  .meta = NA,
  .errorbars = c(0.025, 0.975),
  .errorbars.off = FALSE,
  .stack = FALSE,
  .points = TRUE,
  .test = TRUE,
  .signif.label.size = 3.5,
  .errorbar.width = 0.2,
  .defgroupby = "Sample",
  .grouping.var = "Group",
  .labs = c("X", "Y"),
  .title = "Barplot (.title argument)",
  .subtitle = "Subtitle (.subtitle argument)",
  .legend = NA,
  .leg.title = "Legend (.leg.title argument)",
  .legend.pos = "right",
  .rotate_x = 90
)

Arguments

.data

Data to visualise.

.by

Pass NA if you want to plot samples without grouping.

You can pass a character vector with one or several column names from ".meta" to group your data before plotting. In this case you should provide ".meta".

You can pass a character vector that exactly matches the number of samples in your data, each value should correspond to a sample's property. It will be used to group data based on the values provided. Note that in this case you should pass NA to ".meta".

.meta

A metadata object. An R dataframe with sample names and their properties, such as age, serostatus or hla.

.errorbars

A numeric vector of length two with quantiles for error bars on sectors. Disabled if ".errorbars.off" is TRUE.

.errorbars.off

If TRUE then plot CI bars for distances between each group. Disabled if no group passed to the ".by" argument.

.stack

If TRUE and .errorbars.off is TRUE then plot stacked bar plots for each Group or Sample

.points

A logical value defining whether points will be visualised or not.

.test

A logical vector whether statistical tests should be applied. See "Details" for more information.

.signif.label.size

An integer value defining the size of text for p-value.

.errorbar.width

Numeric. Width for error bars.

.defgroupby

A name for the column with sample names.

.grouping.var

A name for the column to group by.

.labs

A character vector of length two specifying names for x-axis and y-axis.

.title

The text for the plot's title.

.subtitle

The text for the plot's subtitle.

.legend

If TRUE then displays a legend, otherwise removes legend from the plot.

.leg.title

The text for the plots's legend. Provide NULL to remove the legend's title completely.

.legend.pos

Positions of the legend: either "top", "bottom", "left" or "right".

.rotate_x

How much the x tick text should be rotated? In angles.

Value

A ggplot2 object.

Examples

## Not run: 
vis_bar(data.frame(Sample = c("A", "B", "C"), Value = c(1, 2, 3)))

## End(Not run)

Flexible box-plots for visualisation of distributions

Description

[Deprecated]

Visualisation of distributions using ggplot2-based boxplots.

Usage

vis_box(
  .data,
  .by = NA,
  .meta = NA,
  .melt = TRUE,
  .points = TRUE,
  .test = TRUE,
  .signif.label.size = 3.5,
  .defgroupby = "Sample",
  .grouping.var = "Group",
  .labs = c("X", "Y"),
  .title = "Boxplot (.title argument)",
  .subtitle = "Subtitle (.subtitle argument)",
  .legend = NA,
  .leg.title = "Legend (.leg.title argument)",
  .legend.pos = "right"
)

Arguments

.data

Input matrix or data frame.

.by

Pass NA if you want to plot samples without grouping.

You can pass a character vector with one or several column names from ".meta" to group your data before plotting. In this case you should provide ".meta".

You can pass a character vector that exactly matches the number of samples in your data, each value should correspond to a sample's property. It will be used to group data based on the values provided. Note that in this case you should pass NA to ".meta".

.meta

A metadata object. An R dataframe with sample names and their properties, such as age, serostatus or hla.

.melt

If TRUE then apply tidyr::pivot_longer() to the ".data" before plotting. In this case ".data" is supposed to be a data frame with the first character column reserved for names of genes and other numeric columns reserved to counts or frequencies of genes. Each numeric column should be associated with a specific repertoire sample.

.points

A logical value defining whether points will be visualised or not.

.test

A logical vector whether statistical tests should be applied. See "Details" for more information.

.signif.label.size

An integer value defining the size of text for p-value.

.defgroupby

A name for the column with sample names.

.grouping.var

A name for the column to group by.

.labs

Character vector of length two with names for x-axis and y-axis, respectively.

.title

The text for the title of the plot.

.subtitle

The The text for the plot's subtitle.

.legend

If TRUE then displays a legend, otherwise removes legend from the plot.

.leg.title

The The text for the plots's legend. Provide NULL to remove the legend's title completely.

.legend.pos

Positions of the legend: either "top", "bottom", "left" or "right".

Value

A ggplot2 object.

See Also

vis.immunr_gene_usage, geneUsage

Examples

## Not run: 
vis_box(data.frame(Sample = sample(c("A", "B", "C"), 100, TRUE), Value = rnorm(100)), .melt = FALSE)

## End(Not run)

Visualisation of matrices using circos plots

Description

[Deprecated]

Visualise matrices with the circlize::chordDiagram function from the circlize package.

Usage

vis_circos(.data, .title = NULL, ...)

Arguments

.data

Input matrix.

.title

The The text for the title of the plot.

...

Other arguments passed to circlize::chordDiagram from the 'circlize' package.

Value

A circlize object.

See Also

vis, repOverlap.

Examples

## Not run: 
data(immdata)
ov <- repOverlap(immdata$data)
vis(ov, .plot = "circos")

## End(Not run)

Visualisation of matrices and data frames using ggplo2-based heatmaps

Description

[Deprecated]

Fast and easy visualisations of matrices or data frames with functions based on the ggplot2 package.

Usage

vis_heatmap(
  .data,
  .text = TRUE,
  .scientific = FALSE,
  .signif.digits = 2,
  .text.size = 4,
  .axis.text.size = NULL,
  .labs = c("Sample", "Sample"),
  .title = "Overlap",
  .leg.title = "Overlap values",
  .legend = TRUE,
  .na.value = NA,
  .transpose = FALSE,
  ...
)

Arguments

.data

Input object: a matrix or a data frame.

If matrix: column names and row names (if presented) will be used as names for labs.

If data frame: the first column will be used for row names and removed from the data. Other columns will be used for values in the heatmap.

.text

If TRUE then plots values in the heatmap cells. If FALSE does not plot values, just plot coloured cells instead.

.scientific

If TRUE then uses the scientific notation for numbers (e.g., "2.0e+2").

.signif.digits

Number of significant digits to display on plot.

.text.size

Size of text in the cells of heatmap.

.axis.text.size

Size of text on the axis labels.

.labs

A character vector of length two with names for x-axis and y-axis, respectively.

.title

The The text for the plot's title.

.leg.title

The The text for the plots's legend. Provide NULL to remove the legend's title completely.

.legend

If TRUE then displays a legend, otherwise removes the legend from the plot.

.na.value

Replace NA values with this value. By default they remain NA.

.transpose

Logical. If TRUE then switch rows and columns.

...

Other passed arguments.

Value

A ggplot2 object.

See Also

vis, repOverlap.

Examples

## Not run: 
data(immdata)
ov <- repOverlap(immdata$data)
vis_heatmap(ov)
gu <- geneUsage(immdata$data, "hs.trbj")
vis_heatmap(gu)

## End(Not run)

Visualisation of matrices using pheatmap-based heatmaps

Description

[Deprecated]

Visualise matrices with the functions based on the pheatmap package with minimum amount of arguments.

Usage

vis_heatmap2(
  .data,
  .meta = NA,
  .by = NA,
  .title = NA,
  .color = colorRampPalette(c("#67001f", "#d6604d", "#f7f7f7", "#4393c3",
    "#053061"))(1024),
  ...
)

Arguments

.data

Input matrix. Column names and row names (if presented) will be used as names for labs.

.meta

A metadata object. An R dataframe with sample names and their properties, such as age, serostatus or hla.

.by

Set NA if you want to plot samples without grouping.

.title

The text for the plot's title (same as the "main" argument in pheatmap).

.color

A vector specifying the colors (same as the "color" argument in pheatmap). Pass NA to use the default pheatmap colors.

...

Other arguments for the pheatmap function.

Value

A pheatmap object.

See Also

vis, repOverlap

Examples

## Not run: 
data(immdata)
ov <- repOverlap(immdata$data)
vis_heatmap2(ov)

## End(Not run)

Visualisation of distributions using histograms

Description

[Deprecated]

Visualisation of distributions using ggplot2-based histograms.

Usage

vis_hist(
  .data,
  .by = NA,
  .meta = NA,
  .title = "Gene usage",
  .ncol = NA,
  .points = TRUE,
  .test = TRUE,
  .coord.flip = FALSE,
  .grid = FALSE,
  .labs = c("Gene", NA),
  .melt = TRUE,
  .legend = NA,
  .add.layer = NULL,
  ...
)

Arguments

.data

Input matrix or data frame.

.by

Pass NA if you want to plot samples without grouping.

You can pass a character vector with one or several column names from ".meta" to group your data before plotting. In this case you should provide ".meta".

You can pass a character vector that exactly matches the number of samples in your data, each value should correspond to a sample's property. It will be used to group data based on the values provided. Note that in this case you should pass NA to ".meta".

.meta

A metadata object. An R dataframe with sample names and their properties, such as age, serostatus or hla.

.title

The text for the title of the plot.

.ncol

A number of columns to display. Provide NA (by default) if you want the function to automatically detect the optimal number of columns.

.points

A logical value defining whether points will be visualised or not.

.test

A logical vector whether statistical tests should be applied. See "Details" for more information.

.coord.flip

If TRUE then swap x- and y-axes.

.grid

If TRUE then plot separate visualisations for each sample.

.labs

A character vector of length two with names for x-axis and y-axis, respectively.

.melt

If TRUE then apply tidyr::pivot_longer() to the ".data" before plotting. In this case ".data" is supposed to be a data frame with the first character column reserved for names of genes and other numeric columns reserved to counts or frequencies of genes. Each numeric column should be associated with a specific repertoire sample.

.legend

If TRUE then plots the legend. If FALSE removes the legend from the plot. If NA automatically detects the best way to display legend.

.add.layer

Addditional ggplot2 layers, that added to each plot in the output plot or grid of plots.

...

Is not used here.

Details

If data is grouped, then statistical tests for comparing means of groups will be performed, unless .test = FALSE is supplied. In case there are only two groups, the Wilcoxon rank sum test (https://en.wikipedia.org/wiki/Wilcoxon_signed-rank_test) is performed (R function wilcox.test() with an argument exact = FALSE) for testing if there is a difference in mean rank values between two groups. In case there more than two groups, the Kruskal-Wallis test (https://en.wikipedia.org/wiki/Kruskal%E2%80%93Wallis_one-way_analysis_of_variance) is performed (R function kruskal.test()), that is equivalent to ANOVA for ranks and it tests whether samples from different groups originated from the same distribution. A significant Kruskal-Wallis test indicates that at least one sample stochastically dominates one other sample. Adjusted for multiple comparisons P-values are plotted on the top of groups. P-value adjusting is done using the Holm method (https://en.wikipedia.org/wiki/Holm%E2%80%93Bonferroni_method) (also known as Holm-Bonferroni correction). You can execute the command ?p.adjust in the R console to see more.

Value

A ggplot2 object.

See Also

vis.immunr_gene_usage, geneUsage

Examples

## Not run: 
data(immdata)
imm_gu <- geneUsage(immdata$data[[1]])
vis(imm_gu,
  .plot = "hist", .add.layer =
    theme(axis.text.x = element_text(angle = 75, vjust = 1))
)
imm_gu <- geneUsage(immdata$data[1:4])
vis(imm_gu,
  .plot = "hist", .grid = TRUE, .add.layer =
    theme(axis.text.x = element_text(angle = 75, vjust = 1))
)

## End(Not run)

Visualise kmer profiles

Description

#' [Deprecated]

Usage

vis_immunr_kmer_profile_main(.data, .plot, ...)

Arguments

.data

Kmer data, an output from kmer_profile.

.plot

String specifying the plot type:

  • "seqlogo" for traditional sequence logo plots using vis_seqlogo;

  • "textlogo" for modified approach to sequence logo plots via text labels using vis_textlogo;

...

Other arguments passed to vis_textlogo or vis_seqlogo, depending on the ".plot" argument.

Value

A ggplot2 object.

Examples

## Not run: 
data(immdata)
getKmers(immdata$data[[1]], 5) %>%
  kmer_profile() %>%
  vis("seqlogo")

## End(Not run)

Visualisation of public clonotypes

Description

[Deprecated]

Visualise correlation of public clonotype frequencies in pairs of repertoires.

Usage

vis_public_clonotypes(
  .data,
  .x.rep = NA,
  .y.rep = NA,
  .title = NA,
  .ncol = 3,
  .point.size.modif = 1,
  .cut.axes = TRUE,
  .density = TRUE,
  .lm = TRUE,
  .radj.size = 3.5
)

Arguments

.data

Public repertoire data - an output from the pubRep function.

.x.rep

Either indices of samples or character vector of sample names for the x-axis. Must be of the same length as ".y.rep".

.y.rep

Either indices of samples or character vector of sample names for the y-axis. Must be of the same length as ".x.rep".

.title

The text for the title of the plot.

.ncol

An integer number of columns to print in the grid of pairs of repertoires.

.point.size.modif

An integer value that is a modifier of the point size. The larger the number, the larger the points.

.cut.axes

If TRUE then axes limits become shorter.

.density

If TRUE then displays density plot for distributions of clonotypes for each sample. If FALSE then removes density plot from the visualisation.

.lm

If TRUE then fit a linear model and displays an R adjusted coefficient that shows how similar samples are in terms of shared clonotypes.

.radj.size

An integer value, that defines the size of the The text for the R adjusted coefficient.

Value

A ggplot2 object.

See Also

pubRep, vis.immunr_public_repertoire

Examples

## Not run: 
data(immdata)
pr <- pubRep(immdata$data, .verbose = FALSE)
vis(pr, "clonotypes", 1, 2)

## End(Not run)

Public repertoire visualisation

Description

[Deprecated]

Visualise public clonotype frequencies.

Usage

vis_public_frequencies(
  .data,
  .by = NA,
  .meta = NA,
  .type = c("boxplot", "none", "mean")
)

Arguments

.data

Public repertoire - an output from the pubRep function.

.by

Pass NA if you want to plot samples without grouping.

You can pass a character vector with one or several column names from ".meta" to group your data before plotting. In this case you should provide ".meta".

You can pass a character vector that exactly matches the number of samples in your data, each value should correspond to a sample's property. It will be used to group data based on the values provided. Note that in this case you should pass NA to ".meta".

.meta

A metadata object. An R dataframe with sample names and their properties, such as age, serostatus or hla.

.type

Character. Either "boxplot" for plotting distributions of frequencies, "none" for plotting everything, or "mean" for plotting average values only.

Value

A ggplot2 object.

Examples

## Not run: 
data(immdata)
immdata$data <- lapply(immdata$data, head, 500)
pr <- pubRep(immdata$data, .verbose = FALSE)
vis(pr, "freq", .type = "boxplot")
vis(pr, "freq", .type = "none")
vis(pr, "freq", .type = "mean")
vis(pr, "freq", .by = "Status", .meta = immdata$meta)

## End(Not run)

Description

[Deprecated]

Plot sequence logo plots for visualising of amino acid motif sequences / profiles.

vis_textlogo plots sequences in a text format - each letter has the same height. Useful when there are no big differences between occurences of amino acids in the motif.

vis_seqlogo is a traditional sequence logo plots. Useful when there are one or two amino acids with clear differences in their occurrences.

Usage

vis_textlogo(.data, .replace.zero.with.na = TRUE, .width = 0.1, ...)

vis_seqlogo(.data, .scheme = "chemistry", ...)

Arguments

.data

Output from the kmer.profile function.

.replace.zero.with.na

if TRUE then replace all zeros with NAs, therefore letters with zero frequency wont appear at the plot.

.width

Width for jitter, i.e., how much points will scatter around the verical line. Pass 0 (zero) to plot points on the straight vertical line for each position.

...

Not used here.

.scheme

Character. An argument passed to geom_logo from ggseqlogo package specifying how to colour symbols.

Value

A ggplot2 object.

See Also

getKmers, kmer_profile

Examples

## Not run: 
data(immdata)
kmers <- getKmers(immdata$data[[1]], 5)
ppm <- kmer_profile(kmers, "prob")
vis(ppm, .plot = "text")
vis(ppm, .plot = "seq")

d <- kmer_profile(c("CASLL", "CASSQ", "CASGL"))
vis_textlogo(d)
vis_seqlogo(d)

## End(Not run)