Package 'rbiom'

Title: Integrated Analysis and Visualization of Microbiome Data
Description: A toolkit for working with Biological Observation Matrix ('BIOM') files. Read/write all 'BIOM' formats. Compute rarefaction, alpha diversity, and beta diversity (including 'UniFrac'). Summarize counts by taxonomic level. Subset based on metadata. Generate visualizations and statistical analyses. Every result records the R code needed to reproduce it.
Authors: Daniel P. Smith [aut, cre] (ORCID: <https://orcid.org/0000-0002-2479-2044>), Alkek Center for Metagenomics and Microbiome Research [cph, fnd]
Maintainer: Daniel P. Smith <[email protected]>
License: MIT + file LICENSE
Version: 4.0.0
Built: 2026-11-06 00:35:49 UTC
Source: https://github.com/cmmr/rbiom

Help Index


Visualize alpha diversity with boxplots.

Description

Visualize alpha diversity with boxplots.

Usage

adiv_boxplot(
  biom,
  x = NULL,
  adiv = "Shannon",
  layers = "x",
  stat.by = x,
  facet.by = NULL,
  colors = TRUE,
  shapes = TRUE,
  patterns = FALSE,
  test = "auto",
  flip = FALSE,
  stripe = NULL,
  ci = "ci",
  level = 0.95,
  p.adj = "fdr",
  outliers = NULL,
  xlab.angle = "auto",
  p.label = 0.05,
  transform = "none",
  strata = NULL,
  caption = TRUE,
  ...
)

Arguments

biom

An rbiom object, or any value accepted by as_rbiom().

x

A categorical metadata column name to use for the x-axis. Or NULL, which groups all samples into a single category.

adiv

Alpha diversity metric(s) to use. Options are: c("ace", "berger", "brillouin", "chao1", "faith", "fisher", "simpson", "inv_simpson", "margalef", "mcintosh", "menhinick", "observed", "shannon", "squares"). For "faith", a phylogenetic tree must be present in biom or explicitly provided via ⁠tree=⁠. Set adiv=".all" to use all metrics. Multiple/abbreviated values allowed. Default: "shannon"

layers

One or more of c("bar", "box" ("x"), "violin", "dot", "strip", "crossbar", "errorbar", "linerange", "pointrange"). Single letter abbreviations are also accepted. For instance, c("box", "dot") is equivalent to c("x", "d") and "xd". Default: "x"

stat.by

Dataset field with the statistical groups. Must be categorical. Default: NULL

facet.by

Dataset field(s) to use for faceting. Must be categorical. Default: NULL

colors

How to color the groups. Options are:

TRUE -

Automatically select colorblind-friendly colors.

FALSE or NULL -

Don't use colors.

a palette name -

Auto-select colors from this set. E.g. "okabe"

character vector -

Custom colors to use. E.g. c("red", "#00FF00")

named character vector -

Explicit mapping. E.g. c(Male = "blue", Female = "red")

See "Aesthetics" section below for additional information. Default: TRUE

shapes

Shapes for each group. Options are similar to colors's: TRUE, FALSE, NULL, shape names (typically integers 0 - 17), or a named vector mapping groups to specific shape names. See "Aesthetics" section below for additional information. Default: TRUE

patterns

Patterns for each group. Options are similar to colors's: TRUE, FALSE, NULL, pattern names ("brick", "chevron", "fish", "grid", etc), or a named vector mapping groups to specific pattern names. See "Aesthetics" section below for additional information. Default: FALSE

test

Method for computing p-values. 'auto' runs pairwise Mann-Whitney U tests ('wilcox') when x and stat.by are the same field (or 'emmeans' when strata is given), and Kruskal-Wallis tests ('kruskal') across the stat.by groups within each x category otherwise. Beta diversity boxplots use PERMANOVA ('adonis2'), 'mrpp', or 'betadisper' on the samples instead. 'none' skips the statistics. See stats_table() and bdiv_stats(). Default: 'auto'

flip

Transpose the axes, so that taxa are present as rows instead of columns. Default: FALSE

stripe

Shade every other x position. Default: same as flip

ci

How to calculate min/max of the crossbar, errorbar, linerange, and pointrange layers. Options are: "ci" (confidence interval), "range", "sd" (standard deviation), "se" (standard error), and "mad" (median absolute deviation). The center mark of crossbar and pointrange represents the mean, except for "mad" in which case it represents the median. Intervals are drawn as computed, including below zero, unless the y-axis is transformed: bounds below zero are drawn at zero on a "sqrt" or "log1p" axis, and bounds at or below zero are drawn at the smallest positive y value on a log axis. Default: "ci"

level

The confidence level for calculating a confidence interval. Default: 0.95

p.adj

Method to use for multiple comparisons adjustment of p-values. Run p.adjust.methods for a list of available options. The adjustment spans every p-value in the returned table (all metrics, strata, pairs, and positions). Default: "fdr"

outliers

Show boxplot outliers? TRUE to always show. FALSE to always hide. NULL to only hide them when overlaying a dot or strip chart. Default: NULL

xlab.angle

Angle of the labels at the bottom of the plot. Options are "auto", '0', '30', and '90'. Default: "auto".

p.label

Minimum adjusted p-value to display on the plot with a bracket.

p.label = 0.05 -

Show p-values that are <= 0.05.

p.label = 0 -

Don't show any p-values on the plot.

p.label = 1 -

Show all p-values on the plot.

If a numeric vector with more than one value is provided, they will be used as breaks for asterisk notation. Default: 0.05

transform

Transformation to apply to calculated values. Options are: c("none", "rank", "log", "log1p", "sqrt"). "rank" is useful for correcting for non-normal distributions before applying regression statistics. Default: "none"

strata

Dataset field with the blocking/subject variable. Permutation tests permute within strata; regression models include a random intercept per stratum. Default: NULL

caption

Add methodology caption beneath the plot. Default: TRUE

...

Additional parameters to pass along to ggplot2 functions. Prefix a parameter name with a layer name to pass it to only that layer. For instance, d.size = 2 ensures only the points on the dot layer have their size set to 2. Unprefixed parameters go to every layer whose function accepts them (e.g. scales = "free" for the facets). An argument that no layer accepts is an error.

Value

A ggplot2 plot. The computed data points, ggplot2 command, stats table, and stats table commands are available as ⁠$data⁠, ⁠$code⁠, ⁠$stats⁠, and ⁠$stats$code⁠, respectively.

Aesthetics

All built-in color palettes are colorblind-friendly. The available categorical palette names are: "okabe", "carto", "r4", "polychrome", "tol", "bright", "light", "muted", "vibrant", "tableau", "classic", "alphabet", "tableau20", "kelly", and "fishy".

Patterns are added using the fillpattern R package, which must be installed to use patterns. Options are "brick", "chevron", "fish", "grid", "herringbone", "hexagon", "octagon", "rain", "saw", "shingle", "rshingle", "stripe", and "wave", optionally abbreviated and/or suffixed with modifiers. For example, "hex10_sm" for the hexagon pattern rotated 10 degrees and shrunk by 2x. See fillpattern::fill_pattern() for complete documentation of options.

Shapes can be given as per base R - numbers 0 through 17 for various shapes, or the decimal value of an ascii character, e.g. a-z = 65:90; A-Z = 97:122 to use letters instead of shapes on the plot. Character strings may used as well.

The dot and strip layers use the ggbeeswarm package when it is installed, and jittered points otherwise.

See Also

Other alpha_diversity: adiv_corrplot(), adiv_stats(), adiv_table()

Other visualization: adiv_corrplot(), bdiv_boxplot(), bdiv_corrplot(), bdiv_heatmap(), bdiv_ord_plot(), plot_heatmap(), rare_corrplot(), rare_multiplot(), rare_stacked(), stats_boxplot(), stats_corrplot(), taxa_boxplot(), taxa_corrplot(), taxa_heatmap(), taxa_stacked()

Examples

library(rbiom)

    biom <- rarefy(hmp50)

    adiv_boxplot(biom, x="Body Site", stat.by="Body Site")

    adiv_boxplot(biom, x="Sex", stat.by="Body Site", adiv=c("otu", "shan"), layers = "bld")

    adiv_boxplot(biom, x="body", stat.by="sex", adiv=c('sha', 'sim'), flip=TRUE, layers="p")


    # Each plot object includes additional information.
    fig <- adiv_boxplot(biom, x="Body Site")

    ## Computed Data Points -------------------
    fig$data

    ## Statistics Table -----------------------
    fig$stats

    ## ggplot2 Command ------------------------
    fig$code

Visualize alpha diversity with scatterplots and trendlines.

Description

Visualize alpha diversity with scatterplots and trendlines.

Usage

adiv_corrplot(
  biom,
  x,
  adiv = "Shannon",
  layers = "tc",
  stat.by = NULL,
  facet.by = NULL,
  colors = TRUE,
  shapes = TRUE,
  test = "emmeans",
  fit = "gam",
  at = NULL,
  level = 0.95,
  p.adj = "fdr",
  transform = "none",
  alt = "!=",
  mu = 0,
  strata = NULL,
  caption = TRUE,
  check = FALSE,
  ...
)

Arguments

biom

An rbiom object, or any value accepted by as_rbiom().

x

Dataset field with the x-axis values. Equivalent to the regr argument in stats_table(). Required.

adiv

Alpha diversity metric(s) to use. Options are: c("ace", "berger", "brillouin", "chao1", "faith", "fisher", "simpson", "inv_simpson", "margalef", "mcintosh", "menhinick", "observed", "shannon", "squares"). For "faith", a phylogenetic tree must be present in biom or explicitly provided via ⁠tree=⁠. Set adiv=".all" to use all metrics. Multiple/abbreviated values allowed. Default: "shannon"

layers

One or more of c("trend", "confidence", "point", "name", "residual"). Single letter abbreviations are also accepted. For instance, c("trend", "point") is equivalent to c("t", "p") and "tp". Default: "tc"

stat.by

Dataset field with the statistical groups. Must be categorical. Default: NULL

facet.by

Dataset field(s) to use for faceting. Must be categorical. Default: NULL

colors

How to color the groups. Options are:

TRUE -

Automatically select colorblind-friendly colors.

FALSE or NULL -

Don't use colors.

a palette name -

Auto-select colors from this set. E.g. "okabe"

character vector -

Custom colors to use. E.g. c("red", "#00FF00")

named character vector -

Explicit mapping. E.g. c(Male = "blue", Female = "red")

See "Aesthetics" section below for additional information. Default: TRUE

shapes

Shapes for each group. Options are similar to colors's: TRUE, FALSE, NULL, shape names (typically integers 0 - 17), or a named vector mapping groups to specific shape names. See "Aesthetics" section below for additional information. Default: TRUE

test

Method for computing p-values: 'none', 'emmeans', or 'emtrends'. See stats_table(). Default: 'emmeans'

fit

How to fit the trendline. 'lm', 'log', or 'gam'. Default: 'gam'

at

Position(s) along regr where group means or local slopes are evaluated. Default: NULL, which uses the median of regr within each split.by stratum. A vector gives one row per position, and p-values are adjusted across all of them. Ignored by tests that do not depend on a position (e.g. a global slope with fit = "lm").

level

The confidence level for calculating a confidence interval. Default: 0.95

p.adj

Method to use for multiple comparisons adjustment of p-values. Run p.adjust.methods for a list of available options. The adjustment spans every p-value in the returned table (all metrics, strata, pairs, and positions). Default: "fdr"

transform

Transformation to apply to calculated values. Options are: c("none", "rank", "log", "log1p", "sqrt"). "rank" is useful for correcting for non-normal distributions before applying regression statistics. Default: "none"

alt

Alternative hypothesis direction. Options are '!=' (two-sided; not equal to mu), '<' (less than mu), or '>' (greater than mu). Default: '!='

mu

Reference value to test against. Default: 0

strata

Dataset field with the blocking/subject variable. Permutation tests permute within strata; regression models include a random intercept per stratum. The plotted trendlines are descriptive fits without the strata term. Default: NULL

caption

Add methodology caption beneath the plot. Default: TRUE

check

Generate additional plots to aid in assessing data normality. Default: FALSE

...

Additional parameters to pass along to ggplot2 functions. Prefix a parameter name with a layer name to pass it to only that layer. For instance, p.size = 2 ensures only the points have their size set to 2. Unprefixed parameters go to every layer whose function accepts them. An argument that no layer accepts is an error.

Value

A ggplot2 plot. The computed data points, ggplot2 command, stats table, and stats table commands are available as ⁠$data⁠, ⁠$code⁠, ⁠$stats⁠, and ⁠$stats$code⁠, respectively.

Aesthetics

All built-in color palettes are colorblind-friendly. The available categorical palette names are: "okabe", "carto", "r4", "polychrome", "tol", "bright", "light", "muted", "vibrant", "tableau", "classic", "alphabet", "tableau20", "kelly", and "fishy".

Shapes can be given as per base R - numbers 0 through 17 for various shapes, or the decimal value of an ascii character, e.g. a-z = 65:90; A-Z = 97:122 to use letters instead of shapes on the plot. Character strings may used as well.

See Also

Other alpha_diversity: adiv_boxplot(), adiv_stats(), adiv_table()

Other visualization: adiv_boxplot(), bdiv_boxplot(), bdiv_corrplot(), bdiv_heatmap(), bdiv_ord_plot(), plot_heatmap(), rare_corrplot(), rare_multiplot(), rare_stacked(), stats_boxplot(), stats_corrplot(), taxa_boxplot(), taxa_corrplot(), taxa_heatmap(), taxa_stacked()

Examples

library(rbiom)

    p <- adiv_corrplot(babies, "age", stat.by = "deliv", fit = "gam")

    p

    p$stats

    p$code

Test alpha diversity for associations with metadata.

Description

A convenience wrapper for adiv_table() + stats_table().

Usage

adiv_stats(
  biom,
  regr = NULL,
  stat.by = NULL,
  adiv = "Shannon",
  split.by = NULL,
  strata = NULL,
  transform = "none",
  test = "emmeans",
  fit = "gam",
  at = NULL,
  level = 0.95,
  alt = "!=",
  mu = 0,
  p.adj = "fdr"
)

Arguments

biom

An rbiom object, or any value accepted by as_rbiom().

regr

Dataset field with the x-axis (independent; predictive) values. Must be numeric. Default: NULL

stat.by

Dataset field with the statistical groups. Must be categorical. Default: NULL

adiv

Alpha diversity metric(s) to use. Options are: c("ace", "berger", "brillouin", "chao1", "faith", "fisher", "simpson", "inv_simpson", "margalef", "mcintosh", "menhinick", "observed", "shannon", "squares"). For "faith", a phylogenetic tree must be present in biom or explicitly provided via ⁠tree=⁠. Set adiv=".all" to use all metrics. Multiple/abbreviated values allowed. Default: "shannon"

split.by

Dataset field(s) that the data should be split by prior to any calculations. Must be categorical. Default: NULL

strata

Dataset field with a blocking variable, such as a subject identifier for repeated measures. Must be categorical. When given, regression models (test = "emmeans" or "emtrends") include a random intercept per stratum, fitted with mgcv::gam() as s(strata, bs = "re") (a linear mixed model for fit = "lm" and "log"). Not supported by the rank tests. Default: NULL

transform

Transformation to apply to the diversity values. Options are: c("none", "rank", "log", "log1p", "sqrt"). "rank" is useful for correcting for non-normally distributions before applying regression statistics. Default: "none"

test

Method for computing p-values: 'wilcox', 'kruskal', 'emmeans', or 'emtrends'. Default: 'emmeans'

fit

How to fit the trendline. 'lm', 'log', or 'gam'. Default: 'gam'

at

Position(s) along regr where group means or local slopes are evaluated. Only used by test = "emmeans" with stat.by, and by test = "emtrends" with fit = "gam" (the other combinations test a single, global slope). Default: NULL, which evaluates at one prespecified position: the median of regr (computed within each split.by stratum). A vector evaluates at each position; the returned table then has one row per position, and the p-values are adjusted across all of them.

level

The confidence level for calculating a confidence interval. Default: 0.95

alt

Alternative hypothesis direction. Options are '!=' (two-sided; not equal to mu), '<' (less than mu), or '>' (greater than mu). Default: '!='

mu

Reference value to test against. Default: 0

p.adj

Method to use for multiple comparisons adjustment of p-values. Run p.adjust.methods for a list of available options. The adjustment spans the entire returned table: every combination of split.by strata, stat.by pairs, and at positions. Default: "fdr"

Value

A tibble data.frame with the fields below. The R code used to generate the statistics is in ⁠$code⁠.

Field Description
.mean Estimated marginal mean. See emmeans::emmeans().
.mean.diff Difference in means (first group minus second).
.slope Trendline slope. See emmeans::emtrends().
.slope.diff Difference in slopes (first group minus second).
.loc.shift Hodges-Lehmann estimate of the location shift between two groups (wilcox).
.pseudomedian Hodges-Lehmann estimate of the location (one-sample wilcox).
.h1 Alternative hypothesis.
.p.val The probability, under the null hypothesis, of a test statistic at least as extreme as the one observed.
.adj.p .p.val after adjusting for multiple comparisons across the whole table.
.effect.size Cohen's d effect size. See emmeans::eff_size().
.lower Confidence interval lower bound.
.upper Confidence interval upper bound.
.se Standard error.
.n Number of observations used.
.df Degrees of freedom.
.stat Wilcoxon or Kruskal-Wallis rank sum statistic.
.t.ratio t statistic: estimate divided by .se.
.edf, .ref.df Effective and reference degrees of freedom of the smooth term (gam).
.f F statistic for the smooth term (gam).
.r.sqr R-squared (lm); adjusted R-squared (gam).
.adj.r Adjusted R-squared (lm).
.dev.expl Proportion of deviance explained (gam).
.aic Akaike Information Criterion.
.bic Bayesian Information Criterion.
.loglik Log-likelihood of the fitted model.

Tests

Which quantity is tested depends on test and on whether regr and stat.by are given. Rows with an NA in any of the regr, resp, stat.by, split.by, or strata fields are dropped (with a message).

regr stat.by test = "emmeans" test = "emtrends"
no no mean of resp vs mu (not allowed)
no yes pairwise differences in group means (.mean.diff) (not allowed)
yes no fit = "lm"/"log": the slope's t-test (.slope). fit = "gam": the smooth term's approximate significance (.edf, .f) the slope at at (.slope; global for "lm"/"log", local for "gam")
yes yes pairwise differences in group means at at (.mean.diff) pairwise differences in slopes (.slope.diff; global for "lm"/"log", local at at for "gam")

For fit = "log", the slope is with respect to log(regr). mu and alt apply to the mean or slope being tested; they are ignored for pairwise comparisons (always ⁠!= 0⁠) and for the smooth-term test. Pairwise comparisons fit a separate model to each pair of groups. Without regr, fit is irrelevant: the model is resp ~ stat.by.

test = "wilcox" runs stats::wilcox.test() (one-sample against mu, or two-sample for each pair of stat.by groups) with exact = NULL, so R chooses an exact or normal-approximation p-value based on the sample sizes and ties. test = "kruskal" runs stats::kruskal.test() across all stat.by groups.

See Also

Other alpha_diversity: adiv_boxplot(), adiv_corrplot(), adiv_table()

Other stats_tables: bdiv_stats(), distmat_stats(), stats_table(), taxa_stats()

Examples

library(rbiom)

    biom <- rarefy(hmp50)

    adiv_stats(biom, stat.by = "Sex")[,1:6]

    adiv_stats(biom, stat.by = "Sex", split.by = "Body Site")[,1:6]

    adiv_stats(biom, stat.by = "Body Site", test = "kruskal")

    adiv_stats(biom, regr = "Age", fit = "lm")

Calculate the alpha diversity of each sample.

Description

Calculate the alpha diversity of each sample.

Usage

adiv_table(
  biom,
  adiv = "shannon",
  md = ".all",
  tree = NULL,
  transform = "none",
  ties = "random",
  seed = 0,
  cpus = n_cpus()
)

adiv_matrix(
  biom,
  adiv = c("observed", "shannon", "simpson"),
  tree = NULL,
  transform = "none",
  ties = "random",
  seed = 0,
  cpus = n_cpus()
)

adiv_vector(
  biom,
  adiv = "shannon",
  tree = NULL,
  transform = "none",
  ties = "random",
  seed = 0,
  cpus = n_cpus()
)

Arguments

biom

An rbiom object, or any value accepted by as_rbiom().

adiv

Alpha diversity metric(s) to use. Options are: c("ace", "berger", "brillouin", "chao1", "faith", "fisher", "simpson", "inv_simpson", "margalef", "mcintosh", "menhinick", "observed", "shannon", "squares"). For "faith", a phylogenetic tree must be present in biom or explicitly provided via ⁠tree=⁠. Set adiv=".all" to use all metrics. Multiple/abbreviated values allowed. Default: "shannon"

md

Dataset field(s) to include in the output data frame, or '.all' to include all metadata fields. Default: '.all'

tree

A phylo object representing the phylogenetic relationships of the taxa in biom. Only required when computing UniFrac distances. Default: biom$tree

transform

Transformation to apply to the diversity values. Options are: c("none", "rank", "log", "log1p", "sqrt"). "rank" is useful for correcting for non-normally distributions before applying regression statistics. Default: "none"

ties

When transform="rank", how to rank identical values. Options are: c("average", "first", "last", "random", "max", "min"). See rank() for details. Default: "random"

seed

Random seed for permutations, rarefaction, random tie-breaking, and stochastic ordinations. Results are reproducible for a given seed, and the caller's random number generator state is left unchanged. Must be a non-negative integer. Default: 0

cpus

The number of CPUs to use. Set to NULL to use all available, or to 1 to disable parallel processing. Does not affect results. Default: ecodive::n_cpus() (all available cores)

Value

adiv_vector() -

A named numeric vector.

adiv_matrix() -

A matrix of samples x metric. The first column, 'depth', is never transformed.

adiv_table() -

A tibble data.frame of alpha diversity values. Each combination of sample/adiv has its own row. Column names are .sample, .depth, .adiv, and .diversity, followed by any metadata fields requested by md.

Each result carries ⁠$code⁠: the R code that regenerates it, including the steps that produced biom.

See Also

sample_sums() for sample depths.

Other alpha_diversity: adiv_boxplot(), adiv_corrplot(), adiv_stats()

Examples

library(rbiom)

    biom <- hmp50[1:5]

    adiv_table(biom)

    biom <- rarefy(biom)
    adiv_table(biom, md = NULL)

    adiv_vector(biom, 'faith')

    adiv_matrix(biom)

    adiv_matrix(biom)$code

Convert a variety of data types to an rbiom object.

Description

Construct an rbiom object. The returned object is an R6 reference class. Use b <- a$clone() to create copies, not b <- a.

Usage

as_rbiom(biom, ...)

Arguments

biom

Object which can be coerced to an rbiom-class object. For example:

file -

Filepath or URL to a BIOM file (JSON, HDF5, or tabular), or a JSON string.

matrix -

An abundance matrix (base or Matrix) with OTUs in rows and samples in columns.

data.frame -

Treated as an abundance matrix: OTUs in rows (row names) and samples in columns.

list -

With counts and optionally metadata, taxonomy, tree, etc (see details).

rbiom -

Returned as-is, unless ... requests changes, in which case a modified clone is returned.

phyloseq -

From the phyloseq Bioconductor R package.

SummarizedExperiment -

From the SummarizedExperiment Bioconductor R package.

TreeSummarizedExperiment -

From the TreeSummarizedExperiment Bioconductor R package.

MultiAssayExperiment -

From the MultiAssayExperiment Bioconductor R package (its first experiment is used).

biom -

From the biomformat Bioconductor R package.

...

Properties to overwrite in biom: metadata, taxonomy, tree, sequences, id, comment, or date (see details). Setting underscores here will pass it to read_tree().

Value

An rbiom object.

Examples

library(rbiom)

    # create a simple matrix ------------------------
    mtx <- matrix(
      data     = floor(runif(24) * 1000),
      nrow     = 6,
      dimnames = list(paste0("OTU", 1:6), paste0("Sample", 1:4)) )
    mtx

    # and some sample metadata ----------------------
    df <- data.frame(
      .sample   = paste0("Sample", 1:4),
      treatment = c("A", "B", "A", "B"),
      days      = c(12, 3, 7, 8) )

    # convert data set to rbiom ---------------------
    biom <- as_rbiom(mtx, metadata = df, id = "My BIOM")
    biom

Convert an rbiom object to a base R list.

Description

Convert an rbiom object to a base R list.

Usage

## S3 method for class 'rbiom'
as.list(x, ...)

Arguments

x

An rbiom object, such as from as_rbiom().

...

Not used.

Value

A list with names c('counts', 'metadata', 'taxonomy', 'tree', 'sequences', 'id', 'comment', 'date', 'generated_by').

See Also

Other conversion: as.matrix.rbiom()


Convert an rbiom object to a simple count matrix.

Description

Identical to running as.matrix(biom$counts).

Usage

## S3 method for class 'rbiom'
as.matrix(x, ...)

Arguments

x

An rbiom object, such as from as_rbiom().

...

Not used.

Value

A base R matrix with OTUs as rows and samples as columns.

See Also

Other conversion: as.list.rbiom()

Examples

library(rbiom)

    as.matrix(hmp50)[1:5,1:5]

Longitudinal Stool Samples from Infants (n = 2,684)

Description

Longitudinal Stool Samples from Infants (n = 2,684)

Usage

babies

Format

An rbiom object with 2,684 samples. Includes metadata and taxonomy.

Subject ID -

ID1, ID2, ..., ID12

Sex -

Male or Female

Age (days) -

1 - 266

Child's diet -

"Breast milk", "Breast milk and formula", or "Formula"

Sample collection -

"Frozen upon collection" or "Stored in alcohol"

Antibiotic exposure -

Yes or No

Antifungal exposure -

Yes or No

Delivery mode -

Cesarean or Vaginal

Solid food introduced (Age) -

116 - 247

Source

https://www.nature.com/articles/s41467-018-04641-7 and doi:10.1038/s41467-017-01973-8

See Also

Other Built-In Datasets: gems, hmp50

Examples

babies
head(babies$metadata$Age)

Visualize BIOM data with boxplots.

Description

Visualize BIOM data with boxplots.

Usage

bdiv_boxplot(
  biom,
  x = NULL,
  bdiv = "bray",
  layers = "x",
  weighted = NULL,
  tree = NULL,
  within = NULL,
  between = NULL,
  stat.by = x,
  facet.by = NULL,
  colors = TRUE,
  shapes = TRUE,
  patterns = FALSE,
  test = "auto",
  flip = FALSE,
  stripe = NULL,
  ci = "ci",
  level = 0.95,
  p.adj = "fdr",
  outliers = NULL,
  xlab.angle = "auto",
  p.label = 0.05,
  transform = "none",
  strata = NULL,
  seed = 0,
  permutations = 999,
  caption = TRUE,
  alpha = 0.5,
  cpus = n_cpus(),
  ...
)

Arguments

biom

An rbiom object, or any value accepted by as_rbiom().

x

A categorical metadata column name to use for the x-axis. Or NULL, which groups all samples into a single category.

bdiv

Beta diversity distance algorithm(s) to use. Options are: c("aitchison", "bhattacharyya", "bray", "canberra", "chebyshev", "chord", "clark", "sorensen", "divergence", "euclidean", "generalized_unifrac", "gower", "hamming", "hellinger", "horn", "jaccard", "jensen", "jsd", "lorentzian", "manhattan", "matusita", "minkowski", "morisita", "motyka", "normalized_unifrac", "ochiai", "psym_chisq", "soergel", "squared_chisq", "squared_chord", "squared_euclidean", "topsoe", "unweighted_unifrac", "variance_adjusted_unifrac", "wave_hedges", "weighted_unifrac"). For the UniFrac family, a phylogenetic tree must be present in biom or explicitly provided via ⁠tree=⁠. Supports partial matching. Multiple values are allowed for functions which return a table or plot. Default: "bray"

layers

One or more of c("bar", "box" ("x"), "violin", "dot", "strip", "crossbar", "errorbar", "linerange", "pointrange"). Single letter abbreviations are also accepted. For instance, c("box", "dot") is equivalent to c("x", "d") and "xd". Default: "x"

weighted

(Deprecated - weighting is now inherent in bdiv metric name.) Take relative abundances into account. When weighted=FALSE, only presence/absence is considered. Multiple values allowed. Default: NULL

tree

A phylo object representing the phylogenetic relationships of the taxa in biom. Only required when computing UniFrac distances. Default: biom$tree

within, between

Dataset field(s) for intra- or inter- sample comparisons. Alternatively, dataset field names given elsewhere can be prefixed with '==' or '!=' to assign them to within or between, respectively. Default: NULL

stat.by

Dataset field with the statistical groups. Must be categorical. Default: NULL

facet.by

Dataset field(s) to use for faceting. Must be categorical. Default: NULL

colors

How to color the groups. Options are:

TRUE -

Automatically select colorblind-friendly colors.

FALSE or NULL -

Don't use colors.

a palette name -

Auto-select colors from this set. E.g. "okabe"

character vector -

Custom colors to use. E.g. c("red", "#00FF00")

named character vector -

Explicit mapping. E.g. c(Male = "blue", Female = "red")

See "Aesthetics" section below for additional information. Default: TRUE

shapes

Shapes for each group. Options are similar to colors's: TRUE, FALSE, NULL, shape names (typically integers 0 - 17), or a named vector mapping groups to specific shape names. See "Aesthetics" section below for additional information. Default: TRUE

patterns

Patterns for each group. Options are similar to colors's: TRUE, FALSE, NULL, pattern names ("brick", "chevron", "fish", "grid", etc), or a named vector mapping groups to specific pattern names. See "Aesthetics" section below for additional information. Default: FALSE

test

Permutation test for comparing the groups. 'auto' and 'adonis2' run PERMANOVA; 'mrpp' and 'betadisper' are also available (see bdiv_stats()). The tests permute samples, not the plotted pairwise distances. 'none' skips the statistics. Default: 'auto'

flip

Transpose the axes, so that taxa are present as rows instead of columns. Default: FALSE

stripe

Shade every other x position. Default: same as flip

ci

How to calculate min/max of the crossbar, errorbar, linerange, and pointrange layers. Options are: "ci" (confidence interval), "range", "sd" (standard deviation), "se" (standard error), and "mad" (median absolute deviation). The center mark of crossbar and pointrange represents the mean, except for "mad" in which case it represents the median. Intervals are drawn as computed, including below zero, unless the y-axis is transformed: bounds below zero are drawn at zero on a "sqrt" or "log1p" axis, and bounds at or below zero are drawn at the smallest positive y value on a log axis. Default: "ci"

level

The confidence level for calculating a confidence interval. Default: 0.95

p.adj

Method to use for multiple comparisons adjustment of p-values. Run p.adjust.methods for a list of available options. The adjustment spans every p-value in the returned table (all metrics, strata, pairs, and positions). Default: "fdr"

outliers

Show boxplot outliers? TRUE to always show. FALSE to always hide. NULL to only hide them when overlaying a dot or strip chart. Default: NULL

xlab.angle

Angle of the labels at the bottom of the plot. Options are "auto", '0', '30', and '90'. Default: "auto".

p.label

Minimum adjusted p-value to display on the plot with a bracket.

p.label = 0.05 -

Show p-values that are <= 0.05.

p.label = 0 -

Don't show any p-values on the plot.

p.label = 1 -

Show all p-values on the plot.

If a numeric vector with more than one value is provided, they will be used as breaks for asterisk notation. Default: 0.05

transform

Transformation to apply to calculated values. Options are: c("none", "rank", "log", "log1p", "sqrt"). "rank" is useful for correcting for non-normal distributions before applying regression statistics. Default: "none"

strata

Dataset field with the blocking/subject variable. Permutation tests permute within strata; regression models include a random intercept per stratum. Default: NULL

seed

Random seed for permutations, rarefaction, random tie-breaking, and stochastic ordinations. Results are reproducible for a given seed, and the caller's random number generator state is left unchanged. Must be a non-negative integer. Default: 0

permutations

Number of random permutations to use. Default: 999

caption

Add methodology caption beneath the plot. Default: TRUE

alpha

The alpha term to use in Generalized UniFrac. How much weight to give to relative abundances; a value between 0 and 1, inclusive. Setting alpha=1 is equivalent to Normalized UniFrac. Default: 0.5

cpus

The number of CPUs to use. Set to NULL to use all available, or to 1 to disable parallel processing. Does not affect results. Default: ecodive::n_cpus() (all available cores)

...

Additional parameters to pass along to ggplot2 functions. Prefix a parameter name with a layer name to pass it to only that layer. For instance, d.size = 2 ensures only the points on the dot layer have their size set to 2. Unprefixed parameters go to every layer whose function accepts them (e.g. scales = "free" for the facets). An argument that no layer accepts is an error.

Value

A ggplot2 plot. The computed data points, ggplot2 command, stats table, and stats table commands are available as ⁠$data⁠, ⁠$code⁠, ⁠$stats⁠, and ⁠$stats$code⁠, respectively.

Aesthetics

All built-in color palettes are colorblind-friendly. The available categorical palette names are: "okabe", "carto", "r4", "polychrome", "tol", "bright", "light", "muted", "vibrant", "tableau", "classic", "alphabet", "tableau20", "kelly", and "fishy".

Patterns are added using the fillpattern R package, which must be installed to use patterns. Options are "brick", "chevron", "fish", "grid", "herringbone", "hexagon", "octagon", "rain", "saw", "shingle", "rshingle", "stripe", and "wave", optionally abbreviated and/or suffixed with modifiers. For example, "hex10_sm" for the hexagon pattern rotated 10 degrees and shrunk by 2x. See fillpattern::fill_pattern() for complete documentation of options.

Shapes can be given as per base R - numbers 0 through 17 for various shapes, or the decimal value of an ascii character, e.g. a-z = 65:90; A-Z = 97:122 to use letters instead of shapes on the plot. Character strings may used as well.

The dot and strip layers use the ggbeeswarm package when it is installed, and jittered points otherwise.

See Also

Other beta_diversity: bdiv_clusters(), bdiv_corrplot(), bdiv_heatmap(), bdiv_ord_plot(), bdiv_ord_table(), bdiv_stats(), bdiv_table(), distmat_stats()

Other visualization: adiv_boxplot(), adiv_corrplot(), bdiv_corrplot(), bdiv_heatmap(), bdiv_ord_plot(), plot_heatmap(), rare_corrplot(), rare_multiplot(), rare_stacked(), stats_boxplot(), stats_corrplot(), taxa_boxplot(), taxa_corrplot(), taxa_heatmap(), taxa_stacked()

Examples

library(rbiom)

    biom <- rarefy(hmp50)

    bdiv_boxplot(biom, x="==Body Site", bdiv="unweighted_unifrac", stat.by="Body Site")

Cluster samples by beta diversity (k-medoids).

Description

Partitions the samples around k medoids with cluster::pam(), which works directly on the dissimilarity matrix. (k-means is not a valid clustering of a dissimilarity matrix, since it would treat the rows of the matrix as coordinates.)

Usage

bdiv_clusters(
  biom,
  bdiv = "bray",
  weighted = NULL,
  normalized = NULL,
  tree = NULL,
  k = 5,
  seed = 0,
  alpha = 0.5,
  cpus = n_cpus(),
  ...
)

Arguments

biom

An rbiom object, or any value accepted by as_rbiom().

bdiv

Beta diversity distance algorithm(s) to use. Options are: c("aitchison", "bhattacharyya", "bray", "canberra", "chebyshev", "chord", "clark", "sorensen", "divergence", "euclidean", "generalized_unifrac", "gower", "hamming", "hellinger", "horn", "jaccard", "jensen", "jsd", "lorentzian", "manhattan", "matusita", "minkowski", "morisita", "motyka", "normalized_unifrac", "ochiai", "psym_chisq", "soergel", "squared_chisq", "squared_chord", "squared_euclidean", "topsoe", "unweighted_unifrac", "variance_adjusted_unifrac", "wave_hedges", "weighted_unifrac"). For the UniFrac family, a phylogenetic tree must be present in biom or explicitly provided via ⁠tree=⁠. Supports partial matching. Multiple values are allowed for functions which return a table or plot. Default: "bray"

weighted

(Deprecated - weighting is now inherent in bdiv metric name.) Take relative abundances into account. When weighted=FALSE, only presence/absence is considered. Multiple values allowed. Default: NULL

normalized

(Deprecated - normalization is now inherent in bdiv metric name.) Only changes the "Weighted UniFrac" calculation. Divides result by the total branch weights. Default: NULL

tree

A phylo object representing the phylogenetic relationships of the taxa in biom. Only required when computing UniFrac distances. Default: biom$tree

k

Number of clusters. Default: 5L

seed

Random seed; only used when cluster::pam() is asked to sample medoids (medoids = "random"). Default: 0

alpha

The alpha term to use in Generalized UniFrac. How much weight to give to relative abundances; a value between 0 and 1, inclusive. Setting alpha=1 is equivalent to Normalized UniFrac. Default: 0.5

cpus

The number of CPUs to use. Set to NULL to use all available, or to 1 to disable parallel processing. Does not affect results. Default: ecodive::n_cpus() (all available cores)

...

Passed on to cluster::pam().

Value

A numeric factor assigning samples to clusters.

See Also

Other beta_diversity: bdiv_boxplot(), bdiv_corrplot(), bdiv_heatmap(), bdiv_ord_plot(), bdiv_ord_table(), bdiv_stats(), bdiv_table(), distmat_stats()

Other clustering: taxa_clusters()

Examples

library(rbiom)

    biom <- rarefy(hmp50)
    biom$metadata$bray_cluster <- bdiv_clusters(biom)

    pull(biom, 'bray_cluster')[1:10]

    bdiv_ord_plot(biom, stat.by = "bray_cluster")

Visualize beta diversity with scatterplots and trendlines.

Description

Visualize beta diversity with scatterplots and trendlines.

Usage

bdiv_corrplot(
  biom,
  x,
  bdiv = "bray",
  layers = "tc",
  weighted = NULL,
  tree = NULL,
  within = NULL,
  between = NULL,
  stat.by = NULL,
  facet.by = NULL,
  colors = TRUE,
  shapes = TRUE,
  test = "mantel",
  fit = "gam",
  at = NULL,
  level = 0.95,
  p.adj = "fdr",
  transform = "none",
  ties = "random",
  seed = 0,
  permutations = 999,
  alt = "!=",
  mu = 0,
  strata = NULL,
  caption = TRUE,
  check = FALSE,
  alpha = 0.5,
  cpus = n_cpus(),
  ...
)

Arguments

biom

An rbiom object, or any value accepted by as_rbiom().

x

Dataset field with the x-axis values. Equivalent to the regr argument in stats_table(). Required.

bdiv

Beta diversity distance algorithm(s) to use. Options are: c("aitchison", "bhattacharyya", "bray", "canberra", "chebyshev", "chord", "clark", "sorensen", "divergence", "euclidean", "generalized_unifrac", "gower", "hamming", "hellinger", "horn", "jaccard", "jensen", "jsd", "lorentzian", "manhattan", "matusita", "minkowski", "morisita", "motyka", "normalized_unifrac", "ochiai", "psym_chisq", "soergel", "squared_chisq", "squared_chord", "squared_euclidean", "topsoe", "unweighted_unifrac", "variance_adjusted_unifrac", "wave_hedges", "weighted_unifrac"). For the UniFrac family, a phylogenetic tree must be present in biom or explicitly provided via ⁠tree=⁠. Supports partial matching. Multiple values are allowed for functions which return a table or plot. Default: "bray"

layers

One or more of c("trend", "confidence", "point", "name", "residual"). Single letter abbreviations are also accepted. For instance, c("trend", "point") is equivalent to c("t", "p") and "tp". Default: "tc"

weighted

(Deprecated - weighting is now inherent in bdiv metric name.) Take relative abundances into account. When weighted=FALSE, only presence/absence is considered. Multiple values allowed. Default: NULL

tree

A phylo object representing the phylogenetic relationships of the taxa in biom. Only required when computing UniFrac distances. Default: biom$tree

within, between

Dataset field(s) for intra- or inter- sample comparisons. Alternatively, dataset field names given elsewhere can be prefixed with '==' or '!=' to assign them to within or between, respectively. Default: NULL

stat.by

Dataset field with the statistical groups. Must be categorical. Default: NULL

facet.by

Dataset field(s) to use for faceting. Must be categorical. Default: NULL

colors

How to color the groups. Options are:

TRUE -

Automatically select colorblind-friendly colors.

FALSE or NULL -

Don't use colors.

a palette name -

Auto-select colors from this set. E.g. "okabe"

character vector -

Custom colors to use. E.g. c("red", "#00FF00")

named character vector -

Explicit mapping. E.g. c(Male = "blue", Female = "red")

See "Aesthetics" section below for additional information. Default: TRUE

shapes

Shapes for each group. Options are similar to colors's: TRUE, FALSE, NULL, shape names (typically integers 0 - 17), or a named vector mapping groups to specific shape names. See "Aesthetics" section below for additional information. Default: TRUE

test

Method for computing p-values: 'none' or 'mantel' (a Mantel test of the distances against the differences in x; see bdiv_stats()). The trendline is fitted to the pairwise distances for display only. Default: 'mantel'

fit

How to fit the trendline. 'lm', 'log', or 'gam'. Default: 'gam'

at

Position(s) along regr where group means or local slopes are evaluated. Default: NULL, which uses the median of regr within each split.by stratum. A vector gives one row per position, and p-values are adjusted across all of them. Ignored by tests that do not depend on a position (e.g. a global slope with fit = "lm").

level

The confidence level for calculating a confidence interval. Default: 0.95

p.adj

Method to use for multiple comparisons adjustment of p-values. Run p.adjust.methods for a list of available options. The adjustment spans every p-value in the returned table (all metrics, strata, pairs, and positions). Default: "fdr"

transform

Transformation to apply to calculated values. Options are: c("none", "rank", "log", "log1p", "sqrt"). "rank" is useful for correcting for non-normal distributions before applying regression statistics. Default: "none"

ties

When transform="rank", how to rank identical values. Options are: c("average", "first", "last", "random", "max", "min"). See rank() for details. Default: "random"

seed

Random seed for permutations, rarefaction, random tie-breaking, and stochastic ordinations. Results are reproducible for a given seed, and the caller's random number generator state is left unchanged. Must be a non-negative integer. Default: 0

permutations

Number of random permutations to use. Default: 999

alt

Alternative hypothesis direction. Options are '!=' (two-sided; not equal to mu), '<' (less than mu), or '>' (greater than mu). Default: '!='

mu

Reference value to test against. Default: 0

strata

Dataset field with the blocking/subject variable. Permutation tests permute within strata; regression models include a random intercept per stratum. Default: NULL

caption

Add methodology caption beneath the plot. Default: TRUE

check

Generate additional plots to aid in assessing data normality. Default: FALSE

alpha

The alpha term to use in Generalized UniFrac. How much weight to give to relative abundances; a value between 0 and 1, inclusive. Setting alpha=1 is equivalent to Normalized UniFrac. Default: 0.5

cpus

The number of CPUs to use. Set to NULL to use all available, or to 1 to disable parallel processing. Does not affect results. Default: ecodive::n_cpus() (all available cores)

...

Additional parameters to pass along to ggplot2 functions. Prefix a parameter name with a layer name to pass it to only that layer. For instance, p.size = 2 ensures only the points have their size set to 2. Unprefixed parameters go to every layer whose function accepts them. An argument that no layer accepts is an error.

Value

A ggplot2 plot. The computed data points, ggplot2 command, stats table, and stats table commands are available as ⁠$data⁠, ⁠$code⁠, ⁠$stats⁠, and ⁠$stats$code⁠, respectively.

Aesthetics

All built-in color palettes are colorblind-friendly. The available categorical palette names are: "okabe", "carto", "r4", "polychrome", "tol", "bright", "light", "muted", "vibrant", "tableau", "classic", "alphabet", "tableau20", "kelly", and "fishy".

Shapes can be given as per base R - numbers 0 through 17 for various shapes, or the decimal value of an ascii character, e.g. a-z = 65:90; A-Z = 97:122 to use letters instead of shapes on the plot. Character strings may used as well.

See Also

Other beta_diversity: bdiv_boxplot(), bdiv_clusters(), bdiv_heatmap(), bdiv_ord_plot(), bdiv_ord_table(), bdiv_stats(), bdiv_table(), distmat_stats()

Other visualization: adiv_boxplot(), adiv_corrplot(), bdiv_boxplot(), bdiv_heatmap(), bdiv_ord_plot(), plot_heatmap(), rare_corrplot(), rare_multiplot(), rare_stacked(), stats_boxplot(), stats_corrplot(), taxa_boxplot(), taxa_corrplot(), taxa_heatmap(), taxa_stacked()

Examples

library(rbiom)

    biom <- rarefy(hmp50)
    bdiv_corrplot(biom, "Age", stat.by = "Sex", layers = "tcp")

Display beta diversities in an all vs all grid.

Description

Display beta diversities in an all vs all grid.

Usage

bdiv_heatmap(
  biom,
  bdiv = "bray",
  tree = NULL,
  tracks = NULL,
  grid = "devon",
  label = TRUE,
  label_size = NULL,
  rescale = "none",
  clust = "complete",
  trees = TRUE,
  asp = 1,
  tree_height = 10,
  track_height = 10,
  legend = "right",
  title = TRUE,
  xlab.angle = "auto",
  alpha = 0.5,
  cpus = n_cpus(),
  ...
)

Arguments

biom

An rbiom object, or any value accepted by as_rbiom().

bdiv

Beta diversity distance algorithm(s) to use. Options are: c("aitchison", "bhattacharyya", "bray", "canberra", "chebyshev", "chord", "clark", "sorensen", "divergence", "euclidean", "generalized_unifrac", "gower", "hamming", "hellinger", "horn", "jaccard", "jensen", "jsd", "lorentzian", "manhattan", "matusita", "minkowski", "morisita", "motyka", "normalized_unifrac", "ochiai", "psym_chisq", "soergel", "squared_chisq", "squared_chord", "squared_euclidean", "topsoe", "unweighted_unifrac", "variance_adjusted_unifrac", "wave_hedges", "weighted_unifrac"). For the UniFrac family, a phylogenetic tree must be present in biom or explicitly provided via ⁠tree=⁠. Supports partial matching. Multiple values are allowed for functions which return a table or plot. Default: "bray"

tree

A phylo object representing the phylogenetic relationships of the taxa in biom. Only required when computing UniFrac distances. Default: biom$tree

tracks

A character vector of metadata fields to display as tracks at the top of the plot. Or, a list as expected by the tracks argument of plot_heatmap(). Default: NULL

grid

Color palette name, or a list with entries for label, colors, range, bins, na.color, and/or guide. See the Track Definitions section for details. Default: "devon"

label

Label the matrix rows and columns. You can supply a list or logical vector of length two to control row labels and column labels separately, for example label = c(rows = TRUE, cols = FALSE), or simply label = c(TRUE, FALSE). Other valid options are "rows", "cols", "both", "bottom", "right", and "none". Default: TRUE

label_size

The font size to use for the row and column labels. You can supply a numeric vector of length two to control row label sizes and column label sizes separately, for example c(rows = 20, cols = 8), or simply c(20, 8). Default: NULL, which computes: pmax(5, pmin(14, 100 / dim(mtx)))

rescale

Rescale rows or columns to all have a common min/max. Options: "none", "rows", or "cols". Default: "none"

clust

Clustering algorithm for reordering the samples by similarity, applied to the bdiv distances. Options are: "ward.D", "ward.D2", "single", "complete", "average", "mcquitty", "median", "centroid", or FALSE to disable reordering. Default: "complete"

trees

Draw a dendrogram for rows (left) and columns (top). You can supply a list or logical vector of length two to control the row tree and column tree separately, for example trees = c(rows = TRUE, cols = FALSE), or simply trees = c(TRUE, FALSE). Other valid options are "rows", "cols", "both", "left", "top", and "none". Default: TRUE

asp

Aspect ratio (height/width) for entire grid. Default: 1 (square)

tree_height, track_height

The height of the dendrogram or annotation tracks as a percentage of the overall grid size. Use a numeric vector of length two to assign c(top, left) independently. Default: 10 (10% of the grid's height)

legend

Where to place the legend. Options are: "right" or "bottom". Default: "right"

title

Plot title. Set to TRUE for a default title, NULL for no title, or any character string. Default: TRUE

xlab.angle

Angle of the labels at the bottom of the plot. Options are "auto", '0', '30', and '90'. Default: "auto".

alpha

The alpha term to use in Generalized UniFrac. How much weight to give to relative abundances; a value between 0 and 1, inclusive. Setting alpha=1 is equivalent to Normalized UniFrac. Default: 0.5

cpus

The number of CPUs to use. Set to NULL to use all available, or to 1 to disable parallel processing. Does not affect results. Default: ecodive::n_cpus() (all available cores)

...

Additional arguments to pass on to ggplot2::theme(). Arguments prefixed with labs. go to ggplot2::labs() instead, for example labs.subtitle = "Plot subtitle".

Value

A ggplot2 plot. The computed data points and ggplot command are available as ⁠$data⁠ and ⁠$code⁠, respectively.

Annotation Tracks

Metadata can be displayed as colored tracks above the heatmap. Common use cases are provided below, with more thorough documentation available at https://cmmr.github.io/rbiom .

## Categorical ----------------------------
tracks = "Body Site"
tracks = list('Body Site' = "bright")
tracks = list('Body Site' = c('Stool' = "blue", 'Saliva' = "green"))

## Numeric --------------------------------
tracks = "Age"
tracks = list('Age' = "reds")

## Multiple Tracks ------------------------
tracks = c("Body Site", "Age")
tracks = list('Body Site' = "bright", 'Age' = "reds")
tracks = list(
  'Body Site' = c('Stool' = "blue", 'Saliva' = "green"),
  'Age'       = list('colors' = "reds") )

The following entries in the track definitions are understood:

colors -

A pre-defined palette name or custom set of colors to map to.

range -

The c(min,max) to use for scale values.

label -

Label for this track. Defaults to the name of this list element.

side -

Options are "top" (default) or "left". taxa_heatmap() places all tracks on top.

na.color -

The color to use for NA values.

bins -

Bin a gradient into this many bins/steps.

guide -

A list of arguments for guide_colorbar() or guide_legend().

All built-in color palettes are colorblind-friendly.

Categorical palette names: "okabe", "carto", "r4", "polychrome", "tol", "bright", "light", "muted", "vibrant", "tableau", "classic", "alphabet", "tableau20", "kelly", and "fishy".

Numeric palette names: "reds", "oranges", "greens", "purples", "grays", "acton", "bamako", "batlow", "bilbao", "buda", "davos", "devon", "hawaii", "imola", "lajolla", "lapaz", "nuuk", "oslo", "tokyo", "turku", "bam", "berlin", "broc", "cork", "lisbon", "roma", "tofino", "vanimo", and "vik".

See Also

Other beta_diversity: bdiv_boxplot(), bdiv_clusters(), bdiv_corrplot(), bdiv_ord_plot(), bdiv_ord_table(), bdiv_stats(), bdiv_table(), distmat_stats()

Other visualization: adiv_boxplot(), adiv_corrplot(), bdiv_boxplot(), bdiv_corrplot(), bdiv_ord_plot(), plot_heatmap(), rare_corrplot(), rare_multiplot(), rare_stacked(), stats_boxplot(), stats_corrplot(), taxa_boxplot(), taxa_corrplot(), taxa_heatmap(), taxa_stacked()

Examples

library(rbiom)

    # Subset to 10 samples and rarefy them.
    hmp10 <- rarefy(hmp50[1:10])

    bdiv_heatmap(hmp10, tracks=c("Body Site", "Age"))

    bdiv_heatmap(hmp10, bdiv=c("u_unifrac", "n_unifrac"), tracks="sex")

Ordinate samples and taxa on a 2D plane based on beta diversity distances.

Description

Ordinate samples and taxa on a 2D plane based on beta diversity distances.

Usage

bdiv_ord_plot(
  biom,
  bdiv = "bray",
  ord = "PCoA",
  layers = "petm",
  stat.by = NULL,
  facet.by = NULL,
  colors = TRUE,
  shapes = TRUE,
  tree = NULL,
  test = "adonis2",
  seed = 0,
  permutations = 999,
  rank = -1,
  taxa = 4,
  p.top = Inf,
  p.adj = "fdr",
  unc = "singly",
  strata = NULL,
  caption = TRUE,
  alpha = 0.5,
  cpus = n_cpus(),
  ...
)

Arguments

biom

An rbiom object, or any value accepted by as_rbiom().

bdiv

Beta diversity distance algorithm(s) to use. Options are: c("aitchison", "bhattacharyya", "bray", "canberra", "chebyshev", "chord", "clark", "sorensen", "divergence", "euclidean", "generalized_unifrac", "gower", "hamming", "hellinger", "horn", "jaccard", "jensen", "jsd", "lorentzian", "manhattan", "matusita", "minkowski", "morisita", "motyka", "normalized_unifrac", "ochiai", "psym_chisq", "soergel", "squared_chisq", "squared_chord", "squared_euclidean", "topsoe", "unweighted_unifrac", "variance_adjusted_unifrac", "wave_hedges", "weighted_unifrac"). For the UniFrac family, a phylogenetic tree must be present in biom or explicitly provided via ⁠tree=⁠. Supports partial matching. Multiple values are allowed for functions which return a table or plot. Default: "bray"

ord

Method for reducing dimensionality. Options are:

"PCoA" -

Principal coordinate analysis; stats::cmdscale().

"UMAP" -

Uniform manifold approximation and projection; uwot::umap().

"NMDS" -

Nonmetric multidimensional scaling; vegan::metaMDS().

"tSNE" -

t-distributed stochastic neighbor embedding; tsne::tsne().

Multiple/abbreviated values allowed. Default: "PCoA"

layers

One or more of c("point", "spider", "ellipse", "name", "mean", "taxon", "arrow"). The first four are sample-centric; the last three are taxa-centric. Single letter abbreviations are also accepted. For instance, c("point", "ellipse") is equivalent to c("p", "e") and "pe". Default: "petm"

stat.by

Dataset field with the groups to compare and color by. Must be categorical. Default: NULL

facet.by

Dataset field(s) to use for faceting. Must be categorical. Default: NULL

colors

How to color the groups. Options are:

TRUE -

Automatically select colorblind-friendly colors.

FALSE or NULL -

Don't use colors.

a palette name -

Auto-select colors from this set. E.g. "okabe"

character vector -

Custom colors to use. E.g. c("red", "#00FF00")

named character vector -

Explicit mapping. E.g. c(Male = "blue", Female = "red")

See "Aesthetics" section below for additional information. Default: TRUE

shapes

Shapes for each group. Options are similar to colors's: TRUE, FALSE, NULL, shape names (typically integers 0 - 17), or a named vector mapping groups to specific shape names. See "Aesthetics" section below for additional information. Default: TRUE

tree

A phylo object representing the phylogenetic relationships of the taxa in biom. Only required when computing UniFrac distances. Default: biom$tree

test

Permutational test for the sample groups (stat.by). Options are "adonis2" (PERMANOVA; the default), "mrpp", "betadisper", or "none". See distmat_stats(). The taxa biplot always uses vegan::envfit().

seed

Random seed for permutations, rarefaction, random tie-breaking, and stochastic ordinations. Results are reproducible for a given seed, and the caller's random number generator state is left unchanged. Must be a non-negative integer. Default: 0

permutations

Number of random permutations to use. Default: 999

rank

What rank(s) of taxa to display. E.g. "Phylum", "Genus", ".otu", etc. An integer vector can also be given, where 1 is the highest rank, 2 is the second highest, -1 is the lowest rank, -2 is the second lowest, and 0 is the OTU "rank". Run biom$ranks to see all options for a given rbiom object. Default: -1.

taxa

Which taxa to display. An integer value will show the top n most abundant taxa. A value 0 <= n < 1 will show any taxa with that mean abundance or greater (e.g. 0.1 implies >= 10%). A character vector of taxa names will show only those named taxa. Default: 6.

p.top

Only display taxa with the most significant differences in abundance. If p.top is >= 1, then the p.top most significant taxa are displayed. If p.top is less than one, all taxa with an adjusted p-value <= p.top are displayed. Recommended to be used in combination with the taxa parameter to set a lower bound on the mean abundance of considered taxa. Default: Inf

p.adj

Method to use for multiple comparisons adjustment of p-values. Run p.adjust.methods for a list of available options. The adjustment spans every p-value in the returned table (all metrics, strata, pairs, and positions). Default: "fdr"

unc

How to handle unclassified, uncultured, and similarly ambiguous taxa names. Options are:

"singly" -

Replaces them with the OTU name.

"grouped" -

Replaces them with a higher rank's name.

"drop" -

Excludes them from the result.

"asis" -

To not check/modify any taxa names.

Abbreviations are allowed. Default: "singly"

strata

Dataset field with the blocking/subject variable. Permutation tests permute within strata; regression models include a random intercept per stratum. Default: NULL

caption

Add methodology caption beneath the plot. Default: TRUE

alpha

The alpha term to use in Generalized UniFrac. How much weight to give to relative abundances; a value between 0 and 1, inclusive. Setting alpha=1 is equivalent to Normalized UniFrac. Default: 0.5

cpus

The number of CPUs to use. Set to NULL to use all available, or to 1 to disable parallel processing. Does not affect results. Default: ecodive::n_cpus() (all available cores)

...

Parameters for layer geoms (e.g. ggplot2::geom_point()). Prefixing parameter names with a layer name ensures that a particular parameter is passed to, and only to, that layer. For instance, point.size = 2 or p.size = 2 ensures only the points have their size set to 2. Points can also be controlled with the pt. prefix. An argument that no layer accepts is an error.

Details

The ellipse layer draws 95% normal-distribution ellipses (ggplot2::stat_ellipse() with type = "norm"); groups with fewer than four samples get no ellipse. The taxon layer uses the ggrepel package to avoid overlapping labels when it is installed, and plain labels otherwise. Facet strips (or the subtitle) show the test statistic, R-squared (PERMANOVA), and p-value from ⁠$stats⁠.

Value

A ggplot2 plot. The computed sample coordinates and ggplot command are available as $data and $code respectively. If stat.by is given, then $stats and $stats$code are set. If rank is given, then $data$taxa_coords, $taxa_stats, and $taxa_stats$code are set.

See Also

Other beta_diversity: bdiv_boxplot(), bdiv_clusters(), bdiv_corrplot(), bdiv_heatmap(), bdiv_ord_table(), bdiv_stats(), bdiv_table(), distmat_stats()

Other ordination: bdiv_ord_table(), distmat_ord_table()

Other visualization: adiv_boxplot(), adiv_corrplot(), bdiv_boxplot(), bdiv_corrplot(), bdiv_heatmap(), plot_heatmap(), rare_corrplot(), rare_multiplot(), rare_stacked(), stats_boxplot(), stats_corrplot(), taxa_boxplot(), taxa_corrplot(), taxa_heatmap(), taxa_stacked()

Examples

library(rbiom)

    biom <- rarefy(hmp50)

    bdiv_ord_plot(biom, layers="pemt", stat.by="Body Site", rank="g")

Calculate PCoA and other ordinations, including taxa biplots and statistics.

Description

The biplot parameters (taxa, unc, p.top, and p.adj) only only have an effect when rank is not NULL.

Usage

bdiv_ord_table(
  biom,
  bdiv = "bray",
  ord = "PCoA",
  weighted = NULL,
  md = NULL,
  k = 2,
  stat.by = NULL,
  split.by = NULL,
  strata = NULL,
  tree = NULL,
  test = "adonis2",
  seed = 0,
  permutations = 999,
  rank = NULL,
  taxa = 6,
  p.top = Inf,
  p.adj = "fdr",
  unc = "singly",
  alpha = 0.5,
  cpus = n_cpus(),
  ...
)

Arguments

biom

An rbiom object, or any value accepted by as_rbiom().

bdiv

Beta diversity distance algorithm(s) to use. Options are: c("aitchison", "bhattacharyya", "bray", "canberra", "chebyshev", "chord", "clark", "sorensen", "divergence", "euclidean", "generalized_unifrac", "gower", "hamming", "hellinger", "horn", "jaccard", "jensen", "jsd", "lorentzian", "manhattan", "matusita", "minkowski", "morisita", "motyka", "normalized_unifrac", "ochiai", "psym_chisq", "soergel", "squared_chisq", "squared_chord", "squared_euclidean", "topsoe", "unweighted_unifrac", "variance_adjusted_unifrac", "wave_hedges", "weighted_unifrac"). For the UniFrac family, a phylogenetic tree must be present in biom or explicitly provided via ⁠tree=⁠. Supports partial matching. Multiple values are allowed for functions which return a table or plot. Default: "bray"

ord

Method for reducing dimensionality. Options are:

"PCoA" -

Principal coordinate analysis; stats::cmdscale().

"UMAP" -

Uniform manifold approximation and projection; uwot::umap().

"NMDS" -

Nonmetric multidimensional scaling; vegan::metaMDS().

"tSNE" -

t-distributed stochastic neighbor embedding; tsne::tsne().

Multiple/abbreviated values allowed. Default: "PCoA"

weighted

(Deprecated - weighting is now inherent in bdiv metric name.) Take relative abundances into account. When weighted=FALSE, only presence/absence is considered. Multiple values allowed. Default: NULL

md

Dataset field(s) to include in the output data frame, or '.all' to include all metadata fields. Default: '.all'

k

Number of ordination dimensions to return. Either 2L or 3L. Default: 2L

stat.by

The categorical or numeric metadata field over which statistics should be calculated. Default: NULL

split.by

Dataset field(s) that the data should be split by prior to any calculations. Must be categorical. Default: NULL

strata

Metadata field with a blocking variable (e.g. a subject identifier). For the sample statistics, a stat.by that varies within strata is permuted within each stratum, and one that is constant within every stratum is permuted at the stratum level (whole strata exchange their values); see the Details of distmat_stats(). For the taxa biplot, taxa abundances are permuted within each stratum. Default: NULL

tree

A phylo object representing the phylogenetic relationships of the taxa in biom. Only required when computing UniFrac distances. Default: biom$tree

test

Permutational test for the sample groups (stat.by). Options are "adonis2" (PERMANOVA; the default), "mrpp", "betadisper", or "none". See distmat_stats(). The taxa biplot always uses vegan::envfit().

seed

Random seed for the permutation tests and the stochastic ordinations (NMDS, tSNE, UMAP). Default: 0

permutations

Number of random permutations to use. Default: 999

rank

What rank(s) of taxa to compute biplot coordinates and statistics for, or NULL to disable. E.g. "Phylum", "Genus", ".otu", etc. An integer vector can also be given, where 1 is the highest rank, 2 is the second highest, -1 is the lowest rank, -2 is the second lowest, and 0 is the OTU "rank". Run biom$ranks to see all options for a given rbiom object. Default: NULL.

taxa

Which taxa to display. An integer value will show the top n most abundant taxa. A value 0 <= n < 1 will show any taxa with that mean abundance or greater (e.g. 0.1 implies >= 10%). A character vector of taxa names will show only those named taxa. Default: 6.

p.top

Only display taxa with the most significant differences in abundance. If p.top is >= 1, then the p.top most significant taxa are displayed. If p.top is less than one, all taxa with an adjusted p-value <= p.top are displayed. Recommended to be used in combination with the taxa parameter to set a lower bound on the mean abundance of considered taxa. Default: Inf

p.adj

Method to use for multiple comparisons adjustment of p-values. Run p.adjust.methods for a list of available options. The adjustment spans every p-value in the returned table (all metrics, strata, pairs, and positions). Default: "fdr"

unc

How to handle unclassified, uncultured, and similarly ambiguous taxa names. Options are:

"singly" -

Replaces them with the OTU name.

"grouped" -

Replaces them with a higher rank's name.

"drop" -

Excludes them from the result.

"asis" -

To not check/modify any taxa names.

Abbreviations are allowed. Default: "singly"

alpha

The alpha term to use in Generalized UniFrac. How much weight to give to relative abundances; a value between 0 and 1, inclusive. Setting alpha=1 is equivalent to Normalized UniFrac. Default: 0.5

cpus

The number of CPUs to use. Set to NULL to use all available, or to 1 to disable parallel processing. Does not affect results. Default: ecodive::n_cpus() (all available cores)

...

Additional arguments to pass on to stats::cmdscale(), vegan::metaMDS(), tsne::tsne(), or uwot::umap().

Details

Distances are computed from biom as given (not relativized first), so they are identical to bdiv_distmat() on the same object. Relative abundances are used only for the taxa biplot.

Value

A data.frame with columns .sample, .bdiv, .ord, .x, .y, and (optionally) .z. Any columns given by md, split.by, and stat.by are included as well. If stat.by is given, then $stats and $stats$code are set (see distmat_stats()). If rank is given, then $taxa_coords, $taxa_stats, and $taxa_stats$code are set: ⁠$taxa_stats⁠ has one row per taxon and ordination with .r.sqr (the squared correlation of the taxon's relative abundance with the ordination axes, from vegan::envfit()), .p.val (its permutation p-value), and .adj.p (adjusted across all tested taxa, before any p.top filtering); ⁠$taxa_coords⁠ holds the arrow for each taxon (.x0/.y0 at the centroid of the samples, .x/.y at its tip, scaled to fit the sample cloud) and .size, its mean relative abundance. The 'axes' attribute gives the axis labels (see distmat_ord_table()).

See Also

Other beta_diversity: bdiv_boxplot(), bdiv_clusters(), bdiv_corrplot(), bdiv_heatmap(), bdiv_ord_plot(), bdiv_stats(), bdiv_table(), distmat_stats()

Other ordination: bdiv_ord_plot(), distmat_ord_table()

Examples

library(rbiom)

    ord <- bdiv_ord_table(hmp50, "bray", "pcoa", stat.by="Body Site", rank="g")
    head(ord)

    ord$stats

    ord$taxa_stats

Test beta diversity for associations with metadata.

Description

Pairwise distances are not independent observations, so beta diversity is tested with permutation tests in which samples, not distances, are permuted: PERMANOVA and friends for a categorical stat.by, or a Mantel test for a numeric regr. See distmat_stats() for the tests.

Usage

bdiv_stats(
  biom,
  regr = NULL,
  stat.by = NULL,
  bdiv = "bray",
  weighted = NULL,
  tree = NULL,
  within = NULL,
  between = NULL,
  split.by = NULL,
  strata = NULL,
  test = if (is.null(regr)) "adonis2" else "mantel",
  seed = 0,
  permutations = 999,
  p.adj = "fdr",
  alpha = 0.5,
  cpus = n_cpus()
)

Arguments

biom

An rbiom object, or any value accepted by as_rbiom().

regr

Dataset field with a numeric variable to correlate the distances with (Mantel test). When both regr and stat.by are given, the Mantel test is run within each stat.by group. Default: NULL

stat.by

Dataset field with the groups to compare. Must be categorical. Any ==/!= prefix is ignored. Default: NULL

bdiv

Beta diversity distance algorithm(s) to use. Options are: c("aitchison", "bhattacharyya", "bray", "canberra", "chebyshev", "chord", "clark", "sorensen", "divergence", "euclidean", "generalized_unifrac", "gower", "hamming", "hellinger", "horn", "jaccard", "jensen", "jsd", "lorentzian", "manhattan", "matusita", "minkowski", "morisita", "motyka", "normalized_unifrac", "ochiai", "psym_chisq", "soergel", "squared_chisq", "squared_chord", "squared_euclidean", "topsoe", "unweighted_unifrac", "variance_adjusted_unifrac", "wave_hedges", "weighted_unifrac"). For the UniFrac family, a phylogenetic tree must be present in biom or explicitly provided via ⁠tree=⁠. Supports partial matching. Multiple values are allowed for functions which return a table or plot. Default: "bray"

weighted

(Deprecated - weighting is now inherent in bdiv metric name.) Take relative abundances into account. When weighted=FALSE, only presence/absence is considered. Multiple values allowed. Default: NULL

tree

A phylo object representing the phylogenetic relationships of the taxa in biom. Only required when computing UniFrac distances. Default: biom$tree

within, between

Accepted for compatibility with bdiv_table() and bdiv_boxplot(), where they select which sample pairs are displayed. The tests here are computed on samples, so these arguments have no effect.

split.by

Dataset field(s) that the data should be split by prior to any calculations. Must be categorical. Default: NULL

strata

Dataset field with a blocking variable, such as a subject identifier for repeated measures. Must be categorical. When stat.by (or regr) varies within strata, permutations are restricted to within each stratum; when it is constant within every stratum (a between-subject variable), whole strata are permuted instead. See the Details of distmat_stats(). test = "mrpp" and "betadisper" are not available for a between-strata variable. Default: NULL

test

The permutation test. With stat.by: "adonis2" (PERMANOVA; the default), "mrpp", or "betadisper" (homogeneity of dispersion). With regr: "mantel" (the default) or "adonis2" (PERMANOVA with a numeric covariate). See distmat_stats().

seed

Random seed for permutations, rarefaction, random tie-breaking, and stochastic ordinations. Results are reproducible for a given seed, and the caller's random number generator state is left unchanged. Must be a non-negative integer. Default: 0

permutations

Number of random permutations to use. Default: 999

p.adj

Method to use for multiple comparisons adjustment of p-values. Run p.adjust.methods for a list of available options. The adjustment spans the entire returned table. Default: "fdr"

alpha

The alpha term to use in Generalized UniFrac. How much weight to give to relative abundances; a value between 0 and 1, inclusive. Setting alpha=1 is equivalent to Normalized UniFrac. Default: 0.5

cpus

The number of CPUs to use. Set to NULL to use all available, or to 1 to disable parallel processing. Does not affect results. Default: ecodive::n_cpus() (all available cores)

Details

With strata (e.g. repeated samples per subject), the permutation scheme depends on the variable being tested. A variable that varies within strata (e.g. time point) is permuted within each stratum. A variable that is constant within every stratum (e.g. delivery mode, with subject as the stratum) is permuted at the stratum level: whole strata exchange their values, so the effective sample size is the number of strata. When the number of distinct arrangements is no larger than permutations, all of them are enumerated and the p-value is exact. The scheme is chosen separately for each row of the table (a pair of groups can be a between-strata comparison even when the omnibus test is not) and is reported in the table header. See distmat_stats() for details.

Value

A tibble data.frame with one row per test. With a categorical stat.by and more than two groups, each split.by stratum (and bdiv metric) gets an omnibus test across all groups plus one pairwise test per pair of groups, computed on that pair's samples. The columns are:

split.by fields, .bdiv -

The stratum. .bdiv is only present when several bdiv metrics were requested.

stat.by field -

The groups compared, joined by " vs ". The omnibus row lists all groups.

.groups -

The number of groups in the comparison: 2 for pairwise rows, more for the omnibus row.

.n, .stat, .r.sqr, .z, .p.val -

See distmat_stats().

.adj.p -

.p.val adjusted for multiple comparisons across the whole table.

With a numeric regr, one Mantel test per stratum, with .n, .stat (Spearman's r), .p.val, and .adj.p. The R code used to compute the table is in ⁠$code⁠.

See Also

Other beta_diversity: bdiv_boxplot(), bdiv_clusters(), bdiv_corrplot(), bdiv_heatmap(), bdiv_ord_plot(), bdiv_ord_table(), bdiv_table(), distmat_stats()

Other stats_tables: adiv_stats(), distmat_stats(), stats_table(), taxa_stats()

Examples

library(rbiom)

    biom <- rarefy(hmp50)

    bdiv_stats(biom, stat.by = "Sex", bdiv = c("bray", "w_unifrac"))

    biom <- subset(biom, `Body Site` %in% c('Saliva', 'Stool', 'Buccal mucosa'))
    bdiv_stats(biom, stat.by = "Body Site", split.by = "Sex")

    bdiv_stats(biom, regr = "Age")

    # Repeated measures: delivery mode is constant within each subject,
    # so whole subjects are permuted.
    b <- rarefy(subset(babies, `Age (days)` <= 30))
    bdiv_stats(b, stat.by = "Delivery mode", strata = "Subject ID")

Distance / dissimilarity between samples.

Description

Distance / dissimilarity between samples.

Usage

bdiv_table(
  biom,
  bdiv = "bray",
  weighted = NULL,
  normalized = NULL,
  tree = NULL,
  md = ".all",
  within = NULL,
  between = NULL,
  delta = ".all",
  norm = "none",
  pseudocount = NULL,
  power = 1.5,
  alpha = 0.5,
  transform = "none",
  ties = "random",
  seed = 0,
  cpus = n_cpus(),
  ...
)

bdiv_matrix(
  biom,
  bdiv = "bray",
  weighted = NULL,
  normalized = NULL,
  tree = NULL,
  within = NULL,
  between = NULL,
  norm = "none",
  pseudocount = NULL,
  power = 1.5,
  alpha = 0.5,
  transform = "none",
  ties = "random",
  seed = 0,
  cpus = n_cpus()
)

bdiv_distmat(
  biom,
  bdiv = "bray",
  weighted = NULL,
  normalized = NULL,
  tree = NULL,
  within = NULL,
  between = NULL,
  norm = "none",
  pseudocount = NULL,
  power = 1.5,
  alpha = 0.5,
  transform = "none",
  ties = "random",
  seed = 0,
  cpus = n_cpus()
)

Arguments

biom

An rbiom object, or any value accepted by as_rbiom().

bdiv

Beta diversity distance algorithm(s) to use. Options are: c("aitchison", "bhattacharyya", "bray", "canberra", "chebyshev", "chord", "clark", "sorensen", "divergence", "euclidean", "generalized_unifrac", "gower", "hamming", "hellinger", "horn", "jaccard", "jensen", "jsd", "lorentzian", "manhattan", "matusita", "minkowski", "morisita", "motyka", "normalized_unifrac", "ochiai", "psym_chisq", "soergel", "squared_chisq", "squared_chord", "squared_euclidean", "topsoe", "unweighted_unifrac", "variance_adjusted_unifrac", "wave_hedges", "weighted_unifrac"). For the UniFrac family, a phylogenetic tree must be present in biom or explicitly provided via ⁠tree=⁠. Supports partial matching. Multiple values are allowed for functions which return a table or plot. Default: "bray"

weighted

(Deprecated - weighting is now inherent in bdiv metric name.) Take relative abundances into account. When weighted=FALSE, only presence/absence is considered. Multiple values allowed. Default: NULL

normalized

(Deprecated - normalization is now inherent in bdiv metric name.) Only changes the "Weighted UniFrac" calculation. Divides result by the total branch weights. Default: NULL

tree

A phylo object representing the phylogenetic relationships of the taxa in biom. Only required when computing UniFrac distances. Default: biom$tree

md

Dataset field(s) to include in the output data frame, or '.all' to include all metadata fields. Default: '.all'

within, between

Dataset field(s) for intra- or inter- sample comparisons. Alternatively, dataset field names given elsewhere can be prefixed with '==' or '!=' to assign them to within or between, respectively. Default: NULL

delta

For numeric metadata, report the absolute difference in values for the two samples, for instance 2 instead of "10 vs 12". Default: TRUE

norm

Normalize the incoming counts. Options are:

  • 'none': No transformation.

  • 'percent': Relative abundance (sample abundances sum to 1).

  • 'binary': Unweighted presence/absence (each count is either 0 or 1).

  • 'clr': Centered log ratio.

Default: 'none'.

pseudocount

Value added to counts to handle zeros when norm = 'clr'. Ignored for other normalization methods. Default: NULL (emits a warning).

power

Scaling factor for the magnitude of differences between communities (pp) when bdiv = 'minkowski'. Ignored for other beta diversity metrics. Default: 1.5

alpha

The alpha term to use in Generalized UniFrac. How much weight to give to relative abundances; a value between 0 and 1, inclusive. Setting alpha=1 is equivalent to Normalized UniFrac. Default: 0.5

transform

Transformation to apply to calculated values. Options are: c("none", "rank", "log", "log1p", "sqrt"). "rank" is useful for correcting for non-normal distributions before applying regression statistics. Default: "none"

ties

When transform="rank", how to rank identical values. Options are: c("average", "first", "last", "random", "max", "min"). See rank() for details. Default: "random"

seed

Random seed for permutations, rarefaction, random tie-breaking, and stochastic ordinations. Results are reproducible for a given seed, and the caller's random number generator state is left unchanged. Must be a non-negative integer. Default: 0

cpus

The number of CPUs to use. Set to NULL to use all available, or to 1 to disable parallel processing. Does not affect results. Default: ecodive::n_cpus() (all available cores)

...

Not used.

Value

bdiv_matrix() -

An R matrix of samples x samples.

bdiv_distmat() -

A dist-class distance matrix.

bdiv_table() -

A tibble data.frame with columns named .sample1, .sample2, .bdiv, .distance, and any fields requested by md. Numeric metadata fields will be returned as abs(x - y); categorical metadata fields as "x", "y", or "x vs y".

Each result carries ⁠$code⁠: the R code that regenerates it, including the steps that produced biom.

Metadata Comparisons

Prefix metadata fields with == or != to limit comparisons to within or between groups, respectively. For example, stat.by = '==Sex' will run calculations only for intra-group comparisons, returning "Male" and "Female", but NOT "Female vs Male". Similarly, setting stat.by = '!=Body Site' will only show the inter-group comparisons, such as "Saliva vs Stool", "Anterior nares vs Buccal mucosa", and so on.

The same effect can be achieved by using the within and between parameters. stat.by = '==Sex' is equivalent to ⁠stat.by = 'Sex', within = 'Sex'⁠.

See Also

Other beta_diversity: bdiv_boxplot(), bdiv_clusters(), bdiv_corrplot(), bdiv_heatmap(), bdiv_ord_plot(), bdiv_ord_table(), bdiv_stats(), distmat_stats()

Examples

library(rbiom)

    # Subset to four samples
    biom <- hmp50[c("HMP18", "HMP19", "HMP20", "HMP21")]

    # Return in long format with metadata
    bdiv_table(biom, 'w_unifrac', md = ".all")

    # Only look at distances among the stool samples
    bdiv_table(biom, 'w_unifrac', md = c("==Body Site", "Sex"))

    # Or between males and females
    bdiv_table(biom, 'w_unifrac', md = c("Body Site", "!=Sex"))

    # All-vs-all matrix
    bdiv_matrix(biom, 'w_unifrac')

    # All-vs-all distance matrix
    dm <- bdiv_distmat(biom, 'w_unifrac')
    dm
    plot(hclust(dm))

Apply a function to each subset of an rbiom object.

Description

blply() and bdply() let you divide your biom dataset into smaller pieces, run a function on those smaller rbiom objects, and return the results as a data.frame or list.

Usage

bdply(biom, vars, FUN, ..., iters = list(), prefix = FALSE)

blply(biom, vars, FUN, ..., iters = list(), prefix = FALSE)

Arguments

biom

An rbiom object, or any value accepted by as_rbiom().

vars

A character vector of metadata fields. Each unique combination of values in these columns will be used to create a subsetted rbiom object to pass to FUN. If NULL, biom will be passed to FUN unaltered. Unambiguous abbreviations of metadata fields are also accepted. Samples with an NA in any of these fields are left out.

FUN

The function to execute on each subset of biom. For bdply(), the returned value will be coerced to a data.frame. For blply(), any returned value is unmodified.

...

Additional arguments to pass on to FUN.

iters

A named list of values to pass to FUN. Unlike ..., these will be iterated over in all combinations. Default: list()

prefix

When TRUE, prefixes the names in in iters with a '.' in the final data.frame or 'split_labels' attribute. Default: FALSE

Details

You can also specify additional variables for your function to iterate over in unique combinations.

Each subset passed to FUN is a proper rbiom object whose history records how it was made, e.g. subset(biom, Sex == "Male"), so that results computed from it (and their ⁠$code⁠) are reproducible.

Value

For bdply(), a tibble data.frame comprising the accumulated outputs of FUN, along with the columns specified by vars and iters. For blply(), a named list that has details about vars and iters in attr(,'split_labels').

See Also

Other metadata: glimpse.rbiom()

Other biom: biom_merge()

Examples

library(rbiom)

    bdply(hmp50, "Sex", `$`, 'n_samples')

    blply(hmp50, "Sex", `$`, 'n_samples') %>% unlist()

    bdply(hmp50, c("Body Site", "Sex"), function (b) {
      adm <- adiv_matrix(b)[,c("shannon", "simpson")]
      apply(adm, 2L, mean)
    })

    iters <- list(d = c("bray", "euclid"))
    bdply(hmp50, "Sex", iters = iters, function (b, d) {
      r <- range(bdiv_distmat(biom = b, bdiv = d))
      round(data.frame(min = r[[1]], max = r[[2]]))
    })

Inflate Relative Abundances to Integer Counts

Description

Scaling a matrix of proportions (or counts) to a new target depth, rounding to integers while preserving the original total abundance sum exactly.

Usage

biom_inflate(biom, depth = NULL, clone = TRUE)

Arguments

biom

An rbiom object, or any value accepted by as_rbiom().

depth

The target library size (sum) for each sample: a single integer, or one integer per sample. Must be greater than 0. If NULL (the default), the depth is estimated per-sample using the "Singleton Peak Heuristic". See suggest_inflate_depths() for algorithm details. Counts that are already integers are left unchanged when depth = NULL.

clone

Create a copy of biom before modifying. If FALSE, biom is modified in place as a side-effect. See speed ups for use cases. Default: TRUE

Value

An rbiom object.

Rounding (Largest Remainder Method)

To ensure the sum of the resulting counts equals the target depth exactly (avoiding drift caused by simple rounding), this function uses the Largest Remainder Method (also known as the Hare-Niemeyer method).

It assigns the integer part of the scaled value to each feature, and then distributes the remaining counts to the features with the largest fractional parts.

See Also

suggest_inflate_depths() for details on how target depths are estimated when depth = NULL.

Other transformations: biom_relativize(), biom_rescale(), modify_metadata, rarefy(), slice_metadata, subset, with

Examples

library(rbiom)

    biom <- hmp50[1:5]
    sample_sums(biom)

    biom <- biom_relativize(biom)
    sample_sums(biom)

    biom <- biom_inflate(biom)
    sample_sums(biom)

Combine several rbiom objects into one.

Description

WARNING: It is generally ill-advised to merge BIOM datasets, as OTUs mappings are dependent on upstream clustering and are not equivalent between BIOM files.

Usage

biom_merge(
  ...,
  metadata = NA,
  taxonomy = NA,
  tree = NA,
  sequences = NA,
  id = NA,
  comment = NA
)

Arguments

...

Any number of rbiom objects, or anything accepted by the biom parameter of as_rbiom() (matrices, file names, lists with a counts element, phyloseq objects, ...). Lists of such inputs are flattened.

metadata, taxonomy, tree, sequences, id, comment

Replace the corresponding data in the merged rbiom object with these values. The default, NA, derives the component from the inputs (see details). Set to NULL to omit the component.

Details

Samples present in more than one input must have identical counts; otherwise an error is raised. OTUs are matched by name.

With the default NA arguments:

  • metadata and taxonomy are the union of the inputs' tables. A field whose type differs between inputs (for example numeric in one and categorical in another) is converted to categorical, with a single warning listing the affected fields. An OTU with different lineages in different inputs keeps the most detailed one (one summarizing warning).

  • sequences are the union of the inputs' sequences. If only some inputs have sequences, OTUs without one get NA and a warning is issued once.

  • tree is taken from the first input whose tree contains every OTU of the merged object (pruned to those OTUs). This is the case when the inputs are subsets of one dataset. If no input tree covers all of the OTUs, the merged object has no tree and a message says so; a merged tree can't be inferred, so supply ⁠tree=⁠ in that case.

  • id and comment are kept when all inputs agree, and are otherwise "Merged BIOM" and "".

The merged object's ⁠$history⁠ nests the histories of its inputs, so its ⁠$code⁠ reproduces the entire pipeline.

Value

An rbiom object.

See Also

Other biom: bdply()

Examples

library(rbiom)

    b1 <- as_rbiom(hmp50$counts[,1:4])
    b2 <- as_rbiom(hmp50$counts[,5:8])

    biom <- biom_merge(b1, b2)
    print(biom)

    biom$tree     <- hmp50$tree
    biom$metadata <- subset(hmp50$metadata, .sample %in% biom$samples)
    print(biom)

    # Subsets of one dataset keep its tree, and record their history.
    biom <- biom_merge(hmp50[1:10], hmp50[11:20])
    biom$code

Relativize Counts to Proportions

Description

This function normalizes the data by dividing each observation by the total library size of its sample. The resulting values represent the proportion (0 to 1) of the sample composed of that specific feature.

This is a common transformation for microbiome data, as it accounts for differences in sequencing depth across samples, allowing for comparison of community composition. The result has biom$relative == TRUE.

Usage

biom_relativize(biom, clone = TRUE)

Arguments

biom

An rbiom object, or any value accepted by as_rbiom().

clone

Create a copy of biom before modifying. If FALSE, biom is modified in place as a side-effect. See speed ups for use cases. Default: TRUE

Details

Convert absolute counts to relative abundances (proportions) where each sample sums to 1.

Value

An rbiom object.

See Also

Other transformations: biom_inflate(), biom_rescale(), modify_metadata, rarefy(), slice_metadata, subset, with

Examples

library(rbiom)

    biom <- hmp50[1:5]

    # Raw counts sum to different library sizes
    sample_sums(biom)

    # Relativized counts sum to 1
    biom_rel <- biom_relativize(biom)
    sample_sums(biom_rel)
    biom_rel$relative

Rescale Counts to a Specific Range

Description

This function performs a min-max scaling on each sample independently.

It is useful for normalization techniques that require data to be within a specific bounded range, or for visualization purposes where maintaining the relative distances between values is important but the absolute magnitude needs adjustment.

Usage

biom_rescale(biom, range = c(0, 1), clone = TRUE)

Arguments

biom

An rbiom object, or any value accepted by as_rbiom().

range

Numeric vector of length 2. Target min and max. Default: c(0, 1).

clone

Create a copy of biom before modifying. If FALSE, biom is modified in place as a side-effect. See speed ups for use cases. Default: TRUE

Details

Linearly rescale each sample's values to lie between a specified minimum and maximum.

Value

An rbiom object.

Mathematical Transformation

The rescaling is performed in two steps:

  1. Normalize: Divide values by the maximum value in that sample, scaling them to a ⁠[0, 1]⁠ range relative to the sample's peak.

  2. Scale and Shift: Apply the target range using the formula:

    xnew=xnorm×(max−min)+minx_{new} = x_{norm} \times (max - min) + min

Note

If range starts at a non-zero value (e.g., c(1, 10)), the sparsity of the matrix will be destroyed because all zero counts will be shifted to the minimum value. This can significantly increase memory usage for large datasets.

See Also

Other transformations: biom_inflate(), biom_relativize(), modify_metadata, rarefy(), slice_metadata, subset, with

Examples

library(rbiom)

    biom <- hmp50[1:5]

    # Original range
    range(as.matrix(biom))

    # Rescaled to 0-1
    biom_01 <- biom_rescale(biom)
    range(as.matrix(biom_01))

    # Rescaled to 0-100 (Percentages)
    biom_100 <- biom_rescale(biom, range = c(0, 100))
    range(as.matrix(biom_100))

Convert biom data to an external package class

Description

Converts your rbiom object into other common Bioconductor data structures. Each function requires the corresponding target package to be installed.

Usage

convert_to_animalcules(biom, ...)

convert_to_biomformat(biom, ...)

convert_to_phyloseq(biom, ...)

convert_to_SE(biom, ...)

convert_to_TSE(biom, ...)

Arguments

biom

An rbiom object, or any value accepted by as_rbiom().

...

Not Used.

Details

  • convert_to_animalcules(): Converts to a MultiAssayExperiment object tailored for the animalcules interactive microbiome analysis toolkit. Includes: counts, metadata, and taxonomy.

  • convert_to_biomformat(): Converts to a biom object used by the biomformat package, the standard Bioconductor class for reading and writing BIOM data. Includes: counts, metadata, and taxonomy.

  • convert_to_phyloseq(): Converts to a phyloseq object for use with the comprehensive phyloseq ecosystem. Rank names, metadata field names, and metadata column types are preserved. Sequences are included only when every OTU has one (requires the Biostrings package). Includes: counts, metadata, taxonomy, phylogenetic tree, and sequences.

  • convert_to_SE(): Converts to a SummarizedExperiment object, a core SummarizedExperiment Bioconductor container for matrix-like data and annotations. Includes: counts, metadata, and taxonomy.

  • convert_to_TSE(): Converts to a TreeSummarizedExperiment object. This extends the SE class to natively support hierarchical TreeSummarizedExperiment relationships. The tree and sequences are included when present. Includes: counts, metadata, taxonomy, phylogenetic tree, and sequences.

Value

An animalcules (MultiAssayExperiment class), biomformat (biom class), phyloseq, SummarizedExperiment, or TreeSummarizedExperiment object.

Examples

library(rbiom)

    print(hmp50)

    
    # Requires 'animalcules' dependencies, Bioconductor R packages
    if (requireNamespace("MultiAssayExperiment", quietly = TRUE) &&
        requireNamespace("SummarizedExperiment", quietly = TRUE)) {
      ani <- convert_to_animalcules(hmp50)
      print(ani)
    }

    # Requires 'biomformat', a Bioconductor R package
    if (requireNamespace("biomformat", quietly = TRUE)) {
      bio <- convert_to_biomformat(hmp50)
      print(bio)
    }

    # Requires 'phyloseq', a Bioconductor R package
    if (requireNamespace("phyloseq", quietly = TRUE)) {
      phy <- convert_to_phyloseq(hmp50)
      print(phy)
    }

    # Requires 'SummarizedExperiment', a Bioconductor R package
    if (requireNamespace("SummarizedExperiment", quietly = TRUE)) {
      se <- convert_to_SE(hmp50)
      print(se)
    }

    # Requires 'TreeSummarizedExperiment', a Bioconductor R package
    if (requireNamespace("TreeSummarizedExperiment", quietly = TRUE)) {
      tse <- convert_to_TSE(hmp50)
      print(tse)
    }

Run ordinations on a distance matrix.

Description

Run ordinations on a distance matrix.

Usage

distmat_ord_table(dm, ord = "PCoA", k = 2L, seed = 0, ...)

Arguments

dm

A dist-class distance matrix, as returned from bdiv_distmat() or stats::dist(). Required.

ord

Method for reducing dimensionality. Options are:

"PCoA" -

Principal coordinate analysis; stats::cmdscale().

"UMAP" -

Uniform manifold approximation and projection; uwot::umap().

"NMDS" -

Nonmetric multidimensional scaling; vegan::metaMDS().

"tSNE" -

t-distributed stochastic neighbor embedding; tsne::tsne().

Multiple/abbreviated values allowed. Default: "PCoA"

k

Number of ordination dimensions to return. Either 2L or 3L. Default: 2L

seed

Random seed for the stochastic ordinations (NMDS, tSNE, UMAP), so that they are reproducible. PCoA is deterministic. Must be a non-negative integer. Default: 0

...

Additional arguments for the ord function.

Value

A tibble data.frame with columns .ord, .sample, .x, .y, and (optionally) .z. The attribute 'axes' is a tibble with one row per axis (.ord, .axis, .label, .var): for PCoA, .var is the percent of the variance (the positive eigenvalues) explained by that axis and .label reads e.g. "PCoA 1 (24.3%)"; for the other ordinations .var is NA.

See Also

Other ordination: bdiv_ord_plot(), bdiv_ord_table()

Examples

library(rbiom)

    dm  <- bdiv_distmat(hmp50, "bray")
    ord <- distmat_ord_table(dm, "PCoA")
    head(ord)

    attr(ord, 'axes')

Run permutation statistics on a distance matrix.

Description

Tests whether the distances in dm are structured by groups, using permutation tests. Samples, not distances, are the unit of permutation, so the n(n-1)/2 pairwise distances are never treated as independent observations.

Usage

distmat_stats(
  dm,
  groups,
  test = "adonis2",
  seed = 0,
  permutations = 999,
  strata = NULL
)

Arguments

dm

A dist-class distance matrix, as returned from bdiv_distmat() or stats::dist(). Required.

groups

A vector of grouping values, one per sample. Either named with the sample names in attr(dm, 'Labels'), or unnamed and in the same order. Categorical values define groups; numeric values are used as a covariate (test = "adonis2") or correlated with the distances (test = "mantel"). Samples with an NA value are dropped (with a message). Required.

test

The permutation test to run. Options are:

"adonis2" -

PERMANOVA; vegan::adonis2(). Accepts categorical or numeric groups.

"mrpp" -

Multiple response permutation procedure; vegan::mrpp(). Categorical groups only.

"betadisper" -

Homogeneity of multivariate dispersion, i.e. whether groups differ in their spread rather than their location; vegan::betadisper() followed by vegan::permutest(). Categorical groups only. A significant PERMANOVA together with a significant dispersion test means that group differences may be due to differences in spread.

"mantel" -

Mantel test of the correlation (Spearman) between dm and the pairwise absolute differences in a numeric groups; vegan::mantel(). Numeric groups only.

"none" -

Don't run any statistics; returns NULL.

Abbreviations are allowed. Default: "adonis2"

seed

Random seed for permutations, rarefaction, random tie-breaking, and stochastic ordinations. Results are reproducible for a given seed, and the caller's random number generator state is left unchanged. Must be a non-negative integer. Default: 0

permutations

Number of random permutations to use. Default: 999

strata

A blocking variable for repeated measures, e.g. a subject identifier. Given like groups (one value per sample, named or in attr(dm, 'Labels') order). How permutations are restricted depends on whether groups varies within strata; see Details. Default: NULL (samples are exchangeable).

Details

Permutation schemes with strata. Samples from the same stratum (e.g. repeated samples of one subject) are not independent, so they can't be shuffled freely. Which restriction is valid depends on groups:

  • Within-strata variable (groups varies within at least one stratum, e.g. time point or a within-subject treatment): labels are permuted only within each stratum, using permute::how(nperm = permutations, blocks = strata) with the vegan function for test.

  • Between-strata variable (groups is constant within every stratum, e.g. delivery mode with subject as the stratum): permuting within strata would never change the labels (every permutation would reproduce the observed statistic, giving p = 1). Instead, the stratum-level values are permuted among whole strata (strata may have different sizes), and the statistic is recomputed on all samples. The p-value is ⁠(1 + #{permuted >= observed}) / (1 + permutations)⁠. When there are no more distinct arrangements of the values among strata than permutations, all of them are enumerated instead and the p-value is exact: the proportion of arrangements (including the observed one) with a statistic at least as large. The statistics are computed by rbiom with the same formulas as vegan: the PERMANOVA pseudo-F and R-squared from the Gower-centred matrix of squared distances, and Spearman's r between the distances and pairwise differences in groups. The effective sample size is the number of strata, so a warning is given when the null distribution is coarse (e.g. a group present in only one stratum). Only test = "adonis2" and test = "mantel" support this scheme; "mrpp" and "betadisper" give an error.

The scheme used, and the number of permutations or enumerated arrangements, is reported in the table header.

Value

A tibble data.frame with one row and the columns:

.n -

The number of samples in the distance matrix.

.stat -

The observed test statistic: the pseudo-F ratio (adonis2, betadisper), the weighted mean within-group distance delta (mrpp), or Spearman's r (mantel).

.r.sqr -

adonis2 only: the proportion of the total sum of squares explained by groups.

.z -

mrpp only: the observed statistic minus the mean of the permuted statistics, divided by their standard deviation.

.p.val -

The permutation p-value: the probability, under the null hypothesis, of a statistic at least as extreme as the observed one, estimated from the permutations (plus the observed data). Its resolution is limited by permutations (or by the number of distinct arrangements of whole strata; see Details).

The R code used to calculate these statistics is in ⁠$code⁠. The groups (and strata) values are embedded in that code so that it can be re-run as is.

See Also

Other beta_diversity: bdiv_boxplot(), bdiv_clusters(), bdiv_corrplot(), bdiv_heatmap(), bdiv_ord_plot(), bdiv_ord_table(), bdiv_stats(), bdiv_table()

Other stats_tables: adiv_stats(), bdiv_stats(), stats_table(), taxa_stats()

Examples

library(rbiom)

    hmp10 <- hmp50[1:10]

    dm <- bdiv_distmat(hmp10, 'w_unifrac')

    distmat_stats(dm, groups = pull(hmp10, 'Body Site'))

    distmat_stats(dm, groups = pull(hmp10, 'Age'), test = "mantel")

    # See the R code used to calculate these statistics:
    stats <- distmat_stats(dm, groups = pull(hmp10, 'Age'), test = "mantel")
    stats$code

    # Repeated measures: delivery mode is constant within each subject,
    # so whole subjects are permuted (all 220 arrangements of the 12
    # infants are enumerated, giving an exact p-value).
    b  <- rarefy(subset(babies, `Age (days)` <= 10))
    dm <- bdiv_distmat(b, 'bray')
    distmat_stats(dm, pull(b, 'Delivery mode'), strata = pull(b, 'Subject ID'))

Export data to QIIME 2 or mothur.

Description

Populates a directory with the following files, formatted according to QIIME 2 or mothur's specifications.

  • biom_counts.tsv

  • biom_metadata.tsv

  • biom_taxonomy.tsv

  • biom_tree.nwk

  • biom_seqs.fna

biom_counts.tsv will always be created. The others are dependent on whether the content is present in the biom argument.

For QIIME 2, metadata columns are typed numeric or categorical (logical and Date fields are categorical; dates are written as YYYY-MM-DD). For mothur, taxonomy rows use the OTU IDs from the counts file, and missing ranks are written as unclassified.

Usage

write_mothur(biom, dir = tempfile(), prefix = "biom_", overwrite = FALSE)

write_qiime2(biom, dir = tempfile(), prefix = "biom_", overwrite = FALSE)

Arguments

biom

An rbiom object, or any value accepted by as_rbiom().

dir

Where to save the files. If the directory doesn't exist, it will be created. Default: tempfile()

prefix

A string to prepend to each file name. Default: 'biom_'

overwrite

Replace files that already exist? Default: FALSE

Value

The normalized directory path that was written to (invisibly).

Examples

library(rbiom)

    tdir <- tempfile()

    write_qiime2(hmp50, tdir, 'qiime2_')
    write_mothur(hmp50, tdir, 'mothur_')

    list.files(tdir)

    readLines(file.path(tdir, 'qiime2_metadata.tsv'), n = 4)

    readLines(file.path(tdir, 'mothur_taxonomy.tsv'), n = 3)

    unlink(tdir, recursive = TRUE)

Global Enteric Multicenter Study (n = 1,006)

Description

Global Enteric Multicenter Study (n = 1,006)

Usage

gems

Format

An rbiom object with 1,006 samples. Includes metadata and taxonomy.

diarrhea -

Case or Control

age -

0 - 4.8 (years old)

country -

Bangladesh, Gambia, Kenya, or Mali

Source

doi:10.1186/gb-2014-15-6-r76 and doi:10.1093/nar/gkx1027

See Also

Other Built-In Datasets: babies, hmp50

Examples

gems
table(gems$metadata$country)

Get a glimpse of your metadata.

Description

Get a glimpse of your metadata.

Usage

## S3 method for class 'rbiom'
glimpse(x, width = NULL, ...)

Arguments

x

An rbiom object, such as from as_rbiom().

width

Width of output. See tibble::glimpse() documentation. Default: NULL

...

Not used.

Value

The original biom, invisibly.

See Also

Other metadata: bdply()

Examples

library(rbiom)

    glimpse(hmp50)

Human Microbiome Project - demo dataset (n = 50)

Description

Human Microbiome Project - demo dataset (n = 50)

Usage

hmp50

Format

An rbiom object with 50 samples. Includes metadata, taxonomy, phylogeny, and sequences.

Sex -

Male or Female

Body Site -

Anterior nares, Buccal mucosa, Mid vagina, Saliva, or Stool

Age -

21 - 40

BMI -

19 - 32

Source

doi:10.1101/gr.096651.109

See Also

Other Built-In Datasets: babies, gems

Examples

hmp50
hmp50$metadata

Deprecated matrix transformations

Description

A collection of transformations that operate directly on matrices.

Usage

mtx_rarefy(
  mtx,
  margin = 2L,
  depth = 0.1,
  n = NULL,
  seed = 0L,
  upsample = NULL,
  cpus = NULL
)

mtx_percent(mtx, margin = 2L)

mtx_rescale(mtx, margin = 2L, range = c(0, 1))

rarefy_cols(mtx, depth = 0.1, n = NULL, seed = 0L, cpus = NULL)

rescale_rows(mtx)

rescale_cols(mtx)

Arguments

mtx

A numeric matrix or sparse matrix of counts.

margin

Apply the transformation to the matrix's rows (margin=1L) or columns (margin=2L). Instead of 1L and 2L, you may also use 'rows' and 'cols'. Default: 2L (column-wise, aka sample-wise for otu tables)

depth

How many observations to keep per sample.

n

Deprecated. The number of samples to keep. This argument is ignored in the current version.

seed

An integer seed for randomizing which observations to keep or drop.

upsample

If the count data is in percentages, provide an integer value here to scale each sample's observations to integers that sum to this value before rarefying. See biom_inflate().

cpus

The number of CPUs to use. Set to NULL to use all available, or to 1 to disable parallel processing. Does not affect results. Default: ecodive::n_cpus() (all available cores)

range

When rescaling, what should the minimum and maximum values be? Default: c(0, 1)

Value

A A numeric matrix or sparse matrix, depending on the input type, with the same dimensions as mtx.

Examples

mtx <- matrix(1:12, ncol = 3, dimnames = list(paste0("OTU", 1:4), paste0("Sample", 1:3)))

    mtx

    suppressWarnings({

      mtx_rarefy(mtx)

      rarefy_cols(mtx)

      mtx_percent(mtx)

      mtx_rescale(mtx)

      rescale_rows(mtx)

      rescale_cols(mtx)

    })

Create, modify, and delete metadata fields.

Description

mutate() creates new fields in ⁠$metadata⁠ that are functions of existing metadata fields. It can also modify (if the name is the same as an existing field) and delete fields (by setting their value to NULL).

Usage

## S3 method for class 'rbiom'
mutate(.data, ..., clone = TRUE)

## S3 method for class 'rbiom'
rename(.data, ..., clone = TRUE)

Arguments

.data

An rbiom object, such as from as_rbiom().

...

Passed on to dplyr::mutate() or dplyr::rename().

clone

Create a copy of biom before modifying. If FALSE, biom is modified in place as a side-effect. See speed ups for use cases. Default: TRUE

Value

An rbiom object.

See Also

Other transformations: biom_inflate(), biom_relativize(), biom_rescale(), rarefy(), slice_metadata, subset, with

Examples

library(rbiom)

    biom <- slice_max(hmp50, BMI, n = 6)
    biom$metadata

    # Add a new field to the metadata
    biom <- mutate(biom, Obsese = BMI >= 30)
    biom$metadata

    # Rename a metadata field
    biom <- rename(biom, 'Age (years)' = "Age")
    biom$metadata

Create a heatmap with tracks and dendrograms from any matrix.

Description

Create a heatmap with tracks and dendrograms from any matrix.

Usage

plot_heatmap(
  mtx,
  grid = list(label = "Grid Value", colors = "imola"),
  tracks = NULL,
  label = TRUE,
  label_size = NULL,
  rescale = "none",
  trees = TRUE,
  clust = "complete",
  dist = "euclidean",
  asp = 1,
  tree_height = 10,
  track_height = 10,
  legend = "right",
  title = NULL,
  xlab.angle = "auto",
  ...
)

Arguments

mtx

A numeric matrix with named rows and columns.

grid

Color palette name, or a list with entries for label, colors, range, bins, na.color, and/or guide. See the Track Definitions section for details. Default: list(label = "Grid Value", colors = "imola")

tracks

List of track definitions. See details below. Default: NULL.

label

Label the matrix rows and columns. You can supply a list or logical vector of length two to control row labels and column labels separately, for example label = c(rows = TRUE, cols = FALSE), or simply label = c(TRUE, FALSE). Other valid options are "rows", "cols", "both", "bottom", "right", and "none". Default: TRUE

label_size

The font size to use for the row and column labels. You can supply a numeric vector of length two to control row label sizes and column label sizes separately, for example c(rows = 20, cols = 8), or simply c(20, 8). Default: NULL, which computes: pmax(5, pmin(14, 100 / dim(mtx)))

rescale

Rescale rows or columns to all have a common min/max. Options: "none", "rows", or "cols". Default: "none"

trees

Draw a dendrogram for rows (left) and columns (top). You can supply a list or logical vector of length two to control the row tree and column tree separately, for example trees = c(rows = TRUE, cols = FALSE), or simply trees = c(TRUE, FALSE). Other valid options are "rows", "cols", "both", "left", "top", and "none". Default: TRUE

clust

Clustering algorithm for reordering the rows and columns by similarity. You can supply a list or character vector of length two to control the row and column clustering separately, for example clust = c(rows = "complete", cols = NA), or simply clust = c("complete", NA). Options are:

FALSE or NA -

Disable reordering.

An hclust class object

E.g. from stats::hclust().

A method name -

"ward.D", "ward.D2", "single", "complete", "average", "mcquitty", "median", or "centroid".

Default: "complete"

dist

Distance algorithm to use when reordering the rows and columns by similarity. You can supply a list or character vector of length two to control the row and column clustering separately, for example dist = c(rows = "euclidean", cols = "maximum"), or simply dist = c("euclidean", "maximum"). Options are:

A dist class object

E.g. from stats::dist() or bdiv_distmat().

A method name -

"euclidean", "maximum", "manhattan", "canberra", "binary", or "minkowski".

Default: "euclidean"

asp

Aspect ratio (height/width) for entire grid. Default: 1 (square)

tree_height, track_height

The height of the dendrogram or annotation tracks as a percentage of the overall grid size. Use a numeric vector of length two to assign c(top, left) independently. Default: 10 (10% of the grid's height)

legend

Where to place the legend. Options are: "right" or "bottom". Default: "right"

title

Plot title. Default: NULL.

xlab.angle

Angle of the labels at the bottom of the plot. Options are "auto", '0', '30', and '90'. Default: "auto".

...

Additional arguments to pass on to ggplot2::theme(). Arguments prefixed with labs. go to ggplot2::labs() instead, for example labs.subtitle = "Plot subtitle".

Value

A ggplot2 plot. The computed data points and ggplot command are available as ⁠$data⁠ and ⁠$code⁠, respectively.

Track Definitions

One or more colored tracks can be placed on the left and/or top of the heatmap grid to visualize associated metadata values.

## Categorical ----------------------------
cat_vals <- sample(c("Male", "Female"), 10, replace = TRUE)
tracks   <- list('Sex' = cat_vals)
tracks   <- list('Sex' = list(values = cat_vals, colors = "bright"))
tracks   <- list('Sex' = list(
  values = cat_vals,
  colors = c('Male' = "blue", 'Female' = "red")) )

## Numeric --------------------------------
num_vals <- sample(25:40, 10, replace = TRUE)
tracks   <- list('Age' = num_vals)
tracks   <- list('Age' = list(values = num_vals, colors = "greens"))
tracks   <- list('Age' = list(values = num_vals, range = c(0,50)))
tracks   <- list('Age' = list(
  label  = "Age (Years)",
  values = num_vals,
  colors = c("azure", "darkblue", "darkorchid") ))

## Multiple Tracks ------------------------
tracks <- list('Sex' = cat_vals, 'Age' = num_vals)
tracks <- list(
  list(label = "Sex", values = cat_vals, colors = "bright"),
  list(label = "Age", values = num_vals, colors = "greens") )


mtx           <- matrix(sample(1:50), ncol = 10)
dimnames(mtx) <- list(letters[1:5], LETTERS[1:10])
plot_heatmap(mtx = mtx, tracks = tracks)

The following entries in the track definitions are understood:

values -

The metadata values. When unnamed, order must match matrix.

range -

The c(min,max) to use for scale values.

label -

Label for this track. Defaults to the name of this list element.

side -

Options are "top" (default) or "left".

colors -

A pre-defined palette name or custom set of colors to map to.

na.color -

The color to use for NA values.

bins -

Bin a gradient into this many bins/steps.

guide -

A list of arguments for guide_colorbar() or guide_legend().

All built-in color palettes are colorblind-friendly.

The available categorical palette names are: "okabe", "carto", "r4", "polychrome", "tol", "bright", "light", "muted", "vibrant", "tableau", "classic", "alphabet", "tableau20", "kelly", and "fishy".

The available numeric palette names are: "reds", "oranges", "greens", "purples", "grays", "acton", "bamako", "batlow", "bilbao", "buda", "davos", "devon", "hawaii", "imola", "lajolla", "lapaz", "nuuk", "oslo", "tokyo", "turku", "bam", "berlin", "broc", "cork", "lisbon", "roma", "tofino", "vanimo", and "vik".

See Also

Other visualization: adiv_boxplot(), adiv_corrplot(), bdiv_boxplot(), bdiv_corrplot(), bdiv_heatmap(), bdiv_ord_plot(), rare_corrplot(), rare_multiplot(), rare_stacked(), stats_boxplot(), stats_corrplot(), taxa_boxplot(), taxa_corrplot(), taxa_heatmap(), taxa_stacked()

Examples

library(rbiom)

    set.seed(123)
    mtx <- matrix(runif(5*8), nrow = 5, dimnames = list(LETTERS[1:5], letters[1:8]))

    plot_heatmap(mtx)
    plot_heatmap(mtx, grid="oranges")
    plot_heatmap(mtx, grid=list(colors = "oranges", label = "Litres"))

    # Tracks go on top (one value per column) unless side = "left"
    # (one value per row).
    tracks <- list(
      'Number' = sample(1:ncol(mtx)),
      'Person' = list(
        values = factor(sample(c("Alice", "Bob"), ncol(mtx), TRUE)),
        colors = c('Alice' = "purple", 'Bob' = "darkcyan") ),
      'State' = list(
        side   = "left",
        values = sample(c("TX", "OR", "WA"), nrow(mtx), TRUE),
        colors = "bright" )
    )

    plot_heatmap(mtx, tracks=tracks)

Map sample names to metadata field values.

Description

Map sample names to metadata field values.

Usage

## S3 method for class 'rbiom'
pull(.data, var = -1, name = ".sample", ...)

Arguments

.data

An rbiom object, such as from as_rbiom().

var

The metadata field name specified as:

  • The metadata field name to retrieve. Can be abbreviated.

  • A positive integer, giving the position counting from the left.

  • A negative integer, giving the position counting from the right.

Default: -1

name

The column to be used as names for a named vector. Specified in a similar manner as var. Default: ".sample"

...

Not used.

Value

A vector of metadata values, named with sample names.

See Also

taxa_map()

Other samples: sample_sums()

Examples

library(rbiom)

    pull(hmp50, 'Age') %>% head()

    pull(hmp50, 'bod') %>% head(4)

Visualize rarefaction curves with scatterplots and trendlines.

Description

Visualize rarefaction curves with scatterplots and trendlines.

Usage

rare_corrplot(
  biom,
  adiv = "Shannon",
  layers = "tc",
  rline = TRUE,
  stat.by = NULL,
  facet.by = NULL,
  colors = TRUE,
  shapes = TRUE,
  test = "none",
  fit = "log",
  at = NULL,
  level = 0.95,
  p.adj = "fdr",
  transform = "none",
  alt = "!=",
  mu = 0,
  caption = TRUE,
  check = FALSE,
  cpus = n_cpus(),
  ...
)

Arguments

biom

An rbiom object, or any value accepted by as_rbiom().

adiv

Alpha diversity metric(s) to use. Options are: c("ace", "berger", "brillouin", "chao1", "faith", "fisher", "simpson", "inv_simpson", "margalef", "mcintosh", "menhinick", "observed", "shannon", "squares"). For "faith", a phylogenetic tree must be present in biom or explicitly provided via ⁠tree=⁠. Set adiv=".all" to use all metrics. Multiple/abbreviated values allowed. Default: "shannon"

layers

One or more of c("trend", "confidence", "point", "name", "residual"). Single letter abbreviations are also accepted. For instance, c("trend", "point") is equivalent to c("t", "p") and "tp". Default: "tc"

rline

Where to draw a vertical line on the plot, intended to show a particular rarefaction depth. Set to TRUE to show an auto-selected rarefaction depth, FALSE to not show a line, or an integer for a custom position. Default: TRUE

stat.by

Dataset field with the statistical groups. Must be categorical. Default: NULL

facet.by

Dataset field(s) to use for faceting. Must be categorical. Default: NULL

colors

How to color the groups. Options are:

TRUE -

Automatically select colorblind-friendly colors.

FALSE or NULL -

Don't use colors.

a palette name -

Auto-select colors from this set. E.g. "okabe"

character vector -

Custom colors to use. E.g. c("red", "#00FF00")

named character vector -

Explicit mapping. E.g. c(Male = "blue", Female = "red")

See "Aesthetics" section below for additional information. Default: TRUE

shapes

Shapes for each group. Options are similar to colors's: TRUE, FALSE, NULL, shape names (typically integers 0 - 17), or a named vector mapping groups to specific shape names. See "Aesthetics" section below for additional information. Default: TRUE

test

Method for computing p-values: 'none', 'emmeans', or 'emtrends'. See stats_table(). Default: 'emmeans'

fit

How to fit the trendline. Options are 'lm', 'log', and 'gam'. Default: 'log'

at

Position(s) along regr where group means or local slopes are evaluated. Default: NULL, which uses the median of regr within each split.by stratum. A vector gives one row per position, and p-values are adjusted across all of them. Ignored by tests that do not depend on a position (e.g. a global slope with fit = "lm").

level

The confidence level for calculating a confidence interval. Default: 0.95

p.adj

Method to use for multiple comparisons adjustment of p-values. Run p.adjust.methods for a list of available options. The adjustment spans every p-value in the returned table (all metrics, strata, pairs, and positions). Default: "fdr"

transform

Transformation to apply to calculated values. Options are: c("none", "rank", "log", "log1p", "sqrt"). "rank" is useful for correcting for non-normal distributions before applying regression statistics. Default: "none"

alt

Alternative hypothesis direction. Options are '!=' (two-sided; not equal to mu), '<' (less than mu), or '>' (greater than mu). Default: '!='

mu

Reference value to test against. Default: 0

caption

Add methodology caption beneath the plot. Default: TRUE

check

Generate additional plots to aid in assessing data normality. Default: FALSE

cpus

The number of CPUs to use. Set to NULL to use all available, or to 1 to disable parallel processing. Does not affect results. Default: ecodive::n_cpus() (all available cores)

...

Additional parameters to pass along to ggplot2 functions. Prefix a parameter name with a layer name to pass it to only that layer. For instance, p.size = 2 ensures only the points have their size set to 2. Unprefixed parameters go to every layer whose function accepts them. An argument that no layer accepts is an error.

Value

A ggplot2 plot. The computed data points, ggplot2 command, stats table, and stats table commands are available as ⁠$data⁠, ⁠$code⁠, ⁠$stats⁠, and ⁠$stats$code⁠, respectively.

Aesthetics

All built-in color palettes are colorblind-friendly. The available categorical palette names are: "okabe", "carto", "r4", "polychrome", "tol", "bright", "light", "muted", "vibrant", "tableau", "classic", "alphabet", "tableau20", "kelly", and "fishy".

Shapes can be given as per base R - numbers 0 through 17 for various shapes, or the decimal value of an ascii character, e.g. a-z = 65:90; A-Z = 97:122 to use letters instead of shapes on the plot. Character strings may used as well.

See Also

Other rarefaction: rare_multiplot(), rare_stacked(), sample_sums()

Other visualization: adiv_boxplot(), adiv_corrplot(), bdiv_boxplot(), bdiv_corrplot(), bdiv_heatmap(), bdiv_ord_plot(), plot_heatmap(), rare_multiplot(), rare_stacked(), stats_boxplot(), stats_corrplot(), taxa_boxplot(), taxa_corrplot(), taxa_heatmap(), taxa_stacked()

Examples

library(rbiom)

    biom <- subset(hmp50, `Body Site` %in% c('Saliva', 'Stool'))
    rare_corrplot(biom, stat.by = "body", adiv = c("sh", "o"), facet.by = "Sex")

Combines rare_corrplot and rare_stacked into a single figure.

Description

Combines rare_corrplot and rare_stacked into a single figure.

Usage

rare_multiplot(
  biom,
  adiv = "Shannon",
  layers = "tc",
  rline = TRUE,
  stat.by = NULL,
  facet.by = NULL,
  colors = TRUE,
  shapes = TRUE,
  test = "none",
  fit = "log",
  at = NULL,
  level = 0.95,
  p.adj = "fdr",
  transform = "none",
  alt = "!=",
  mu = 0,
  caption = TRUE,
  check = FALSE,
  cpus = n_cpus(),
  ...
)

Arguments

biom

An rbiom object, or any value accepted by as_rbiom().

adiv

Alpha diversity metric(s) to use. Options are: c("ace", "berger", "brillouin", "chao1", "faith", "fisher", "simpson", "inv_simpson", "margalef", "mcintosh", "menhinick", "observed", "shannon", "squares"). For "faith", a phylogenetic tree must be present in biom or explicitly provided via ⁠tree=⁠. Set adiv=".all" to use all metrics. Multiple/abbreviated values allowed. Default: "shannon"

layers

One or more of c("trend", "confidence", "point", "name", "residual"). Single letter abbreviations are also accepted. For instance, c("trend", "point") is equivalent to c("t", "p") and "tp". Default: "tc"

rline

Where to draw the rarefaction depth line on both plots. Set to TRUE to show an auto-selected rarefaction depth, FALSE to not show a line, or an integer for a custom position. Default: TRUE

stat.by

Dataset field with the statistical groups. Must be categorical. Default: NULL

facet.by

Dataset field(s) to use for faceting. Must be categorical. Default: NULL

colors

How to color the groups. Options are:

TRUE -

Automatically select colorblind-friendly colors.

FALSE or NULL -

Don't use colors.

a palette name -

Auto-select colors from this set. E.g. "okabe"

character vector -

Custom colors to use. E.g. c("red", "#00FF00")

named character vector -

Explicit mapping. E.g. c(Male = "blue", Female = "red")

See "Aesthetics" section below for additional information. Default: TRUE

shapes

Shapes for each group. Options are similar to colors's: TRUE, FALSE, NULL, shape names (typically integers 0 - 17), or a named vector mapping groups to specific shape names. See "Aesthetics" section below for additional information. Default: TRUE

test

Method for computing p-values: 'none', 'emmeans', or 'emtrends'. See stats_table(). Default: 'emmeans'

fit

How to fit the trendline. Options are 'lm', 'log', and 'gam'. Default: 'log'

at

Position(s) along regr where group means or local slopes are evaluated. Default: NULL, which uses the median of regr within each split.by stratum. A vector gives one row per position, and p-values are adjusted across all of them. Ignored by tests that do not depend on a position (e.g. a global slope with fit = "lm").

level

The confidence level for calculating a confidence interval. Default: 0.95

p.adj

Method to use for multiple comparisons adjustment of p-values. Run p.adjust.methods for a list of available options. The adjustment spans every p-value in the returned table (all metrics, strata, pairs, and positions). Default: "fdr"

transform

Transformation to apply to calculated values. Options are: c("none", "rank", "log", "log1p", "sqrt"). "rank" is useful for correcting for non-normal distributions before applying regression statistics. Default: "none"

alt

Alternative hypothesis direction. Options are '!=' (two-sided; not equal to mu), '<' (less than mu), or '>' (greater than mu). Default: '!='

mu

Reference value to test against. Default: 0

caption

Add methodology caption beneath the plot. Default: TRUE

check

Generate additional plots to aid in assessing data normality. Default: FALSE

cpus

The number of CPUs to use. Set to NULL to use all available, or to 1 to disable parallel processing. Does not affect results. Default: ecodive::n_cpus() (all available cores)

...

Additional parameters to pass along to ggplot2 functions. Prefix a parameter name with a layer name to pass it to only that layer. For instance, p.size = 2 ensures only the points have their size set to 2. Unprefixed parameters go to every layer whose function accepts them. An argument that no layer accepts is an error.

Value

A ggplot2 plot. The computed data points, ggplot2 command, stats table, and stats table commands are available as ⁠$data⁠, ⁠$code⁠, ⁠$stats⁠, and ⁠$stats$code⁠, respectively.

Aesthetics

All built-in color palettes are colorblind-friendly. The available categorical palette names are: "okabe", "carto", "r4", "polychrome", "tol", "bright", "light", "muted", "vibrant", "tableau", "classic", "alphabet", "tableau20", "kelly", and "fishy".

Shapes can be given as per base R - numbers 0 through 17 for various shapes, or the decimal value of an ascii character, e.g. a-z = 65:90; A-Z = 97:122 to use letters instead of shapes on the plot. Character strings may used as well.

See Also

Other rarefaction: rare_corrplot(), rare_stacked(), sample_sums()

Other visualization: adiv_boxplot(), adiv_corrplot(), bdiv_boxplot(), bdiv_corrplot(), bdiv_heatmap(), bdiv_ord_plot(), plot_heatmap(), rare_corrplot(), rare_stacked(), stats_boxplot(), stats_corrplot(), taxa_boxplot(), taxa_corrplot(), taxa_heatmap(), taxa_stacked()

Examples

library(rbiom)

    rare_multiplot(hmp50, stat.by = "Body Site")

Visualize the number of observations per sample.

Description

Visualize the number of observations per sample.

Usage

rare_stacked(
  biom,
  rline = TRUE,
  counts = TRUE,
  labels = TRUE,
  y.transform = "log10",
  ...
)

Arguments

biom

An rbiom object, or any value accepted by as_rbiom().

rline

Where to draw a horizontal line on the plot, intended to show a particular rarefaction depth. Set to TRUE to show an auto-selected rarefaction depth, FALSE to not show a line, or an integer for a custom position. Default: TRUE.

counts

Display the number of samples and reads remaining after rarefying to rline reads per sample. Default: TRUE.

labels

Show sample names under each bar. Default: TRUE.

y.transform

Y-axis transformation. Options are "log10" or "none". Default: "log10". Use xaxis.transform or yaxis.transform to pass custom values directly to ggplot2's ⁠scale_*⁠ functions.

...

Additional parameters to pass along to ggplot2 functions. Prefix a parameter name with r. to ensure it gets passed to (and only to) geom_hline. For instance, r.color = "black" ensures only the horizontal rarefaction line has its color set to "black".

Value

A ggplot2 plot. The computed data points and ggplot command are available as ⁠$data⁠ and ⁠$code⁠, respectively.

See Also

Other rarefaction: rare_corrplot(), rare_multiplot(), sample_sums()

Other visualization: adiv_boxplot(), adiv_corrplot(), bdiv_boxplot(), bdiv_corrplot(), bdiv_heatmap(), bdiv_ord_plot(), plot_heatmap(), rare_corrplot(), rare_multiplot(), stats_boxplot(), stats_corrplot(), taxa_boxplot(), taxa_corrplot(), taxa_heatmap(), taxa_stacked()

Examples

library(rbiom)

    rare_stacked(hmp50)

    rare_stacked(hmp50, rline = 500, r.linewidth = 2, r.linetype = "twodash")

    fig <- rare_stacked(hmp50, counts = FALSE)
    fig$code

Rarefy Counts to a Constant Depth

Description

This function reduces the number of observations (reads) in each sample to a fixed integer value (depth). Samples with fewer observations than the specified depth are discarded.

Rarefaction is a common technique in microbiome analysis used to account for uneven sequencing effort across samples. By standardizing the library size, it allows for fair comparisons of alpha and beta diversity metrics.

The transformation is recorded in the object's history (biom$code).

Usage

rarefy(
  biom,
  depth = NULL,
  seed = 0L,
  inflate = FALSE,
  clone = TRUE,
  cpus = n_cpus()
)

Arguments

biom

An rbiom object, or any value accepted by as_rbiom().

depth

The number of observations to keep per sample. Must be an integer greater than 0.

  • If NULL (the default), a depth is automatically selected that retains at least 10% of the dataset's total abundance while maximizing the number of samples kept. See suggest_rarefy_depth() for the specific heuristic used. The selected depth is recorded in biom$code.

  • Samples with total counts less than depth will be dropped from the result.

seed

Random seed for selecting which observations to keep. The same seed, depth, and input always give the same result. Must be a non-negative integer. Default: 0

inflate

Logical. Handling for non-integer data (e.g. relative abundances).

  • FALSE (Default): The function will error if non-integers are detected. Rarefaction requires discrete counts (integers).

  • TRUE: The function will automatically rescale (inflate) non-integers to integers using biom_inflate() before rarefying. This is useful for 'shoehorning' metagenomic relative abundance data into diversity functions that strictly require integers.

clone

Create a copy of biom before modifying. If FALSE, biom is modified in place as a side-effect. See speed ups for use cases. Default: TRUE

cpus

The number of CPUs to use. Set to NULL to use all available, or to 1 to disable parallel processing. Does not affect results. Default: ecodive::n_cpus() (all available cores)

Details

Normalizes the library sizes of a dataset by randomly sub-sampling observations from each sample to a specific depth.

Value

An rbiom object.

See Also

suggest_rarefy_depth() for details on the default depth selection.

Other transformations: biom_inflate(), biom_relativize(), biom_rescale(), modify_metadata, slice_metadata, subset, with

Examples

library(rbiom)

    biom <- hmp50[1:5]
    sample_sums(biom)

    # Rarefy to the lowest sample depth
    # (All samples are kept, but counts are reduced)
    biom_rare <- rarefy(biom, depth = min(sample_sums(biom)))
    sample_sums(biom_rare)

    # Auto-select depth (may drop samples with low coverage)
    biom_auto <- rarefy(biom)
    sample_sums(biom_auto)

    biom_auto$code

Parse counts, metadata, taxonomy, and phylogeny from a BIOM file.

Description

Parse counts, metadata, taxonomy, and phylogeny from a BIOM file.

Usage

read_biom(src, ...)

Arguments

src

Input data as either a file path, URL, or JSON string. BIOM files can be formatted according to version 1.0 (JSON) or 2.1 (HDF5) specifications, or as classical tabular format. URLs must begin with http://, https://, ftp://, or ftps://. JSON strings are recognized by their first non-whitespace character being {. Compressed (gzip or bzip2) BIOM files are also supported. NOTE: to read HDF5 formatted BIOM files, the h5lite R package must be installed.

...

Properties to set in the new rbiom object, for example, metadata, id, comment, or tree. These override the corresponding content of the file.

Details

The file's generated_by and date fields are kept in the returned object's ⁠$generated_by⁠ and ⁠$date⁠.

For classic tabular files, the first column must hold OTU IDs and a column named taxonomy (or lineage) is parsed into taxonomic ranks. All other columns are abundance counts: blank cells are read as 0 with a warning, and columns containing non-numeric text are ignored with a warning. Empty taxonomic ranks are NA.

Value

An rbiom object.

See Also

as_rbiom()

Examples

library(rbiom)

    infile <- system.file("extdata", "hmp50.bz2", package = "rbiom")
    biom <- read_biom(infile)

    print(biom)

    # Taxa Abundances
    biom$counts[1:4,1:10] %>% as.matrix()

    biom$taxonomy %>% head()

    # Metadata
    biom$metadata %>% head()

    table(biom$metadata$Sex, biom$metadata$`Body Site`)

    sprintf("Mean age: %.1f", mean(biom$metadata$Age))

    # Phylogenetic tree (plotting requires the 'ape' package)
    tree <- tree_subset(biom$tree, 1:10)
    tree
    if (requireNamespace("ape", quietly = TRUE))
      ape::plot.phylo(tree)

Parse a fasta file into a named character vector.

Description

Parse a fasta file into a named character vector.

Usage

read_fasta(file, ids = NULL)

Arguments

file

A file path, URL, or literal string with fasta-formatted sequences. Files can optionally be compressed with gzip or bzip2.

ids

Character vector of IDs to retrieve. The default, NULL, will retrieve everything.

Value

A named character vector in which names are the fasta headers (the text after > up to the first whitespace) and values are the sequences. Sequences spanning multiple lines are joined, and whitespace within sequences is removed.

Examples

library(rbiom)

    fasta <- ">OTU1 first sequence\nATCG\nGGCC\n>OTU2\nTTAA\n"
    read_fasta(fasta)

    outfile <- write_fasta(hmp50, tempfile(fileext = ".fna.gz"))
    seqs    <- read_fasta(outfile)
    unlink(outfile)

    identical(seqs, hmp50$sequences)

Read a newick formatted phylogenetic tree.

Description

A phylogenetic tree is required for computing UniFrac distance matrices. You can load a tree from a file or by providing the tree string directly. This tree must be in Newick format, also known as parenthetic format and New Hampshire format.

Usage

read_tree(src, underscores = FALSE)

Arguments

src

Input data as either a file path, URL, or Newick string. Compressed (gzip or bzip2) files are also supported.

underscores

When parsing the tree, should underscores be kept as is? By default they will be converted to spaces (unless the entire ID is quoted). Default FALSE

Details

Labels may be enclosed in single quotes, following the Newick standard: inside quotes every character is literal (including ⁠( ) [ ] : ; ,⁠ and whitespace), and '' stands for one apostrophe. Quoted labels are never altered by underscores. Outside quotes, ⁠[...]⁠ is a comment and is ignored. [write_tree()] quotes labels the same way, so trees round-trip exactly.

[ ]: R:%20 [...]: R:... [write_tree()]: R:write_tree()

Value

A phylo class object representing the tree.

See Also

Other phylogeny: tree_subset()

Examples

library(rbiom)

    infile <- system.file("extdata", "newick.tre", package = "rbiom")
    tree <- read_tree(infile)
    print(tree)

    tree <- read_tree("
        (A:0.99,((B:0.87,C:0.89):0.51,(((D:0.16,(E:0.83,F:0.96)
        :0.94):0.69,(G:0.92,(H:0.62,I:0.85):0.54):0.23):0.74,J:0.1
        2):0.43):0.67);")

    # Plotting a tree requires the 'ape' package.
    if (requireNamespace("ape", quietly = TRUE))
      ape::plot.phylo(tree)

Summarize the taxa observations in each sample.

Description

Summarize the taxa observations in each sample.

Usage

sample_sums(biom, rank = -1, sort = NULL, unc = "singly")

sample_apply(biom, FUN, rank = -1, sort = NULL, unc = "singly", ...)

Arguments

biom

An rbiom object, or any value accepted by as_rbiom().

rank

What rank(s) of taxa to display. E.g. "Phylum", "Genus", ".otu", etc. An integer vector can also be given, where 1 is the highest rank, 2 is the second highest, -1 is the lowest rank, -2 is the second lowest, and 0 is the OTU "rank". Run biom$ranks to see all options for a given rbiom object. Default: -1.

sort

Sort the result. Options: NULL - don't sort; "asc" - in ascending order (smallest to largest); "desc" - in descending order (largest to smallest). Ignored when the result is not a simple numeric vector. Default: NULL

unc

How to handle unclassified, uncultured, and similarly ambiguous taxa names. Options are:

"singly" -

Replaces them with the OTU name.

"grouped" -

Replaces them with a higher rank's name.

"drop" -

Excludes them from the result.

"asis" -

To not check/modify any taxa names.

Abbreviations are allowed. Default: "singly"

FUN

The function to apply to each column of taxa_matrix().

...

Optional arguments to FUN.

Value

For sample_sums, A named numeric vector of the number of observations in each sample. For sample_apply, a named vector or list with the results of FUN. The names are the taxa IDs.

See Also

Other samples: pull.rbiom()

Other rarefaction: rare_corrplot(), rare_multiplot(), rare_stacked()

Other taxa_abundance: taxa_boxplot(), taxa_clusters(), taxa_corrplot(), taxa_heatmap(), taxa_stacked(), taxa_stats(), taxa_sums(), taxa_table()

Examples

library(rbiom)
    library(ggplot2)

    sample_sums(hmp50, sort = 'asc') %>% head()

    # Unique OTUs and "cultured" classes per sample
    nnz <- function (x) sum(x > 0) # number of non-zeroes
    sample_apply(hmp50, nnz, 'otu') %>% head()
    sample_apply(hmp50, nnz, 'class', unc = 'drop') %>% head()

    # Number of reads in each sample's most abundant family
    sample_apply(hmp50, base::max, 'f', sort = 'desc') %>% head()

    ggplot() + geom_histogram(aes(x=sample_sums(hmp50)), bins = 20)

Subset to a specific number of samples.

Description

Subset to a specific number of samples.

Usage

## S3 method for class 'rbiom'
slice(.data, ..., .by = NULL, .preserve = FALSE, clone = TRUE)

## S3 method for class 'rbiom'
slice_head(.data, n, prop, by = NULL, clone = TRUE, ...)

## S3 method for class 'rbiom'
slice_tail(.data, n, prop, by = NULL, clone = TRUE, ...)

## S3 method for class 'rbiom'
slice_min(
  .data,
  order_by,
  n,
  prop,
  by = NULL,
  with_ties = TRUE,
  na_rm = FALSE,
  clone = TRUE,
  ...
)

## S3 method for class 'rbiom'
slice_max(
  .data,
  order_by,
  n,
  prop,
  by = NULL,
  with_ties = TRUE,
  na_rm = FALSE,
  clone = TRUE,
  ...
)

## S3 method for class 'rbiom'
slice_sample(
  .data,
  n,
  prop,
  by = NULL,
  weight_by = NULL,
  replace = FALSE,
  clone = TRUE,
  ...
)

Arguments

.data

An rbiom object, such as from as_rbiom().

...

For slice(), integer row indexes. For other ⁠slice_*()⁠ functions, not used. See dplyr::slice().

.by, by

<tidy-select> Optionally, a selection of columns to group by for just this operation, functioning as an alternative to group_by(). For details and examples, see ?dplyr_by.

.preserve

Relevant when the .data input is grouped. If .preserve = FALSE (the default), the grouping structure is recalculated based on the resulting data, otherwise the grouping is kept as is.

clone

Create a copy of biom before modifying. If FALSE, biom is modified in place as a side-effect. See speed ups for use cases. Default: TRUE

n, prop

Provide either n, the number of rows, or prop, the proportion of rows to select. If neither are supplied, n = 1 will be used. If n is greater than the number of rows in the group (or prop > 1), the result will be silently truncated to the group size. prop will be rounded towards zero to generate an integer number of rows.

A negative value of n or prop will be subtracted from the group size. For example, n = -2 with a group of 5 rows will select 5 - 2 = 3 rows; prop = -0.25 with 8 rows will select 8 * (1 - 0.25) = 6 rows.

order_by

<data-masking> Variable or function of variables to order by. To order by multiple variables, wrap them in a data frame or tibble.

with_ties

Should ties be kept together? The default, TRUE, may return more rows than you request. Use FALSE to ignore ties, and return the first n rows.

na_rm

Should missing values in order_by be removed from the result? If FALSE, NA values are sorted to the end (like in arrange()), so they will only be included if there are insufficient non-missing values to reach n/prop.

weight_by

<data-masking> Sampling weights. This must evaluate to a vector of non-negative numbers the same length as the input. Weights are automatically standardised to sum to 1. See the Details section for more technical details regarding these weights.

replace

Should sampling be performed with (TRUE) or without (FALSE, the default) replacement.

Value

An rbiom object.

See Also

Other transformations: biom_inflate(), biom_relativize(), biom_rescale(), modify_metadata, rarefy(), subset, with

Examples

library(rbiom)

    # The last 3 samples in the metadata table.
    biom <- slice_tail(hmp50, n = 3)
    biom$metadata

    # The 3 oldest subjects sampled.
    biom <- slice_max(hmp50, Age, n = 3)
    biom$metadata

    # Pick 3 samples at random.
    biom <- slice_sample(hmp50, n = 3)
    biom$metadata

Visualize categorical metadata effects on numeric values.

Description

Visualize categorical metadata effects on numeric values.

Usage

stats_boxplot(
  df,
  x = NULL,
  y = attr(df, "response"),
  layers = "x",
  stat.by = x,
  facet.by = NULL,
  colors = TRUE,
  shapes = TRUE,
  patterns = FALSE,
  test = "auto",
  flip = FALSE,
  stripe = NULL,
  ci = "ci",
  level = 0.95,
  p.adj = "fdr",
  p.top = Inf,
  outliers = NULL,
  xlab.angle = "auto",
  p.label = 0.05,
  strata = NULL,
  caption = TRUE,
  ...
)

Arguments

df

The dataset (data.frame or tibble object). "Dataset fields" mentioned below should match column names in df. Required.

x

A categorical metadata column name to use for the x-axis. Or NULL, which groups all samples into a single category.

y

A numeric metadata column name to use for the y-axis. Default: attr(df, 'response')

layers

One or more of c("bar", "box" ("x"), "violin", "dot", "strip", "crossbar", "errorbar", "linerange", "pointrange"). Single letter abbreviations are also accepted. For instance, c("box", "dot") is equivalent to c("x", "d") and "xd". Default: "x"

stat.by

Dataset field with the statistical groups. Must be categorical. Default: NULL

facet.by

Dataset field(s) to use for faceting. Must be categorical. Default: NULL

colors

How to color the groups. Options are:

TRUE -

Automatically select colorblind-friendly colors.

FALSE or NULL -

Don't use colors.

a palette name -

Auto-select colors from this set. E.g. "okabe"

character vector -

Custom colors to use. E.g. c("red", "#00FF00")

named character vector -

Explicit mapping. E.g. c(Male = "blue", Female = "red")

See "Aesthetics" section below for additional information. Default: TRUE

shapes

Shapes for each group. Options are similar to colors's: TRUE, FALSE, NULL, shape names (typically integers 0 - 17), or a named vector mapping groups to specific shape names. See "Aesthetics" section below for additional information. Default: TRUE

patterns

Patterns for each group. Options are similar to colors's: TRUE, FALSE, NULL, pattern names ("brick", "chevron", "fish", "grid", etc), or a named vector mapping groups to specific pattern names. See "Aesthetics" section below for additional information. Default: FALSE

test

Method for computing p-values. 'auto' runs pairwise Mann-Whitney U tests ('wilcox') when x and stat.by are the same field (or 'emmeans' when strata is given), and Kruskal-Wallis tests ('kruskal') across the stat.by groups within each x category otherwise. Beta diversity boxplots use PERMANOVA ('adonis2'), 'mrpp', or 'betadisper' on the samples instead. 'none' skips the statistics. See stats_table() and bdiv_stats(). Default: 'auto'

flip

Transpose the axes, so that taxa are present as rows instead of columns. Default: FALSE

stripe

Shade every other x position. Default: same as flip

ci

How to calculate min/max of the crossbar, errorbar, linerange, and pointrange layers. Options are: "ci" (confidence interval), "range", "sd" (standard deviation), "se" (standard error), and "mad" (median absolute deviation). The center mark of crossbar and pointrange represents the mean, except for "mad" in which case it represents the median. Intervals are drawn as computed, including below zero, unless the y-axis is transformed: bounds below zero are drawn at zero on a "sqrt" or "log1p" axis, and bounds at or below zero are drawn at the smallest positive y value on a log axis. Default: "ci"

level

The confidence level for calculating a confidence interval. Default: 0.95

p.adj

Method to use for multiple comparisons adjustment of p-values. Run p.adjust.methods for a list of available options. The adjustment spans every p-value in the returned table (all metrics, strata, pairs, and positions). Default: "fdr"

p.top

Only display taxa with the most significant differences in abundance. If p.top is >= 1, then the p.top most significant taxa are displayed. If p.top is less than one, all taxa with an adjusted p-value <= p.top are displayed. Recommended to be used in combination with the taxa parameter to set a lower bound on the mean abundance of considered taxa. Default: Inf

outliers

Show boxplot outliers? TRUE to always show. FALSE to always hide. NULL to only hide them when overlaying a dot or strip chart. Default: NULL

xlab.angle

Angle of the labels at the bottom of the plot. Options are "auto", '0', '30', and '90'. Default: "auto".

p.label

Minimum adjusted p-value to display on the plot with a bracket.

p.label = 0.05 -

Show p-values that are <= 0.05.

p.label = 0 -

Don't show any p-values on the plot.

p.label = 1 -

Show all p-values on the plot.

If a numeric vector with more than one value is provided, they will be used as breaks for asterisk notation. Default: 0.05

strata

Dataset field with the blocking/subject variable. Permutation tests permute within strata; regression models include a random intercept per stratum. Default: NULL

caption

Add methodology caption beneath the plot. Default: TRUE

...

Additional parameters to pass along to ggplot2 functions. Prefix a parameter name with a layer name to pass it to only that layer. For instance, d.size = 2 ensures only the points on the dot layer have their size set to 2. Unprefixed parameters go to every layer whose function accepts them (e.g. scales = "free" for the facets). An argument that no layer accepts is an error.

Value

A ggplot2 plot. The computed data points, ggplot2 command, stats table, and stats table commands are available as ⁠$data⁠, ⁠$code⁠, ⁠$stats⁠, and ⁠$stats$code⁠, respectively.

Aesthetics

All built-in color palettes are colorblind-friendly. The available categorical palette names are: "okabe", "carto", "r4", "polychrome", "tol", "bright", "light", "muted", "vibrant", "tableau", "classic", "alphabet", "tableau20", "kelly", and "fishy".

Patterns are added using the fillpattern R package, which must be installed to use patterns. Options are "brick", "chevron", "fish", "grid", "herringbone", "hexagon", "octagon", "rain", "saw", "shingle", "rshingle", "stripe", and "wave", optionally abbreviated and/or suffixed with modifiers. For example, "hex10_sm" for the hexagon pattern rotated 10 degrees and shrunk by 2x. See fillpattern::fill_pattern() for complete documentation of options.

Shapes can be given as per base R - numbers 0 through 17 for various shapes, or the decimal value of an ascii character, e.g. a-z = 65:90; A-Z = 97:122 to use letters instead of shapes on the plot. Character strings may used as well.

The dot and strip layers use the ggbeeswarm package when it is installed, and jittered points otherwise.

See Also

Other visualization: adiv_boxplot(), adiv_corrplot(), bdiv_boxplot(), bdiv_corrplot(), bdiv_heatmap(), bdiv_ord_plot(), plot_heatmap(), rare_corrplot(), rare_multiplot(), rare_stacked(), stats_corrplot(), taxa_boxplot(), taxa_corrplot(), taxa_heatmap(), taxa_stacked()

Examples

library(rbiom)

    df <- adiv_table(rarefy(hmp50))
    stats_boxplot(df, x = "Body Site")
    stats_boxplot(df, x = "Sex", stat.by = "Body Site", layers = "be")

Visualize regression with scatterplots and trendlines.

Description

Visualize regression with scatterplots and trendlines.

Usage

stats_corrplot(
  df,
  x,
  y = attr(df, "response"),
  layers = "tc",
  stat.by = NULL,
  facet.by = NULL,
  colors = TRUE,
  shapes = TRUE,
  test = "emmeans",
  fit = "gam",
  at = NULL,
  level = 0.95,
  p.adj = "fdr",
  p.top = Inf,
  alt = "!=",
  mu = 0,
  strata = NULL,
  caption = TRUE,
  check = FALSE,
  ...
)

Arguments

df

The dataset (data.frame or tibble object). "Dataset fields" mentioned below should match column names in df. Required.

x

Dataset field with the x-axis values. Equivalent to the regr argument in stats_table(). Required.

y

A numeric metadata column name to use for the y-axis. Default: attr(df, 'response')

layers

One or more of c("trend", "confidence", "point", "name", "residual"). Single letter abbreviations are also accepted. For instance, c("trend", "point") is equivalent to c("t", "p") and "tp". Default: "tc"

stat.by

Dataset field with the statistical groups. Must be categorical. Default: NULL

facet.by

Dataset field(s) to use for faceting. Must be categorical. Default: NULL

colors

How to color the groups. Options are:

TRUE -

Automatically select colorblind-friendly colors.

FALSE or NULL -

Don't use colors.

a palette name -

Auto-select colors from this set. E.g. "okabe"

character vector -

Custom colors to use. E.g. c("red", "#00FF00")

named character vector -

Explicit mapping. E.g. c(Male = "blue", Female = "red")

See "Aesthetics" section below for additional information. Default: TRUE

shapes

Shapes for each group. Options are similar to colors's: TRUE, FALSE, NULL, shape names (typically integers 0 - 17), or a named vector mapping groups to specific shape names. See "Aesthetics" section below for additional information. Default: TRUE

test

Method for computing p-values: 'none', 'emmeans', or 'emtrends'. See stats_table(). Default: 'emmeans'

fit

How to fit the trendline. 'lm', 'log', or 'gam'. Default: 'gam'

at

Position(s) along regr where group means or local slopes are evaluated. Default: NULL, which uses the median of regr within each split.by stratum. A vector gives one row per position, and p-values are adjusted across all of them. Ignored by tests that do not depend on a position (e.g. a global slope with fit = "lm").

level

The confidence level for calculating a confidence interval. Default: 0.95

p.adj

Method to use for multiple comparisons adjustment of p-values. Run p.adjust.methods for a list of available options. The adjustment spans every p-value in the returned table (all metrics, strata, pairs, and positions). Default: "fdr"

p.top

Only display taxa with the most significant differences in abundance. If p.top is >= 1, then the p.top most significant taxa are displayed. If p.top is less than one, all taxa with an adjusted p-value <= p.top are displayed. Recommended to be used in combination with the taxa parameter to set a lower bound on the mean abundance of considered taxa. Default: Inf

alt

Alternative hypothesis direction. Options are '!=' (two-sided; not equal to mu), '<' (less than mu), or '>' (greater than mu). Default: '!='

mu

Reference value to test against. Default: 0

strata

Dataset field with the blocking/subject variable. Permutation tests permute within strata; regression models include a random intercept per stratum. The plotted trendlines are descriptive fits without the strata term. Default: NULL

caption

Add methodology caption beneath the plot. Default: TRUE

check

Generate additional plots to aid in assessing data normality. Default: FALSE

...

Additional parameters to pass along to ggplot2 functions. Prefix a parameter name with a layer name to pass it to only that layer. For instance, p.size = 2 ensures only the points have their size set to 2. Unprefixed parameters go to every layer whose function accepts them. An argument that no layer accepts is an error.

Value

A ggplot2 plot. The computed data points, ggplot2 command, stats table, and stats table commands are available as ⁠$data⁠, ⁠$code⁠, ⁠$stats⁠, and ⁠$stats$code⁠, respectively.

Aesthetics

All built-in color palettes are colorblind-friendly. The available categorical palette names are: "okabe", "carto", "r4", "polychrome", "tol", "bright", "light", "muted", "vibrant", "tableau", "classic", "alphabet", "tableau20", "kelly", and "fishy".

Shapes can be given as per base R - numbers 0 through 17 for various shapes, or the decimal value of an ascii character, e.g. a-z = 65:90; A-Z = 97:122 to use letters instead of shapes on the plot. Character strings may used as well.

See Also

Other visualization: adiv_boxplot(), adiv_corrplot(), bdiv_boxplot(), bdiv_corrplot(), bdiv_heatmap(), bdiv_ord_plot(), plot_heatmap(), rare_corrplot(), rare_multiplot(), rare_stacked(), stats_boxplot(), taxa_boxplot(), taxa_corrplot(), taxa_heatmap(), taxa_stacked()

Examples

library(rbiom)

    biom <- subset(hmp50, `Body Site` %in% c('Saliva', 'Stool'))
    df   <- adiv_table(rarefy(biom))
    stats_corrplot(df, "age", stat.by = "body")
    stats_corrplot(
      df       = df,
      x        = "Age",
      stat.by  = "Body Site",
      facet.by = "Sex",
      layers   = "trend" )

Run statistics on a data.frame.

Description

A simple interface to lower-level statistics functions: stats::wilcox.test(), stats::kruskal.test(), emmeans::emmeans(), and emmeans::emtrends() on models fitted with stats::lm() or mgcv::gam(). The default test ("emmeans") is parametric; use "wilcox" or "kruskal" for rank-based tests.

Usage

stats_table(
  df,
  regr = NULL,
  resp = attr(df, "response"),
  stat.by = NULL,
  split.by = NULL,
  strata = NULL,
  test = "emmeans",
  fit = "gam",
  at = NULL,
  level = 0.95,
  alt = "!=",
  mu = 0,
  p.adj = "fdr"
)

Arguments

df

The dataset (data.frame or tibble object). "Dataset fields" mentioned below should match column names in df. Required.

regr

Dataset field with the x-axis (independent; predictive) values. Must be numeric. Default: NULL

resp

Dataset field with the y-axis (dependent; response) values, such as taxa abundance or alpha diversity. Default: attr(df, 'response')

stat.by

Dataset field with the statistical groups. Must be categorical. Default: NULL

split.by

Dataset field(s) that the data should be split by prior to any calculations. Must be categorical. Default: NULL

strata

Dataset field with a blocking variable, such as a subject identifier for repeated measures. Must be categorical. When given, regression models (test = "emmeans" or "emtrends") include a random intercept per stratum, fitted with mgcv::gam() as s(strata, bs = "re") (a linear mixed model for fit = "lm" and "log"). Not supported by the rank tests. Default: NULL

test

Method for computing p-values: 'wilcox', 'kruskal', 'emmeans', or 'emtrends'. Default: 'emmeans'

fit

How to fit the trendline. 'lm', 'log', or 'gam'. Default: 'gam'

at

Position(s) along regr where group means or local slopes are evaluated. Only used by test = "emmeans" with stat.by, and by test = "emtrends" with fit = "gam" (the other combinations test a single, global slope). Default: NULL, which evaluates at one prespecified position: the median of regr (computed within each split.by stratum). A vector evaluates at each position; the returned table then has one row per position, and the p-values are adjusted across all of them.

level

The confidence level for calculating a confidence interval. Default: 0.95

alt

Alternative hypothesis direction. Options are '!=' (two-sided; not equal to mu), '<' (less than mu), or '>' (greater than mu). Default: '!='

mu

Reference value to test against. Default: 0

p.adj

Method to use for multiple comparisons adjustment of p-values. Run p.adjust.methods for a list of available options. The adjustment spans the entire returned table: every combination of split.by strata, stat.by pairs, and at positions. Default: "fdr"

Value

A tibble data.frame with the fields below. The R code used to generate the statistics is in ⁠$code⁠.

Field Description
.mean Estimated marginal mean. See emmeans::emmeans().
.mean.diff Difference in means (first group minus second).
.slope Trendline slope. See emmeans::emtrends().
.slope.diff Difference in slopes (first group minus second).
.loc.shift Hodges-Lehmann estimate of the location shift between two groups (wilcox).
.pseudomedian Hodges-Lehmann estimate of the location (one-sample wilcox).
.h1 Alternative hypothesis.
.p.val The probability, under the null hypothesis, of a test statistic at least as extreme as the one observed.
.adj.p .p.val after adjusting for multiple comparisons across the whole table.
.effect.size Cohen's d effect size. See emmeans::eff_size().
.lower Confidence interval lower bound.
.upper Confidence interval upper bound.
.se Standard error.
.n Number of observations used.
.df Degrees of freedom.
.stat Wilcoxon or Kruskal-Wallis rank sum statistic.
.t.ratio t statistic: estimate divided by .se.
.edf, .ref.df Effective and reference degrees of freedom of the smooth term (gam).
.f F statistic for the smooth term (gam).
.r.sqr R-squared (lm); adjusted R-squared (gam).
.adj.r Adjusted R-squared (lm).
.dev.expl Proportion of deviance explained (gam).
.aic Akaike Information Criterion.
.bic Bayesian Information Criterion.
.loglik Log-likelihood of the fitted model.

Tests

Which quantity is tested depends on test and on whether regr and stat.by are given. Rows with an NA in any of the regr, resp, stat.by, split.by, or strata fields are dropped (with a message).

regr stat.by test = "emmeans" test = "emtrends"
no no mean of resp vs mu (not allowed)
no yes pairwise differences in group means (.mean.diff) (not allowed)
yes no fit = "lm"/"log": the slope's t-test (.slope). fit = "gam": the smooth term's approximate significance (.edf, .f) the slope at at (.slope; global for "lm"/"log", local for "gam")
yes yes pairwise differences in group means at at (.mean.diff) pairwise differences in slopes (.slope.diff; global for "lm"/"log", local at at for "gam")

For fit = "log", the slope is with respect to log(regr). mu and alt apply to the mean or slope being tested; they are ignored for pairwise comparisons (always ⁠!= 0⁠) and for the smooth-term test. Pairwise comparisons fit a separate model to each pair of groups. Without regr, fit is irrelevant: the model is resp ~ stat.by.

test = "wilcox" runs stats::wilcox.test() (one-sample against mu, or two-sample for each pair of stat.by groups) with exact = NULL, so R chooses an exact or normal-approximation p-value based on the sample sizes and ties. test = "kruskal" runs stats::kruskal.test() across all stat.by groups.

See Also

Other stats_tables: adiv_stats(), bdiv_stats(), distmat_stats(), taxa_stats()

Examples

library(rbiom)

    biom <- rarefy(hmp50)

    df <- taxa_table(biom, rank = "Family")
    stats_table(df, stat.by = "Body Site")[,1:6]

    df <- adiv_table(biom)
    stats_table(df, stat.by = "Sex", split.by = "Body Site")[,1:7]

    stats_table(df, regr = "Age", fit = "lm")

    # Repeated measures: a random intercept per subject.
    df <- adiv_table(babies)
    stats_table(df, regr = "Age", stat.by = "Delivery", strata = "Subject", fit = "lm")

Subset an rbiom object by sample names, OTU names, metadata, or taxonomy.

Description

Dropping samples or OTUs will lead to observations being removed from the OTU matrix (biom$counts). OTUs and samples with zero observations are automatically removed from the rbiom object.

Usage

## S3 method for class 'rbiom'
subset(x, subset, clone = TRUE, ...)

## S3 method for class 'rbiom'
x[i, j, ..., clone = TRUE, drop = FALSE]

## S3 method for class 'rbiom'
na.omit(object, fields = ".all", clone = TRUE, ...)

subset_taxa(x, subset, clone = TRUE, ...)

Arguments

x

An rbiom object, such as from as_rbiom().

subset

Logical expression for rows to keep. See base::subset(). As with base::subset(), NA values are treated as FALSE.

clone

Create a copy of biom before modifying. If FALSE, biom is modified in place as a side-effect. See speed ups for use cases. Default: TRUE

...

Not used.

i, j

The sample or OTU names to keep. Or a logical/integer vector indicating which sample names from biom$samples or biom$otus to keep. Subsetting with ⁠[i]⁠ takes i as samples, whereas ⁠[i,j]⁠ takes i as otus and j as samples (corresponding to ⁠[rows, cols]⁠ in the underlying biom$counts matrix).

drop

Not used

object

An rbiom object, such as from as_rbiom().

fields

Which metadata field(s) to check for NAs, or ".all" to check all metadata fields.

Value

An rbiom object.

See Also

Other transformations: biom_inflate(), biom_relativize(), biom_rescale(), modify_metadata, rarefy(), slice_metadata, with

Examples

library(rbiom)
    library(dplyr)

    # Subset to specific samples
    biom <- hmp50[c('HMP20', 'HMP42', 'HMP12')]
    biom$metadata

    # Subset to specific OTUs
    biom <- hmp50[c('LtbAci52', 'UncO2012'),] # <- Trailing ,
    biom$taxonomy

    # Subset to specific samples and OTUs
    biom <- hmp50[c('LtbAci52', 'UncO2012'), c('HMP20', 'HMP42', 'HMP12')]
    as.matrix(biom)

    # Subset samples according to metadata
    biom <- subset(hmp50, `Body Site` %in% c('Saliva') & Age < 25)
    biom$metadata

    # Subset OTUs according to taxonomy
    biom <- subset_taxa(hmp50, Phylum == 'Cyanobacteria')
    biom$taxonomy

    # Remove samples with NA metadata values
    biom <- mutate(hmp50, BS2 = na_if(`Body Site`, 'Saliva'))
    biom$metadata
    biom <- na.omit(biom)
    biom$metadata

    # The steps that produced an object are recorded.
    biom$code

Suggest Inflation Depths

Description

Estimates the optimal sequencing depth for each sample in a matrix by leveraging the global abundance distribution structure.

Usage

suggest_inflate_depths(biom, adjust = 1.5)

Arguments

biom

An rbiom object, or any value accepted by as_rbiom().

adjust

Numeric. Bandwidth adjustment for the kernel density estimation. Default: 1.5.

Value

A named integer vector of recommended depths for each sample.

The Singleton Peak Heuristic

When depth = NULL, biom_inflate() calls this function to estimate the original sequencing depth for each sample. The underlying assumption is that in typical microbiome datasets, the most frequent count value (the mode of the abundance distribution) is 1 (a singleton).

The algorithm works as follows:

  1. Log-Transformation: Non-zero relative abundances are log10-transformed.

  2. Global Consensus: To overcome sparsity in individual samples, distributions are centered by their medians and aggregated across all samples.

  3. Peak Detection: Kernel Density Estimation (KDE) is used to identify the peak (mode) of this aggregated distribution.

  4. Scaling: A scaling factor is calculated for each sample that shifts this peak to correspond to an integer count of 1.

This approach effectively "shoehorns" relative abundance data into integer formats required by diversity metrics (like rarefaction or Chao1) by maximizing the number of singletons in the resulting matrix.

Samples with fewer than two non-zero features carry no information about the distribution's shape; they are assigned the median depth of the other samples (or, if there are too few informative samples for the heuristic, every sample is scaled so that its smallest non-zero value becomes 1). Counts that are already integers are returned as their current sums.

See Also

biom_inflate() which uses this heuristic when depth = NULL.

Examples

library(rbiom)

    depths <- suggest_inflate_depths(biom_relativize(hmp50))
    head(depths)

Suggest Rarefaction Depth

Description

Calculates a rarefaction depth that balances retaining samples against retaining total observations.

Usage

suggest_rarefy_depth(biom)

Arguments

biom

An rbiom object, or any value accepted by as_rbiom().

Value

A single integer representing the suggested rarefaction depth.

Heuristic

This function selects a depth by analyzing the trade-off between dropping samples (to increase depth) and lowering depth (to keep samples).

  1. Calculate Yields: For every distinct sample depth in the dataset, calculate the total number of observations that would remain if the dataset were rarefied to that level.

    Yieldd=d×N≥dYield_d = d \times N_{\ge d}

    Where dd is the depth and N≥dN_{\ge d} is the number of samples with at least that many reads.

  2. Define Threshold: Calculate 10% of the total observations in the original un-rarefied dataset.

  3. Select Depth: Find the lowest depth dd where the YielddYield_d exceeds this 10% threshold.

This approach prioritizes keeping as many samples as possible, provided that doing so doesn't discard more than 90% of the dataset's total information.

See Also

rarefy() which uses this heuristic when depth = NULL.

Examples

library(rbiom)

    suggest_rarefy_depth(hmp50)

Visualize BIOM data with boxplots.

Description

Visualize BIOM data with boxplots.

Usage

taxa_boxplot(
  biom,
  x = NULL,
  rank = -1,
  layers = "x",
  taxa = 6,
  unc = "singly",
  other = FALSE,
  p.top = Inf,
  stat.by = x,
  facet.by = NULL,
  colors = TRUE,
  shapes = TRUE,
  patterns = FALSE,
  test = "auto",
  flip = FALSE,
  stripe = NULL,
  ci = "ci",
  level = 0.95,
  p.adj = "fdr",
  outliers = NULL,
  xlab.angle = "auto",
  p.label = 0.05,
  transform = "none",
  y.transform = "sqrt",
  strata = NULL,
  caption = TRUE,
  ...
)

Arguments

biom

An rbiom object, or any value accepted by as_rbiom().

x

A categorical metadata column name to use for the x-axis. Or NULL, which puts taxa along the x-axis. Default: NULL

rank

What rank(s) of taxa to display. E.g. "Phylum", "Genus", ".otu", etc. An integer vector can also be given, where 1 is the highest rank, 2 is the second highest, -1 is the lowest rank, -2 is the second lowest, and 0 is the OTU "rank". Run biom$ranks to see all options for a given rbiom object. Default: -1.

layers

One or more of c("bar", "box" ("x"), "violin", "dot", "strip", "crossbar", "errorbar", "linerange", "pointrange"). Single letter abbreviations are also accepted. For instance, c("box", "dot") is equivalent to c("x", "d") and "xd". Default: "x"

taxa

Which taxa to display. An integer value will show the top n most abundant taxa. A value 0 <= n < 1 will show any taxa with that mean abundance or greater (e.g. 0.1 implies >= 10%). A character vector of taxa names will show only those named taxa. Default: 6.

unc

How to handle unclassified, uncultured, and similarly ambiguous taxa names. Options are:

"singly" -

Replaces them with the OTU name.

"grouped" -

Replaces them with a higher rank's name.

"drop" -

Excludes them from the result.

"asis" -

To not check/modify any taxa names.

Abbreviations are allowed. Default: "singly"

other

Sum all non-itemized taxa into an "Other" taxa. When FALSE, only returns taxa matched by the taxa argument. Specifying TRUE adds "Other" to the returned set. A string can also be given to imply TRUE, but with that value as the name to use instead of "Other". Default: FALSE

p.top

Only display taxa with the most significant differences in abundance. If p.top is >= 1, then the p.top most significant taxa are displayed. If p.top is less than one, all taxa with an adjusted p-value <= p.top are displayed. Recommended to be used in combination with the taxa parameter to set a lower bound on the mean abundance of considered taxa. Default: Inf

stat.by

Dataset field with the statistical groups. Must be categorical. Default: NULL

facet.by

Dataset field(s) to use for faceting. Must be categorical. Default: NULL

colors

How to color the groups. Options are:

TRUE -

Automatically select colorblind-friendly colors.

FALSE or NULL -

Don't use colors.

a palette name -

Auto-select colors from this set. E.g. "okabe"

character vector -

Custom colors to use. E.g. c("red", "#00FF00")

named character vector -

Explicit mapping. E.g. c(Male = "blue", Female = "red")

See "Aesthetics" section below for additional information. Default: TRUE

shapes

Shapes for each group. Options are similar to colors's: TRUE, FALSE, NULL, shape names (typically integers 0 - 17), or a named vector mapping groups to specific shape names. See "Aesthetics" section below for additional information. Default: TRUE

patterns

Patterns for each group. Options are similar to colors's: TRUE, FALSE, NULL, pattern names ("brick", "chevron", "fish", "grid", etc), or a named vector mapping groups to specific pattern names. See "Aesthetics" section below for additional information. Default: FALSE

test

Method for computing p-values. 'auto' runs pairwise Mann-Whitney U tests ('wilcox') when x and stat.by are the same field (or 'emmeans' when strata is given), and Kruskal-Wallis tests ('kruskal') across the stat.by groups within each x category otherwise. Beta diversity boxplots use PERMANOVA ('adonis2'), 'mrpp', or 'betadisper' on the samples instead. 'none' skips the statistics. See stats_table() and bdiv_stats(). Default: 'auto'

flip

Transpose the axes, so that taxa are present as rows instead of columns. Default: FALSE

stripe

Shade every other x position. Default: same as flip

ci

How to calculate min/max of the crossbar, errorbar, linerange, and pointrange layers. Options are: "ci" (confidence interval), "range", "sd" (standard deviation), "se" (standard error), and "mad" (median absolute deviation). The center mark of crossbar and pointrange represents the mean, except for "mad" in which case it represents the median. Intervals are drawn as computed, including below zero, unless the y-axis is transformed: bounds below zero are drawn at zero on a "sqrt" or "log1p" axis, and bounds at or below zero are drawn at the smallest positive y value on a log axis. Default: "ci"

level

The confidence level for calculating a confidence interval. Default: 0.95

p.adj

Method to use for multiple comparisons adjustment of p-values. Run p.adjust.methods for a list of available options. The adjustment spans every p-value in the returned table (all metrics, strata, pairs, and positions). Default: "fdr"

outliers

Show boxplot outliers? TRUE to always show. FALSE to always hide. NULL to only hide them when overlaying a dot or strip chart. Default: NULL

xlab.angle

Angle of the labels at the bottom of the plot. Options are "auto", '0', '30', and '90'. Default: "auto".

p.label

Minimum adjusted p-value to display on the plot with a bracket.

p.label = 0.05 -

Show p-values that are <= 0.05.

p.label = 0 -

Don't show any p-values on the plot.

p.label = 1 -

Show all p-values on the plot.

If a numeric vector with more than one value is provided, they will be used as breaks for asterisk notation. Default: 0.05

transform

Transformation to apply to the abundance values. Options are: c("none", "rank", "log", "log1p", "sqrt", "percent"). "percent" (and relative-abundance data) labels the y-axis as percentages. Default: "none"

y.transform

The transformation to apply to the y-axis. Visualizing differences of both high- and low-abundance taxa is best done with a non-linear axis. Options are:

"sqrt" -

square-root transformation

"log1p" -

log(y + 1) transformation

"none" -

no transformation

These methods allow visualization of both high- and low-abundance taxa simultaneously, without complaint about 'zero' count observations. Default: "sqrt" Use xaxis.transform or yaxis.transform to pass custom values directly to ggplot2's ⁠scale_*⁠ functions.

strata

Dataset field with the blocking/subject variable. Permutation tests permute within strata; regression models include a random intercept per stratum. Default: NULL

caption

Add methodology caption beneath the plot. Default: TRUE

...

Additional parameters to pass along to ggplot2 functions. Prefix a parameter name with a layer name to pass it to only that layer. For instance, d.size = 2 ensures only the points on the dot layer have their size set to 2. Unprefixed parameters go to every layer whose function accepts them (e.g. scales = "free" for the facets). An argument that no layer accepts is an error.

Value

A ggplot2 plot. The computed data points, ggplot2 command, stats table, and stats table commands are available as ⁠$data⁠, ⁠$code⁠, ⁠$stats⁠, and ⁠$stats$code⁠, respectively.

Aesthetics

All built-in color palettes are colorblind-friendly. The available categorical palette names are: "okabe", "carto", "r4", "polychrome", "tol", "bright", "light", "muted", "vibrant", "tableau", "classic", "alphabet", "tableau20", "kelly", and "fishy".

Patterns are added using the fillpattern R package, which must be installed to use patterns. Options are "brick", "chevron", "fish", "grid", "herringbone", "hexagon", "octagon", "rain", "saw", "shingle", "rshingle", "stripe", and "wave", optionally abbreviated and/or suffixed with modifiers. For example, "hex10_sm" for the hexagon pattern rotated 10 degrees and shrunk by 2x. See fillpattern::fill_pattern() for complete documentation of options.

Shapes can be given as per base R - numbers 0 through 17 for various shapes, or the decimal value of an ascii character, e.g. a-z = 65:90; A-Z = 97:122 to use letters instead of shapes on the plot. Character strings may used as well.

The dot and strip layers use the ggbeeswarm package when it is installed, and jittered points otherwise.

See Also

Other taxa_abundance: sample_sums(), taxa_clusters(), taxa_corrplot(), taxa_heatmap(), taxa_stacked(), taxa_stats(), taxa_sums(), taxa_table()

Other visualization: adiv_boxplot(), adiv_corrplot(), bdiv_boxplot(), bdiv_corrplot(), bdiv_heatmap(), bdiv_ord_plot(), plot_heatmap(), rare_corrplot(), rare_multiplot(), rare_stacked(), stats_boxplot(), stats_corrplot(), taxa_corrplot(), taxa_heatmap(), taxa_stacked()

Examples

library(rbiom)

    biom <- rarefy(hmp50)

    taxa_boxplot(biom, stat.by = "Body Site", stripe = TRUE)
    taxa_boxplot(biom, layers = "bed", rank = c("Phylum", "Genus"), flip = TRUE)
    taxa_boxplot(
      biom    = subset(biom, `Body Site` %in% c('Saliva', 'Stool')),
      taxa    = 3,
      layers  = "ps",
      stat.by = "Body Site",
      colors  = c('Saliva' = "blue", 'Stool' = "red") )

Cluster samples by taxa abundances (k-means).

Description

Runs stats::kmeans() on the samples x taxa abundance matrix, with nstart = 10 random starts so that the partition is stable, and with the random number generator seeded by seed so that it is reproducible.

Usage

taxa_clusters(biom, rank = ".otu", k = 5, seed = 0, ...)

Arguments

biom

An rbiom object, or any value accepted by as_rbiom().

rank

Which taxa rank to use. E.g. "Phylum", "Genus", ".otu", etc. An integer can also be given, where 1 is the highest rank, 2 is the second highest, -1 is the lowest rank, -2 is the second lowest, and 0 is the OTU "rank". Run biom$ranks to see all options for a given rbiom object. Default: .otu.

k

Number of clusters. Default: 5L

seed

Random seed for the k-means starting centers. Default: 0

...

Passed on to stats::kmeans().

Value

A numeric factor assigning samples to clusters.

See Also

Other taxa_abundance: sample_sums(), taxa_boxplot(), taxa_corrplot(), taxa_heatmap(), taxa_stacked(), taxa_stats(), taxa_sums(), taxa_table()

Other clustering: bdiv_clusters()

Examples

library(rbiom)

    biom <- rarefy(hmp50)
    biom$metadata$otu_cluster <- taxa_clusters(biom)

    pull(biom, 'otu_cluster')[1:10]

    bdiv_ord_plot(biom, layers = "p", stat.by = "otu_cluster")

Visualize taxa abundance with scatterplots and trendlines.

Description

Visualize taxa abundance with scatterplots and trendlines.

Usage

taxa_corrplot(
  biom,
  x,
  rank = -1,
  layers = "tc",
  taxa = 6,
  lineage = FALSE,
  unc = "singly",
  other = FALSE,
  p.top = Inf,
  stat.by = NULL,
  facet.by = NULL,
  colors = TRUE,
  shapes = TRUE,
  test = "emmeans",
  fit = "gam",
  at = NULL,
  level = 0.95,
  p.adj = "fdr",
  transform = "none",
  ties = "random",
  seed = 0,
  alt = "!=",
  mu = 0,
  strata = NULL,
  caption = TRUE,
  check = FALSE,
  ...
)

Arguments

biom

An rbiom object, or any value accepted by as_rbiom().

x

Dataset field with the x-axis values. Equivalent to the regr argument in stats_table(). Required.

rank

What rank(s) of taxa to display. E.g. "Phylum", "Genus", ".otu", etc. An integer vector can also be given, where 1 is the highest rank, 2 is the second highest, -1 is the lowest rank, -2 is the second lowest, and 0 is the OTU "rank". Run biom$ranks to see all options for a given rbiom object. Default: -1.

layers

One or more of c("trend", "confidence", "point", "name", "residual"). Single letter abbreviations are also accepted. For instance, c("trend", "point") is equivalent to c("t", "p") and "tp". Default: "tc"

taxa

Which taxa to display. An integer value will show the top n most abundant taxa. A value 0 <= n < 1 will show any taxa with that mean abundance or greater (e.g. 0.1 implies >= 10%). A character vector of taxa names will show only those named taxa. Default: 6.

lineage

Include all ranks in the name of the taxa. For instance, setting to TRUE will produce ⁠Bacteria; Actinobacteria; Coriobacteriia; Coriobacteriales⁠. Otherwise the taxa name will simply be Coriobacteriales. You want to set this to TRUE when unc = "asis" and you have taxa names (such as Incertae_Sedis) that map to multiple higher level ranks. Default: FALSE

unc

How to handle unclassified, uncultured, and similarly ambiguous taxa names. Options are:

"singly" -

Replaces them with the OTU name.

"grouped" -

Replaces them with a higher rank's name.

"drop" -

Excludes them from the result.

"asis" -

To not check/modify any taxa names.

Abbreviations are allowed. Default: "singly"

other

Sum all non-itemized taxa into an "Other" taxa. When FALSE, only returns taxa matched by the taxa argument. Specifying TRUE adds "Other" to the returned set. A string can also be given to imply TRUE, but with that value as the name to use instead of "Other". Default: FALSE

p.top

Only display taxa with the most significant differences in abundance. If p.top is >= 1, then the p.top most significant taxa are displayed. If p.top is less than one, all taxa with an adjusted p-value <= p.top are displayed. Recommended to be used in combination with the taxa parameter to set a lower bound on the mean abundance of considered taxa. Default: Inf

stat.by

Dataset field with the statistical groups. Must be categorical. Default: NULL

facet.by

Dataset field(s) to use for faceting. Must be categorical. Default: NULL

colors

How to color the groups. Options are:

TRUE -

Automatically select colorblind-friendly colors.

FALSE or NULL -

Don't use colors.

a palette name -

Auto-select colors from this set. E.g. "okabe"

character vector -

Custom colors to use. E.g. c("red", "#00FF00")

named character vector -

Explicit mapping. E.g. c(Male = "blue", Female = "red")

See "Aesthetics" section below for additional information. Default: TRUE

shapes

Shapes for each group. Options are similar to colors's: TRUE, FALSE, NULL, shape names (typically integers 0 - 17), or a named vector mapping groups to specific shape names. See "Aesthetics" section below for additional information. Default: TRUE

test

Method for computing p-values: 'none', 'emmeans', or 'emtrends'. See stats_table(). Default: 'emmeans'

fit

How to fit the trendline. 'lm', 'log', or 'gam'. Default: 'gam'

at

Position(s) along regr where group means or local slopes are evaluated. Default: NULL, which uses the median of regr within each split.by stratum. A vector gives one row per position, and p-values are adjusted across all of them. Ignored by tests that do not depend on a position (e.g. a global slope with fit = "lm").

level

The confidence level for calculating a confidence interval. Default: 0.95

p.adj

Method to use for multiple comparisons adjustment of p-values. Run p.adjust.methods for a list of available options. The adjustment spans every p-value in the returned table (all metrics, strata, pairs, and positions). Default: "fdr"

transform

Transformation to apply to calculated values. Options are: c("none", "rank", "log", "log1p", "sqrt"). "rank" is useful for correcting for non-normal distributions before applying regression statistics. Default: "none"

ties

When transform="rank", how to rank identical values. Options are: c("average", "first", "last", "random", "max", "min"). See rank() for details. Default: "random"

seed

Random seed for permutations, rarefaction, random tie-breaking, and stochastic ordinations. Results are reproducible for a given seed, and the caller's random number generator state is left unchanged. Must be a non-negative integer. Default: 0

alt

Alternative hypothesis direction. Options are '!=' (two-sided; not equal to mu), '<' (less than mu), or '>' (greater than mu). Default: '!='

mu

Reference value to test against. Default: 0

strata

Dataset field with the blocking/subject variable. Permutation tests permute within strata; regression models include a random intercept per stratum. The plotted trendlines are descriptive fits without the strata term. Default: NULL

caption

Add methodology caption beneath the plot. Default: TRUE

check

Generate additional plots to aid in assessing data normality. Default: FALSE

...

Additional parameters to pass along to ggplot2 functions. Prefix a parameter name with a layer name to pass it to only that layer. For instance, p.size = 2 ensures only the points have their size set to 2. Unprefixed parameters go to every layer whose function accepts them. An argument that no layer accepts is an error.

Value

A ggplot2 plot. The computed data points, ggplot2 command, stats table, and stats table commands are available as ⁠$data⁠, ⁠$code⁠, ⁠$stats⁠, and ⁠$stats$code⁠, respectively.

Aesthetics

All built-in color palettes are colorblind-friendly. The available categorical palette names are: "okabe", "carto", "r4", "polychrome", "tol", "bright", "light", "muted", "vibrant", "tableau", "classic", "alphabet", "tableau20", "kelly", and "fishy".

Shapes can be given as per base R - numbers 0 through 17 for various shapes, or the decimal value of an ascii character, e.g. a-z = 65:90; A-Z = 97:122 to use letters instead of shapes on the plot. Character strings may used as well.

See Also

Other taxa_abundance: sample_sums(), taxa_boxplot(), taxa_clusters(), taxa_heatmap(), taxa_stacked(), taxa_stats(), taxa_sums(), taxa_table()

Other visualization: adiv_boxplot(), adiv_corrplot(), bdiv_boxplot(), bdiv_corrplot(), bdiv_heatmap(), bdiv_ord_plot(), plot_heatmap(), rare_corrplot(), rare_multiplot(), rare_stacked(), stats_boxplot(), stats_corrplot(), taxa_boxplot(), taxa_heatmap(), taxa_stacked()

Examples

library(rbiom)

    biom <- rarefy(subset(hmp50, `Body Site` %in% c('Buccal mucosa', 'Saliva')))
    taxa_corrplot(biom, x = "BMI", stat.by = "Body Site", taxa = 'Streptococcus')

Display taxa abundances as a heatmap.

Description

Display taxa abundances as a heatmap.

Usage

taxa_heatmap(
  biom,
  rank = -1,
  taxa = 6,
  tracks = NULL,
  grid = "bilbao",
  other = FALSE,
  unc = "singly",
  lineage = FALSE,
  label = TRUE,
  label_size = NULL,
  rescale = "none",
  trees = TRUE,
  clust = "complete",
  dist = "euclidean",
  asp = 1,
  tree_height = 10,
  track_height = 10,
  legend = "right",
  title = TRUE,
  xlab.angle = "auto",
  ...
)

Arguments

biom

An rbiom object, or any value accepted by as_rbiom().

rank

What rank(s) of taxa to display. E.g. "Phylum", "Genus", ".otu", etc. An integer vector can also be given, where 1 is the highest rank, 2 is the second highest, -1 is the lowest rank, -2 is the second lowest, and 0 is the OTU "rank". Run biom$ranks to see all options for a given rbiom object. Default: -1.

taxa

Which taxa to display. An integer value will show the top n most abundant taxa. A value 0 <= n < 1 will show any taxa with that mean abundance or greater (e.g. 0.1 implies >= 10%). A character vector of taxa names will show only those named taxa. Default: 6.

tracks

A character vector of metadata fields to display as tracks at the top of the plot. Or, a list as expected by the tracks argument of plot_heatmap(). Tracks describe samples, so they are always placed on top (side = "left" is ignored). Default: NULL

grid

Color palette name, or a list as expected plot_heatmap(). Default: "bilbao"

other

Sum all non-itemized taxa into an "Other" taxa. When FALSE, only returns taxa matched by the taxa argument. Specifying TRUE adds "Other" to the returned set. A string can also be given to imply TRUE, but with that value as the name to use instead of "Other". Default: FALSE

unc

How to handle unclassified, uncultured, and similarly ambiguous taxa names. Options are:

"singly" -

Replaces them with the OTU name.

"grouped" -

Replaces them with a higher rank's name.

"drop" -

Excludes them from the result.

"asis" -

To not check/modify any taxa names.

Abbreviations are allowed. Default: "singly"

lineage

Include all ranks in the name of the taxa. For instance, setting to TRUE will produce ⁠Bacteria; Actinobacteria; Coriobacteriia; Coriobacteriales⁠. Otherwise the taxa name will simply be Coriobacteriales. You want to set this to TRUE when unc = "asis" and you have taxa names (such as Incertae_Sedis) that map to multiple higher level ranks. Default: FALSE

label

Label the matrix rows and columns. You can supply a list or logical vector of length two to control row labels and column labels separately, for example label = c(rows = TRUE, cols = FALSE), or simply label = c(TRUE, FALSE). Other valid options are "rows", "cols", "both", "bottom", "right", and "none". Default: TRUE

label_size

The font size to use for the row and column labels. You can supply a numeric vector of length two to control row label sizes and column label sizes separately, for example c(rows = 20, cols = 8), or simply c(20, 8). Default: NULL, which computes: pmax(5, pmin(14, 100 / dim(mtx)))

rescale

Rescale rows or columns to all have a common min/max. Options: "none", "rows", or "cols". Default: "none"

trees

Draw a dendrogram for rows (left) and columns (top). You can supply a list or logical vector of length two to control the row tree and column tree separately, for example trees = c(rows = TRUE, cols = FALSE), or simply trees = c(TRUE, FALSE). Other valid options are "rows", "cols", "both", "left", "top", and "none". Default: TRUE

clust

Clustering algorithm for reordering the rows and columns by similarity. You can supply a list or character vector of length two to control the row and column clustering separately, for example clust = c(rows = "complete", cols = NA), or simply clust = c("complete", NA). Options are:

FALSE or NA -

Disable reordering.

An hclust class object

E.g. from stats::hclust().

A method name -

"ward.D", "ward.D2", "single", "complete", "average", "mcquitty", "median", or "centroid".

Default: "complete"

dist

Distance algorithm to use when reordering the rows and columns by similarity. You can supply a list or character vector of length two to control the row and column clustering separately, for example dist = c(rows = "euclidean", cols = "maximum"), or simply dist = c("euclidean", "maximum"). Options are:

A dist class object

E.g. from stats::dist() or bdiv_distmat().

A method name -

"euclidean", "maximum", "manhattan", "canberra", "binary", or "minkowski".

Default: "euclidean"

asp

Aspect ratio (height/width) for entire grid. Default: 1 (square)

tree_height, track_height

The height of the dendrogram or annotation tracks as a percentage of the overall grid size. Use a numeric vector of length two to assign c(top, left) independently. Default: 10 (10% of the grid's height)

legend

Where to place the legend. Options are: "right" or "bottom". Default: "right"

title

Plot title. Set to TRUE for a default title, NULL for no title, or any character string. Default: TRUE

xlab.angle

Angle of the labels at the bottom of the plot. Options are "auto", '0', '30', and '90'. Default: "auto".

...

Additional arguments to pass on to ggplot2::theme(). Arguments prefixed with labs. go to ggplot2::labs() instead, for example labs.subtitle = "Plot subtitle".

Value

A ggplot2 plot. The computed data points and ggplot command are available as ⁠$data⁠ and ⁠$code⁠, respectively.

Annotation Tracks

Metadata can be displayed as colored tracks above the heatmap. Common use cases are provided below, with more thorough documentation available at https://cmmr.github.io/rbiom .

## Categorical ----------------------------
tracks = "Body Site"
tracks = list('Body Site' = "bright")
tracks = list('Body Site' = c('Stool' = "blue", 'Saliva' = "green"))

## Numeric --------------------------------
tracks = "Age"
tracks = list('Age' = "reds")

## Multiple Tracks ------------------------
tracks = c("Body Site", "Age")
tracks = list('Body Site' = "bright", 'Age' = "reds")
tracks = list(
  'Body Site' = c('Stool' = "blue", 'Saliva' = "green"),
  'Age'       = list('colors' = "reds") )

The following entries in the track definitions are understood:

colors -

A pre-defined palette name or custom set of colors to map to.

range -

The c(min,max) to use for scale values.

label -

Label for this track. Defaults to the name of this list element.

side -

Options are "top" (default) or "left". taxa_heatmap() places all tracks on top.

na.color -

The color to use for NA values.

bins -

Bin a gradient into this many bins/steps.

guide -

A list of arguments for guide_colorbar() or guide_legend().

All built-in color palettes are colorblind-friendly.

Categorical palette names: "okabe", "carto", "r4", "polychrome", "tol", "bright", "light", "muted", "vibrant", "tableau", "classic", "alphabet", "tableau20", "kelly", and "fishy".

Numeric palette names: "reds", "oranges", "greens", "purples", "grays", "acton", "bamako", "batlow", "bilbao", "buda", "davos", "devon", "hawaii", "imola", "lajolla", "lapaz", "nuuk", "oslo", "tokyo", "turku", "bam", "berlin", "broc", "cork", "lisbon", "roma", "tofino", "vanimo", and "vik".

See Also

Other taxa_abundance: sample_sums(), taxa_boxplot(), taxa_clusters(), taxa_corrplot(), taxa_stacked(), taxa_stats(), taxa_sums(), taxa_table()

Other visualization: adiv_boxplot(), adiv_corrplot(), bdiv_boxplot(), bdiv_corrplot(), bdiv_heatmap(), bdiv_ord_plot(), plot_heatmap(), rare_corrplot(), rare_multiplot(), rare_stacked(), stats_boxplot(), stats_corrplot(), taxa_boxplot(), taxa_corrplot(), taxa_stacked()

Examples

library(rbiom)

    # Subset to 10 samples and rarefy them.
    hmp10 <- rarefy(hmp50[1:10])

    taxa_heatmap(hmp10, rank = "Phylum", tracks = "Body Site")

    taxa_heatmap(hmp10, rank = "Genus", tracks = c("sex", "bo"))

    taxa_heatmap(hmp10, rank = "Phylum", tracks = list(
      'Sex'       = list(colors = c(m = "#0000FF", f = "violetred")),
      'Body Site' = list(colors = "muted", label = "Source") ))

Map OTUs names to taxa names at a given rank.

Description

Map OTUs names to taxa names at a given rank.

Usage

taxa_map(
  biom,
  rank = NULL,
  taxa = Inf,
  unc = "singly",
  lineage = FALSE,
  other = FALSE
)

Arguments

biom

An rbiom object, or any value accepted by as_rbiom().

rank

When NULL, the entire biom$taxonomy data.frame is returned, transformed as per unc. Alternatively, a single taxonomic rank (rank name or integer position in biom$ranks) which returns a named character vector for mapping OTUs to taxa names.

taxa

Which taxa to keep in the mapping. An integer value keeps the top n most abundant taxa, and a value 0 <= n < 1 keeps taxa with that mean relative abundance or greater, both ranked exactly as in taxa_matrix(). A character vector of taxa names keeps only those taxa. OTUs belonging to other taxa are dropped from the mapping, or mapped to other when it is given. Default: Inf (all taxa)

unc

How to handle unclassified, uncultured, and similarly ambiguous taxa names. Options are:

"singly" -

Replaces them with the OTU name.

"grouped" -

Replaces them with a higher rank's name.

"drop" -

Excludes them from the result.

"asis" -

To not check/modify any taxa names.

Abbreviations are allowed. Default: "singly"

lineage

Include all ranks in the name of the taxa. For instance, setting to TRUE will produce ⁠Bacteria; Actinobacteria; Coriobacteriia; Coriobacteriales⁠. Otherwise the taxa name will simply be Coriobacteriales. You want to set this to TRUE when unc = "asis" and you have taxa names (such as Incertae_Sedis) that map to multiple higher level ranks. Default: FALSE

other

Sum all non-itemized taxa into an "Other" taxa. When FALSE, only returns taxa matched by the taxa argument. Specifying TRUE adds "Other" to the returned set. A string can also be given to imply TRUE, but with that value as the name to use instead of "Other". Default: FALSE

Value

A tibble data.frame when rank=NULL, or a character vector named with the OTU names.

See Also

pull.rbiom()

Examples

library(rbiom)
    library(dplyr, warn.conflicts = FALSE)

    # In $taxonomy, .otu is the first column (like a row identifier)  -----
    hmp50$taxonomy %>% head(4)

    # In taxa_map, .otu is the last column (most precise rank)  -----------
    taxa_map(hmp50) %>% head(4)

    # Generate an OTU to Genus mapping  -----------------------------------
    taxa_map(hmp50, "Genus") %>% head(4)

    # Keep the five most abundant OTUs; map the rest to "Other" -----------
    taxa_map(hmp50, ".otu", taxa = 5, other = TRUE) %>% table()

    # Sometimes taxonomic names are incomplete ----------------------------
    otus <- c('GemAsacc', 'GcbBacte', 'Unc58411')
    taxa_map(hmp50, unc = "asis") %>% filter(.otu %in% otus) %>% select(Phylum:.otu)

    # rbiom can replace them with unique placeholders ---------------------
    taxa_map(hmp50, unc = "singly") %>% filter(.otu %in% otus) %>% select(Class:.otu)

    # Or collapse them into groups ----------------------------------------
    taxa_map(hmp50, unc = "grouped") %>% filter(.otu %in% otus) %>% select(Class:Genus)

Display taxa abundances as a stacked bar graph.

Description

Display taxa abundances as a stacked bar graph.

Usage

taxa_stacked(
  biom,
  rank = -1,
  taxa = 6,
  colors = TRUE,
  patterns = FALSE,
  label.by = NULL,
  order.by = NULL,
  facet.by = NULL,
  dist = "euclidean",
  clust = "complete",
  other = TRUE,
  unc = "singly",
  lineage = FALSE,
  xlab.angle = 90,
  ...
)

Arguments

biom

An rbiom object, or any value accepted by as_rbiom().

rank

What rank(s) of taxa to display. E.g. "Phylum", "Genus", ".otu", etc. An integer vector can also be given, where 1 is the highest rank, 2 is the second highest, -1 is the lowest rank, -2 is the second lowest, and 0 is the OTU "rank". Run biom$ranks to see all options for a given rbiom object. Default: -1.

taxa

Which taxa to display. An integer value will show the top n most abundant taxa. A value 0 <= n < 1 will show any taxa with that mean abundance or greater (e.g. 0.1 implies >= 10%). A character vector of taxa names will show only those named taxa. Default: 6.

colors, patterns

A character vector of colors or patterns to use in the graph. A named character vector can be used to map taxon names to specific colors or patterns. Set to TRUE to auto-select colors or patterns, or to FALSE to disable per-taxa colors or patterns. Patterns require the fillpattern package. Default: colors=TRUE, patterns=FALSE.

label.by, order.by

What metadata column to use for labeling and/or sorting the samples across the x-axis. Set label.by='.sample' to display sample names. When order.by=NULL, samples are arranged based on dist and clust, below. Default: label.by=NULL, order.by=NULL.

facet.by

Dataset field(s) to use for faceting. Must be categorical. Default: NULL

dist, clust

Distance (stats::dist()) and clustering (stats::hclust()) methods to use for automatically arranging samples along the x-axis to put samples with similar composition near one another. Default: dist="euclidean", clust="complete".

other

Sum all non-itemized taxa into an "Other" taxa. When FALSE, only returns taxa matched by the taxa argument. Specifying TRUE adds "Other" to the returned set. A string can also be given to imply TRUE, but with that value as the name to use instead of "Other". Default: FALSE

unc

How to handle unclassified, uncultured, and similarly ambiguous taxa names. Options are:

"singly" -

Replaces them with the OTU name.

"grouped" -

Replaces them with a higher rank's name.

"drop" -

Excludes them from the result.

"asis" -

To not check/modify any taxa names.

Abbreviations are allowed. Default: "singly"

lineage

Include all ranks in the name of the taxa. For instance, setting to TRUE will produce ⁠Bacteria; Actinobacteria; Coriobacteriia; Coriobacteriales⁠. Otherwise the taxa name will simply be Coriobacteriales. You want to set this to TRUE when unc = "asis" and you have taxa names (such as Incertae_Sedis) that map to multiple higher level ranks. Default: FALSE

xlab.angle

Angle of the sample labels at the bottom of the plot. Options are "auto", 0, 30, and 90. Default: 90

...

Parameters for underlying functions. Prefixing parameter names with a layer name ensures that a particular parameter is passed to, and only to, that layer. An argument that no layer accepts is an error.

Details

If biom is rarefied (or holds relative abundances), then relative abundance will be shown on the y-axis. Otherwise, raw abundance will be displayed. Samples with NA values in label.by, order.by, or facet.by are dropped.

Value

A ggplot2 plot. The computed data points and ggplot command are available as ⁠$data⁠ and ⁠$code⁠, respectively.

See Also

Other taxa_abundance: sample_sums(), taxa_boxplot(), taxa_clusters(), taxa_corrplot(), taxa_heatmap(), taxa_stats(), taxa_sums(), taxa_table()

Other visualization: adiv_boxplot(), adiv_corrplot(), bdiv_boxplot(), bdiv_corrplot(), bdiv_heatmap(), bdiv_ord_plot(), plot_heatmap(), rare_corrplot(), rare_multiplot(), rare_stacked(), stats_boxplot(), stats_corrplot(), taxa_boxplot(), taxa_corrplot(), taxa_heatmap()

Examples

library(rbiom)

    biom <- rarefy(hmp50)

    taxa_stacked(biom, rank="Phylum")

    taxa_stacked(biom, rank = "genus", facet.by = "body site")

Test taxa abundances for associations with metadata.

Description

A convenience wrapper for taxa_table() + stats_table().

Usage

taxa_stats(
  biom,
  regr = NULL,
  stat.by = NULL,
  rank = -1,
  taxa = 6,
  lineage = FALSE,
  unc = "singly",
  other = FALSE,
  split.by = NULL,
  strata = NULL,
  transform = "none",
  test = "emmeans",
  fit = "gam",
  at = NULL,
  level = 0.95,
  alt = "!=",
  mu = 0,
  p.adj = "fdr"
)

Arguments

biom

An rbiom object, or any value accepted by as_rbiom().

regr

Dataset field with the x-axis (independent; predictive) values. Must be numeric. Default: NULL

stat.by

Dataset field with the statistical groups. Must be categorical. Default: NULL

rank

What rank(s) of taxa to display. E.g. "Phylum", "Genus", ".otu", etc. An integer vector can also be given, where 1 is the highest rank, 2 is the second highest, -1 is the lowest rank, -2 is the second lowest, and 0 is the OTU "rank". Run biom$ranks to see all options for a given rbiom object. Default: -1.

taxa

Which taxa to display. An integer value will show the top n most abundant taxa. A value 0 <= n < 1 will show any taxa with that mean abundance or greater (e.g. 0.1 implies >= 10%). A character vector of taxa names will show only those named taxa. Default: 6.

lineage

Include all ranks in the name of the taxa. For instance, setting to TRUE will produce ⁠Bacteria; Actinobacteria; Coriobacteriia; Coriobacteriales⁠. Otherwise the taxa name will simply be Coriobacteriales. You want to set this to TRUE when unc = "asis" and you have taxa names (such as Incertae_Sedis) that map to multiple higher level ranks. Default: FALSE

unc

How to handle unclassified, uncultured, and similarly ambiguous taxa names. Options are:

"singly" -

Replaces them with the OTU name.

"grouped" -

Replaces them with a higher rank's name.

"drop" -

Excludes them from the result.

"asis" -

To not check/modify any taxa names.

Abbreviations are allowed. Default: "singly"

other

Sum all non-itemized taxa into an "Other" taxa. When FALSE, only returns taxa matched by the taxa argument. Specifying TRUE adds "Other" to the returned set. A string can also be given to imply TRUE, but with that value as the name to use instead of "Other". Default: FALSE

split.by

Dataset field(s) that the data should be split by prior to any calculations. Must be categorical. Default: NULL

strata

Dataset field with a blocking variable, such as a subject identifier for repeated measures. Must be categorical. When given, regression models (test = "emmeans" or "emtrends") include a random intercept per stratum, fitted with mgcv::gam() as s(strata, bs = "re") (a linear mixed model for fit = "lm" and "log"). Not supported by the rank tests. Default: NULL

transform

Transformation to apply to calculated values. Options are: c("none", "rank", "log", "log1p", "sqrt"). "rank" is useful for correcting for non-normal distributions before applying regression statistics. Default: "none"

test

Method for computing p-values: 'wilcox', 'kruskal', 'emmeans', or 'emtrends'. Default: 'emmeans'

fit

How to fit the trendline. 'lm', 'log', or 'gam'. Default: 'gam'

at

Position(s) along regr where group means or local slopes are evaluated. Only used by test = "emmeans" with stat.by, and by test = "emtrends" with fit = "gam" (the other combinations test a single, global slope). Default: NULL, which evaluates at one prespecified position: the median of regr (computed within each split.by stratum). A vector evaluates at each position; the returned table then has one row per position, and the p-values are adjusted across all of them.

level

The confidence level for calculating a confidence interval. Default: 0.95

alt

Alternative hypothesis direction. Options are '!=' (two-sided; not equal to mu), '<' (less than mu), or '>' (greater than mu). Default: '!='

mu

Reference value to test against. Default: 0

p.adj

Method to use for multiple comparisons adjustment of p-values. Run p.adjust.methods for a list of available options. The adjustment spans the entire returned table: every combination of split.by strata, stat.by pairs, and at positions. Default: "fdr"

Value

A tibble data.frame with the fields below. The R code used to generate the statistics is in ⁠$code⁠.

Field Description
.mean Estimated marginal mean. See emmeans::emmeans().
.mean.diff Difference in means (first group minus second).
.slope Trendline slope. See emmeans::emtrends().
.slope.diff Difference in slopes (first group minus second).
.loc.shift Hodges-Lehmann estimate of the location shift between two groups (wilcox).
.pseudomedian Hodges-Lehmann estimate of the location (one-sample wilcox).
.h1 Alternative hypothesis.
.p.val The probability, under the null hypothesis, of a test statistic at least as extreme as the one observed.
.adj.p .p.val after adjusting for multiple comparisons across the whole table.
.effect.size Cohen's d effect size. See emmeans::eff_size().
.lower Confidence interval lower bound.
.upper Confidence interval upper bound.
.se Standard error.
.n Number of observations used.
.df Degrees of freedom.
.stat Wilcoxon or Kruskal-Wallis rank sum statistic.
.t.ratio t statistic: estimate divided by .se.
.edf, .ref.df Effective and reference degrees of freedom of the smooth term (gam).
.f F statistic for the smooth term (gam).
.r.sqr R-squared (lm); adjusted R-squared (gam).
.adj.r Adjusted R-squared (lm).
.dev.expl Proportion of deviance explained (gam).
.aic Akaike Information Criterion.
.bic Bayesian Information Criterion.
.loglik Log-likelihood of the fitted model.

Tests

Which quantity is tested depends on test and on whether regr and stat.by are given. Rows with an NA in any of the regr, resp, stat.by, split.by, or strata fields are dropped (with a message).

regr stat.by test = "emmeans" test = "emtrends"
no no mean of resp vs mu (not allowed)
no yes pairwise differences in group means (.mean.diff) (not allowed)
yes no fit = "lm"/"log": the slope's t-test (.slope). fit = "gam": the smooth term's approximate significance (.edf, .f) the slope at at (.slope; global for "lm"/"log", local for "gam")
yes yes pairwise differences in group means at at (.mean.diff) pairwise differences in slopes (.slope.diff; global for "lm"/"log", local at at for "gam")

For fit = "log", the slope is with respect to log(regr). mu and alt apply to the mean or slope being tested; they are ignored for pairwise comparisons (always ⁠!= 0⁠) and for the smooth-term test. Pairwise comparisons fit a separate model to each pair of groups. Without regr, fit is irrelevant: the model is resp ~ stat.by.

test = "wilcox" runs stats::wilcox.test() (one-sample against mu, or two-sample for each pair of stat.by groups) with exact = NULL, so R chooses an exact or normal-approximation p-value based on the sample sizes and ties. test = "kruskal" runs stats::kruskal.test() across all stat.by groups.

See Also

Other taxa_abundance: sample_sums(), taxa_boxplot(), taxa_clusters(), taxa_corrplot(), taxa_heatmap(), taxa_stacked(), taxa_sums(), taxa_table()

Other stats_tables: adiv_stats(), bdiv_stats(), distmat_stats(), stats_table()

Examples

library(rbiom)

    biom <- rarefy(hmp50)

    taxa_stats(biom, stat.by = "Body Site", rank = "Family")[,1:6]

Get summary taxa abundances.

Description

Get summary taxa abundances.

Usage

taxa_sums(
  biom,
  rank = -1,
  sort = NULL,
  lineage = FALSE,
  unc = "singly",
  transform = "none"
)

taxa_means(
  biom,
  rank = -1,
  sort = NULL,
  lineage = FALSE,
  unc = "singly",
  transform = "none"
)

taxa_apply(
  biom,
  FUN,
  rank = -1,
  sort = NULL,
  lineage = FALSE,
  unc = "singly",
  transform = "none",
  ...
)

Arguments

biom

An rbiom object, or any value accepted by as_rbiom().

rank

What rank(s) of taxa to display. E.g. "Phylum", "Genus", ".otu", etc. An integer vector can also be given, where 1 is the highest rank, 2 is the second highest, -1 is the lowest rank, -2 is the second lowest, and 0 is the OTU "rank". Run biom$ranks to see all options for a given rbiom object. Default: -1.

sort

Sort the result. Options: NULL, "asc", or "desc", where NULL will not sort the result. "asc" will sort in ascending order (smallest to largest), and "desc" in descending order (largest to smallest). Ignored when the result is not a simple numeric vector. Default: NULL

lineage

Include all ranks in the name of the taxa. For instance, setting to TRUE will produce ⁠Bacteria; Actinobacteria; Coriobacteriia; Coriobacteriales⁠. Otherwise the taxa name will simply be Coriobacteriales. You want to set this to TRUE when unc = "asis" and you have taxa names (such as Incertae_Sedis) that map to multiple higher level ranks. Default: FALSE

unc

How to handle unclassified, uncultured, and similarly ambiguous taxa names. Options are:

"singly" -

Replaces them with the OTU name.

"grouped" -

Replaces them with a higher rank's name.

"drop" -

Excludes them from the result.

"asis" -

To not check/modify any taxa names.

Abbreviations are allowed. Default: "singly"

transform

Transformation to apply to calculated values. Options are: c("none", "rank", "log", "log1p", "sqrt"). "rank" is useful for correcting for non-normal distributions before applying regression statistics. Default: "none"

FUN

The function to apply to each row of the taxa_matrix().

...

Optional arguments to FUN.

Value

For taxa_sums and taxa_means, a named numeric vector. For taxa_apply, a named vector or list with the results of FUN. The names are the taxa IDs.

See Also

Other taxa_abundance: sample_sums(), taxa_boxplot(), taxa_clusters(), taxa_corrplot(), taxa_heatmap(), taxa_stacked(), taxa_stats(), taxa_table()

Examples

library(rbiom)

    taxa_sums(hmp50) %>% head(4)

    taxa_means(hmp50, 'Family') %>% head(5)

    taxa_apply(hmp50, max) %>% head(5)

    taxa_apply(hmp50, fivenum) %>% head(5)

Taxa abundances per sample.

Description

taxa_matrix() -

Accepts a single rank and returns a matrix.

taxa_table() -

Can accept more than one rank and returns a tibble data.frame.

Usage

taxa_table(
  biom,
  rank = -1,
  taxa = 6,
  lineage = FALSE,
  md = ".all",
  unc = "singly",
  other = FALSE,
  transform = "none",
  ties = "random",
  seed = 0
)

taxa_matrix(
  biom,
  rank = -1,
  taxa = NULL,
  lineage = FALSE,
  sparse = FALSE,
  unc = "singly",
  other = FALSE,
  transform = "none",
  ties = "random",
  seed = 0
)

Arguments

biom

An rbiom object, or any value accepted by as_rbiom().

rank

What rank(s) of taxa to display. E.g. "Phylum", "Genus", ".otu", etc. An integer vector can also be given, where 1 is the highest rank, 2 is the second highest, -1 is the lowest rank, -2 is the second lowest, and 0 is the OTU "rank". Run biom$ranks to see all options for a given rbiom object. Default: -1.

taxa

Which taxa to display. An integer value will show the top n most abundant taxa. A value 0 <= n < 1 will show any taxa with that mean abundance or greater (e.g. 0.1 implies >= 10%). A character vector of taxa names will show only those named taxa. Default: 6.

lineage

Include all ranks in the name of the taxa. For instance, setting to TRUE will produce ⁠Bacteria; Actinobacteria; Coriobacteriia; Coriobacteriales⁠. Otherwise the taxa name will simply be Coriobacteriales. You want to set this to TRUE when unc = "asis" and you have taxa names (such as Incertae_Sedis) that map to multiple higher level ranks. Default: FALSE

md

Dataset field(s) to include in the output data frame, or '.all' to include all metadata fields. Default: '.all'

unc

How to handle unclassified, uncultured, and similarly ambiguous taxa names. Options are:

"singly" -

Replaces them with the OTU name.

"grouped" -

Replaces them with a higher rank's name.

"drop" -

Excludes them from the result.

"asis" -

To not check/modify any taxa names.

Abbreviations are allowed. Default: "singly"

other

Sum all non-itemized taxa into an "Other" taxa. When FALSE, only returns taxa matched by the taxa argument. Specifying TRUE adds "Other" to the returned set. A string can also be given to imply TRUE, but with that value as the name to use instead of "Other". Default: FALSE

transform

Transformation to apply to the abundance values. Options are: c("none", "rank", "log", "log1p", "sqrt", "percent"). "percent" converts counts to relative abundances before summing by taxa. "log" adds a pseudocount of half the smallest non-zero value in the matrix before taking the logarithm, so that absent taxa rank below the rarest observed ones. "rank" is useful for correcting for non-normally distributions before applying regression statistics. Default: "none"

ties

When transform="rank", how to rank identical values. Options are: c("average", "first", "last", "random", "max", "min"). See rank() for details. Default: "random"

seed

Random seed for permutations, rarefaction, random tie-breaking, and stochastic ordinations. Results are reproducible for a given seed, and the caller's random number generator state is left unchanged. Must be a non-negative integer. Default: 0

sparse

If TRUE, returns a sparse matrix from the Matrix package, otherwise returns a normal R matrix object. Default: FALSE

Value

taxa_matrix() -

A numeric matrix with taxa as rows, and samples as columns.

taxa_table() -

A tibble data frame with column names .sample, .taxa, .abundance, and any requested by md.

Each result carries ⁠$code⁠: the R code that regenerates it, including the steps that produced biom.

See Also

Other taxa_abundance: sample_sums(), taxa_boxplot(), taxa_clusters(), taxa_corrplot(), taxa_heatmap(), taxa_stacked(), taxa_stats(), taxa_sums()

Examples

library(rbiom)

    hmp50$ranks

    taxa_matrix(hmp50, 'Phylum')[1:4,1:6]

    taxa_table(hmp50, 'Phylum')

Create a subtree by specifying tips to keep.

Description

Internal nodes left with a single descendant are collapsed (their branch lengths are summed), node labels are kept, and the result is rooted at the most recent common ancestor of the retained tips. Tips are kept in their original order regardless of the order of tips.

Usage

tree_subset(tree, tips, underscores = FALSE)

Arguments

tree

A phylo object, as returned from read_tree().

tips

A character, numeric, or logical vector of tips to keep.

underscores

When parsing the tree, should underscores be kept as is? By default they will be converted to spaces (unless the entire ID is quoted). Default FALSE

Value

A phylo object for the subtree.

See Also

Other phylogeny: read_tree()

Examples

library(rbiom)

    infile <- system.file("extdata", "newick.tre", package = "rbiom")
    tree <- read_tree(infile)
    tree

    subtree <- tree_subset(tree, tips = head(tree$tip.label))
    subtree

Evaluate expressions on metadata.

Description

with() will return the result of your expression. within() will return an rbiom object.

Usage

## S3 method for class 'rbiom'
with(data, expr, ...)

## S3 method for class 'rbiom'
within(data, expr, clone = TRUE, ...)

Arguments

data

An rbiom object, such as from as_rbiom().

expr

Passed on to base::with() or base::within().

...

Not used.

clone

Create a copy of biom before modifying. If FALSE, biom is modified in place as a side-effect. See speed ups for use cases. Default: TRUE

Value

See description.

See Also

Other transformations: biom_inflate(), biom_relativize(), biom_rescale(), modify_metadata, rarefy(), slice_metadata, subset

Examples

library(rbiom)

    with(hmp50, table(`Body Site`, Sex))

    biom <- within(hmp50, {
      age_bin = cut(Age, 5)
      bmi_bin = cut(BMI, 5)
    })
    biom$metadata

Save an rbiom object to a file.

Description

Automatically creates directories and adds compression based on file name.

write_biom() -

According to BIOM format specification.

write_xlsx() -

Raw data and summary tables in Excel file format. See details.

write_fasta() -

Sequences only in fasta format. biom may also be a named character vector.

write_tree() -

Phylogenetic tree only in newick format. biom may also be a phylo object.

write_counts(), write_metadata(), write_taxonomy() -

Tab-separated values.

Usage

write_biom(biom, file, format = "json", overwrite = FALSE)

write_metadata(biom, file, quote = FALSE, sep = "\t", overwrite = FALSE, ...)

write_counts(biom, file, quote = FALSE, sep = "\t", overwrite = FALSE, ...)

write_taxonomy(biom, file, quote = FALSE, sep = "\t", overwrite = FALSE, ...)

write_fasta(biom, file = NULL, overwrite = FALSE)

write_tree(biom, file = NULL, overwrite = FALSE)

write_xlsx(
  biom,
  file,
  depth = NULL,
  seed = 0,
  unc = "singly",
  overwrite = FALSE
)

Arguments

biom

An rbiom object, or any value accepted by as_rbiom().

file

Path to the output file. File names ending in .gz or .bz2 will be compressed accordingly. Setting file=NULL for write_fasta(), write_tree(), and write_biom(format='json') returns a string of the output which would have been written. For write_biom(format='tab'), file=NULL returns the tibble that would have been written.

format

Options are "tab", "json", and "hdf5", corresponding to classic tabular format, BIOM format version 1.0 and biom version 2.1, respectively. NOTE: to write HDF5 formatted BIOM files, the h5lite R package must be installed. Default: "json"

overwrite

Replace file if it already exists? All of the writers refuse to overwrite an existing file unless overwrite = TRUE. Default: FALSE

quote, sep, ...

Parameters passed on to write.table(). Default: ⁠quote=FALSE, sep="\t"⁠

depth

Passed on to rarefy(). For write_xlsx() only, depth=0 disables rarefaction. Default: NULL

seed

Random seed to use in rarefying. See rarefy() function for details. Must be a non-negative integer. Default: 0

unc

How to handle unclassified, uncultured, and similarly ambiguous taxa names. Options are:

"singly" -

Replaces them with the OTU name.

"grouped" -

Replaces them with a higher rank's name.

"drop" -

Excludes them from the result.

"asis" -

To not check/modify any taxa names.

Abbreviations are allowed. Default: "singly"

Details

Output is first written to a temporary file in the same directory and then moved into place, so a failed write never leaves a partial file behind.

In the tabular ("tab") format, OTU IDs, sample names and taxonomy strings that contain a tab, a double quote, or a line break are enclosed in double quotes (with embedded quotes doubled), and missing taxonomic ranks are written as empty strings. In the JSON format, numbers are written at full precision and missing values are null. In the HDF5 format, the order of metadata fields, logical fields, and Date fields (stored as ISO 8601 strings) are preserved through attributes on the datasets, which other BIOM readers ignore.

For write_xlsx(), attributes(biom) are saved as additional worksheets if the attribute is a data frame, matrix, or dist -class object. An attribute named 'Reads Per Step' is treated specially and merged with the usual 'Reads Per Sample' tab.

Value

The normalized filepath that was written to (invisibly), unless file=NULL (see file argument above).

Examples

library(rbiom)

    write_tree(hmp50) %>% substr(1, 50)

    outfile <- write_biom(hmp50, tempfile(fileext = ".biom.gz"))
    file.size(outfile)
    unlink(outfile)

    if (requireNamespace("openxlsx", quietly = TRUE)) {

      hmp10 <- rarefy(hmp50[1:10])

      attr(hmp10, "Weighted UniFrac") <- bdiv_distmat(hmp10, 'weighted_unifrac')
      attr(hmp10, "Jaccard")          <- bdiv_distmat(hmp10, 'jaccard')

      outfile <- write_xlsx(hmp10, tempfile(fileext = ".xlsx"))
      unlink(outfile)
    }