| Title: | Chromatographic Data Analysis Toolkit |
|---|---|
| Description: | Analyzes chromatographic data from high performance liquid chromatography with diode-array or ultraviolet detection (HPLC-DAD/UV), as well as other detectors, in a high-throughput and reproducible workflow. Provides functionality for preprocessing, alignment, peak detection, peak model fitting, peak table construction, and data visualization. Chromatogram alignment is available via parametric time warping (as implemented in 'ptw') or variable penalty dynamic time warping (as implemented in 'VPdtw'). Peak detection is based on a first-derivative zero-crossing algorithm, and peak shapes are fitted using non-linear least squares. Underlying methodologies are described in: Wehrens et al. (2015) <doi:10.1007/s11306-014-0683-5> for preprocessing and peak table construction; Eilers (2004) <doi:10.1021/ac034800e> and Wehrens et al. (2015) <doi:10.1093/bioinformatics/btv299> for parametric time warping; Clifford & Stone (2012) <doi:10.18637/jss.v047.i08> for variable penalty dynamic time warping; Tom O'Haver <https://terpconnect.umd.edu/~toh/spectrum/PeakFindingandMeasurement.htm> for peak detection; Lan & Jorgenson (2001) <doi:10.1016/S0021-9673(01)00594-5> for exponential-Gaussian hybrid fitting; and Naish & Hartwell (1988) <doi:10.1007/BF02268168> for bi-exponentially modified Gaussian fitting. |
| Authors: | Ethan Bass [aut, cre, cph] (ORCID: <https://orcid.org/0000-0002-6175-6739>), Hans W Borchers [ctb, cph] (Author of savgol and pinv functions bundled from pracma), Ron Wehrens [ctb, cph] (Author of code adapted from alsace and ptw) |
| Maintainer: | Ethan Bass <[email protected]> |
| License: | GPL (>= 2) |
| Version: | 0.9.0 |
| Built: | 2026-11-13 21:20:49 UTC |
| Source: | https://github.com/ethanbass/chromatographR |
Analyzes chromatographic data from high performance liquid chromatography with diode-array or ultraviolet detection (HPLC-DAD/UV), as well as other detectors, in a high-throughput and reproducible workflow. Provides functionality for preprocessing, alignment, peak detection, peak model fitting, peak table construction, and data visualization.
A typical workflow includes signal preprocessing and peak table construction following general approaches described in Wehrens et al. (2015).
Chromatogram alignment is implemented using parametric time warping (PTW) or variable penalty dynamic time warping (VPdtw).
Peak detection is based on zero-crossings in smoothed derivatives. Peaks are then modeled using Gaussian, exponential-Gaussian hybrid, or bidirectional exponentially modified Gaussian peak functions via nonlinear least squares, or integrated directly from the signal.
Further details and example workflows are provided in the package vignettes.
read_chroms(): Import chromatograms from a variety of vendor formats.
preprocess(): Preprocess chromatographic matrices.
correct_baseline(): Estimate and subtract a baseline.
crop_chroms(): Restrict chromatograms to a range of times or wavelengths.
subtract_blanks(): Subtract blank chromatograms.
correct_rt(): Align chromatograms.
get_peaks(): Find and integrate peaks.
get_peaktable(): Assemble peak table.
attach_metadata(): Attach metadata to peak table.
attach_ref_spectra(): Attach reference spectra to peak table.
normalize_data(): Normalize peak_table or chrom_list.
get_purity(): Calculate peak purity.
combine_peaks(): Combine duplicate peaks based on retention time and spectral similarity.
merge_peaks(): Merge split peaks into a single feature in a peak table.
filter_peaktable(): Filter peak features in a peak table.
filter_peaks(): Filter peaks in peak lists.
plot_chroms(): Plot chromatograms as traces.
plot_chroms_heatmap(): Plot chromatograms as heatmap.
annotate_peaks(): Add peak labels to chromatogram plots.
mirror_plot(): Plot chromatograms as mirror plots.
plot_baseline(): Plot an estimated baseline over its trace.
plot.ptw_list(): Plot parametric time warping (PTW) alignment object.
plot_spectrum(): Plot spectrum and/or trace of specified peak.
plot_spectrum_inset(): Plot spectrum over chromatogram.
plot_all_spectra(): Plot all spectra for specified peak.
scan_chrom(): Interactively extract spectra from a chromatogram.
plot.peak_list(): Plot fitted peaks over chromatographic trace.
plot.peak_table(): Plot chromatograms and/or spectra from a peak table.
boxplot.peak_table(): Create boxplot from a peak table object.
get_times(): Return retention times from a peak table or a list of chromatograms.
get_lambdas(): Return wavelengths from a peak table or a list of chromatograms.
get_time_resolution(): Return the sampling interval of a chromatogram.
get_baseline(): Retrieve a baseline retained by preprocessing.
write_peaktable(): Export peak table to CSV or XLSX format.
reshape_chroms(): Reshape a list of chromatograms to long format.
reshape_peaktable(): Reshape a peak table to long format.
Sa: A list of four goldenrod root chromatograms.
Sa_pr: Preprocessed goldenrod root chromatograms.
Sa_warp: Preprocessed and aligned goldenrod root chromatograms.
pk_tab: Peak table from aligned goldenrod root chromatograms.
Ethan Bass
Clifford, D., Stone, G., Montoliu, I., Rezzi, S., Martin, F. P., Guy, P., Bruce, S., & Kochhar, S. 2009. Alignment using variable penalty dynamic time warping. Analytical chemistry, 81(3):1000-1007. doi:10.1021/ac802041e.
Clifford, D., & Stone, G. 2012. Variable Penalty Dynamic Time Warping Code for Aligning Mass Spectrometry Chromatograms in R. Journal of Statistical Software, 47(8):1-17. doi:10.18637/jss.v047.i08.
Eilers, P.H.C. 2004. Parametric Time Warping. Analytical Chemistry, 76:404-411. doi:10.1021/ac034800e.
Wehrens, R., Bloemberg, T.G., and Eilers P.H.C. 2015. Fast parametric time warping of peak lists. Bioinformatics, 31:3063-3065. doi:10.1093/bioinformatics/btv299.
Wehrens, R., Carvalho, E., Fraser, P.D. 2015. Metabolite profiling in LC–DAD using multivariate curve resolution: the alsace package for R. Metabolomics, 11:143-154. doi:10.1007/s11306-014-0683-5.
Useful links:
Report bugs at https://github.com/ethanbass/chromatographR/issues/
Subsets a matched_peak_list while preserving metadata attributes.
## S3 method for class 'matched_peak_list' x[i, j, ..., drop = FALSE]## S3 method for class 'matched_peak_list' x[i, j, ..., drop = FALSE]
x |
A |
i |
Indices specifying elements to extract. |
j |
Not used. |
... |
Additional arguments (ignored). |
drop |
Not used. |
A matched_peak_list object.
Ethan Bass
Subsets a peak_list while preserving metadata attributes.
## S3 method for class 'peak_list' x[i, j, ..., drop = FALSE]## S3 method for class 'peak_list' x[i, j, ..., drop = FALSE]
x |
A |
i |
Indices specifying elements to extract. |
j |
Not used. |
... |
Additional arguments (ignored). |
drop |
Not used. |
A peak_list object.
Ethan Bass
Subsets a peak_table while preserving and subsetting all associated
slots (tab, pk_meta, sample_meta, instrument_meta, ref_spectra).
## S3 method for class 'peak_table' x[i, j, ..., drop = FALSE]## S3 method for class 'peak_table' x[i, j, ..., drop = FALSE]
x |
A |
i |
Row indices (samples) to subset. |
j |
Column indices (peaks) to subset. |
... |
Additional arguments (ignored). |
drop |
Passed to the |
A peak_table object.
Subsetting a peak_table does not modify the associated chrom_list.
Methods that rely on the chrom_list (e.g., plot_spectrum) may not work
as expected on a subsetted peak_table unless the chrom_list is subsetted
separately.
Ethan Bass
Adds text labels to peaks on a chromatogram plot produced by
plot_chroms(). Peaks named in a peak table are labeled at their
retention time, above the highest point of the chromatograms in idx
between the peak's start and end. Peaks given as retention times are
labeled at that time, above the highest plotted point within tol of it,
and need no peak table; the label then marks the tallest trace in that
window, whichever peak it belongs to.
annotate_peaks( p, loc, peak_table = NULL, chrom_list = NULL, label = NULL, lambda = NULL, idx = NULL, tol = 0.05, vjust = -0.5, ... )annotate_peaks( p, loc, peak_table = NULL, chrom_list = NULL, label = NULL, lambda = NULL, idx = NULL, tol = 0.05, vjust = -0.5, ... )
p |
A |
loc |
Either a character vector of peak names from |
peak_table |
A |
chrom_list |
A list of chromatograms in matrix format (timepoints ×
wavelengths). If no argument is provided here, the function will try to find
the |
label |
Labels to display at each peak. Can be a character vector of
labels (one per peak), or |
lambda |
Wavelength(s) to use for locating the peak apex. Inherited
from |
idx |
Index of chromatogram(s) to use for locating the peak apex.
Inherited from
|
tol |
Half-width of the window around each retention time in which the
highest plotted point is found, in minutes. Defaults to |
vjust |
Vertical justification of the label relative to the peak apex.
Defaults to |
... |
Additional arguments passed to |
A ggplot object.
plot_chroms(), plot_spectrum_inset()
if (requireNamespace("ggplot2", quietly = TRUE)) { data(Sa_warp) data(pk_tab) plot_chroms(Sa_warp, lambdas = 210, engine = "ggplot") |> annotate_peaks(c(C1="V7", C2="V9", C3="V15"), peak_table = pk_tab) plot_chroms(Sa_warp, lambdas = 210, engine = "ggplot") |> annotate_peaks(c(C1 = 12.18, C2 = 12.70)) }if (requireNamespace("ggplot2", quietly = TRUE)) { data(Sa_warp) data(pk_tab) plot_chroms(Sa_warp, lambdas = 210, engine = "ggplot") |> annotate_peaks(c(C1="V7", C2="V9", C3="V15"), peak_table = pk_tab) plot_chroms(Sa_warp, lambdas = 210, engine = "ggplot") |> annotate_peaks(c(C1 = 12.18, C2 = 12.70)) }
peak_table
Matches rows of metadata to samples by name and stores them in the
sample_meta slot, in the same order as the rows of peak_table$tab.
Samples missing from metadata get NA values, with a warning. Columns
already in sample_meta, such as fields added to the chromatograms with
chromConverter::add_metadata() (chromConverter 0.11.0 or later), are kept
unless metadata replaces them.
To replace sample_meta entirely, set peak_table$sample_meta <- NA first.
attach_metadata(peak_table, metadata, column)attach_metadata(peak_table, metadata, column)
peak_table |
A |
metadata |
A |
column |
Name of the column in |
A peak_table object with metadata stored in the sample_meta slot.
Ethan Bass
data(pk_tab) path <- system.file("extdata", "Sa_metadata.csv", package = "chromatographR") meta <- read.csv(path) pk_tab <- attach_metadata(peak_table = pk_tab, metadata = meta, column="vial")data(pk_tab) path <- system.file("extdata", "Sa_metadata.csv", package = "chromatographR") meta <- read.csv(path) pk_tab <- attach_metadata(peak_table = pk_tab, metadata = meta, column="vial")
peak_table objectFor each peak, selects one sample's spectrum as the reference: either the
spectrum with the highest mean correlation to that peak's spectra in the
other samples ("max.cor"), or the spectrum from the sample where the peak
is most intense ("max.int"). Spectra are scaled before they are stored.
attach_ref_spectra(peak_table, chrom_list, ref = c("max.cor", "max.int"))attach_ref_spectra(peak_table, chrom_list, ref = c("max.cor", "max.int"))
peak_table |
A |
chrom_list |
Optional list of chromatograms (timepoints × wavelengths).
If omitted, the function attempts to retrieve the original |
ref |
Method for selecting reference spectra: |
A peak_table object with reference spectra stored in the
$ref_spectra slot.
Ethan Bass
data(pk_tab) data(Sa_warp) pk_tab <- attach_ref_spectra(pk_tab, ref = "max.int") pk_tab <- attach_ref_spectra(pk_tab, ref = "max.cor")data(pk_tab) data(Sa_warp) pk_tab <- attach_ref_spectra(pk_tab, ref = "max.int") pk_tab <- attach_ref_spectra(pk_tab, ref = "max.cor")
Reference for the baseline estimators available through the baseline
argument of preprocess and correct_baseline.
A baseline is estimated separately for each wavelength, since the drift
differs across the spectrum. Which estimator performs best depends on the
noise, the drift, and how crowded the trace is, and a smoothing parameter
that suits one chromatogram need not suit another. Rather than choosing on
general grounds, fit a baseline and look at it: set attach_baseline = TRUE
in preprocess or correct_baseline and plot the estimate with
plot_baseline, as in the examples below.
| Estimator | Parameters (defaults) | Asymmetry | Overshoots | Scope |
"als" (default) |
stiffness (1e7)p (0.001) |
fixed | yes | global |
"arpls" |
stiffness (1e7) |
adaptive | yes | global |
"aspls" |
stiffness (1e9)k (0.5) |
adaptive | yes | global |
"snip" |
m (required) |
fixed | no | local |
"als" is asymmetric least squares, as implemented by
asysm. A Whittaker smoother is fit to the signal with
residuals above the fit weighted by p and residuals below it by 1 - p.
p is fixed for the whole trace, so the asymmetry is set in advance rather
than taken from the data.
"arpls" is asymmetrically reweighted penalized least squares (Baek et
al. 2015). It uses the same Whittaker solve, but replaces the fixed p with
weights computed at each iteration from the mean and standard deviation of
the negative residuals, so the asymmetry follows the trace. On very clean
traces it can fail to follow steep drift, and the baseline falls below the
trace where the drift is steepest.
"aspls" is adaptive smoothness parameter penalized least squares (Zhang
et al. 2020). It keeps the re-weighting and additionally scales the penalty
at each timepoint by the normalized absolute residual, so the fit is
stiffest where residuals are largest and most flexible where they are
smallest. Since that scaling is at most one, it lowers the effective
penalty. Accordingly, the default stiffness is set 100 times higher than
the other two estimators and a value tuned for "als" or "arpls" will
under-smooth. The best conversion varies by trace, so retune stiffness
rather than rescaling it.
"snip" is Statistics-sensitive Non-linear Iterative Peak-clipping
(Ryan et al. 1988). Its baseline follows variation broader than its
2m + 1 timepoint window and passes beneath narrower features, such as
peaks. Two of its properties follow from its construction: the estimate can never exceed the
signal, so the corrected trace is non-negative; and each point depends only
on the 2m + 1 window around it, so a distortion in one part of the trace
cannot propagate along it the way it can through a global solve.
"als" and "snip" are both one-sided: the first weights positive
residuals down by a fixed factor, the second cannot exceed the signal at
all. Both therefore fit below the center of the noise, which leaves the
corrected trace biased high. The bias is a constant offset in signal units,
so it inflates small peaks proportionally more than large ones. "arpls"
and "aspls" take their asymmetry from the residuals instead and fit closer
to the center of the noise.
Parameters are passed to the estimator through the ... of preprocess
or correct_baseline.
stiffness ("als", "arpls", "aspls") is the smoothing penalty.
Larger values give a stiffer, smoother baseline. It acts between adjacent
timepoints, so the same value spans a different stretch of time on a
differently sampled trace; retune it if you change the sampling interval.
The defaults are starting points, not calibrated optima.
p ("als") is the weight given to points above the fit, and 1 - p
the weight given to points below it. At the default of 0.001, points
above the fit, which are mostly peaks, barely pull on it.
k ("aspls") sets the steepness of the weighting curve. Larger values
switch more abruptly between points treated as baseline and points treated
as peak.
m ("snip") is the half-width of the clipping window, in timepoints.
It has no default: the window has to be wider than the peaks it clips,
which depends on your chromatography.
The "aspls" implementation follows pybaselines (Erb 2025) at two points
that Zhang et al. leave open: the default asymmetric coefficient k is
0.5 rather than the 2 printed in the paper, and the second-difference
matrix is left-multiplied by the diagonal matrix of per-timepoint penalty
scalings, an ordering the paper's notation does not settle.
Ethan Bass
Baek, S.-J., Park, A., Ahn, Y.-J., and Choo, J. 2015. Baseline correction using asymmetrically reweighted penalized least squares smoothing. Analyst 140:250-257. doi:10.1039/C4AN01061B.
Zhang, F., Tang, X., Tong, A., Wang, B., Wang, J., Lv, Y., Tang, C., and Wang, J. 2020. Baseline correction for infrared spectra using adaptive smoothness parameter penalized least squares method. Spectroscopy Letters 53:222-233. doi:10.1080/00387010.2020.1730908.
Ryan, C.G., Clayton, E., Griffin, W.L., Sie, S.H., and Cousens, D.R. 1988. SNIP, a statistics-sensitive background treatment for the quantitative analysis of PIXE spectra in geoscience applications. Nuclear Instruments and Methods in Physics Research B 34:396-402. doi:10.1016/0168-583X(88)90063-8.
Erb, D. 2025. pybaselines: A Python library of algorithms for the baseline correction of experimental data. doi:10.5281/zenodo.5608581.
preprocess, correct_baseline, plot_baseline,
get_baseline
data(Sa) als <- preprocess(Sa[1], dim1 = seq(10, 18, by = .01), dim2 = seq(200, 318, by = 2), attach_baseline = TRUE, show_progress = FALSE, cl = 1) snip <- preprocess(Sa[1], dim1 = seq(10, 18, by = .01), dim2 = seq(200, 318, by = 2), baseline = "snip", m = 50, attach_baseline = TRUE, show_progress = FALSE, cl = 1) plot_baseline(als, lambda = 210, annotate = FALSE) plot_baseline(snip, lambda = 210, col = "blue", add = TRUE) legend("topright", legend = c("als", "snip"), col = c("red", "blue"), lwd = 2)data(Sa) als <- preprocess(Sa[1], dim1 = seq(10, 18, by = .01), dim2 = seq(200, 318, by = 2), attach_baseline = TRUE, show_progress = FALSE, cl = 1) snip <- preprocess(Sa[1], dim1 = seq(10, 18, by = .01), dim2 = seq(200, 318, by = 2), baseline = "snip", m = 50, attach_baseline = TRUE, show_progress = FALSE, cl = 1) plot_baseline(als, lambda = 210, annotate = FALSE) plot_baseline(snip, lambda = 210, col = "blue", add = TRUE) legend("topright", legend = c("als", "snip"), col = c("red", "blue"), lwd = 2)
The function can take multiple response variables on the left hand side of the
formula (separated by +). In this case, a separate boxplot will be
produced for each response variable.
## S3 method for class 'peak_table' boxplot(x, formula, ...)## S3 method for class 'peak_table' boxplot(x, formula, ...)
x |
A |
formula |
A formula object. |
... |
Additional arguments to |
No return value, called for side effects.
Creates a boxplot according to the provided formula, using data from the
supplied peak_table object.
Ethan Bass
Other visualization functions:
mirror_plot(),
plot.chrom_list(),
plot.matched_peak_list(),
plot.peak_list(),
plot.peak_table(),
plot_all_spectra(),
plot_chrom_contour(),
plot_chroms(),
plot_chroms_heatmap(),
plot_spectrum(),
scan_chrom()
data(pk_tab) path <- system.file("extdata", "Sa_metadata.csv", package = "chromatographR") meta <- read.csv(path) pk_tab <- attach_metadata(peak_table = pk_tab, metadata = meta, column="vial") boxplot(pk_tab, formula=V9 ~ trt)data(pk_tab) path <- system.file("extdata", "Sa_metadata.csv", package = "chromatographR") meta <- read.csv(path) pk_tab <- attach_metadata(peak_table = pk_tab, metadata = meta, column="vial") boxplot(pk_tab, formula=V9 ~ trt)
Cluster peaks by spectral similarity.
cluster_spectra( peak_table, alpha = 0.05, min_size = 5, max_size = NULL, nboot = 1000, plot_dend = TRUE, plot_spectra = TRUE, verbose = getOption("verbose"), outfile = NULL, save = NULL, parallel = TRUE, max.only = FALSE, output = c("pvclust", "clusters"), col = palette.colors(palette = "Okabe-Ito")[-c(1, 5, 9)], ... )cluster_spectra( peak_table, alpha = 0.05, min_size = 5, max_size = NULL, nboot = 1000, plot_dend = TRUE, plot_spectra = TRUE, verbose = getOption("verbose"), outfile = NULL, save = NULL, parallel = TRUE, max.only = FALSE, output = c("pvclust", "clusters"), col = palette.colors(palette = "Okabe-Ito")[-c(1, 5, 9)], ... )
peak_table |
A |
alpha |
Significance threshold used to select clusters based on
approximately unbiased (AU) bootstrap p-values from
|
min_size |
Clusters must contain more than |
max_size |
Clusters must contain fewer than |
nboot |
Number of bootstrap replicates for |
plot_dend |
Logical. If |
plot_spectra |
Logical. If |
verbose |
Logical. If |
outfile |
Optional path to an |
save |
The |
parallel |
Logical. If |
max.only |
Logical. If |
output |
What to return: |
col |
Colors for each cluster's box and number on the dendrogram and the title of its spectra panel, recycled if there are more clusters than colors. Defaults to the Okabe-Ito palette, without black, yellow and grey. |
... |
Additional arguments to |
Before using this function, reference spectra must be attached to the
peak_table using the attach_ref_spectra function. These spectra are
then used to construct a distance matrix from pairwise Pearson correlations
among peaks, and pvclust clusters the peaks
hierarchically, with bootstrap resampling. Clusters whose bootstrap support
exceeds the confidence set by alpha are returned. Peaks whose reference
spectrum is constant are dropped before clustering.
Clusters can be filtered by size using the min_size and max_size
arguments. The clustering algorithm often returns nested clusters, so an
individual peak can appear in more than one. If max.only is TRUE, only
the largest cluster in a nested tree of clusters meeting the confidence
threshold is returned.
The example uses nboot = 100 to reduce run time. For real data, the
pvclust authors recommend the default of 1000 replicates for a first look,
then 10,000 for smaller errors.
Returns a named list with an element for each value of output:
pvclust, the pvclust object, and clusters, a list of S4 cluster
objects.
The cluster objects consist of the following components:
peaks: a character vector containing the names of all peaks contained in
the given cluster.
pval: a numeric scalar containing one minus the approximately unbiased
(AU) value that pvclust reports for the given cluster,
so that small values indicate strong support.
Ethan Bass
R. Suzuki & H. Shimodaira. 2006. Pvclust: an R package for assessing the uncertainty in hierarchical clustering. Bioinformatics, 22(12):1540-1542. doi:10.1093/bioinformatics/btl117.
if (requireNamespace("pvclust", quietly = TRUE)) { data(pk_tab) data(Sa_warp) pk_tab <- attach_ref_spectra(pk_tab, Sa_warp, ref = "max.int") cl <- cluster_spectra(pk_tab, nboot = 100, max.only = FALSE, alpha = 0.03) }if (requireNamespace("pvclust", quietly = TRUE)) { data(pk_tab) data(Sa_warp) pk_tab <- attach_ref_spectra(pk_tab, Sa_warp, ref = "max.int") cl <- cluster_spectra(pk_tab, nboot = 100, max.only = FALSE, alpha = 0.03) }
Identifies groups of duplicate peaks in a peak table and retains a single
representative peak from each group. Peaks are considered duplicates when
their retention times differ by less than tol and their spectral
correlation exceeds min_cor. Use it to collapse a compound that was
integrated at more than one wavelength into a single feature.
combine_peaks( peak_table, tol = 0.01, min_cor = 0.9, choose = c("max", "least_sparse", "lambda"), lambda = NULL, verbose = getOption("verbose"), min.cor = NULL )combine_peaks( peak_table, tol = 0.01, min_cor = 0.9, choose = c("max", "least_sparse", "lambda"), lambda = NULL, verbose = getOption("verbose"), min.cor = NULL )
peak_table |
Peak table from |
tol |
Tolerance for matching retention times (maximum retention time
difference), in minutes. Defaults to |
min_cor |
Minimum spectral correlation to confirm a match. Defaults to
|
choose |
Method used to select a representative peak from each group of
duplicate peaks. |
lambda |
Character vector of preferred wavelength(s) to retain when
|
verbose |
Logical. Whether to print status to the console. |
min.cor |
The |
A peak table derived from the original, but with columns corresponding to duplicate peaks combined according to the specified criteria.
Ethan Bass
Other utility functions:
merge_peaks(),
reshape_chroms(),
reshape_peaktable()
data(pk_tab) data(Sa_warp) pk_tab <- attach_ref_spectra(pk_tab) combine_peaks(pk_tab, tol = 0.02, min_cor = 0.9)data(pk_tab) data(Sa_warp) pk_tab <- attach_ref_spectra(pk_tab) combine_peaks(pk_tab, tol = 0.02, min_cor = 0.9)
Estimates a baseline along the time axis of each chromatogram and subtracts
it, using any of the estimators described in baseline_estimators.
correct_baseline( x, baseline = c("als", "arpls", "aspls", "snip"), attach_baseline = FALSE, zero_floor = FALSE, cl = 2, show_progress = NULL, ... )correct_baseline( x, baseline = c("als", "arpls", "aspls", "snip"), attach_baseline = FALSE, zero_floor = FALSE, cl = 2, show_progress = NULL, ... )
x |
A numeric matrix (time × wavelength), a list of such matrices, or a plain numeric vector for a single trace. Row names (or, for a vector, names) must correspond to time points and column names to wavelengths. |
baseline |
Baseline estimator to use along the time axis. Either
asymmetric least squares ( |
attach_baseline |
Logical. Whether to retain the estimated baseline
alongside the corrected data, as an |
zero_floor |
Logical. Whether to clip negative values in the corrected
data to zero. Defaults to |
cl |
Either an integer specifying the number of cores to use for
parallel processing or a cluster object created by
|
show_progress |
Logical. Whether to show a progress bar. Defaults to
|
... |
Additional arguments to the selected |
Unlike preprocess, this function only subtracts the baseline; it
does not interpolate, smooth, or rescale.
The baseline-corrected data, in the same shape as x, with row and
column names (or, for a vector, names) unchanged.
Ethan Bass
Baek, S.-J., Park, A., Ahn, Y.-J., and Choo, J. 2015. Baseline correction using asymmetrically reweighted penalized least squares smoothing. Analyst 140:250-257. doi:10.1039/C4AN01061B.
Zhang, F., Tang, X., Tong, A., Wang, B., Wang, J., Lv, Y., Tang, C., and Wang, J. 2020. Baseline correction for infrared spectra using adaptive smoothness parameter penalized least squares method. Spectroscopy Letters 53:222-233. doi:10.1080/00387010.2020.1730908.
Ryan, C.G., Clayton, E., Griffin, W.L., Sie, S.H., and Cousens, D.R. 1988. SNIP, a statistics-sensitive background treatment for the quantitative analysis of PIXE spectra in geoscience applications. Nuclear Instruments and Methods in Physics Research B 34:396-402. doi:10.1016/0168-583X(88)90063-8.
Erb, D. 2025. pybaselines: A Python library of algorithms for the baseline correction of experimental data. doi:10.5281/zenodo.5608581.
baseline_estimators, preprocess, get_baseline,
subtract_blanks
Other preprocessing functions:
crop_chroms(),
preprocess(),
subtract_blanks()
data(Sa_pr) bc <- correct_baseline(Sa_pr[1], cl = 1, show_progress = FALSE)data(Sa_pr) bc <- correct_baseline(Sa_pr[1], cl = 1, show_progress = FALSE)
Corrects retention time differences in peak_list using warping models
fitted by correct_rt with any of its algorithms.
correct_peaks( peak_list, mod_list, chrom_list, match_names = TRUE, chrom_list_aligned = NULL )correct_peaks( peak_list, mod_list, chrom_list, match_names = TRUE, chrom_list_aligned = NULL )
peak_list |
A |
mod_list |
Warping models, as returned by |
chrom_list |
List of chromatograms from which the models are derived.
If omitted, it is retrieved using the name stored in |
match_names |
Logical. If |
chrom_list_aligned |
Optional aligned chromatograms, as returned by
|
Once an appropriate warping model has been established, corrected retention
times can be predicted for each peak. These are stored in an rt.cor
column, alongside start.cor and end.cor when the peak tables have
start and end columns.
The corrected times refer to the aligned time axis, so functions that later
read spectra or traces at those times need the aligned chromatograms. The
returned peak list stores the warping models for this purpose, and
get_peaktable carries them into the peak table, where they are
re-applied to the unaligned chromatograms when needed. To use a particular
aligned object instead, pass it as chrom_list_aligned.
The input list of peak tables is returned with extra columns containing the corrected retention times.
This function is adapted from the correctPeaks function in the alsace
package by Ron Wehrens: https://github.com/rwehrens/alsace/blob/master/R/correctPeaks.R.
Ron Wehrens, Ethan Bass
data(Sa_pr) warp <- correct_rt(chrom_list = Sa_pr, lambdas = 210, what = "models") pks <- get_peaks(Sa_pr, lambda = "210") correct_peaks(pks, mod_list = warp, chrom_list = Sa_pr)data(Sa_pr) warp <- correct_rt(chrom_list = Sa_pr, lambdas = 210, what = "models") pks <- get_peaks(Sa_pr, lambda = "210") correct_peaks(pks, mod_list = warp, chrom_list = Sa_pr)
Chromatograms are aligned using one of three algorithms, according to the
value of alg: parametric time warping ("ptw"), as implemented in
ptw; variable penalty dynamic time warping ("vpdtw"), as
implemented in VPdtw; or landmark parametric time warping
("lptw"), which fits the warping polynomial directly to matched peak
positions rather than full chromatographic signals.
correct_rt( chrom_list, lambdas, models = NULL, reference = "best", alg = c("ptw", "lptw", "vpdtw"), peaks = NULL, what = c("corrected.values", "models"), init.coef = c(0, 1, 0), n_traces = NULL, fill_zeros = FALSE, n_zeros = 0, scale = FALSE, trwdth = 0.2, plot_it = FALSE, penalty = 0.2, max_shift = 1, dilation_span = 0.3, rt_window = 0.3, spectral_cutoff = 0.95, regularization = 0, verbose = getOption("verbose"), show_progress = NULL, cl = 2, ..., n.traces = NULL, n.zeros = NULL, maxshift = NULL )correct_rt( chrom_list, lambdas, models = NULL, reference = "best", alg = c("ptw", "lptw", "vpdtw"), peaks = NULL, what = c("corrected.values", "models"), init.coef = c(0, 1, 0), n_traces = NULL, fill_zeros = FALSE, n_zeros = 0, scale = FALSE, trwdth = 0.2, plot_it = FALSE, penalty = 0.2, max_shift = 1, dilation_span = 0.3, rt_window = 0.3, spectral_cutoff = 0.95, regularization = 0, verbose = getOption("verbose"), show_progress = NULL, cl = 2, ..., n.traces = NULL, n.zeros = NULL, maxshift = NULL )
chrom_list |
List of chromatograms in matrix format, sharing a common
time axis (see |
lambdas |
A character or numeric vector specifying the wavelengths to
use for alignment. |
models |
List of models to warp by. The models provided here (if any)
must match the algorithm selected in |
reference |
Index or name of the sample to be used as the reference.
Fitted models record it by name. If not specified, chosen by
|
alg |
Alignment algorithm to use: parametric time warping ( |
peaks |
A peak list object from |
what |
Output type: either the |
init.coef |
Starting values for the optimization. Named to match the
argument of the same name in |
n_traces |
Number of wavelengths to warp by, chosen from |
fill_zeros |
Logical. If |
n_zeros |
Number of zeros to pad onto each end of the chromatograms
before fitting. Only used when |
scale |
Logical. If |
trwdth |
Width of the triangle in the weighted cross-correlation (WCC)
criterion, passed to
|
plot_it |
Logical. Whether to plot alignment. Defaults to |
penalty |
Numeric >= 0. Strength of the penalty against warping
for |
max_shift |
Maximum allowable shift for |
dilation_span |
Width of the moving-maximum window used to build the
|
rt_window |
Numeric. Argument to |
spectral_cutoff |
Numeric. Argument to |
regularization |
Numeric >= 0. Strength of the penalty against warping
for |
verbose |
Logical. Whether to print a progress message as the warping
models are fit and applied. Defaults to |
show_progress |
Logical. Whether to show progress bar. Defaults to
|
cl |
Either an integer specifying the number of cores to use for
parallel processing or a cluster object created by
|
... |
For |
n.traces |
The |
n.zeros |
The |
maxshift |
The |
Some arguments are specific to particular warping functions. For example
n_traces applies only to "ptw" warping;
penalty, max_shift, and dilation_span apply only to "vpdtw" warping;
and peaks, rt_window, spectral_cutoff, and regularization apply only
to "lptw" warping.
trwdth, max_shift and dilation_span are widths along the time axis,
given in minutes, regardless of the time unit of chrom_list, and rounded
internally to a whole number of timepoints. trwdth was a count of
timepoints up to chromatographR 0.8.0; multiply an old value by the sampling
interval in minutes to convert it. A width wider than the chromatogram itself
is rejected with an error, since it is almost certainly a stale timepoint
count. max_shift replaces maxshift, which is still accepted as a count of
timepoints.
regularization ("lptw") and penalty ("vpdtw") are not comparable:
both are dimensionless and higher means less warping, but they are on
unrelated scales.
A list of warping models or a list of warped absorbance profiles,
according to the value of the what argument. With alg = "vpdtw", the
warped chromatograms share a new time axis, which can be longer than the
input.
The PTW branch of correct_rt is adapted from the correctRT
function in Ron Wehrens' alsace
package.
Ethan Bass
Clifford, D., Stone, G., Montoliu, I., Rezzi, S., Martin, F. P., Guy, P., Bruce, S., & Kochhar, S. 2009. Alignment using variable penalty dynamic time warping. Analytical chemistry, 81(3):1000-1007. doi:10.1021/ac802041e.
Clifford, D., & Stone, G. 2012. Variable Penalty Dynamic Time Warping Code for Aligning Mass Spectrometry Chromatograms in R. Journal of Statistical Software, 47(8):1-17. doi:10.18637/jss.v047.i08.
Eilers, P.H.C. 2004. Parametric Time Warping. Analytical Chemistry, 76:404-411. doi:10.1021/ac034800e.
Wehrens, R., Bloemberg, T.G., and Eilers P.H.C. 2015. Fast parametric time warping of peak lists. Bioinformatics, 31:3063-3065. doi:10.1093/bioinformatics/btv299.
Wehrens, R., Carvalho, E., Fraser, P.D. 2015. Metabolite profiling in LC–DAD using multivariate curve resolution: the alsace package for R. Metabolomics, 11:143-154. doi:10.1007/s11306-014-0683-5.
correct_rt_group, correct_peaks, ptw,
VPdtw
data(Sa_pr) warp <- correct_rt(chrom_list = Sa_pr, lambdas=210)data(Sa_pr) warp <- correct_rt(chrom_list = Sa_pr, lambdas=210)
Aligns chromatograms using parametric time warping ("ptw"), as
implemented in ptw, or landmark parametric time warping
("lptw"), with warping functions estimated from within-group averages.
This is useful when samples fall into batches with shared retention time
shifts, or when individual samples contain peaks absent in other groups that
would otherwise confound alignment. One warp is fit per group rather than one
per sample, so the cost of warping falls roughly in proportion to the number
of groups.
correct_rt_group( chrom_list, lambdas, groups, reference = "best", reference_group = NULL, alg = c("ptw", "lptw"), init.coef = c(0, 1, 0), n_traces = NULL, fill_zeros = FALSE, n_zeros = 0, scale = FALSE, trwdth = 0.2, plot_it = FALSE, penalty = NULL, max_shift = 1, rt_window = 0.3, spectral_cutoff = 0.95, regularization = 0, verbose = getOption("verbose"), show_progress = NULL, cl = 2, what = c("corrected.values", "models"), ..., n.traces = NULL, n.zeros = NULL, maxshift = NULL )correct_rt_group( chrom_list, lambdas, groups, reference = "best", reference_group = NULL, alg = c("ptw", "lptw"), init.coef = c(0, 1, 0), n_traces = NULL, fill_zeros = FALSE, n_zeros = 0, scale = FALSE, trwdth = 0.2, plot_it = FALSE, penalty = NULL, max_shift = 1, rt_window = 0.3, spectral_cutoff = 0.95, regularization = 0, verbose = getOption("verbose"), show_progress = NULL, cl = 2, what = c("corrected.values", "models"), ..., n.traces = NULL, n.zeros = NULL, maxshift = NULL )
chrom_list |
A list of chromatograms in matrix format, sharing a common
time axis (see |
lambdas |
A character or numeric vector specifying the wavelengths to use for alignment. |
groups |
A vector of group assignments for each chromatogram, or a
single string naming a metadata attribute from which to extract the group
assignments (e.g. |
reference |
Index or name of a sample in |
reference_group |
Name of the group to use as the reference group. If
supplied, overrides |
alg |
Alignment algorithm to use: parametric time warping ( |
init.coef |
Starting values for the optimization. Named to match the
argument of the same name in |
n_traces |
Number of wavelengths to warp by, chosen from |
fill_zeros |
Logical. If |
n_zeros |
Number of zeros to pad onto each end of the chromatograms
before fitting. Only used when |
scale |
Logical. If |
trwdth |
Width of the triangle in the weighted cross-correlation (WCC)
criterion, passed to
|
plot_it |
Logical. Whether to plot alignment. Defaults to |
penalty |
Unused. |
max_shift |
Unused. |
rt_window |
Numeric. Argument to |
spectral_cutoff |
Numeric. Argument to |
regularization |
Numeric >= 0. Strength of the penalty against warping
for |
verbose |
Logical. Whether to print a progress message as the warping
models are fit and applied. Defaults to |
show_progress |
Logical. Whether to show progress bar. Defaults to
|
cl |
Either an integer specifying the number of cores to use for
parallel processing or a cluster object created by
|
what |
What to return: |
... |
For |
n.traces |
The |
n.zeros |
The |
maxshift |
Deprecated and unused. See |
With alg = "lptw", peaks are found in each group average by get_peaks
at its default settings and matched to the peaks of the reference group's
average, so landmarks come from the averaged signal rather than from
individual samples.
If what = "corrected.values", a list of warped chromatogram
matrices in the same order as chrom_list, with each sample warped using
the warp coefficients estimated from its group average. If
what = "models", a ptw_list (alg = "ptw") or lptw_list
(alg = "lptw") with one model per sample, in the same order.
Ethan Bass
data(Sa_pr) groups <- c("a", "a", "b", "b") warp <- correct_rt_group(chrom_list = Sa_pr, lambdas = 210, groups = groups)data(Sa_pr) groups <- c("a", "a", "b", "b") warp <- correct_rt_group(chrom_list = Sa_pr, lambdas = 210, groups = groups)
Restricts chromatograms to a range of retention times and/or wavelengths by subsetting the existing grid.
crop_chroms(x, rt_range = NULL, lambda_range = NULL)crop_chroms(x, rt_range = NULL, lambda_range = NULL)
x |
A numeric matrix (time × wavelength) or a list of such matrices. Row names must correspond to time points and column names to wavelengths. |
rt_range |
Numeric vector of length 2 giving the inclusive range of
retention times to keep, in the time unit of the data. Either element may be
|
lambda_range |
Numeric vector of length 2 giving the inclusive range of
wavelengths to keep. Either element may be |
Cropping is pure subsetting: the returned data are a submatrix of
the input, so values and dimnames pass through verbatim. This is the
difference from cropping via preprocess, which reaches a narrower range
by interpolating onto a new axis — resampling the signal unless the requested
grid happens to coincide with the existing time points, and reformatting the
retention times either way.
Bounds are inclusive, and either end of a range may be NA to leave it
open. Ranges are expressed in the units of the data itself: retention times
in whatever unit the chromatogram carries, as returned by get_times, and
wavelengths as labeled in the column names, as returned by get_lambdas.
An "estimated_baseline" attribute attached by preprocess or correct_baseline
is cropped alongside the data, so it stays aligned and can still be
retrieved with get_baseline.
A range that does not overlap the data at all is an error. A range that merely extends past one end is honored as far as the data allow, with a warning reporting what was actually kept, since this is usually a typo or a unit mismatch. Cropping chromatograms whose time axes are offset from one another — as unaligned chromatograms generally are — can leave them with different numbers of rows, which also warns: functions that read the time axis from the first chromatogram would then mislabel the rest, so align before cropping if the result needs a common time axis.
The cropped data, in the same shape as x.
Ethan Bass
preprocess, correct_baseline, get_times, get_lambdas
Other preprocessing functions:
correct_baseline(),
preprocess(),
subtract_blanks()
data(Sa_pr) cropped <- crop_chroms(Sa_pr, rt_range = c(12, 16)) trimmed <- crop_chroms(Sa_pr, lambda_range = c(220, NA))data(Sa_pr) cropped <- crop_chroms(Sa_pr, rt_range = c(12, 16)) trimmed <- crop_chroms(Sa_pr, lambda_range = c(220, NA))
Filters peaks from a peak_list object by height, area, width, retention
time, or fit diagnostics (converged and window_limited).
filter_peaks( peak_list, min_height, min_area, min_sd, max_sd, min_rt, max_rt, min_fwhm, max_fwhm, converged, window_limited )filter_peaks( peak_list, min_height, min_area, min_sd, max_sd, min_rt, max_rt, min_fwhm, max_fwhm, converged, window_limited )
peak_list |
A |
min_height |
Minimum peak height. Peaks whose |
min_area |
Minimum peak area. Peaks whose |
min_sd |
The |
max_sd |
The |
min_rt |
Minimum retention time. |
max_rt |
Maximum retention time. |
min_fwhm |
Minimum peak width, as a full width at half maximum, in the
time units of the peak list. Peaks whose |
max_fwhm |
Maximum peak width, as a full width at half maximum, in the
time units of the peak list. Peaks whose |
converged |
Logical. If |
window_limited |
Logical. If |
A filtered peak_list object containing only peaks that satisfy the
specified criteria. The call is appended to the filters attribute, as a
line of code with numbers to 15 significant digits; print shows it, and
get_peaktable copies it into args$filters.
The structure of filter_peaks is adapted from the filterPeaks
function in Ron Wehrens' alsace
package.
Ron Wehrens, Ethan Bass
data(Sa_warp) pks <- get_peaks(Sa_warp[1], lambda = "210") filter_peaks(pks, min_height = 100) filter_peaks(pks, converged = TRUE, window_limited = FALSE)data(Sa_warp) pks <- get_peaks(Sa_warp[1], lambda = "210") filter_peaks(pks, min_height = 100) filter_peaks(pks, converged = TRUE, window_limited = FALSE)
Filters features (columns) in a peak_table. Filtering is
applied consistently across all components of the peak table, including the
intensity matrix (tab), feature metadata (pk_meta), and reference spectra
(if present). Filtering can be based on retention time, wavelength, feature
intensity summarized across samples (mean, median, or max), feature
sparsity (i.e., proportion of zero values across samples), and/or fit
convergence.
filter_peaktable( peak_table, rts, min_rt, max_rt, min_value, max_zeros, lambda, min_converged, what = c("median", "mean", "max"), tol = 0 )filter_peaktable( peak_table, rts, min_rt, max_rt, min_value, max_zeros, lambda, min_converged, what = c("median", "mean", "max"), tol = 0 )
peak_table |
A peak_table object from |
rts |
Vector of retention times used to select features. Values are
mapped to the closest retention times in the peak table. If no
match is found within |
min_rt |
Minimum retention time for features to be retained. |
max_rt |
Maximum retention time for features to be retained. |
min_value |
Minimum threshold for feature intensity summarized across
samples (using the method specified by |
max_zeros |
Maximum allowed feature sparsity (proportion of zero values across samples). |
lambda |
Wavelength(s) used to select features in the peak table. Only features matching the specified wavelength(s) are retained. |
min_converged |
Minimum value of the |
what |
Method used to summarize feature intensity across samples for
filtering. One of |
tol |
Tolerance for matching of retention times to |
A filtered peak_table containing only features (columns) that
satisfy the specified criteria. The same feature indices are applied to all
peak_table components. The call is appended to args$filters, as a line
of code with numbers to 15 significant digits.
Ethan Bass
data(pk_tab) pk_tab <- filter_peaktable(pk_tab, min_rt = 10, max_rt = 16)data(pk_tab) pk_tab <- filter_peaktable(pk_tab, min_rt = 10, max_rt = 16)
Retrieves the baseline retained by preprocess or correct_baseline
when called with attach_baseline = TRUE. This function does not estimate
a baseline itself.
get_baseline(x)get_baseline(x)
x |
A chromatogram, or a list of chromatograms, returned by
|
The baseline is dropped by correct_rt, which warps the signal along the
time axis, and by subtract_blanks, after which it no longer describes
the signal. Retrieve it before either step. crop_chroms keeps it,
cropped to match.
A matrix of the same dimensions as x containing the estimated
baseline, or a list of such matrices if x is a list.
Other accessors:
get_lambdas(),
get_time_resolution(),
get_times()
data(Sa) pr <- preprocess(Sa[[1]], dim1 = seq(10, 18.66, by = .01), dim2 = seq(200, 318, by = 2), attach_baseline = TRUE) bl <- get_baseline(pr)data(Sa) pr <- preprocess(Sa[[1]], dim1 = seq(10, 18.66, by = .01), dim2 = seq(200, 318, by = 2), attach_baseline = TRUE) bl <- get_baseline(pr)
Get wavelengths from a chromatogram, a list of chromatograms, or a
peak_table object.
get_lambdas(x)get_lambdas(x)
x |
A chromatogram, a list of chromatograms, or a |
A numeric vector of wavelengths, taken from the first chromatogram
if x is a list.
Other accessors:
get_baseline(),
get_time_resolution(),
get_times()
data(Sa_warp) get_lambdas(Sa_warp)data(Sa_warp) get_lambdas(Sa_warp)
Detects chromatographic peaks, fits peak models, and extracts peak parameters at one or more wavelengths.
get_peaks( chrom_list, lambdas, fit = c("egh", "bemg", "gaussian", "raw"), windows = NULL, targets = NULL, tol = 0.1, select_by = c("height", "proximity", "none"), mod_list = NULL, sd_max = NULL, max_iter = 1000, time_unit = NULL, baseline = c("none", "flat", "sloped"), estimate_purity = FALSE, purity_args = list(), show_progress = NULL, cl = 2, collapse = FALSE, time.units = NULL, sd.max = NULL, max.iter = NULL, ... )get_peaks( chrom_list, lambdas, fit = c("egh", "bemg", "gaussian", "raw"), windows = NULL, targets = NULL, tol = 0.1, select_by = c("height", "proximity", "none"), mod_list = NULL, sd_max = NULL, max_iter = 1000, time_unit = NULL, baseline = c("none", "flat", "sloped"), estimate_purity = FALSE, purity_args = list(), show_progress = NULL, cl = 2, collapse = FALSE, time.units = NULL, sd.max = NULL, max.iter = NULL, ... )
chrom_list |
A list of chromatograms in matrix format (timepoints × wavelengths). |
lambdas |
A character or numeric vector specifying the wavelengths to
find peaks at. Omit for one-dimensional chromatograms, or when |
fit |
Peak model. Options are bidirectional exponentially modified
Gaussian ( |
windows |
Optional two-column matrix or |
targets |
Target retention times, as a numeric vector or a table of
targets (see |
tol |
Numeric. The maximum distance between a peak's apex and its target
in |
select_by |
Character. Which peak to keep when more than one falls in a
target's window: |
mod_list |
Optional warping models from |
sd_max |
Deprecated. Filter peaks by width with |
max_iter |
Maximum number of iterations for non-linear least squares
in |
time_unit |
Units for |
baseline |
Whether to measure each peak above a local baseline:
|
estimate_purity |
Logical. Whether to estimate purity. Defaults to
|
purity_args |
A named list of additional arguments passed to
|
show_progress |
Logical. Whether to show progress bar. Defaults to
|
cl |
Number of cores (integer) or a cluster object from
|
collapse |
Logical. Whether to combine the peaks from every wavelength
into a single |
time.units |
The |
sd.max |
The |
max.iter |
The |
... |
Additional arguments passed to |
Peaks are detected by find_peaks as zero-crossings in the smoothed first
derivative of each trace, then fitted by fit_peaks according to fit
(see Peak models and Fitting procedure). Peak areas are the trapezoidal
integral of the fitted curve (or, for fit = "raw", of the signal) above the
local baseline (see Local baselines). To integrate fixed retention-time
ranges instead, see Manual integration windows.
An S3 object of class peak_list: a nested list
(sample, then wavelength) of data.frames, or a list of one data.frame per
sample when collapse = TRUE, with one row per peak and columns:
rt: The retention time of the peak maximum. For the fitted models it
generally falls between timepoints, so match it to the time axis with a
tolerance rather than == or match(); get_spectra with what = "rt"
returns the spectrum at the nearest timepoint.
start: The retention time where the peak is estimated to begin.
end: The retention time where the peak is estimated to end.
sd: The standard deviation () of the Gaussian component of
the fitted peak shape. This is a parameter of the model rather than the width
of the peak: for "egh" and "bemg" the asymmetry of the peak is carried by
tau or by tau_left/tau_right, so describes only the core
of the peak and is not comparable across values of fit. Use FWHM to
compare widths. NA when fit = "raw", which fits no model; the width of
the integration window is available as end - start.
tau: Empirical skewness parameter (in units of time) determining peak
asymmetry when fit == "egh".
tau_right: Time constant (in units of time) of the exponential tail on
the right side of the peak when fit = "bemg". A larger value gives a
longer tail, and a value near 0 means no tail on that side.
tau_left: Time constant (in units of time) of the exponential tail on
the left side of the peak when fit = "bemg". A larger value gives a
longer tail, and a value near 0 means no tail on that side.
h: The amplitude parameter of the fitted BEMG shape function (only when
fit = "bemg"). It scales the shape but is not its value at center, so
use the height column for the height of the peak.
center: The center parameter of the fitted BEMG shape function (only
when fit = "bemg"). This is the location around which the exponential
tails are applied. Because BEMG peaks can be asymmetric
(tau_right != tau_left) and a sloped baseline shifts the fitted curve,
the actual peak maximum (rt) may differ from center.
FWHM: The full width at half maximum of the peak. For "gaussian" this
is ; for "egh" it is the
closed form implied by the model
(Lan & Jorgenson, 2001); and for "bemg", which has no closed form, it is
measured numerically from the fitted shape. For "raw" it is measured
directly from the signal above the local baseline, and is NA when the
integration window does not fall below half the height of the peak on both
sides, as for a peak fused with a neighbor. Unlike sd,
FWHM is comparable across values of fit.
height: The height of the peak above the fitted baseline.
area: The area of the peak above the fitted baseline, estimated by
trapezoidal approximation.
r.squared: Coefficient of determination () of the fitted
curve over the peak window, 1 - SS_res / SS_tot. Negative when the fit is
worse than a flat line at the mean. Not returned when fit = "raw".
purity: The peak purity as estimated by get_purity. NA unless
estimate_purity = TRUE.
window_limited: 1 if a fitted shape parameter hit a limit set by the
integration window, or a "gaussian" or "egh" fit narrowed to one
sampling interval at half height, meaning the window or the sampling rather
than the data
determined the reported shape, and 0 otherwise. Not returned when
fit = "raw".
converged: 1 if the nonlinear least squares optimizer reported
convergence for the final stage of the fit, and 0 otherwise. A 0 means
the reported parameters are wherever the optimizer stopped rather than a
converged fit, so treat the corresponding height and area with caution.
It also covers the case where part or all of the fit was skipped because
the integration window holds too few points to determine it; the peak then
keeps the last step that ran, or its starting values (see Fitting procedure).
get_peaks warns when more than 20% of peaks sit in such a window.
Not returned when fit = "raw".
floor: Constant baseline level (only when baseline = "flat").
floor_start: Baseline level at the left edge of the peak window (only
when baseline = "sloped").
floor_end: Baseline level at the right edge of the peak window (only
when baseline = "sloped"). For the peak models, floor, floor_start
and floor_end are constrained to be non-negative.
target: The row of targets the peak was selected for (only when targets is
supplied).
The three peak models are fitted to each peak by nonlinear least squares;
"raw" uses no model.
"gaussian": a symmetric Gaussian, with a center, a width (sd) and a
height.
"egh": the exponential-Gaussian hybrid of Lan & Jorgenson (2001), a
Gaussian whose width grows on one side of the apex. It adds one parameter,
tau, which is positive for a tailing peak and negative for a fronting one.
"bemg": the average of two exponentially modified Gaussians, one with an
exponential tail to the left and one to the right. Their time constants,
tau_left and tau_right, set the two tails independently, so a peak can
tail, front, or both; a value near 0 means no tail on that side.
"raw": no model. The signal itself is integrated across the window, so
r.squared, window_limited and converged are not reported.
"gaussian" cannot follow tailing or fronting; "egh" follows one or the
other, but not both in the same peak; "bemg" follows both. The more
flexible models have more parameters (3, 4 and 5 respectively for the peak
shape, plus one more for a "flat" baseline or two more for a "sloped"
baseline).
A peak's height and area are measured over its integration window, which
runs from the valley before the peak to the valley after it, as found by
find_peaks, or spans the manual window if the windows argument is given.
With baseline = "none", height and area are measured from zero, so
the chromatogram should already be baseline corrected (see preprocess).
With the fitted peak models ("gaussian", "egh", "bemg"), a "flat"
or "sloped" baseline is fitted together with the peak shape by nonlinear
least squares. It cannot be negative; a flat baseline is capped at the
lowest intensity in the window, and each end of a sloped one is capped at the
median intensity of the first or last 2% of the window. height and
area are those of the fitted shape above the baseline, with the area
integrated across the integration window only.
With fit = "raw", nothing is fitted: a "flat" baseline is a horizontal
line at the lower of the two boundary intensities, and a "sloped" one a
straight line between them. Where that line lies above the signal, it
subtracts area, so the area can come out negative; get_peaktable
records a negative area as 0.
With "flat" or "sloped", each peak gets its own baseline. This differs
from drop-line integration in vendor software such as ChemStation, where a
vertical line from each valley meets a baseline shared by the whole cluster
of peaks.
A fit is built up in successive steps: first the peak shape, then a constant
baseline, and finally its slope. To fit the full model, a peak's integration
window must have at least as many timepoints as there are parameters in the
model. A step is skipped if the window has too few timepoints to fit all the
required parameters, and discarded if the optimizer cannot start from its
initial values or, for "bemg", if a fitted tail rises towards the edge of
the window instead of falling back towards the baseline. Either way, the
peak keeps the last step that worked. A "sloped" baseline can therefore
come out flat, or a baseline can be left at its starting estimate rather than
fitted, and if even the shape fails, every parameter will keep its starting
value. In each of these cases, converged is set to 0.
Peaks that can't be fitted at all are dropped, unless they come from
targets. Those are kept, with height and area set to NA and
converged to 0, so that every target found has a row.
Manual windows integrate every sample over the same retention-time ranges,
so each compound is measured the same way in every sample, and every sample
gets the same set of peak table columns. The raw signal in each window is
integrated whether or not a peak is detected there, so a window with no peak
gets an area near zero. With baseline = "none", two adjacent windows
sharing a boundary time act as a vertical drop line: their areas sum exactly
to the area of their union, so a peak can be split at a chosen time. The
"flat" and "sloped" baselines are drawn within each window separately, so
their areas do not sum to that of the union. To fit peak models at known
retention times, use targets instead.
Adapted from getAllPeaks by Ron Wehrens
(https://github.com/rwehrens/alsace/blob/master/R/getAllPeaks.R); however,
the underlying algorithms for finding and integrating peaks differ.
Ethan Bass
Lan, K. & Jorgenson, J. W. 2001. A hybrid of exponential and gaussian functions as a simple model of asymmetric chromatographic peaks. Journal of Chromatography A 915:1-13. doi:10.1016/S0021-9673(01)00594-5.
Naish, P. J. & Hartwell, S. 1988. Exponentially Modified Gaussian functions — A good model for chromatographic peaks in isocratic HPLC? Chromatographia, 26: 285-296. doi:10.1007/BF02268168.
Arase, Shuntaro, Kanta Horie, Takashi Kato, et al. 2016. Intelligent Peak Deconvolution through In-Depth Study of the Data Matrix from Liquid Chromatography Coupled with a Photo-Diode Array Detector Applied to Pharmaceutical Analysis. Journal of Chromatography. A, 1469: 35–47. doi:10.1016/j.chroma.2016.09.037.
O'Haver, Tom. Pragmatic Introduction to Signal Processing: Applications in scientific measurement. https://terpconnect.umd.edu/~toh/spectrum/ (Accessed January, 2022).
Wehrens, R., Carvalho, E., Fraser, P.D. 2015. Metabolite profiling in LC–DAD using multivariate curve resolution: the alsace package for R. Metabolomics 11:143-154. doi:10.1007/s11306-014-0683-5.
find_peaks, fit_peaks, print.peak_list,
[.peak_list, targeted_analysis
data(Sa_pr) pks <- get_peaks(Sa_pr, lambdas = c('210'), fit = "egh") pks <- filter_peaks(pks, max_fwhm = 1)data(Sa_pr) pks <- get_peaks(Sa_pr, lambdas = c('210'), fit = "egh") pks <- filter_peaks(pks, max_fwhm = 1)
Converts a peak_list object containing peaks from multiple samples into
an aligned peak table by clustering peaks across samples according to
retention time and (optionally) spectral similarity. The tree is cut at
height hmax, whose meaning depends on clust (see hmax).
get_peaktable(peak_list, ...) ## Default S3 method: get_peaktable( peak_list, chrom_list, response = c("area", "height"), use_corrected_rt = NULL, hmax = 0.2, summarize_by = c("weighted.mean", "median", "mean", "max"), plot_it = FALSE, ask = plot_it, clust = c("rt", "sp.rt"), sigma_t = NULL, sigma_r = 0.5, deepSplit = FALSE, verbose = FALSE, ..., sigma.t = NULL, sigma.r = NULL, use.cor = NULL ) ## S3 method for class 'matched_peak_list' get_peaktable( peak_list, pks, response = c("area", "height"), rt_tol = 0.01, na.fill = 0, verbose = FALSE, ... ) ## S3 method for class 'matched_peak_list_set' get_peaktable( peak_list, pks, response = c("area", "height"), rt_tol = 0.01, na.fill = 0, verbose = FALSE, ... )get_peaktable(peak_list, ...) ## Default S3 method: get_peaktable( peak_list, chrom_list, response = c("area", "height"), use_corrected_rt = NULL, hmax = 0.2, summarize_by = c("weighted.mean", "median", "mean", "max"), plot_it = FALSE, ask = plot_it, clust = c("rt", "sp.rt"), sigma_t = NULL, sigma_r = 0.5, deepSplit = FALSE, verbose = FALSE, ..., sigma.t = NULL, sigma.r = NULL, use.cor = NULL ) ## S3 method for class 'matched_peak_list' get_peaktable( peak_list, pks, response = c("area", "height"), rt_tol = 0.01, na.fill = 0, verbose = FALSE, ... ) ## S3 method for class 'matched_peak_list_set' get_peaktable( peak_list, pks, response = c("area", "height"), rt_tol = 0.01, na.fill = 0, verbose = FALSE, ... )
peak_list |
A |
... |
Additional arguments (currently unused). |
chrom_list |
A list of chromatographic matrices. Only required when
|
response |
Peak intensity measure: either |
use_corrected_rt |
Logical. Indicates whether to use corrected retention times
( |
hmax |
Height at which the clustering tree is cut. With |
summarize_by |
How to summarize peak metadata within each cluster.
Options are |
plot_it |
Logical. If |
ask |
Logical. Ask before showing new plot? Defaults to |
clust |
Specify whether to perform hierarchical clustering based on
spectral similarity and retention time ( |
sigma_t |
Width of Gaussian kernel for retention time similarity, in
minutes. Controls the weight given to retention time when
|
sigma_r |
Width of Gaussian kernel for spectral similarity. Controls
the weight given to spectral correlation when |
deepSplit |
Logical. Controls sensitivity to cluster splitting when
|
verbose |
Logical. Whether to warn when two peaks from the same sample
fall in the same cluster. Defaults to |
sigma.t |
The |
sigma.r |
The |
use.cor |
The |
pks |
A |
rt_tol |
Numeric. Maximum allowed deviation (in retention-time units)
when joining matched peak RTs back to the corresponding row in |
na.fill |
Value used to fill cells where no peak was matched in a given
sample. Defaults to |
An S3 peak_table object, containing the following elements:
tab: The peak table itself — a data.frame of
intensities in a sample × peak configuration. A peak that was not found in a
sample, or whose response is negative, is recorded as 0 (na.fill for a
matched_peak_list). A peak whose model failed, which
get_peaks(targets = ) keeps with a missing height and area, is
recorded as NA.
pk_meta: A data.frame of peak metadata, one column per peak. Its rows
are the wavelength (lambda), the peak number (peak), and whichever of the
peak list's rt, start, end, sd, tau, FWHM, r.squared, purity,
window_limited and converged columns it has. See the Value section of
get_peaks for their meanings. The rows taken from the peak list are
summarized across samples according to summarize_by; by default, peaks
are weighted by intensity, which reduces the influence of small peaks. With
"weighted.mean" or "mean", the converged and window_limited rows
become the share of the column's peaks with that flag, so 0.25 means a
quarter of them. In a table built from a matched_peak_list, the rows hold
the reference sample's values instead.
sample_meta: A data.frame of sample metadata: the fields added to the
chromatograms with chromConverter::add_metadata() (chromConverter 0.11.0
or later), and any attached with attach_metadata. NA if there are none.
instrument_meta: A data.frame of instrumental metadata transferred
automatically from the chromatograms.
ref_spectra: A matrix of reference spectra (in a wavelength × peak
configuration). NA until added with attach_ref_spectra.
args: A list of the arguments given to get_peaktable to generate
the peak table, with the fit, baseline and max_iter the peaks were
fitted with in get_peaks. Its filters element holds any
filter_peaks and filter_peaktable calls applied, as code, separated
by "; ".
By default, clustering is performed on retention times alone (when
clust = "rt"). Alternatively, clustering can also incorporate information
about spectral similarity (when clust = "sp.rt") using a similarity function
adapted from Broeckling et al., 2014:
where is the spectral correlation between spectra and
, and and control the relative
contributions of retention time and spectral similarity, respectively (see
sigma_t and sigma_r).
When two peaks from the same sample fall in the same cluster, only the more
intense one enters the peak table, with a warning if verbose = TRUE. Such
warnings are often benign, but they can also mean hmax is too large. Lowering hmax merges fewer peaks, at the
cost of splitting some across multiple clusters; filtering low-intensity
peaks before clustering reduces the warnings without that trade-off.
Peak lists produced by get_peaks(windows = ) are grouped by
integration window rather than clustered by retention time, including after
correct_peaks. This gives one peak table column per window, ordered by
retention time.
Peak lists produced by get_peaks(targets = ) are grouped by target
instead of being clustered, each peak going to the matching target.
Targets found in no sample are omitted from the peak table. If targets has
a name column, the columns are named after the targets.
Peak tables built from get_peaks(windows = ) or get_peaks(targets = )
keep those windows or targets as an attribute of the same name, as a
record of how the table was built. The targets attribute lists every
target that was searched for, including any found in no sample, which have
no column. Neither attribute is updated when columns are removed.
match_peaks pairs the peaks in each sample with the peaks of a reference
sample, by spectrum as well as retention time. Each column then follows one
compound across the samples, even where retention times drift too far for
clustering to group the peaks reliably. In crowded stretches of the
chromatogram, this works only if neighboring compounds have distinct
spectra. This suits targeted analysis (see targeted_analysis) and
studies in which one sample, such as a standard mix or a pooled sample,
contains every compound of interest.
The peak table has one column for each peak
in the reference sample, at each of the specified wavelengths. A peak that's
missing in the reference sample gets no column, even if it's present in other
samples, so choose the reference with care (see match_peaks).
This function is adapted from the getPeakTable function in the alsace
package by Ron Wehrens: https://github.com/rwehrens/alsace/blob/master/R/getPeakTable.R.
Ron Wehrens, Ethan Bass
Broeckling, C. D., Afsar F.A., Neumann S., Ben-Hur A., and Prenni J.E. 2014. RAMClust: A Novel Feature Clustering Method Enables Spectral-Matching-Based Annotation for Metabolomics Data. Anal. Chem. 86:6812-6817. doi:10.1021/ac501530d.
Wehrens, R., Carvalho, E., Fraser, P.D. 2015. Metabolite profiling in LC–DAD using multivariate curve resolution: the alsace package for R. Metabolomics 11:143-154. doi:10.1007/s11306-014-0683-5.
peak_table, attach_ref_spectra, attach_metadata
data(Sa_pr) pks <- get_peaks(Sa_pr, lambdas = c('210')) get_peaktable(pks, response = "area")data(Sa_pr) pks <- get_peaks(Sa_pr, lambdas = c('210')) get_peaktable(pks, response = "area")
Extracts the UV-VIS spectrum at a specified retention time from one or more
chromatograms in a chrom_list.
get_spectra( loc, peak_table, chrom_list = NULL, idx = seq_along(chrom_list), scale_spectrum = FALSE, what = c("peak", "rt", "idx"), format = c("wide", "long") )get_spectra( loc, peak_table, chrom_list = NULL, idx = seq_along(chrom_list), scale_spectrum = FALSE, what = c("peak", "rt", "idx"), format = c("wide", "long") )
loc |
Peak or retention time to extract the spectrum at. Interpretation
depends on |
peak_table |
A |
chrom_list |
A list of chromatographic matrices. If |
idx |
Indices of chromatograms to extract spectra from. Defaults to all
chromatograms in |
scale_spectrum |
Logical. Whether to normalize absorbance values to
the range [0, 1]. Defaults to |
what |
How to interpret |
format |
One of |
Returns a data.frame in the format specified by format.
data(pk_tab) data(Sa_warp) get_spectra("V8", peak_table = pk_tab)data(pk_tab) data(Sa_warp) get_spectra("V8", peak_table = pk_tab)
Get the sampling interval of a chromatogram: the median gap between consecutive retention times.
get_time_resolution(x, idx = 1, digits = 6, unit = NULL)get_time_resolution(x, idx = 1, digits = 6, unit = NULL)
x |
A chromatogram, a list of chromatograms, or a |
idx |
Index of the chromatogram from which to derive the interval, if
|
digits |
Number of significant digits to round to. Defaults to |
unit |
Unit for the returned interval: |
A length-one numeric giving the time between consecutive timepoints,
in unit if supplied and otherwise in the units of the chromatogram's time
axis.
Other accessors:
get_baseline(),
get_lambdas(),
get_times()
data(Sa_warp) get_time_resolution(Sa_warp)data(Sa_warp) get_time_resolution(Sa_warp)
Get retention times from a chromatogram, a list of chromatograms, or a
peak_table object.
get_times(x, idx = 1)get_times(x, idx = 1)
x |
A chromatogram, a list of chromatograms, or a |
idx |
Index of the chromatogram from which to extract times, if |
Numeric vector of retention times from the chromatogram specified by
idx.
Other accessors:
get_baseline(),
get_lambdas(),
get_time_resolution()
data(Sa_warp) get_times(Sa_warp)data(Sa_warp) get_times(Sa_warp)
Matches peaks across chromatograms by spectral correlation and retention
time proximity. Each reference peak is matched to
at most one sample peak, taking candidate pairs in order of score, highest
first. The resulting matched_peak_list object can be passed to
correct_rt to perform landmark parametric time warping
(alg = "lptw").
match_peaks( peak_list, chrom_list = NULL, reference = NULL, targets = NULL, lambda = NULL, rt_window = 0.3, spectral_cutoff = 0.95, background_correction = c("none", "linear"), rt_weight = 0.15, use_corrected_rt = NULL, spectral_test = c("cutoff", "noise"), alpha = 0.01, plot_it = FALSE, verbose = getOption("verbose") )match_peaks( peak_list, chrom_list = NULL, reference = NULL, targets = NULL, lambda = NULL, rt_window = 0.3, spectral_cutoff = 0.95, background_correction = c("none", "linear"), rt_weight = 0.15, use_corrected_rt = NULL, spectral_test = c("cutoff", "noise"), alpha = 0.01, plot_it = FALSE, verbose = getOption("verbose") )
peak_list |
A peak list object from |
chrom_list |
List of chromatograms in matrix format. If |
reference |
Index or name of the reference sample, or |
targets |
Optional table of targets, or a numeric vector of their
retention times (see |
lambda |
A character or numeric value specifying the wavelength to use
for peak matching. Required if peaks were detected at multiple wavelengths,
unless |
rt_window |
Numeric. Maximum allowed difference in retention time, in
minutes, between a reference and sample peak to be considered a candidate
match. An |
spectral_cutoff |
Numeric. Minimum spectral correlation for a candidate
peak pair to be retained. A |
background_correction |
How to correct the apex spectrum of each peak
before correlating: |
rt_weight |
Numeric in [0, 1]. Penalizes retention time offset when
ranking candidate pairs: each pair's spectral correlation is multiplied by
|
use_corrected_rt |
Logical. Whether to compare corrected retention
times ( |
spectral_test |
How a candidate pair's spectra are compared:
|
alpha |
Significance level for |
plot_it |
Logical. Whether to plot the matches with
|
verbose |
Whether to print messages to console. |
A matched_peak_list object: a list with one element per sample
containing the matched peak pairs, per-pair spectral correlation scores,
and peak data in index space for use with correct_rt. A sample with no
peaks or no matches is NULL, with a warning. When targets is given,
the targets with rt replaced by the reference's own retention times are
stored as the "reference_targets" attribute. When the targets
span several wavelengths, peaks are matched separately at each, and the
result is a matched_peak_list_set: a list of matched_peak_list objects
named by wavelength, which get_peaktable combines into one table.
Unless reference is given, every wavelength uses the same reference
sample, chosen from all the targets; if no sample contains every target,
each wavelength gets its own, with a warning.
With targets, a sample's peak for a target is its tallest peak within
tol of it that, when fitted, has r.squared of at least 0.5; a peak
within tol of several targets counts only for the nearest. Unless
reference is given, the reference is chosen among samples with a peak for
every target, where a peak counts if it is at least a tenth of that target's
median height across samples. The sample whose weakest target is largest
relative to its median is chosen, then the one whose farthest peak lies
closest to its target time.
With background_correction = "linear", the apex spectrum is averaged over
2 scans either side and each boundary spectrum over 5 scans either side, to
limit the noise the subtraction adds. The subtraction removes a background
that varies linearly across the peak, such as a sloping baseline or a
neighbor's tail. It also adds noise, and where a boundary lies on a
neighboring peak it subtracts part of that peak's spectrum.
With spectral_test = "noise", each candidate pair is tested rather than
thresholded. The sample spectrum is fitted as an offset plus a multiple of
the reference spectrum by least squares, each wavelength weighted by the
reciprocal of the sample's noise there. The hypothesis is that, without
noise, the two spectra would correlate at spectral_cutoff; the residual
that this mismatch would leave is subtracted, and what remains is compared
with the residuals left under the same fit by pairs of noise spectra, one
from the sample and one from the reference scaled by the fitted multiple.
For a peak far above the noise, this reduces to requiring a noise-weighted
correlation of at least spectral_cutoff; for a small peak, it allows for
the noise, so a real peak is not rejected because its spectrum is noisy.
Each matched sample's spectral_p holds the p-values of its matched pairs.
This test is experimental. It has had little testing on real data, and the way its p-values are calculated may change in future versions.
The noise spectra come from each chromatogram's own peak-free timepoints:
those outside every peak in peak_list taller than 5 times its trace's
noise, at any wavelength in peak_list, after dropping timepoints whose
spectra still stand out from the rest. A trace's noise is the scaled median
absolute deviation of its timepoints outside every peak taller than 3 times
the noise, found by iterating from the estimate given by its point-to-point
differences, mad(diff(y)) / sqrt(2) (von Neumann 1941; Donoho and
Johnstone 1994).
The test cannot tell compounds apart near the noise level, where every
spectrum is consistent with every other; decide whether a small peak is
present by its height instead. A peak overlapped by a neighbor or sitting on
structured background may be rejected because its apex spectrum really is a
mixture. The test needs background_correction = "none" and, in each
chromatogram, at least 30 peak-free timepoints and at least 1 / alpha,
since with fewer it could never reject a match. On short traces with strongly
autocorrelated noise, the peak-free timepoints are fewer independent spectra
than their number, so a spectral_cutoff of 1 rejects identical spectra up
to about twice as often as alpha.
Ethan Bass
Donoho, D. L., and Johnstone, I. M. 1994. Ideal spatial adaptation by wavelet shrinkage. Biometrika 81:425-455. doi:10.1093/biomet/81.3.425.
von Neumann, J. 1941. Distribution of the ratio of the mean square successive difference to the variance. Ann. Math. Stat. 12:367-395. doi:10.1214/aoms/1177731677.
correct_rt, get_peaks, targeted_analysis
data(Sa_pr) pks <- get_peaks(Sa_pr, lambdas = 210, fit = "egh") match_peaks(pks, lambda = 210)data(Sa_pr) pks <- get_peaks(Sa_pr, lambdas = 210, fit = "egh") match_peaks(pks, lambda = 210)
Combines split peaks into a single column of the peak table.
merge_peaks(peak_table, peaks, method = c("max", "sum"))merge_peaks(peak_table, peaks, method = c("max", "sum"))
peak_table |
A |
peaks |
A vector specifying the names or indices of peaks to be merged. |
method |
Method to merge peaks. Either |
In each sample, method = "max" keeps the largest of the specified peaks
and method = "sum" adds them. The result replaces the peak with the
highest mean across samples, whose metadata is retained; the other peaks
are removed.
A peak table similar to the input peak table, but where the specified columns are combined.
Ethan Bass
Other utility functions:
combine_peaks(),
reshape_chroms(),
reshape_peaktable()
data(pk_tab) pk_tab <- merge_peaks(peak_table = pk_tab, peaks = c("V8","V9"))data(pk_tab) pk_tab <- merge_peaks(peak_table = pk_tab, peaks = c("V8","V9"))
Plots chromatograms as a mirror plot.
mirror_plot( x, chrom_list, lambdas = NULL, var, subset = NULL, print_legend = TRUE, legend_txt = NULL, legend_pos = "topright", legend_size = 1, mirror = TRUE, xlim = NULL, ylim = NULL, ... )mirror_plot( x, chrom_list, lambdas = NULL, var, subset = NULL, print_legend = TRUE, legend_txt = NULL, legend_pos = "topright", legend_size = 1, mirror = TRUE, xlim = NULL, ylim = NULL, ... )
x |
The peak table (output from |
chrom_list |
A list of chromatograms in matrix format (timepoints ×
wavelengths). If no argument is provided here, the function will try to find the
|
lambdas |
The wavelength(s) at which to plot the traces. Required for multi-wavelength chromatograms; ignored for one-dimensional chromatograms. |
var |
Name of the column in the sample metadata that defines the two groups. |
subset |
Character vector of the two levels of |
print_legend |
Logical. Whether to print legend. Defaults to |
legend_txt |
Character vector containing labels for legend. |
legend_pos |
Legend position, used only when |
legend_size |
Legend size ( |
mirror |
Logical. Whether to plot as mirror or stacked plots.
Defaults to |
xlim |
Numerical vector specifying limits for x axis. |
ylim |
Numerical vector specifying limits for y axis. |
... |
Additional arguments to |
Compares the chromatograms in two groups, defined by the levels of var.
When mirror is TRUE both are drawn in one panel, with the second
inverted below the axis; when it is FALSE they are drawn in two stacked
panels.
No return value, called for side effects.
Plots are rendered to the active graphics device.
Ethan Bass
Other visualization functions:
boxplot.peak_table(),
plot.chrom_list(),
plot.matched_peak_list(),
plot.peak_list(),
plot.peak_table(),
plot_all_spectra(),
plot_chrom_contour(),
plot_chroms(),
plot_chroms_heatmap(),
plot_spectrum(),
scan_chrom()
data(Sa_warp) data(pk_tab) path <- system.file("extdata", "Sa_metadata.csv", package = "chromatographR") meta <- read.csv(path) pk_tab <- attach_metadata(peak_table = pk_tab, metadata = meta, column="vial") mirror_plot(pk_tab,lambdas = c("210","260"), var = "trt", mirror = TRUE, col = c("green","blue"))data(Sa_warp) data(pk_tab) path <- system.file("extdata", "Sa_metadata.csv", package = "chromatographR") meta <- read.csv(path) pk_tab <- attach_metadata(peak_table = pk_tab, metadata = meta, column="vial") mirror_plot(pk_tab,lambdas = c("210","260"), var = "trt", mirror = TRUE, col = c("green","blue"))
Divides each sample in a peak table or list of chromatograms by its value in
a column of the sample metadata or of the peak table. For normalization by
sample metadata, the metadata must first be attached to the peak_table
using attach_metadata.
normalize_data( peak_table, column, chrom_list = NULL, what = c("peak_table", "chrom_list"), by = NULL, on_invalid = c("warn", "error", "silent") )normalize_data( peak_table, column, chrom_list = NULL, what = c("peak_table", "chrom_list"), by = NULL, on_invalid = c("warn", "error", "silent") )
peak_table |
A |
column |
The name of the column to be used for normalization. |
chrom_list |
List of chromatograms for normalization. Its names must
match the sample names of the |
what |
Output type to return: either |
by |
Whether to normalize by a column in sample metadata ( |
on_invalid |
How to handle invalid normalization values (i.e. zero,
negative, or |
Either a normalized peak_table object or a normalized chrom_list,
depending on the value of what.
Ethan Bass
get_peaktable, attach_metadata
data(pk_tab) path <- system.file("extdata", "Sa_metadata.csv", package = "chromatographR") meta <- read.csv(path) # normalize by sample mass pk_tab <- attach_metadata(peak_table = pk_tab, metadata = meta, column="vial") norm <- normalize_data(pk_tab, "mass", what = "peak_table") # normalize by internal standard norm <- normalize_data(pk_tab, column = "V14", by = "peak")data(pk_tab) path <- system.file("extdata", "Sa_metadata.csv", package = "chromatographR") meta <- read.csv(path) # normalize by sample mass pk_tab <- attach_metadata(peak_table = pk_tab, metadata = meta, column="vial") norm <- normalize_data(pk_tab, "mass", what = "peak_table") # normalize by internal standard norm <- normalize_data(pk_tab, column = "V14", by = "peak")
S3 objects of class peak_table store chromatographic peak data along with
associated metadata and reference spectra.
A peak_table object contains the following elements:
tab: The peak table itself — a data.frame of
intensities in a sample × peak configuration.
pk_meta: A data.frame containing peak metadata (e.g., the spectral
component, peak number, and summarized retention time). See
get_peaktable for its rows.
sample_meta: A data.frame of sample metadata: the fields added to the
chromatograms with chromConverter::add_metadata() (chromConverter 0.11.0
or later), and any attached with attach_metadata. NA if there are none.
instrument_meta: A data.frame of instrumental metadata transferred
automatically from the chromatograms.
ref_spectra: A matrix of reference spectra (in a wavelength × peak
configuration). NA until added with attach_ref_spectra.
args: A list of the arguments given to get_peaktable to generate
the peak table, with the peak list's fitting settings. See
get_peaktable.
The following methods are available:
get_peaktable() for creating peak_table objects
# See get_peaktable() for creation examples # To access peak_table components: data(pk_tab) pk_tab$tab # peak table pk_tab$pk_meta # peak metadata pk_tab$sample_meta # sample metadata# See get_peaktable() for creation examples # To access peak_table components: data(pk_tab) pk_tab$tab # peak table pk_tab$pk_meta # peak metadata pk_tab$sample_meta # sample metadata
A peak table generated from the exemplary goldenrod root extracts stored in
Sa.
data(pk_tab)data(pk_tab)
A peak_table object.
Other data objects:
Sa,
Sa_pr,
Sa_warp
Plot the spectra of a peak from several chromatograms. Wrapper for
plot_spectrum.
plot_all_spectra( loc, peak_table, chrom_list, idx = "all", engine = c("base", "ggplot2", "plotly"), plot_spectrum = TRUE, export_spectrum = TRUE, scale_spectrum = TRUE, overlapping = TRUE, verbose = FALSE, what = c("peak", "rt", "idx"), peak = NULL, ... )plot_all_spectra( loc, peak_table, chrom_list, idx = "all", engine = c("base", "ggplot2", "plotly"), plot_spectrum = TRUE, export_spectrum = TRUE, scale_spectrum = TRUE, overlapping = TRUE, verbose = FALSE, what = c("peak", "rt", "idx"), peak = NULL, ... )
loc |
The peak, retention time, or scan index from which to extract spectral data. |
peak_table |
A |
chrom_list |
A list of chromatograms in matrix format (timepoints ×
wavelengths). If no argument is provided here, the function will try to find
the |
idx |
Vector of chromatograms to plot, or |
engine |
Plotting backend to use. One of |
plot_spectrum |
Logical. If |
export_spectrum |
Logical. If |
scale_spectrum |
Logical. If |
overlapping |
Logical. If |
verbose |
Logical. If |
what |
What to look for. Either |
peak |
The |
... |
Additional arguments to |
If export_spectrum = TRUE (the default), invisibly returns a
data.frame with wavelengths as rows and one column per sample encoding
absorbance at each wavelength (normalized if scale_spectrum = TRUE).
If export_spectrum = FALSE, returns a plotly or ggplot object, or
nothing if engine == "base".
If engine == "base", the spectra are rendered to the active graphics
device.
Ethan Bass
Other visualization functions:
boxplot.peak_table(),
mirror_plot(),
plot.chrom_list(),
plot.matched_peak_list(),
plot.peak_list(),
plot.peak_table(),
plot_chrom_contour(),
plot_chroms(),
plot_chroms_heatmap(),
plot_spectrum(),
scan_chrom()
data(Sa_warp) pks <- get_peaks(Sa_warp, lambda = "220") pk_tab <- get_peaktable(pks) plot_all_spectra(loc = "V11", peak_table = pk_tab, overlapping = TRUE)data(Sa_warp) pks <- get_peaks(Sa_warp, lambda = "220") pk_tab <- get_peaktable(pks) plot_all_spectra(loc = "V11", peak_table = pk_tab, overlapping = TRUE)
Plots the baseline retained by preprocess or correct_baseline over
the trace it was estimated from, annotated with the estimator, smoothing
parameter and sampling interval that produced it.
plot_baseline( x, lambda = NULL, idx = 1, zoom = TRUE, col = "red", lty = 1, lwd = 2, add = FALSE, annotate = TRUE, ... )plot_baseline( x, lambda = NULL, idx = 1, zoom = TRUE, col = "red", lty = 1, lwd = 2, add = FALSE, annotate = TRUE, ... )
x |
A matrix or vector with an attached |
lambda |
Wavelength to plot, as a string or number. Optional for a single-wavelength chromatogram. |
idx |
Index or name of the chromatogram to plot, if |
zoom |
Logical. Whether to scale the y axis to the baseline, letting
the peaks run off the top of the panel. At full scale the baseline is
usually pressed against the axis, which hides the estimate bending up into a peak.
Defaults to |
col, lty, lwd
|
Graphical parameters for the baseline itself. The trace beneath it is always drawn in gray. |
add |
Logical. Whether to draw the baseline over an existing plot
rather than starting a new one, for comparing two estimates on the same
trace. The title and annotation are drawn only by the first call, and |
annotate |
Logical. Whether to annotate the plot with the estimator,
its smoothing parameter and the sampling interval. Set |
... |
Additional arguments to |
The plot uses base graphics. For other plots, extract the baseline with
get_baseline.
The annotation label, invisibly, so it can be reused in a
legend. The plot is rendered to the active graphics
device.
Ethan Bass
get_baseline, preprocess, correct_baseline
data(Sa) x <- preprocess(Sa[1], dim1 = seq(10, 18, by = .01), dim2 = seq(200, 318, by = 2), attach_baseline = TRUE, show_progress = FALSE, cl = 1) plot_baseline(x, lambda = 210)data(Sa) x <- preprocess(Sa[1], dim1 = seq(10, 18, by = .01), dim2 = seq(200, 318, by = 2), attach_baseline = TRUE, show_progress = FALSE, cl = 1) plot_baseline(x, lambda = 210)
Plots a single multi-wavelength chromatogram as an image, with retention time on the x axis, wavelength on the y axis, and color encoding absorbance.
plot_chrom_contour( x, idx = 1, xlim = NULL, ylim = NULL, scale = c("asinh", "linear"), zlim = NULL, show_legend = TRUE, title = NULL, xlab = "", ylab = "Wavelength", ... )plot_chrom_contour( x, idx = 1, xlim = NULL, ylim = NULL, scale = c("asinh", "linear"), zlim = NULL, show_legend = TRUE, title = NULL, xlab = "", ylab = "Wavelength", ... )
x |
A list of chromatograms in matrix format (timepoints × wavelengths)
or a |
idx |
Name or numerical index of the chromatogram to plot. Defaults to the first. |
xlim |
Range of retention times to plot. |
ylim |
Range of wavelengths to plot. |
scale |
Color scale: |
zlim |
Range of absorbance values spanned by the color scale. Values outside it are drawn in the end colors. Defaults to the range of the plotted region. |
show_legend |
Logical. Whether to display a color bar. Defaults to
|
title |
Title for plot. Defaults to the name of the chromatogram;
|
xlab |
X label. |
ylab |
Y label. Defaults to |
... |
Additional arguments to |
With scale = "asinh" (the default), color follows asinh(x / s), where
s is 1/100 of the largest absolute value in the plotted region, or in
zlim when it is given. The scale is linear near zero and logarithmic
above s, so peaks up to about 100 times smaller than the tallest one stay
visible. The color bar is labeled in absorbance units.
By default each plot is scaled to its own data, so colors cannot be
compared between plots. Pass the same zlim to every plot to put them on
one scale (see examples).
No return value.
The plot is rendered to the active graphics device.
Ethan Bass
Other visualization functions:
boxplot.peak_table(),
mirror_plot(),
plot.chrom_list(),
plot.matched_peak_list(),
plot.peak_list(),
plot.peak_table(),
plot_all_spectra(),
plot_chroms(),
plot_chroms_heatmap(),
plot_spectrum(),
scan_chrom()
data(Sa_pr) plot_chrom_contour(Sa_pr, idx = 1) # one color scale for every sample zlim <- range(unlist(Sa_pr)) plot_chrom_contour(Sa_pr, idx = 1, zlim = zlim) plot_chrom_contour(Sa_pr, idx = 2, zlim = zlim) # the same, zoomed in zoomed <- crop_chroms(Sa_pr, rt_range = c(12, 13)) plot_chrom_contour(zoomed, idx = 1, zlim = range(unlist(zoomed)))data(Sa_pr) plot_chrom_contour(Sa_pr, idx = 1) # one color scale for every sample zlim <- range(unlist(Sa_pr)) plot_chrom_contour(Sa_pr, idx = 1, zlim = zlim) plot_chrom_contour(Sa_pr, idx = 2, zlim = zlim) # the same, zoomed in zoomed <- crop_chroms(Sa_pr, rt_range = c(12, 13)) plot_chrom_contour(zoomed, idx = 1, zlim = range(unlist(zoomed)))
Visualizes absorbance traces from a list of one- or multi-wavelength
chromatograms using base R, ggplot2, or plotly graphics. For
multi-wavelength chromatograms, one or more wavelengths can be selected
using lambdas. Traces are thinned to time_resolution before plotting.
Each chromatogram specified by idx is plotted as a separate trace in its
own color.
plot_chroms( x, lambdas = NULL, idx, time_resolution = 0.01, time_unit = NULL, xlim = NULL, ylim = NULL, xlab = "", ylab = "Absorbance", engine = c("base", "ggplot", "plotly"), linewidth = 1, show_legend = FALSE, legend_position = "topright", title = "", what = NULL, ... )plot_chroms( x, lambdas = NULL, idx, time_resolution = 0.01, time_unit = NULL, xlim = NULL, ylim = NULL, xlab = "", ylab = "Absorbance", engine = c("base", "ggplot", "plotly"), linewidth = 1, show_legend = FALSE, legend_position = "topright", title = "", what = NULL, ... )
x |
A list of chromatograms in matrix format (timepoints × wavelengths)
or a |
lambdas |
A character or numeric vector specifying the wavelengths to plot. Required for multi-wavelength chromatograms and optional for one-dimensional ones, where a supplied wavelength must match the column name. |
idx |
A vector representing the names or numerical indices of the chromatograms to plot. Defaults to all chromatograms. |
time_resolution |
Desired temporal resolution for plotting (in minutes).
Chromatograms are thinned to approximately this interval prior to plotting,
which speeds up rendering of large datasets. Defaults to |
time_unit |
Time units of the provided chromatograms: either |
xlim |
Range of x axis values. Unless |
ylim |
Range of y axis values. |
xlab |
X label. |
ylab |
Y label. Defaults to |
engine |
Plotting backend to use. One of |
linewidth |
Line width. Defaults to |
show_legend |
Logical. Whether to display a legend. Defaults to
|
legend_position |
Position of legend. Defaults to |
title |
Title for plot. |
what |
Which element to plot when each chromatogram in |
... |
Additional arguments to |
A plotly or ggplot object when engine = "plotly" or
engine = "ggplot", respectively. No value is returned when
engine = "base".
If engine == "base", the plot is rendered to the active graphics device.
Ethan Bass
Other visualization functions:
boxplot.peak_table(),
mirror_plot(),
plot.chrom_list(),
plot.matched_peak_list(),
plot.peak_list(),
plot.peak_table(),
plot_all_spectra(),
plot_chrom_contour(),
plot_chroms_heatmap(),
plot_spectrum(),
scan_chrom()
data(Sa_warp) plot_chroms(Sa_warp, lambdas = 210)data(Sa_warp) plot_chroms(Sa_warp, lambdas = 210)
Plots the traces from a list of chromatograms as a heatmap, with one row
per chromatogram and color encoding absorbance at a single wavelength.
Adapted from VPdtw::plot.VPdtw.
plot_chroms_heatmap( x, idx = NULL, lambdas = NULL, engine = c("base", "ggplot", "plotly"), show_legend = TRUE, xlim = NULL, zlim = NULL, legend_position = "topright", title = "", show_ylabs = FALSE )plot_chroms_heatmap( x, idx = NULL, lambdas = NULL, engine = c("base", "ggplot", "plotly"), show_legend = TRUE, xlim = NULL, zlim = NULL, legend_position = "topright", title = "", show_ylabs = FALSE )
x |
A list of chromatograms in matrix format (timepoints × wavelengths)
or a |
idx |
A vector of names or numerical indices of the chromatograms to plot. Defaults to all chromatograms. |
lambdas |
A single wavelength to plot. Required for multi-wavelength chromatograms and optional for one-dimensional ones, where a supplied wavelength must match the column name. |
engine |
Plotting backend to use. One of |
show_legend |
Logical. Whether to display a color bar. Defaults to
|
xlim |
Range of retention times to plot. |
zlim |
Range of intensities spanned by the color scale. Values outside
it are drawn in the end colors. Defaults to the range within |
legend_position |
Position of legend. Defaults to |
title |
Title for plot. |
show_ylabs |
Logical. Whether to label each row with its chromatogram
name. Defaults to |
A plotly or ggplot object when engine = "plotly" or
engine = "ggplot", respectively. No value is returned when
engine = "base".
If engine == "base", the plot is rendered to the active graphics device.
Ethan Bass
Other visualization functions:
boxplot.peak_table(),
mirror_plot(),
plot.chrom_list(),
plot.matched_peak_list(),
plot.peak_list(),
plot.peak_table(),
plot_all_spectra(),
plot_chrom_contour(),
plot_chroms(),
plot_spectrum(),
scan_chrom()
data(Sa_warp) plot_chroms_heatmap(Sa_warp, lambdas = 210) # zoomed in, on the color scale of the whole run zlim <- range(sapply(Sa_warp, function(m) m[, "210"]), na.rm = TRUE) plot_chroms_heatmap(Sa_warp, lambdas = 210, xlim = c(13, 15), zlim = zlim)data(Sa_warp) plot_chroms_heatmap(Sa_warp, lambdas = 210) # zoomed in, on the color scale of the whole run zlim <- range(sapply(Sa_warp, function(m) m[, "210"]), na.rm = TRUE) plot_chroms_heatmap(Sa_warp, lambdas = 210, xlim = c(13, 15), zlim = zlim)
Visualizes chromatographic traces and/or UV spectra for a selected peak,
retention time, or scan index from a peak_table or list of chromatograms.
Spectra can also be exported as a data.frame when export_spectrum = TRUE.
plot_spectrum( loc = NULL, peak_table, chrom_list = NULL, idx = "max", lambda = "max", plot_spectrum = TRUE, plot_trace = TRUE, spectrum_labels = TRUE, scale_spectrum = FALSE, export_spectrum = FALSE, verbose = TRUE, what = c("peak", "rt", "idx", "click"), engine = c("base", "plotly", "ggplot2"), ... )plot_spectrum( loc = NULL, peak_table, chrom_list = NULL, idx = "max", lambda = "max", plot_spectrum = TRUE, plot_trace = TRUE, spectrum_labels = TRUE, scale_spectrum = FALSE, export_spectrum = FALSE, verbose = TRUE, what = c("peak", "rt", "idx", "click"), engine = c("base", "plotly", "ggplot2"), ... )
loc |
The peak, retention time, or scan index from which to extract spectral data. |
peak_table |
A |
chrom_list |
A list of chromatograms in matrix format (timepoints ×
wavelengths). If no argument is provided here, the function will try to find
the |
idx |
Index or name of the chromatogram to plot, or |
lambda |
The wavelength at which to plot the chromatographic trace, or
|
plot_spectrum |
Logical. If |
plot_trace |
Logical. If |
spectrum_labels |
Logical. If |
scale_spectrum |
Logical. If |
export_spectrum |
Logical. If |
verbose |
Logical. If |
what |
What to look for. Either |
engine |
Plotting backend to use. One of |
... |
Additional arguments. |
Use it to confirm the identity of a peak, or to assess whether
a peak table column likely represents a single compound. Retention times may
also be selected interactively by clicking on a chromatographic trace when
what = "click".
When plot_trace is TRUE, the chromatographic trace for the
specified chromatogram (idx) is plotted at wavelength lambda, with a
dotted red line indicating the selected retention time (loc). The trace
corresponds to a single column of the chromatographic matrix.
When plot_spectrum is TRUE, the UV spectrum at the specified retention
time is plotted. The spectrum corresponds to a single row of the
chromatographic matrix.
If export_spectrum = FALSE (default), returns a plotly or ggplot
object according to the specified engine. No value is returned when
engine = "base".
If export_spectrum is TRUE, invisibly returns the spectrum as a
data.frame with wavelengths as rows and a single column encoding the
absorbance (normalized, if scale_spectrum = TRUE).
If engine == "base", plots are rendered to the active graphics device.
Ethan Bass
Other visualization functions:
boxplot.peak_table(),
mirror_plot(),
plot.chrom_list(),
plot.matched_peak_list(),
plot.peak_list(),
plot.peak_table(),
plot_all_spectra(),
plot_chrom_contour(),
plot_chroms(),
plot_chroms_heatmap(),
scan_chrom()
data(Sa) pks <- get_peaks(Sa, lambda = "220.00000") pk_tab <- get_peaktable(pks) oldpar <- par(no.readonly = TRUE) par(mfrow = c(2, 1)) plot_spectrum(loc = "V8", peak_table = pk_tab, what = "peak") par(oldpar)data(Sa) pks <- get_peaks(Sa, lambda = "220.00000") pk_tab <- get_peaktable(pks) oldpar <- par(no.readonly = TRUE) par(mfrow = c(2, 1)) plot_spectrum(loc = "V8", peak_table = pk_tab, what = "peak") par(oldpar)
Plots a chromatogram (either a single trace or multiple traces) with an inset UV spectrum for a specified peak. Dotted lines connect the peak apex to the two nearest corners of the inset box.
plot_spectrum_inset( loc, peak_table, chrom_list = NULL, idx = "max", lambda = "max", position = "topright", inset_width = 0.35, inset_height = 0.35, ylim = NULL, xlim = NULL, engine = "ggplot", scale_spectrum = TRUE, verbose = getOption("verbose"), inset_text_size = 8, ... )plot_spectrum_inset( loc, peak_table, chrom_list = NULL, idx = "max", lambda = "max", position = "topright", inset_width = 0.35, inset_height = 0.35, ylim = NULL, xlim = NULL, engine = "ggplot", scale_spectrum = TRUE, verbose = getOption("verbose"), inset_text_size = 8, ... )
loc |
Peak name or vector of names in the peak table (e.g. |
peak_table |
A |
chrom_list |
A list of chromatograms in matrix format (timepoints ×
wavelengths). If no argument is provided here, the function will try to find
the |
idx |
Index of chromatogram(s) to plot. If |
lambda |
Wavelength to use for the chromatographic trace and for
locating the peak apex. Either a numeric value or |
position |
Position of the inset. One of |
inset_width |
Width of the inset as a proportion of the plot width.
Defaults to |
inset_height |
Height of the inset as a proportion of the plot height.
Defaults to |
ylim |
Y axis limits for the main plot. Passed to |
xlim |
X axis limits for the main plot. Passed to |
engine |
Plotting engine. Currently only |
scale_spectrum |
Logical. If |
verbose |
Logical. If |
inset_text_size |
Base size for text elements in inset. Defaults to |
... |
Additional arguments passed to |
A ggplot object.
plot_spectrum(), plot_chroms()
if (requireNamespace("ggplot2", quietly = TRUE)) { data(pk_tab) data(Sa_warp) # single trace with inset spectrum plot_spectrum_inset("V13", peak_table = pk_tab) # multiple traces, inset in the center plot_spectrum_inset("V13", peak_table = pk_tab, idx=c(1:4), position = "top") # manual inset placement plot_spectrum_inset("V13", peak_table = pk_tab, position = c(0.6, 0.3), inset_width = 0.35, inset_height = 0.25) # multiple peaks with a list of positions plot_spectrum_inset(c("V13", "V25"), peak_table = pk_tab, position = list(c(0.3, 0.5), c(0.65, 0.3)), inset_width = 0.3, inset_height = 0.3) }if (requireNamespace("ggplot2", quietly = TRUE)) { data(pk_tab) data(Sa_warp) # single trace with inset spectrum plot_spectrum_inset("V13", peak_table = pk_tab) # multiple traces, inset in the center plot_spectrum_inset("V13", peak_table = pk_tab, idx=c(1:4), position = "top") # manual inset placement plot_spectrum_inset("V13", peak_table = pk_tab, position = c(0.6, 0.3), inset_width = 0.35, inset_height = 0.25) # multiple peaks with a list of positions plot_spectrum_inset(c("V13", "V25"), peak_table = pk_tab, position = list(c(0.3, 0.5), c(0.65, 0.3)), inset_width = 0.3, inset_height = 0.3) }
Plots a chrom_list, as returned by chromConverter::read_chroms(), as
traces (plot_chroms()), a heatmap of samples (plot_chroms_heatmap()),
or a contour plot of one sample (plot_chrom_contour()). If each sample
holds several elements, the "dad" element is plotted, or for
type = "traces" the one named by what.
## S3 method for class 'chrom_list' plot(x, type = c("traces", "heatmap", "contour"), ...)## S3 method for class 'chrom_list' plot(x, type = c("traces", "heatmap", "contour"), ...)
x |
A |
type |
Type of plot: |
... |
Arguments to the plotting function selected by |
The value returned by the selected plotting function.
Ethan Bass
Other visualization functions:
boxplot.peak_table(),
mirror_plot(),
plot.matched_peak_list(),
plot.peak_list(),
plot.peak_table(),
plot_all_spectra(),
plot_chrom_contour(),
plot_chroms(),
plot_chroms_heatmap(),
plot_spectrum(),
scan_chrom()
data(Sa_pr) class(Sa_pr) <- c("chrom_list", "list") plot(Sa_pr, lambdas = 210) plot(Sa_pr, type = "heatmap", lambdas = 210) plot(Sa_pr, type = "contour", idx = 1)data(Sa_pr) class(Sa_pr) <- c("chrom_list", "list") plot(Sa_pr, lambdas = 210) plot(Sa_pr, type = "heatmap", lambdas = 210) plot(Sa_pr, type = "contour", idx = 1)
Shows how peaks in each sample were matched to the reference by
match_peaks.
## S3 method for class 'matched_peak_list' plot(x, idx = NULL, type = c("ladder", "scatter"), ...) ## S3 method for class 'matched_peak_list_set' plot(x, ...)## S3 method for class 'matched_peak_list' plot(x, idx = NULL, type = c("ladder", "scatter"), ...) ## S3 method for class 'matched_peak_list_set' plot(x, ...)
x |
A |
idx |
Integer or character vector of sample indices or names to plot. Defaults to all non-reference samples. |
type |
Plot type, either |
... |
Additional arguments passed to |
With type = "ladder" (the default), each sample gets one row, with
retention time on the x-axis. Dotted vertical lines mark the reference
peaks, and a short tick marks each one in every row. A matched sample peak
is drawn as a point filled by its spectral correlation with the reference
peak, joined to the reference tick by a horizontal bar, so the length and
direction of the bar show the retention time shift. A tick without a bar is
a reference peak left unmatched in that sample, and an open circle is a
sample peak left unmatched. Where a bar would overlap another bar or run
through an unmatched peak, it is lifted slightly above its row.
With type = "scatter", each sample gets its own panel, plotting every
candidate pair (a pair within the retention time window and above the
spectral cutoff) at its reference and sample retention times, so retention
time drift shows as distance from the diagonal. Candidate pairs
are colored by spectral correlation, matched pairs are outlined in black,
and unmatched peaks are marked on the axes.
Invisibly returns x.
Ethan Bass
Other visualization functions:
boxplot.peak_table(),
mirror_plot(),
plot.chrom_list(),
plot.peak_list(),
plot.peak_table(),
plot_all_spectra(),
plot_chrom_contour(),
plot_chroms(),
plot_chroms_heatmap(),
plot_spectrum(),
scan_chrom()
Draws fitted peak shapes over chromatographic traces to assess integration accuracy.
## S3 method for class 'peak_list' plot( x, ..., chrom_list, idx = 1, lambda = NULL, targets = NULL, tol = 0.1, pad = 0.5, points = FALSE, ticks = FALSE, alpha = 0.5, color = NULL, cex.points = 0.5, numbers = FALSE, cex.font = 0.5, digits = 2, y.offset = 0.03, plot_purity = c("none", "ratio", "curves", "curves_local"), purity_args = list(), res )## S3 method for class 'peak_list' plot( x, ..., chrom_list, idx = 1, lambda = NULL, targets = NULL, tol = 0.1, pad = 0.5, points = FALSE, ticks = FALSE, alpha = 0.5, color = NULL, cex.points = 0.5, numbers = FALSE, cex.font = 0.5, digits = 2, y.offset = 0.03, plot_purity = c("none", "ratio", "curves", "curves_local"), purity_args = list(), res )
x |
A |
... |
Additional arguments to main plot function. The plot is titled
with the sample, wavelength and peak model by default; pass |
chrom_list |
List of chromatograms (retention time × wavelength
matrices). If missing, extracted from environment using the pointer in |
idx |
Index or name of chromatogram to plot from |
lambda |
Wavelength (column) to use for plotting. Defaults to the first
wavelength in |
targets |
Optional target retention times, as a numeric vector or a
table of targets (see |
tol |
Numeric. Half-width of the window around each target, in
minutes, regardless of the time unit of |
pad |
Fraction of the selected peak span to add on either side when
zooming. Defaults to |
points |
Logical. If |
ticks |
Logical. If |
alpha |
Transparency of fitted peak shapes. Defaults to |
color |
Color used to fill fitted peak shapes. If |
cex.points |
Size of points. Defaults to |
numbers |
Labels drawn above each peak. |
cex.font |
Font size if peaks are numbered. Defaults to |
digits |
Number of decimal places for retention time labels when
|
y.offset |
Vertical offset of peak numbers, as a fraction of the height
of the plot region. Defaults to |
plot_purity |
Whether and how to draw peak purity traces below the
chromatogram. |
purity_args |
A named list of additional arguments controlling the
purity calculation, e.g. |
res |
Time resolution for peak fitting. If missing, inferred from
|
The appearance of fitted peaks depends on the "fit" attribute of x, which
may be "gaussian", "egh", "bemg", or "raw".
Peak lists must contain columns rt, height, start, end, and sd,
with additional columns depending on the fit type.
Width parameters are rescaled using the time units of x.
A peak whose shape cannot be drawn is skipped with a warning.
No return value, called for side effects.
Plots the trace of chromatogram idx at wavelength lambda, with the
fitted peak shapes from x filled in beneath it.
Ethan Bass
Other visualization functions:
boxplot.peak_table(),
mirror_plot(),
plot.chrom_list(),
plot.matched_peak_list(),
plot.peak_table(),
plot_all_spectra(),
plot_chrom_contour(),
plot_chroms(),
plot_chroms_heatmap(),
plot_spectrum(),
scan_chrom()
data(Sa_warp) pks <- get_peaks(chrom_list = Sa_warp[1], lambdas = 210) plot(pks, points = TRUE, ticks = TRUE) plot(pks, targets = 11.12, ticks = TRUE) op <- par(mfrow = c(1, 2)) for (t in c(12.19, 14.41)) plot(pks, targets = t) par(op)data(Sa_warp) pks <- get_peaks(chrom_list = Sa_warp[1], lambdas = 210) plot(pks, points = TRUE, ticks = TRUE) plot(pks, targets = 11.12, ticks = TRUE) op <- par(mfrow = c(1, 2)) for (t in c(12.19, 14.41)) plot(pks, targets = t) par(op)
Plots the trace and/or spectrum for a given peak in peak table.
## S3 method for class 'peak_table' plot( x, loc, chrom_list = NULL, what = "peak", idx = "max", lambda = "max", plot_spectrum = TRUE, plot_trace = TRUE, box_plot = FALSE, vars = NULL, spectrum_labels = TRUE, scale_spectrum = FALSE, export_spectrum = FALSE, verbose = TRUE, engine = c("base", "plotly", "ggplot"), ... )## S3 method for class 'peak_table' plot( x, loc, chrom_list = NULL, what = "peak", idx = "max", lambda = "max", plot_spectrum = TRUE, plot_trace = TRUE, box_plot = FALSE, vars = NULL, spectrum_labels = TRUE, scale_spectrum = FALSE, export_spectrum = FALSE, verbose = TRUE, engine = c("base", "plotly", "ggplot"), ... )
x |
The peak table (output from |
loc |
A vector specifying the peak(s) or retention time(s) to plot.
If missing when |
chrom_list |
A list of chromatograms in matrix format (timepoints ×
wavelengths). If no argument is provided here, the function will try to find
the |
what |
What to look for. Either |
idx |
Numerical index of chromatogram you wish to plot; |
lambda |
The wavelength at which to plot the trace. |
plot_spectrum |
Logical. If |
plot_trace |
Logical. If |
box_plot |
Logical. If |
vars |
Character vector of column names in the sample metadata, used as the right-hand side of the boxplot formula. |
spectrum_labels |
Logical. If |
scale_spectrum |
Logical. If |
export_spectrum |
Logical. If |
verbose |
Logical. If |
engine |
Plotting backend to use. One of |
... |
Additional arguments to boxplot. |
Use it to confirm the identity of a peak, or to check that a particular column in the peak table represents a single compound. It also draws simple box plots of the distribution of a peak against variables defined in sample metadata.
When plot_trace is TRUE, plots the trace of chromatogram idx at
wavelength lambda, with a dotted red line at the retention time given by
loc. When plot_spectrum is TRUE, plots the spectrum of the same
chromatogram at that retention time. When box_plot is TRUE, draws a
boxplot of the peak with groups defined by vars.
If export_spectrum = FALSE (default), a plotly or ggplot object, or
nothing if engine == "base".
If export_spectrum = TRUE, the spectrum as a data.frame with
wavelengths as rows and one column per sample giving absorbance at each
wavelength (normalized if scale_spectrum = TRUE).
If engine == "base", plots are rendered to the active graphics device.
Ethan Bass
Other visualization functions:
boxplot.peak_table(),
mirror_plot(),
plot.chrom_list(),
plot.matched_peak_list(),
plot.peak_list(),
plot_all_spectra(),
plot_chrom_contour(),
plot_chroms(),
plot_chroms_heatmap(),
plot_spectrum(),
scan_chrom()
Plots ptw alignments.
## S3 method for class 'ptw_list' plot( x, what = c("traces", "heatmap"), engine = c("base", "ggplot", "plotly"), lambdas, show_legend = TRUE, ... )## S3 method for class 'ptw_list' plot( x, what = c("traces", "heatmap"), engine = c("base", "ggplot", "plotly"), lambdas, show_legend = TRUE, ... )
x |
A |
what |
What type of plot to return. Either |
engine |
What plotting engine to use. One of |
lambdas |
Wavelengths to plot, from among those used for warping. Defaults to all of them. The heatmap shows only the first. |
show_legend |
Logical. Whether to include sample legend. |
... |
Ignored. |
Plots raw and warped chromatograms, one above the other, either as
individual traces or as a heatmap, according to the value of what. The
plot can be produced using either base R graphics, ggplot2, or plotly,
according to the value of the engine argument.
A plotly or ggplot object when engine = "plotly" or
engine = "ggplot", respectively. No value is returned when
engine = "base".
If engine == "base", plots are rendered to the active graphics device.
Ethan Bass
data(Sa_pr) warp <- correct_rt(chrom_list = Sa_pr, what = "models", lambdas = 210) plot(warp)data(Sa_pr) warp <- correct_rt(chrom_list = Sa_pr, what = "models", lambdas = 210) plot(warp)
Standard preprocessing of time × wavelength response matrices
(e.g. HPLC-DAD/UV data), consisting of: (i) optional subtraction of a
reference band of wavelengths, (ii) optional interpolation in either
dimension for dimensionality reduction, (iii) optional smoothing along the
spectral axis, and (iv) optional baseline correction along the time axis.
For densely sampled data (e.g., UV-VIS spectra), the size of the matrix can
be reduced by interpolation. By default, the data are smoothed along the
spectral axis using cubic smoothing splines (smooth.spline), then
baseline-corrected along the time axis by asymmetric least squares
(asysm). Three other baseline estimators are available
through baseline, and baseline = "none" skips the step; see
baseline_estimators.
preprocess( X, dim1, dim2, remove.time.baseline = NULL, baseline = c("als", "arpls", "aspls", "snip", "none"), attach_baseline = FALSE, zero_floor = FALSE, smooth_spectra = TRUE, reference_wavelengths = NULL, interpolate_rows = TRUE, interpolate_cols = TRUE, cl = 2, show_progress = NULL, outlier_cutoff = 5/60, ..., maxI = NULL, spec.smooth = NULL )preprocess( X, dim1, dim2, remove.time.baseline = NULL, baseline = c("als", "arpls", "aspls", "snip", "none"), attach_baseline = FALSE, zero_floor = FALSE, smooth_spectra = TRUE, reference_wavelengths = NULL, interpolate_rows = TRUE, interpolate_cols = TRUE, cl = 2, show_progress = NULL, outlier_cutoff = 5/60, ..., maxI = NULL, spec.smooth = NULL )
X |
A numeric matrix (time × wavelength) or a list of such matrices. Row names must correspond to time points and column names to wavelengths. |
dim1 |
Numeric vector specifying the target time grid, usually built
with |
dim2 |
Numeric vector specifying the target wavelength grid, usually
built with |
remove.time.baseline |
The |
baseline |
Baseline estimator to use along the time axis. Either
asymmetric least squares ( |
attach_baseline |
Logical. Whether to retain the estimated baseline
alongside the corrected data as an |
zero_floor |
Logical. Whether to clip negative values in the
corrected data to zero. Defaults to |
smooth_spectra |
Logical, indicating whether smoothing should be done along
the spectral axis, according to |
reference_wavelengths |
Numeric vector of length 2 giving a band of
wavelengths, |
interpolate_rows |
Logical. Whether to interpolate along the time axis
( |
interpolate_cols |
Logical. Whether to interpolate along the spectral
axis ( |
cl |
Either an integer specifying the number of cores to use for
parallel processing or a cluster object created by
|
show_progress |
Logical. Whether to show progress bar. Defaults to
|
outlier_cutoff |
Threshold (in minutes) for excluding chromatograms
that end earlier than expected. Samples ending more than this value before
the median end time are removed with a warning. The value is always in
minutes, whatever time unit the chromatograms are stored in. Defaults to
|
... |
Additional arguments to the selected |
maxI |
If supplied, each chromatogram is rescaled so that its maximum
intensity equals |
spec.smooth |
The |
The operations are applied in the order given above: reference subtraction
first, on the original wavelengths, then interpolation, then spectral
smoothing, then baseline correction. Because the
baseline is estimated after the time axis is interpolated, stiffness is
tied to whichever dim1 grid was chosen: the penalty applies on the index
axis, so the same value gives a different baseline on a differently sampled
grid. Choose dim1 first, then tune stiffness against that grid.
The function returns the preprocessed data matrix (or list of matrices), with row names and column names indicating the time points and wavelengths, respectively.
Adapted from the preprocess function in the alsace package by
Ron Wehrens: https://github.com/rwehrens/alsace/blob/master/R/preprocess.R.
Ethan Bass
Baek, S.-J., Park, A., Ahn, Y.-J., and Choo, J. 2015. Baseline correction using asymmetrically reweighted penalized least squares smoothing. Analyst 140:250-257. doi:10.1039/C4AN01061B.
Zhang, F., Tang, X., Tong, A., Wang, B., Wang, J., Lv, Y., Tang, C., and Wang, J. 2020. Baseline correction for infrared spectra using adaptive smoothness parameter penalized least squares method. Spectroscopy Letters 53:222-233. doi:10.1080/00387010.2020.1730908.
Ryan, C.G., Clayton, E., Griffin, W.L., Sie, S.H., and Cousens, D.R. 1988. SNIP, a statistics-sensitive background treatment for the quantitative analysis of PIXE spectra in geoscience applications. Nuclear Instruments and Methods in Physics Research B 34:396-402. doi:10.1016/0168-583X(88)90063-8.
Erb, D. 2025. pybaselines: A Python library of algorithms for the baseline correction of experimental data. doi:10.5281/zenodo.5608581.
baseline_estimators, correct_baseline, crop_chroms,
get_baseline
Other preprocessing functions:
correct_baseline(),
crop_chroms(),
subtract_blanks()
data(Sa) new.ts <- seq(10,18.66,by=.01) # choose time-points new.lambdas <- seq(200, 318, by = 2) # choose wavelengths Sa_pr <- preprocess(Sa[[1]], dim1 = new.ts, dim2 = new.lambdas)data(Sa) new.ts <- seq(10,18.66,by=.01) # choose time-points new.lambdas <- seq(200, 318, by = 2) # choose wavelengths Sa_pr <- preprocess(Sa[[1]], dim1 = new.ts, dim2 = new.lambdas)
Prints a summary of a matched_peak_list: the wavelength and reference
sample, the matching settings, and how many peaks each sample matched.
## S3 method for class 'matched_peak_list' print(x, ...)## S3 method for class 'matched_peak_list' print(x, ...)
x |
A |
... |
Additional arguments (ignored). |
Invisibly returns x.
Ethan Bass
Prints a summary of a matched_peak_list_set: its wavelengths, the reference
sample, and the reference peaks and targets at each wavelength.
## S3 method for class 'matched_peak_list_set' print(x, ...)## S3 method for class 'matched_peak_list_set' print(x, ...)
x |
A |
... |
Additional arguments (ignored). |
Invisibly returns x.
Ethan Bass
Prints a summary of a peak_list object, including the number of
samples, wavelengths, fit method, and total number of peaks.
## S3 method for class 'peak_list' print(x, ...)## S3 method for class 'peak_list' print(x, ...)
x |
A |
... |
Additional arguments (ignored). |
Invisibly returns x.
Ethan Bass
Converts a list of chromatographic matrices into a single long-format data frame with one row per sample × retention time × wavelength combination.
reshape_chroms( x, idx, time_resolution = NULL, time_unit = NULL, sample_var = "sample", lambdas = NULL, rts = NULL, transfer_metadata = FALSE )reshape_chroms( x, idx, time_resolution = NULL, time_unit = NULL, sample_var = "sample", lambdas = NULL, rts = NULL, transfer_metadata = FALSE )
x |
A list of chromatographic matrices in wide format. |
idx |
Indices of chromatograms to convert. Defaults to all of them. |
time_resolution |
Desired temporal resolution, in minutes, regardless of the
time unit of |
time_unit |
Time units of the provided chromatograms: either |
sample_var |
Name of the new column containing sample identifiers. |
lambdas |
Wavelength(s) to include. Defaults to all wavelengths. |
rts |
Retention times to include, each matched to the nearest time point. Defaults to all retention times. |
transfer_metadata |
Logical. If |
A data frame in long format with columns rt, lambda, absorbance,
and a sample identifier column specified by sample_var.
Ethan Bass
Other utility functions:
combine_peaks(),
merge_peaks(),
reshape_peaktable()
data(Sa_warp) reshape_chroms(Sa_warp, lambdas = 210)data(Sa_warp) reshape_chroms(Sa_warp, lambdas = 210)
Reshapes a peak table to long format, or to a wide data.frame with the selected peaks alongside sample metadata.
reshape_peaktable( x, peaks, metadata, fixed_levels = TRUE, format = c("long", "wide") )reshape_peaktable( x, peaks, metadata, fixed_levels = TRUE, format = c("long", "wide") )
x |
A |
peaks |
A character vector specifying the peaks to include. If the character vector is named, the names of the vector elements will be used in place of the original peak names. |
metadata |
A character vector specifying the metadata fields to include. |
fixed_levels |
Logical. Whether to fix factor levels of features in the
order provided. Defaults to |
format |
Either |
A data.frame containing the information for the specified peaks. In
long format it has columns sample, peak, lambda, rt, the response and
any metadata; in wide format, sample, any metadata, then one column per
peak.
Ethan Bass
Other utility functions:
combine_peaks(),
merge_peaks(),
reshape_chroms()
data(pk_tab) reshape_peaktable(pk_tab, peaks = c("V8", "V13")) reshape_peaktable(pk_tab, peaks = c(a = "V8", b = "V13"), format = "wide")data(pk_tab) reshape_peaktable(pk_tab, peaks = c("V8", "V13")) reshape_peaktable(pk_tab, peaks = c(a = "V8", b = "V13"), format = "wide")
A list of four HPLC-DAD data matrices of Solidago altissima roots extracted in 90\ wavelengths are stored in columns. Data were collected on an Agilent 1100 HPLC.
data(Sa)data(Sa)
A list of four matrices (1301 timepoints × 60 wavelengths).
Other data objects:
Sa_pr,
Sa_warp,
pk_tab
A list of four pre-processed HPLC-DAD chromatograms derived from the raw data
stored in Sa. Retention times are stored in rows and wavelengths
are stored in columns. The time axis is interpolated from the 0.0067-minute
interval of Sa to 0.02 minutes, to save space and processing time.
data(Sa_pr)data(Sa_pr)
A list of four pre-processed matrices (434 timepoints × 60 wavelengths).
Other data objects:
Sa,
Sa_warp,
pk_tab
A list of four pre-processed and warped goldenrod root chromatograms derived
from the raw data stored in Sa.
data(Sa_warp)data(Sa_warp)
A list of four pre-processed and warped matrices (434 timepoints × 60 wavelengths).
Other data objects:
Sa,
Sa_pr,
pk_tab
Plots a chromatographic trace from the specified chromatogram (idx),
at the specified wavelength (lambda) with a dotted red line to indicate
the user-selected retention time. The trace is a single column from the
chromatographic matrix.
scan_chrom( chrom_list, idx, lambda, plot_spectrum = TRUE, peak_table = NULL, scale_spectrum = FALSE, spectrum_labels = TRUE, export_spectrum = FALSE, ... )scan_chrom( chrom_list, idx, lambda, plot_spectrum = TRUE, peak_table = NULL, scale_spectrum = FALSE, spectrum_labels = TRUE, export_spectrum = FALSE, ... )
chrom_list |
A list of chromatograms in matrix format (timepoints ×
wavelengths). If no argument is provided here, the function will try to find
the |
idx |
Index or name of the chromatogram to plot. If missing, you are prompted for one. |
lambda |
The wavelength at which to plot the chromatographic trace.
Required; |
plot_spectrum |
Logical. If |
peak_table |
A |
scale_spectrum |
Logical. If |
spectrum_labels |
Logical. If |
export_spectrum |
Logical. If |
... |
Additional arguments to |
If plot_spectrum is TRUE, plots the spectrum for the specified
chromatogram at the user-specified retention time. The spectrum is a single
row from the chromatographic matrix.
Invisibly returns the spectrum when export_spectrum = TRUE and
plot_spectrum = TRUE; otherwise the numeric index of the scan selected by
the user.
Plots are rendered to the active graphics device.
Ethan Bass
Other visualization functions:
boxplot.peak_table(),
mirror_plot(),
plot.chrom_list(),
plot.matched_peak_list(),
plot.peak_list(),
plot.peak_table(),
plot_all_spectra(),
plot_chrom_contour(),
plot_chroms(),
plot_chroms_heatmap(),
plot_spectrum()
data(Sa_pr) scan_chrom(Sa_pr, lambda = "210", idx = 2, export_spectrum = TRUE)data(Sa_pr) scan_chrom(Sa_pr, lambda = "210", idx = 2, export_spectrum = TRUE)
Subtracts a blank chromatogram from each sample in a chrom_list,
using either the mean of all blanks, the nearest blank in run order,
or the most recent preceding blank.
subtract_blanks( chrom_list, pattern = NULL, blank_id, method = c("mean", "nearest", "preceding"), zero_floor = FALSE )subtract_blanks( chrom_list, pattern = NULL, blank_id, method = c("mean", "nearest", "preceding"), zero_floor = FALSE )
chrom_list |
A |
pattern |
A regular expression matched against
|
blank_id |
Names or indices of the elements in |
method |
How to select the blank to subtract for each sample:
|
zero_floor |
Logical. If |
Blanks recorded on a different time grid from a sample (for example, one or two points longer or shorter) are linearly interpolated onto the sample's retention times before subtraction. Where the sample runs past either end of the blank, the blank's first or last value is carried forward, with a warning if this spans more than 5 time points. Blanks and samples must share the same wavelengths.
A chrom_list with blank-subtracted samples. Blanks
themselves are removed from the returned list, and so is any
"estimated_baseline" attribute on the samples.
Other preprocessing functions:
correct_baseline(),
crop_chroms(),
preprocess()
data(Sa_warp) subtract_blanks(Sa_warp, blank_id = 1)data(Sa_warp) subtract_blanks(Sa_warp, blank_id = 1)
Targeted analysis measures a set of known compounds. Two routes lead from a
table of target compounds to a peak table with a named column for each
target: selecting peaks by retention time in get_peaks, or matching peaks
to a reference sample with match_peaks.
Select peaks by retention time using get_peaks when the samples are
aligned, or can be aligned with correct_rt, and no other peak falls
within tol of a target. Only the peaks near the targets are fitted, which
is quicker, and each target can be measured at its own wavelength.
Match peaks to a reference using match_peaks when retention times alone
cannot identify the targets (e.g., in crowded windows). Peaks are matched by
spectrum as well as retention time, so a target can be picked out from its
neighbors, and the retention-time window can be wider to allow for drift.
Every peak is fitted, and every target is measured at the same wavelength.
Build a data.frame with an rt column giving the retention time of each target
and, optionally:
name: Unique names, used as peak table column names.
lambda: The wavelength at which to measure each target. When matching to
a reference, it must equal the lambda given to match_peaks.
tol: How far each target's peak may lie from its rt, in minutes,
regardless of the time unit of the chromatograms. Defaults to 0.1.
spectral_cutoff: Used only by match_peaks. The minimum spectral
correlation for a match to each target's reference peak. Defaults to the
spectral_cutoff argument of match_peaks.
rt_window: Used only by match_peaks. The maximum difference in
retention time, in minutes, between each target's reference peak and its
match in another sample. Defaults to the rt_window argument of
match_peaks.
Call get_peaks(chrom_list, targets = targets). In each sample, get_peaks
fits only the peaks whose apex lies within tol of a target.
Call get_peaktable on the result. The peak table has one column per
target found in at least one sample; a target found in no sample gets no
column.
Peaks are assigned by retention time only, so each target must stay within
tol of its listed time in every sample, and closer to it than to any
neighboring target. If the samples drift more than that, fit warping models
with correct_rt and pass them as a mod_list; the targets are then found
on the aligned time axis.
When more than one peak falls within tol of a target, the select_by
argument of get_peaks decides which is retained. The default,
select_by = "height", keeps the tallest, which may not be the target;
narrow tol, or set select_by = "proximity" to keep the peak closest to
the target. Peaks are selected before they are fitted, so "height"
compares the signal at each apex, including any baseline beneath it.
To keep every candidate in the peak list, set select_by = "none". Where a
sample has several peaks for one target, get_peaktable enters the one
with the largest response in the table, but summarizes the target's
pk_meta over all of them, so its rt can fall between the candidates. To
take the metadata from the most intense peak instead, set
summarize_by = "max" in get_peaktable.
Call get_peaks without providing targets, so that every peak is fitted.
Call match_peaks(peak_list, targets = targets, lambda = ...).
Unless reference is supplied, match_peaks picks as reference a sample that
has a peak for every target, then matches each sample's peaks to the
reference peaks by spectral correlation and retention time.
Call get_peaktable(matched, pks = peak_list). Unlike the other
pathway, the peak table will still include untargeted peaks. Use
[, targets$name] to keep only the targets.
In the reference sample, each target is assigned to the tallest well-fitted
peak within tol minutes of the specified rt. A peak in another sample can
match a reference peak only if it lies within rt_window minutes of it and
their spectral correlation is above the spectral_cutoff.
Ethan Bass
get_peaks, match_peaks, get_peaktable
data(Sa_pr) targets <- data.frame(name = c("A", "B"), rt = c(12.07, 14.31)) # selecting by retention time, on the aligned time axis mods <- correct_rt(Sa_pr, lambdas = 220, what = "models", reference = 1) pks_t <- get_peaks(Sa_pr, lambdas = 220, targets = targets, mod_list = mods) get_peaktable(pks_t) # matching to a reference sample pks <- get_peaks(Sa_pr, lambdas = 220) matched <- match_peaks(pks, targets = targets, lambda = 220) get_peaktable(matched, pks = pks)[, targets$name]data(Sa_pr) targets <- data.frame(name = c("A", "B"), rt = c(12.07, 14.31)) # selecting by retention time, on the aligned time axis mods <- correct_rt(Sa_pr, lambdas = 220, what = "models", reference = 1) pks_t <- get_peaks(Sa_pr, lambdas = 220, targets = targets, mod_list = mods) get_peaktable(pks_t) # matching to a reference sample pks <- get_peaks(Sa_pr, lambdas = 220) matched <- match_peaks(pks, targets = targets, lambda = 220) get_peaktable(matched, pks = pks)[, targets$name]
Exports peak table in csv or xlsx format.
write_peaktable( peak_table, path, filename = "peak_table", format = c("csv", "xlsx"), what = c("tab", "pk_meta", "sample_meta", "instrument_meta", "ref_spectra", "args") )write_peaktable( peak_table, path, filename = "peak_table", format = c("csv", "xlsx"), what = c("tab", "pk_meta", "sample_meta", "instrument_meta", "ref_spectra", "args") )
peak_table |
Peak table object from |
path |
Path to an existing directory in which to write the files. |
filename |
File name. Defaults to |
format |
File format to export. Either |
what |
Which elements of the |
No return value. The function is called for its side effects.
With format = "csv", writes one file per element of what, named
<filename>-<element>.csv. With format = "xlsx", writes a single
<filename>.xlsx workbook with one sheet per element. Requires the
openxlsx package.
data(pk_tab) path_out = tempdir() write_peaktable(pk_tab, path = path_out, what = c("tab"))data(pk_tab) path_out = tempdir() write_peaktable(pk_tab, path = path_out, what = c("tab"))