| Title: | Small Molecule Mass Spectrometry Data Processing, Quality Control, and Reporting |
|---|---|
| Description: | MRMhub-QUANT, the quantitation and reporting module of the MRMhub toolchain, is a tool for processing, quality control, and visualization of targeted metabolomics and lipidomics mass spectrometry data. |
| Authors: | Bo Burla [aut, cre] (ORCID: <https://orcid.org/0000-0002-5918-3249>), Guo Shou Teo [aut] (ORCID: <https://orcid.org/0000-0003-3891-1494>), Hyungwon Choi [aut] (ORCID: <https://orcid.org/0000-0002-6687-3088>) |
| Maintainer: | Bo Burla <[email protected]> |
| License: | AGPL-3 |
| Version: | 1.0.1 |
| Built: | 2026-10-12 06:44:02 UTC |
| Source: | https://github.com/SLINGhub/MRMhub |
MRMhubExperiment object via $ syntax$ syntax can be used to as a shortcut for getting specific variables and results from a MRMhubExperiment object
## S4 method for signature 'MRMhubExperiment' x$name## S4 method for signature 'MRMhubExperiment' x$name
x |
|
name |
|
Value with a variable or a tibble
mexp <- MRMhubExperiment(title = "Test Experiment", analysis_type = "lipidomics") mexp$analysis_type mexp$title mexp$annot_analysesmexp <- MRMhubExperiment(title = "Test Experiment", analysis_type = "lipidomics") mexp$analysis_type mexp$title mexp$annot_analyses
MRMhubExperiment objectMetadata provided as a list of tibbles will be validated for consistency against the loaded analysis data of the provided MRMhubExperiment object and then transferred.
add_metadata(data = NULL, metadata, excl_unmatched_analyses = FALSE)add_metadata(data = NULL, metadata, excl_unmatched_analyses = FALSE)
data |
|
metadata |
List of tibbles or data.frames containing analysis, feature, istd, response curve tables |
excl_unmatched_analyses |
Exclude analyses (samples) that have no matching metadata |
An updated MRMhubExperiment object
The metadata guide.
Opens an interactive Shiny application that helps you turn your data and
metadata files into a runnable Quarto (.qmd) mrmhub workflow. Point the app
at your files, tick the processing steps you need, and the app validates the
inputs against each step (warning, for example, when normalize_by_istd is
selected but no istd_feature_id is defined) while previewing the generated
workflow document for download.
build_workflow()build_workflow()
Invisible NULL. Launches the Shiny app in the default browser.
generate_workflow_qmd() for the non-interactive generator.
if (interactive()) { build_workflow() }if (interactive()) { build_workflow() }
Calculates the average molecular weight of one or more chemical formulas, based on the natural isotopic distribution of elements. The calculation uses the enviPat package to retrieve isotopic masses and abundances, and computes the weighted mean of the isotopic distribution.
calc_average_molweight(formula)calc_average_molweight(formula)
formula |
A character vector of one or more chemical formulas to process. |
This function calculates the average molecular weight (not monoisotopic mass), which reflects the average of the isotopic distribution found in nature.
Isotopes can be specified explicitly in the formula. Atomic mass numbers for isotopes must be enclosed in square brackets (e.g., [13]C for carbon-13).
Deuterium must be written as D instead of [2]H.
The function uses the enviPat package to validate and parse chemical formulas, calculate isotopic patterns, and determine the average molecular weight based on weighted means of isotopic abundances.
A numeric vector of average molecular weights, one for each formula;
NA for a missing formula.
Loos, M., Gerber, C., Corona, F., Hollender, J., & Singer, H. (2015). Accelerated Isotope Fine Structure Calculation Using Pruned Transition Trees. Analytical Chemistry, 87(11), 5738–5744. doi:10.1021/acs.analchem.5b00941
calc_average_molweight(c("C6H12O6", "[13]C6H12O6", "C8H10N4O2", "D2O"))calc_average_molweight(c("C6H12O6", "[13]C6H12O6", "C8H10N4O2", "D2O"))
Calibration curves are calculated for each feature using ISTD-normalized
intensities and the corresponding concentrations of calibration samples, as
defined in the qc_concentrations metadata. The regression fit model (linear
or quadratic) and the weighting method (either "none", "1/x", "1/x^2", or
"1/sqrt(x)")
can be defined globally via the arguments fit_model and fit_weighting
for all features, if fit_overwrite is TRUE. Alternatively, the
model and weighting can be defined individually for each feature in the
feature metadata (columns curve_fit_model and curve_fit_weighting). If
these details are missing in the metadata, the default values provided via
fit_model and fit_weighting will be used.
calc_calibration_results( data = NULL, variable = "feature_norm_intensity", include_qualifier = TRUE, fit_overwrite, fit_model, fit_weighting, ignore_missing_annotation = FALSE, include_fit_object = FALSE, lod_sigma = c("residual", "intercept"), ignore_failed_calibration = FALSE )calc_calibration_results( data = NULL, variable = "feature_norm_intensity", include_qualifier = TRUE, fit_overwrite, fit_model, fit_weighting, ignore_missing_annotation = FALSE, include_fit_object = FALSE, lod_sigma = c("residual", "intercept"), ignore_failed_calibration = FALSE )
data |
A |
variable |
A character string specifying the variable for calibration.
Use |
include_qualifier |
A logical value. If |
fit_overwrite |
If |
fit_model |
A character string specifying the default regression fit
method to use for the calibration curve. Must be one of |
fit_weighting |
A character string specifying the default weighting
method for the regression points in the calibration curve. Must be one of
|
ignore_missing_annotation |
If |
include_fit_object |
If |
lod_sigma |
A character string selecting the response standard deviation
(sigma) used in the ICH Q2 LoD/LoQ formulas. Must be one of |
ignore_failed_calibration |
If |
A linear curve is also fitted with 2 calibrators, and a single calibrator
gives a line through the origin (coef_a = 0). A quadratic curve needs at
least 3 calibrators. A zero-concentration calibrator is dropped from
weighted fits, so a blank plus one standard is then fitted through the
origin. A curve that passes through all its calibrators (e.g. 2 points for a
line, 3 for a quadratic) has no R², sigma, LoD or LoQ (NA).
Additionally, the limit of detection (LoD) and limit of quantification (LoQ)
are calculated for each feature based on the calibration curve, following the
ICH Q2(R1/R2) approach (LoD = 3.3 sigma / S, LoQ = 10 sigma / S). Here S is
the slope of the calibration curve, taken at zero concentration (the linear
coefficient coef_b). For a quadratic fit the true slope is b + 2 c x,
which reduces to coef_b at zero concentration, so the quadratic term does
not contribute to the slope used here. ICH Q2 specifies the slope formula for
linear responses only; using the low-concentration tangent slope for a
quadratic fit is an approximation beyond the guideline (adequate when the
curvature near zero is small).
The response standard deviation sigma is selected via lod_sigma, following
the ICH-acceptable choices: "residual" uses the residual standard error of
the regression (Sy/x; the default and prior behaviour), while "intercept"
uses the standard error of the intercept. The sigma column reported in
metrics_calibration is always the residual standard error, independent of
this choice.
The results of the regression and the calculated LoD and LoQ values are
stored in the metrics_calibration table of the returned MRMhubExperiment
object.
The fitted curve is stored in ascending power order, following R's
lm() / poly() convention. The model is
response = coef_a + coef_b * x + coef_c * x^2
coef_a — intercept (0th-order term, x^0)
coef_b — 1st-order (linear) coefficient (x^1); the slope of a linear fit
coef_c — 2nd-order (quadratic) coefficient (x^2); NA for a linear fit
Only linear and quadratic models are fitted, so there are no higher-order
terms. This ascending order is the reverse of the descending
a*x^2 + b*x + c form printed by some vendor software (e.g. Agilent
MassHunter, where a is the quadratic term). When comparing against such an
export, match coefficients by power (coef_a = intercept, coef_c = x^2),
not by letter.
A modified MRMhubExperiment object with an updated
metrics_calibration table containing the calibration curve results,
including concentrations, LoD, and LoQ values for each feature.
ICH Harmonised Tripartite Guideline. Validation of Analytical Procedures: Text and Methodology Q2(R1) (2005); Q2(R2) (2023). International Council for Harmonisation of Technical Requirements for Pharmaceuticals for Human Use.
quantify_by_calibration() for calculating concentrations based on
external calibration curves.
Automatically discovers isotopic (M+2) interference relationships
between measured features and stores them in the annot_interferences slot,
ready for correct_isotopic_interferences(). Two levels are supported:
"MRM" (default): fragment-based front/back correction for class-based
LC-MRM data, derived from the LICAR method (see the manual). Requires
precursor and product m/z and an mrm_pattern per feature.
"MS1": whole-molecule M+2 correction for MS1 / full-scan
acquisitions. The factor is the M+2 relative abundance of each species'
molecular formula; interfering pairs are matched by precursor m/z (~2 Da
apart) within a feature class. Requires precursor m/z only.
calc_isotopic_interferences( data = NULL, level = c("MRM", "MS1"), mz_tol = 0.5, min_contribution = 0, check_coelution = FALSE )calc_isotopic_interferences( data = NULL, level = c("MRM", "MS1"), mz_tol = 0.5, min_contribution = 0, check_coelution = FALSE )
data |
A |
level |
Correction level, |
mz_tol |
Precursor m/z tolerance (Da) for matching interfering pairs at
the MS1 level (MRM uses a fixed 2 +/- 0.2 Da precursor window). Default |
min_contribution |
Drop derived edges whose contribution factor |
check_coelution |
(experimental) If |
Important — MS1 is not a fallback for MRM. For MRM data the
isotopic correction must be fragment-based: the contribution of heavy
isotopes to a transition depends on the isotope's location relative to the
fragmentation (Gao et al. 2021). The whole-molecule ("MS1") level is only
valid for genuine MS1/full-scan measurements and must not be used as a
substitute for MRM data that happens to lack a product m/z.
Derived factors are sensitive to the enviPat version; version 2.8 is the
reference. Existing manual interferences (source == "manual") are preserved;
previously derived ("auto") rows are replaced.
The contribution K is the fraction of a lighter species' signal that appears
at M+2; it is subtracted downstream by correct_isotopic_interferences() as
.
MS1 (whole-molecule): , computed from the species' molecular
formula with enviPat isopattern (see mN_rel_abundance()).
MRM (fragment-based, LICAR): the fragment elemental formula is built from
the precursor carbon/hydrogen count plus a per-class offset c(C, H, O, N),
with ; K is that fragment's M+2 isotopologue
fraction from enviPat isowrap (centroided, algorithm 2 — chosen over
isopattern for parity with published LICAR values). Front vs back
distinguishes whether the heavy isotope lands on the retained product ion or
the neutral loss; FA/LCB species carry a front + back pair, and LCB inverts
the front/back assignment relative to FA.
The MRMhubExperiment with a populated annot_interferences slot.
Gao L. et al. (2021). LICAR: An Application for Isotopic Correction of Targeted Lipidomic Data Acquired with Class-Based Chromatographic Separations Using Multiple Reaction Monitoring. Analytical Chemistry, 93(6), 3163-3171. doi:10.1021/acs.analchem.0c04565
Computes various quality control (QC) metrics for each feature in a
MRMhubExperiment object. Metrics are derived from different sample
types and can be computed either across the full dataset or as medians
of batch-wise calculations.
calc_qc_metrics( data = NULL, use_batch_medians = FALSE, use_robust_cv = FALSE, include_norm_intensity_stats = NA, include_conc_stats = NA, include_response_stats = NA, include_calibration_results = NA )calc_qc_metrics( data = NULL, use_batch_medians = FALSE, use_robust_cv = FALSE, include_norm_intensity_stats = NA, include_conc_stats = NA, include_response_stats = NA, include_calibration_results = NA )
data |
A |
use_batch_medians |
Logical, whether to compute QC metrics using the
median of batch-wise derived values instead of the full dataset. Default is
|
use_robust_cv |
Logical, whether to use robust coefficient of variation (MAD/median) or the standard coefficient of variation (SD/mean) for intensity, norm_intensity and concentration metrics. |
include_norm_intensity_stats |
Logical. If |
include_conc_stats |
Logical. If |
include_response_stats |
Logical. If |
include_calibration_results |
Logical. If |
Batch-wise calculations: The function computes the following QC metrics for each feature and for different QC sample types (e.g., SPL, TQC, BQC, PBLK, NIST, LTR)
The format for the metrics is standardized as metric_name_qc_type, where
qc_type refers to the specific QC sample type for which the metric is
calculated. For example: intensity_min_spl refers to the minimum intensity
Statistics of normalized intensities, external calibration, and response
curves can be included by setting the relevant arguments
(include_norm_intensity_stats, include_conc_stats,
include_response_stats, include_calibration_results) to TRUE.
Note when corresponding underlying processed data is not available,
the function will not raise an error but will return NA values for the
respective metrics. This, however, does not apply for the optional metrics
mentioned above. For these cases an error will be raised if the underlying
data is missing.
If use_batch_medians = TRUE, batch-specific QC statistics are computed
first, and then the median of these values is returned for each feature.
However, response curve and calibration statistics are calculated per
curve, irrespective of batches and use_batch_medians settings.
The calculated metrics are stored in the metrics_qc table of the
MRMhubExperiment objects and comprises following details
Feature details: Specific feature information extracted from the feature metadata table, such as feature class, associated ISTD, quantifier status.
Feature MS method information (if available in the imported data):
precursor_mz, product_mz and collision_energy per feature. A value
that differs between analyses indicates inconsistent acquisition
conditions; it is set to NA with a warning naming the features.
Missing Value Metrics:
missing_intensity_prop_spl: Proportion of missing intensities for the SPL sample type.
missing_norm_intensity_prop_spl: Proportion of missing normalized intensities for SPL samples.
missing_conc_prop_spl: Proportion of missing concentration values for SPL samples.
na_in_all: Indicator if a feature has all missing intensities across all samples
Retention Time (RT) Metrics: Requires that retention time data are available.
rt_min_*: Minimum retention time across different QC sample types (e.g., SPL, BQC, TQC).
rt_max_*: Maximum retention time across different QC sample types.
rt_median_*: Median retention time for specific QC sample types like PBLK, SPL, BQC, TQC, etc.
Intensity Metrics:
n_bqc, n_tqc, n_spl: Number of analyses with a non-missing intensity
per QC type, i.e. the replicates behind the %CV and D-ratio (the median
of the per-batch counts with use_batch_medians = TRUE). %CV and D-ratio
are NA below 3 replicates.
intensity_min_*: Minimum intensity value for features across different QC sample types such as SPL, TQC, BQC, etc.
intensity_max_*: Maximum intensity values across sample types.
intensity_median_*: Median intensity for various QC sample types.
intensity_cv_*: Coefficient of variation (CV) of intensity values for specific QC types.
sb_ratio_*: Signal-to-blank ratios such as the ratio of intensity values for SPL vs PBLK, UBLK, or SBLK.
Blank medians count a blank analysis without detected signal (a missing
value or no row for the feature) as zero, giving a ratio of Inf.
intensity_q10_*: The 10th percentile of intensity values for the SPL sample type.
Normalized Intensity Metrics (only if include_norm_intensity_stats = TRUE):
Requires that raw intensities were normalized, see normalize_by_istd()
for details.
norm_intensity_cv_*: Coefficient of variation (CV) of normalized intensities for QC sample types like TQC, BQC, SPL, etc.
Concentration Metrics (only if include_conc_stats = TRUE):
Requires that concentration were calculated, see quantify_by_istd() or
quantify_by_calibration() for details.
conc_median_*: Median concentration values for different QC sample types like TQC, BQC, SPL, NIST, and LTR.
conc_cv_*: Coefficient of variation (CV) for concentration values.
conc_dratio_sd_*: The ratio of standard deviations of concentration between BQC or TQC and SPL samples.
conc_dratio_mad_*: The ratio of median absolute deviations (MAD) between BQC or TQC and SPL concentrations.
Response Curve Metrics (if include_response_stats = TRUE):
Calculates response curve statistics for each feature and each curve
(where # refers to the curve identifier). Requires that response curves
are defined in the data. See get_response_curve_stats() for additional details.
r2_rqc_#: R² value of the linear regression for the response
curve, representing the goodness of fit.
slopenorm_rqc_#: Normalized slope of the linear regression for the
response curve, indicating the relationship between the response and
concentration.
y0norm_rqc_#: Normalized intercept of the linear regression for the
response curve, representing the baseline or starting value.
External Calibration Results Incorporates external calibration results,
if include_calibration_results = TRUE and calibration curves are defined
in the data:
fit_model: The regression model used for curve fitting.
fit_weighting: The weighting method applied during curve fitting.
lowest_cal: The lowest nonzero calibration concentration.
highest_cal: The highest calibration concentration.
r.squared: R² value indicating the goodness of fit.
coef_a: The intercept of the regression line (both linear and
quadratic fits).
coef_b:
For linear fits, the slope of the regression line.
For quadratic fits, the coefficient of the linear term (x).
coef_c:
For quadratic fits, the coefficient of the quadratic term (x²).
Set to NA for linear fits.
sigma: The residual standard error of the regression model.
reg_failed: Boolean flag indicating if regression fitting failed.
A MRMhubExperiment object with an updated metrics_qc table
containing computed QC metrics for each feature.
This function calibrates feature abundances based on a specified reference sample.
Calibration can be applied to the entire dataset using one or more reference samples,
or batch-wise using reference sample analyses present within each batch.
For both approaches, multiple measurements of the same reference sample are
summarized using either mean (default) or median (set by the summarize_fun argument).
calibrate_by_reference( data, variable, reference_sample_id, absolute_calibration, batch_wise = FALSE, summarize_fun = "mean", store_conc_ratio = NULL, undefined_conc_action = NULL, store_normalized = FALSE )calibrate_by_reference( data, variable, reference_sample_id, absolute_calibration, batch_wise = FALSE, summarize_fun = "mean", store_conc_ratio = NULL, undefined_conc_action = NULL, store_normalized = FALSE )
data |
A |
variable |
Character string indicating which data type to calibrate. Must be one of: "intensity", "norm_intensity", or "conc" |
reference_sample_id |
Character vector specifying the sample ID(s) to use as
reference(s) or standards. When more than one ID is given, all analyses
whose |
absolute_calibration |
Logical indicating whether to perform absolute calibration using
known concentrations of the reference sample ( |
batch_wise |
Logical indicating whether to perform calibration for each batch seperately ( |
summarize_fun |
Either "mean" or "median". If |
store_conc_ratio |
Logical. Whether to store the ratio of measured
(non-calibrated) compared to the expected (known) concentrations. Only applied if |
undefined_conc_action |
Character string specifying how to handle features
without defined concentrations in reference samples when |
store_normalized |
Logical indicating whether to keep the normalized values in the dataset
when |
Calibration can be performed in two ways, either absolute, resulting in concentrations, or relative, resulting in ratios:
Absolute calibration (when absolute_calibration = TRUE)
Calibrates (or re-calibrates) feature abundances based on known concentrations of the corresponding features defined for a reference sample. The calibrated concentration for a given analyte is calculated as:
The input variable can be either conc, norm_intensity, or intensity, whereas the result is
always stored under the variable conc (concentration), in the unit defined
for the feature concentrations in the reference sample.
Metadata requirements:
sample_id and analyte_id must be defined for the reference sample and features in the analysis and feature metadata, respectively.
Known analyte concentrations must be defined in the QC concentration metadata for the for the reference sample
An error will be raised if no concentrations are defined for any features
Missing analyte concentrations for the reference sample can be handled via undefined_conc_action with following options:
original: Keep original feature values, i.e. the non-calibrated values will be returned. Note: this is only available when variable = conc. Use with caution to avoid mixing units.
na: Set affected features values to NA
error: The function stops with error in case of any undefined reference sample feature concentration.
In case all feature concentrations are undefined, the function will stop with an error.
The re-calibrated feature concentrations are stored as conc, overwriting existing conc values.
The original conc values are stored as conc_beforecal.
The ratio between the measured and expected (known) concentrations in the
reference sample is available via the feature variable feature_conc_ratio
and is calculated as follows:
where is the measured (non-calibrated) concentration, and
is the known or reference concentration for the same analyte.
A ratio of 1 indicates perfect agreement; values above or below 1 indicate over- or underestimation.
To export the calibrated concentrations use save_dataset_csv() with variable = "conc",
or to export non-calibrated values with variable = "conc_beforecal".
When saving the MRMhub XLSX report, the calibrated concentrations will also be stored as conc.
Normalization (relative calibration, absolute_calibration = FALSE)
Normalizes feature abundances with corresponding feature abundances in a reference sample,
resulting in ratios. Any available feature abundance variable
(i.e., conc, norm_intensity, or intensity) can be used as input. The normalization is calculated for all present features.
The resulting output will be stored as [VARIABLE]_normalized, whereby [VARIABLE] is the input variable, e.g., conc_normalized.
To export the normalized abundances, use save_dataset_csv() with variable = "[VARIABLE]_normalized".
When saving the MRMhub XLSX report via save_report_xlsx(), available unfiltered normalized feature abundances
will be included by default. To include filtered normalized feature abundances, set filtered_variable = "[VARIABLE]_normalized".
A MRMhubExperiment object with calibrated data
normalize_by_istd(), quantify_by_istd(), quantify_by_calibration()
Validates that the user's R environment is correctly configured to use mrmhub. Checks R version, key dependencies, and optional packages.
check_setup(verbose = TRUE)check_setup(verbose = TRUE)
verbose |
Logical. If |
A list (invisibly) with elements r_version, required, and
optional, each containing pass/fail status.
check_setup()check_setup()
This function performs batch centering correction on each feature.
Optionally, the scale of the batches can be equalized across batches.
The selected QC types (ref_qc_types) are used to calculate
the medians, which are then used to align all other samples. The
correction can be applied to one of three variables: "intensity",
"norm_intensity", or "conc". The correction can either be applied
on top of previous corrections or replace all prior batch corrections.
correct_batch_centering( data = NULL, variable, ref_qc_types, correct_scale = FALSE, ignore_istd = TRUE, replace_previous = TRUE, log_transform_internal = TRUE, feature_list = NULL, replace_exisiting_trendcurves = FALSE, ... )correct_batch_centering( data = NULL, variable, ref_qc_types, correct_scale = FALSE, ignore_istd = TRUE, replace_previous = TRUE, log_transform_internal = TRUE, feature_list = NULL, replace_exisiting_trendcurves = FALSE, ... )
data |
A |
variable |
The variable to be corrected. Must be one of "intensity", "norm_intensity", or "conc". |
ref_qc_types |
A character vector specifying the QC types to be used as references for batch centering. |
correct_scale |
A logical value indicating whether to equalize the scale
of the batches in addition to center them. Defaults to |
ignore_istd |
Logical. Exclude internal standards (ISTDs) from correction
if |
replace_previous |
A logical value indicating whether to replace any
previous batch corrections or apply the new correction on top. Defaults to
|
log_transform_internal |
A logical value indicating whether to log-transform
the data internally during correction. Defaults to |
feature_list |
Sets specific features for correction only. Can be character vector or a single string which is then interpreted as regular expression. Default is |
replace_exisiting_trendcurves |
A logical value indicating whether to replace
trend curves from previous corrections. This is only used for plotting using |
... |
Additional arguments that can be passed to the batch correction function. |
A MRMhubExperiment object containing the corrected data.
plot_runscatter() for visualizing the correction before and after; the drift-correction tutorial for a worked example.
Adjusts batch effects with the empirical-Bayes ComBat method (Johnson et al. 2007), applied to one of "intensity", "norm_intensity", or "conc". ComBat models a location and scale batch effect per feature and shrinks those estimates across features, which can stabilise many small batches better than simple median centering.
Unlike correct_batch_centering() and correct_batch_serrf(), ComBat
estimates batch effects from all study samples and routine QCs (optionally
protecting biology via covariates), not only from the reference QCs.
Blanks, response curves, calibrants and other analysis types are left out of
the fit and keep their uncorrected values. On strongly unbalanced designs
this can remove genuine biological signal, so supply covariates when the
biological grouping is not balanced across batches. ref_qc_types is used
only for the before/after QC-CV report and the plotting trend curves.
Batch correction is performed after normalization and drift correction in the recommended pipeline. Features with any missing or non-finite values in the selected variable are left uncorrected (ComBat requires complete data).
correct_batch_combat( data = NULL, variable, ref_qc_types, covariates = NULL, ref_batch = NULL, parametric = TRUE, ignore_istd = TRUE, replace_previous = TRUE, log_transform_internal = TRUE, feature_list = NULL, replace_exisiting_trendcurves = FALSE )correct_batch_combat( data = NULL, variable, ref_qc_types, covariates = NULL, ref_batch = NULL, parametric = TRUE, ignore_istd = TRUE, replace_previous = TRUE, log_transform_internal = TRUE, feature_list = NULL, replace_exisiting_trendcurves = FALSE )
data |
A |
variable |
The variable to correct: one of "intensity", "norm_intensity", or "conc". |
ref_qc_types |
Character vector of QC types used for the QC-CV report and trend curves (not for the ComBat fit itself). |
covariates |
Optional model matrix of biological covariates to preserve
(passed to |
ref_batch |
Optional reference batch to adjust the others towards
(passed to |
parametric |
Use the parametric empirical-Bayes prior ( |
ignore_istd |
Logical. Exclude internal standards (ISTDs) from correction
if |
replace_previous |
Replace a previous batch correction ( |
log_transform_internal |
Fit ComBat in log10 space ( |
feature_list |
Optional feature selection (character vector or a single
regular expression); |
replace_exisiting_trendcurves |
Reseed the plotting trend curves. Default
|
A MRMhubExperiment with corrected data.
Johnson WE, Li C, Rabinovic A (2007). Adjusting batch effects in microarray expression data using empirical Bayes methods. Biostatistics, 8(1), 118-127. doi:10.1093/biostatistics/kxj037
Applied through sva::ComBat() from the sva package. See also
Broadhurst D, et al. (2018), Metabolomics, 14, 72
(doi:10.1007/s11306-018-1367-3) on QC-based signal correction.
correct_batch_centering(), correct_batch_serrf(),
correct_drift_loess() and plot_runscatter() for visualisation. The
drift and batch correction manual.
# mexp <- correct_batch_combat(mexp, variable = "conc", ref_qc_types = "BQC")# mexp <- correct_batch_combat(mexp, variable = "conc", ref_qc_types = "BQC")
This is an independent re-implementation of SERRF in mrmhub, adapted from the
reference code in the malbacR package (not the original authors' package);
see Details. Validate results against the reference SERRF for your data.
Normalises systematic error with SERRF (Systematic Error Removal using Random Forest; Fan et al. 2019). For each feature and batch a random forest is trained on the reference QC samples, using the batch's most-correlated features as predictors, and the learned systematic error is removed from the study samples and routine QCs; blanks, response curves, calibrants and other analysis types keep their uncorrected values. Unlike ComBat, SERRF captures non-linear drift and batch effects jointly and is anchored on the QC samples, matching the QC-based design of the package; it is best suited to larger panels with dense QC coverage.
SERRF operates on the raw abundance scale (no log transform). Features with missing or non-positive values, and batches with fewer than two reference QCs, are left uncorrected. Batch correction is performed after normalization and drift correction in the recommended pipeline.
correct_batch_serrf( data = NULL, variable, ref_qc_types, n_correlated = 10, num_trees = 500, seed = 1L, num_threads = 1L, show_progress = TRUE, ignore_istd = TRUE, replace_previous = TRUE, feature_list = NULL, replace_exisiting_trendcurves = FALSE )correct_batch_serrf( data = NULL, variable, ref_qc_types, n_correlated = 10, num_trees = 500, seed = 1L, num_threads = 1L, show_progress = TRUE, ignore_istd = TRUE, replace_previous = TRUE, feature_list = NULL, replace_exisiting_trendcurves = FALSE )
data |
A |
variable |
The variable to correct: one of "intensity", "norm_intensity", or "conc". |
ref_qc_types |
Character vector of QC types used as the SERRF training (reference) samples per batch. |
n_correlated |
Number of most-correlated features used as random-forest
predictors per feature. Default |
num_trees |
Number of trees per random forest. Default |
seed |
Random seed for |
num_threads |
Threads per random forest passed to |
show_progress |
Show a progress bar over batches. Default |
ignore_istd |
Logical. Exclude internal standards (ISTDs) from correction
if |
replace_previous |
Replace a previous batch correction ( |
feature_list |
Optional feature selection (character vector or a single
regular expression); |
replace_exisiting_trendcurves |
Reseed the plotting trend curves. Default
|
The implementation adapts the reference SERRF code in the malbacR package,
keeping its normalization arithmetic but selecting each feature's predictors
from the per-batch QC-sample Spearman correlation (a simplification of
malbacR's QC/sample correlation intersection). Random forests are fit with
ranger::ranger() and a fixed seed, so results are reproducible. Users are
encouraged to validate results against the reference SERRF implementation for
their data.
Batches are corrected independently and in parallel via mirai (through
purrr::in_parallel()); set up workers with mirai::daemons() beforehand to
use them, otherwise the batches are processed sequentially.
A MRMhubExperiment with corrected data.
Fan S, Kind T, Cajka T, et al. (2019). Systematic Error Removal Using Random Forest for Normalizing Large-Scale Untargeted Lipidomics Data. Analytical Chemistry, 91(5), 3590-3596. doi:10.1021/acs.analchem.8b05592
Implementation adapted from the malbacR package
(https://github.com/pmartR/malbacR); random forests via ranger
(Wright MN, Ziegler A, 2017, Journal of Statistical Software, 77(1),
doi:10.18637/jss.v077.i01).
correct_batch_centering(), correct_batch_combat(),
correct_drift_loess() and plot_runscatter() for visualisation. The
drift and batch correction manual.
# mexp <- correct_batch_serrf(mexp, variable = "conc", ref_qc_types = "BQC")# mexp <- correct_batch_serrf(mexp, variable = "conc", ref_qc_types = "BQC")
Applies the interference corrections you declared in the feature
metadata (the legacy interference_feature_id / interference_contribution
columns, and any source == "manual" rows in annot_interferences) to the raw
feature intensities, using the same engine and formula as
correct_isotopic_interferences(). Use this for in-source fragments,
co-eluting isobars or other non-isotopic interferences you know about. Warns
and returns the data unchanged if none are defined.
correct_custom_interferences( data = NULL, variable = "feature_intensity", sequential_correction = TRUE, neg_to_na = FALSE )correct_custom_interferences( data = NULL, variable = "feature_intensity", sequential_correction = TRUE, neg_to_na = FALSE )
data |
|
variable |
Name of the variable to correct. Only |
sequential_correction |
Logical. If |
neg_to_na |
If |
MRMhubExperiment object with feature intensities corrected.
correct_isotopic_interferences(), correct_interference_manual(); the interference-correction guide.
Function to correct for run-order drifts within or across batches via a provided custom function
correct_drift( data = NULL, smooth_fun, variable, ref_qc_types, batch_wise, replace_previous = TRUE, log_transform_internal = TRUE, conditional_correction = FALSE, cv_diff_threshold = 0, use_original_if_fail = TRUE, ignore_istd = TRUE, feature_list = NULL, recalc_trend_after = FALSE, show_progress = TRUE, ... )correct_drift( data = NULL, smooth_fun, variable, ref_qc_types, batch_wise, replace_previous = TRUE, log_transform_internal = TRUE, conditional_correction = FALSE, cv_diff_threshold = 0, use_original_if_fail = TRUE, ignore_istd = TRUE, feature_list = NULL, recalc_trend_after = FALSE, show_progress = TRUE, ... )
data |
|
smooth_fun |
Function that performs the drift correction for a single
feature within one batch. It must accept the arguments |
variable |
The variable to be corrected for drift effects. Must be one of "intensity", "norm_intensity", or "conc" |
ref_qc_types |
QC types used for drift correction |
batch_wise |
Apply to each batch separately if |
replace_previous |
Logical. Replace previous correction ( |
log_transform_internal |
Apply log transformation internally for smoothing if |
conditional_correction |
Determines whether drift correction is applied to all features unconditionally ( |
cv_diff_threshold |
This parameter defines the maximum allowable change (difference) in the coefficient of variation (CV) of samples before and after smoothing for the correction to be applied. A value of 0 (the default) requires the CV to improve, while a value above 0 allows the CV to also become worse by a maximum of the defined difference. |
use_original_if_fail |
Determines the action when smoothing fails or results in invalid values for a feature. If |
ignore_istd |
Do not apply corrections to ISTDs |
feature_list |
Sets specific features for correction only. Can be character vector or a single string which is then interpreted as regular expression. Default is |
recalc_trend_after |
Recalculate trend post-drift correction for |
show_progress |
Show progress bar. Default = |
... |
Arguments specific for the smoothing function |
The drift correction function needs to be provided by the user. See smooth_fun for details.
MRMhubExperiment object
This function corrects for run-order drifts within or across batches using cubic spline smoothing. The correction is typically based on QC (Quality Control) samples that are measured at specific intervals throughout the run sequence. The smoothed curve derived from the QC samples is then used to adjust all other samples in the dataset. The correction can be applied to "intensity", "norm_intensity", or "conc" data.
The cubic spline smoothing approach, particularly when used with the
regularization parameter lambda, is similar but not identical to previously described
QC-based drift correction methods, such as QC-RSC (Quality Control Regularized
Spline Correction), described in Dunn et al. (Nat Protoc, 2011) and Kirwan et al.
(Anal Bioanal Chem, 2013).
By default, the smoothing parameter is determined using cross-validation,
which can lead to overfitting. To reduce overfitting
the regularization parameter lambda may be defined, with a good starting point
being lambda = 0.01. Additionally, the global
smoothing parameter can be specified via spar.
It is recommended to visually inspect the correction using the
plot_runscatter() function. Set the argument
recalc_trend_after = TRUE so that the trends after correction are also
available for plotting. For further details, refer to the description
of plot_runscatter().
The corrections can be applied on a batch-by-batch basis (batch_wise = TRUE, default) or across all batches (batch_wise = FALSE). Existing
corrections are either replaced (replace_previous = TRUE) or added on top
of them (replace_previous = FALSE).
Furthermore, drift correction can be applied unconditionally
(conditional_correction = FALSE) or conditionally, based on whether the
sample CV change before and after correction is below a defined
threshold (cv_diff_threshold). This conditional correction is assessed
independently for each batch if batch_wise = TRUE, where the median of
the CV changes across the batch is compared with the threshold.
Note: The function outputs a message indicating the median CV change and the median absolute CV before and after correction for all samples. However, these metrics are experimental and should not be used as definitive criteria for correction (see Details below).
This cubic spline method is implemented using the base R function
stats::smooth.spline().
correct_drift_cubicspline( data = NULL, variable, ref_qc_types, batch_wise = TRUE, ignore_istd = TRUE, replace_previous = TRUE, cv = TRUE, spar = NULL, lambda = NULL, penalty = 1, conditional_correction = FALSE, recalc_trend_after = FALSE, log_transform_internal = TRUE, feature_list = NULL, cv_diff_threshold = 0, use_original_if_fail = FALSE, show_progress = TRUE )correct_drift_cubicspline( data = NULL, variable, ref_qc_types, batch_wise = TRUE, ignore_istd = TRUE, replace_previous = TRUE, cv = TRUE, spar = NULL, lambda = NULL, penalty = 1, conditional_correction = FALSE, recalc_trend_after = FALSE, log_transform_internal = TRUE, feature_list = NULL, cv_diff_threshold = 0, use_original_if_fail = FALSE, show_progress = TRUE )
data |
|
variable |
The variable to be corrected for drift effects. Must be one of "intensity", "norm_intensity", or "conc" |
ref_qc_types |
QC types used for drift correction |
batch_wise |
Logical. Apply the correction to each batch separately ( |
ignore_istd |
Logical. Exclude internal standards (ISTDs) from correction if |
replace_previous |
Logical. Replace existing correction ( |
cv |
Ordinary leave-one-out ( |
spar |
Smoothing parameter for cubic spline smoothing. If not specified or |
lambda |
Regularization parameter for cubic spline smoothing. Default is |
penalty |
The coefficient of the penalty for degrees of freedom in the GCV criterion. |
conditional_correction |
Determines whether drift correction is applied to all features unconditionally ( |
recalc_trend_after |
Recalculate trend post-drift correction for |
log_transform_internal |
Log transform the data for correction when |
feature_list |
Subset the features for correction whose names match the specified text using regular expression. Default is |
cv_diff_threshold |
Maximum allowable change (difference) in CV before and after smoothing for correction to be applied. |
use_original_if_fail |
Determines the action when smoothing fails or results in invalid values for a feature. If |
show_progress |
Logical. Display progress bars if |
In the output message, the median CV change is computed as the median of CV changes for all
features in global correction or for
features where the correction passed the defined CV difference threshold in
case of conditional correction (conditional_correction = TRUE).
For batch-wise correction, the change is calculated per batch, with the final median CV
change being the median of these batch medians across features.
MRMhubExperiment object
Dunn, W., Broadhurst, D., Begley, P. et al. Procedures for large-scale metabolic profiling of serum and plasma using gas chromatography and liquid chromatography coupled to mass spectrometry. Nat Protoc 6, 1060–1083 (2011). https://doi.org/10.1038/nprot.2011.335
Kirwan, J.A., Broadhurst, D.I., Davidson, R.L. et al. Characterising and correcting batch variation in an automated direct infusion mass spectrometry (DIMS) metabolomics workflow. Anal Bioanal Chem 405, 5147–5157 (2013). https://doi.org/10.1007/s00216-013-6856-7
stats::smooth.spline(); the drift-correction tutorial for a worked example.
This function corrects for run-order drifts within or across batches using Generalized Additive Models (GAMs). The correction uses penalized splines, with automatic selection of smoothing parameters based on cross-validation or penalized likelihood. It is typically based on QC (Quality Control) samples measured at specific intervals throughout the run sequence. The correction can be applied to "intensity", "norm_intensity", or "conc" data.
It is recommended to visually inspect the correction using the
plot_runscatter() function. Set the argument
recalc_trend_after = TRUE so that the trends after correction are also
available for plotting. For further details, refer to the description
of plot_runscatter().
The corrections can be applied on a batch-by-batch basis (batch_wise = TRUE, default) or across all batches (batch_wise = FALSE). Existing
corrections are either replaced (replace_previous = TRUE) or added on top
of them (replace_previous = FALSE).
Furthermore, drift correction can be applied unconditionally
(conditional_correction = FALSE) or conditionally, based on whether the
sample CV change before and after correction is below a defined
threshold (cv_diff_threshold). This conditional correction is assessed
independently for each batch if batch_wise = TRUE, where the median of
the CV changes across the batch is compared with the threshold.
Note: The function outputs a message indicating the median CV change and the median absolute CV before and after correction for all samples. However, these metrics are experimental and should not be used as definitive criteria for correction (see Details below).
This method is implemented using penalized splines via the
mgcv::gam() function.
correct_drift_gam( data = NULL, variable, ref_qc_types, batch_wise = TRUE, ignore_istd = TRUE, replace_previous = TRUE, bs = "ps", k = -1, sp = NULL, log_transform_internal = TRUE, conditional_correction = FALSE, recalc_trend_after = FALSE, feature_list = NULL, cv_diff_threshold = 0, use_original_if_fail = FALSE, show_progress = TRUE )correct_drift_gam( data = NULL, variable, ref_qc_types, batch_wise = TRUE, ignore_istd = TRUE, replace_previous = TRUE, bs = "ps", k = -1, sp = NULL, log_transform_internal = TRUE, conditional_correction = FALSE, recalc_trend_after = FALSE, feature_list = NULL, cv_diff_threshold = 0, use_original_if_fail = FALSE, show_progress = TRUE )
data |
|
variable |
The variable to be corrected for drift effects. Must be one of "intensity", "norm_intensity", or "conc" |
ref_qc_types |
QC types used for drift correction |
batch_wise |
Logical. Apply the correction to each batch separately ( |
ignore_istd |
Logical. Exclude internal standards (ISTDs) from correction if |
replace_previous |
Logical. Replace existing correction ( |
bs |
Basis type for the spline: |
k |
Number of basis functions (default: |
sp |
Smoothing parameter ( |
log_transform_internal |
Log transform the data for correction when |
conditional_correction |
Determines whether drift correction is applied to all features unconditionally ( |
recalc_trend_after |
Recalculate trend post-drift correction for |
feature_list |
Subset the features for correction whose names match the specified text using regular expression. Default is |
cv_diff_threshold |
Maximum allowable change (difference) in CV before and after smoothing for correction to be applied. |
use_original_if_fail |
Determines the action when smoothing fails or results in invalid values for a feature. If |
show_progress |
Logical. Display progress bars if |
In the output message, the median CV change is computed as the median of CV changes for all
features in global correction or for
features where the correction passed the defined CV difference threshold in
case of conditional correction (conditional_correction = TRUE).
For batch-wise correction, the change is calculated per batch, with the final median CV
change being the median of these batch medians across features.
This smoothing is based on Generalized Additive Models (GAM) using penalized splines, implemented via mgcv::gam().
MRMhubExperiment object
mgcv::gam(); the drift-correction tutorial for a worked example.
Performs drift correction for run-order effects within or across batches
using Gaussian kernel smoothing, as detailed in Teo et al. (2020). The
Gaussian kernel estimates the local data trend, with bandwidth defined by
the kernel_size parameter. This smoothing approach is mostly used with
study samples and should only be applied to datasets with sufficiently randomized or
stratified samples to avoid local biases and artifacts. The smoothing can be
applied to concentration, norm_intensity, and intensity data.
Corrections can be applied on a batch-by-batch basis (batch_wise = TRUE,
default) or across all batches (batch_wise = FALSE). The correction can
either replace existing drift or batch corrections (replace_previous = TRUE, default) or applied on top of existing corrections (replace_previous = FALSE).
Drift correction can be applied to all features (conditional_correction = FALSE)
or conditionally, based on whether the sample CV difference before and
after correction is below a defined threshold (cv_diff_threshold). The
conditional correction is applied separately for each batch if
batch_wise = TRUE.
It is recommended to visually inspect the correction using the
plot_runscatter() function. Set the argument
recalc_trend_after = TRUE so that the trends after correction are also
available for plotting. For further details, refer to the description
of plot_runscatter(). This will double the processing time.
Note: The function outputs a message indicating the median CV change and the median absolute CV before and after correction for all samples. However, these metrics are experimental and should not be used as definitive criteria for correction (see Details below).
correct_drift_gaussiankernel( data = NULL, variable, ref_qc_types, batch_wise = TRUE, ignore_istd = TRUE, replace_previous = TRUE, kernel_size = 10, outlier_filter = FALSE, outlier_ksd = 5, location_smooth = TRUE, scale_smooth = FALSE, log_transform_internal = TRUE, conditional_correction = FALSE, cv_diff_threshold = 0, recalc_trend_after = FALSE, feature_list = NULL, use_original_if_fail = FALSE, show_progress = TRUE )correct_drift_gaussiankernel( data = NULL, variable, ref_qc_types, batch_wise = TRUE, ignore_istd = TRUE, replace_previous = TRUE, kernel_size = 10, outlier_filter = FALSE, outlier_ksd = 5, location_smooth = TRUE, scale_smooth = FALSE, log_transform_internal = TRUE, conditional_correction = FALSE, cv_diff_threshold = 0, recalc_trend_after = FALSE, feature_list = NULL, use_original_if_fail = FALSE, show_progress = TRUE )
data |
A |
variable |
The target variable for drift correction; options include "intensity", "norm_intensity", or "conc". |
ref_qc_types |
QC types used for drift correction, typically
including study samples ( |
batch_wise |
Logical. Apply the correction to each batch separately
( |
ignore_istd |
Logical. Exclude internal standards (ISTDs) from
correction if |
replace_previous |
Logical. Replace existing correction ( |
kernel_size |
Numeric. Defines the Gaussian kernel's bandwidth. |
outlier_filter |
Logical. Enable kernel outlier filtering if |
outlier_ksd |
Numeric. Set the kernel's k times standard deviation for outlier detection. |
location_smooth |
Logical. Apply smoothing to the location parameter if
|
scale_smooth |
Logical. Apply smoothing to the scale parameter if
|
log_transform_internal |
Logical. Conduct log transformation internally
for enhanced outlier robustness if |
conditional_correction |
Determines whether drift correction is applied to all features unconditionally ( |
cv_diff_threshold |
This parameter defines the maximum allowable change (difference) in the coefficient of variation (CV) of samples before and after smoothing for the correction to be applied. A value of 0 (the default) requires the CV to improve, while a value above 0 allows the CV to also become worse by a maximum of the defined difference. |
recalc_trend_after |
Logical. Recalculate trends post-smoothing for
visualization (e.g., |
feature_list |
Character vector. Regular expression pattern to select
specific features for correction. Default is |
use_original_if_fail |
Determines the action when smoothing fails or results in invalid values for a feature. If |
show_progress |
Logical. Display progress bars if |
In the output message, the median CV change is computed as the median of CV changes for all
features in global correction or for
features where the correction passed the defined CV difference threshold in
case of conditional correction (conditional_correction = TRUE).
For batch-wise correction, the change is calculated per batch, with the final median CV
change being the median of these batch medians across features.
Returns a MRMhubExperiment object.
Teo G., Chew WS, Burla B, Herr D, Tai ES, Wenk MR, Torta F, & Choi H (2020). MRMkit: Automated Data Processing for Large-Scale Targeted Metabolomics Analysis. Analytical Chemistry, 92(20), 13677–13682. https://doi.org/10.1021/acs.analchem.0c03060
This function corrects for run-order drifts within or across batches using LOESS (Locally Estimated Scatterplot Smoothing). The correction is typically based on QC (Quality Control) samples that were measured at specific intervals throughout the run sequence. The smoothed curve derived from the QC samples is then used to adjust all other samples in the dataset. The correction can be applied to "intensity", "norm_intensity", or "conc" data.
The degree of smoothing is controlled by the span parameter span (default is 0.75).
Additionally,
the degree parameter can be specified to
control the degree of the polynomial used in the local regression (default is 2)
It is recommended to visually inspect the correction using the
plot_runscatter() function. Set the argument
recalc_trend_after = TRUE so that the trends after correction are also
available for plotting. For further details, refer to the description
of plot_runscatter().
The LOESS correction only applies to samples that lie within the span of the
QC samples used for smoothing. Extrapolation outside this range is
not recommended, as it can lead to unreliable corrections or artefacts in the extrapolated regions. However,
extrapolation can be activated by setting extrapolate = TRUE. This may be
useful in cases where specific drifts occur in segments of the analysis
sequence that are not spanned by the QC samples, such as when the
analysis was interrupted or the instrument had rapid changes in performance.
The corrections can be applied on a batch-by-batch basis (batch_wise = TRUE, default) or across all batches (batch_wise = FALSE). Existing
corrections are either replaced (replace_previous = TRUE) or added on top
of them (replace_previous = FALSE).
Furthermore, drift correction can be applied unconditionally
(conditional_correction = FALSE) or conditionally, based on whether the
sample CV change before and after correction is below a defined
threshold (cv_diff_threshold). This conditional correction is assessed
independently for each batch if batch_wise = TRUE, where the median of
the CV changes across the batch is compared with the threshold.
Note: The function outputs a message indicating the median CV change and the median absolute CV before and after correction for all samples. However, these metrics are experimental and should not be used as definitive criteria for correction (see Details below).
This LOESS method is implemented using the base R function
stats::loess().
correct_drift_loess( data = NULL, variable, ref_qc_types, span = 0.75, degree = 2, batch_wise = TRUE, ignore_istd = TRUE, replace_previous = TRUE, conditional_correction = FALSE, recalc_trend_after = FALSE, log_transform_internal = TRUE, feature_list = NULL, cv_diff_threshold = 0, use_original_if_fail = FALSE, extrapolate = FALSE, show_progress = TRUE )correct_drift_loess( data = NULL, variable, ref_qc_types, span = 0.75, degree = 2, batch_wise = TRUE, ignore_istd = TRUE, replace_previous = TRUE, conditional_correction = FALSE, recalc_trend_after = FALSE, log_transform_internal = TRUE, feature_list = NULL, cv_diff_threshold = 0, use_original_if_fail = FALSE, extrapolate = FALSE, show_progress = TRUE )
data |
|
variable |
The variable to be corrected for drift effects. Must be one of "intensity", "norm_intensity", or "conc" |
ref_qc_types |
QC types used for drift correction |
span |
Loess span width (default is 0.75) |
degree |
Degree of the polynomial to be used in the loess smoothing, normally 1 or 2. Default is 2. |
batch_wise |
Logical. Apply the correction to each batch separately
( |
ignore_istd |
Logical. Exclude internal standards (ISTDs) from
correction if |
replace_previous |
Logical. Replace existing correction ( |
conditional_correction |
Determines whether drift correction is applied to all features unconditionally ( |
recalc_trend_after |
Recalculate trend post-drift correction for |
log_transform_internal |
Log transform the data for correction when |
feature_list |
Subset the features for correction whose names matches the specified text using regular expression. Default is |
cv_diff_threshold |
This parameter defines the maximum allowable change (difference) in the coefficient of variation (CV) of samples before and after smoothing for the correction to be applied. A value of 0 (the default) requires the CV to improve, while a value above 0 allows the CV to also become worse by a maximum of the defined difference. |
use_original_if_fail |
Determines the action when smoothing fails or results in invalid values for a feature. If |
extrapolate |
Extrapolate loess smoothing. WARNING: It is generally not recommended to extrapolate outside of the range spanned by the QCs used for smoothing. See details below. |
show_progress |
Logical. Display progress bars if |
In the output message, the median CV change is computed as the median of CV changes for all
features in global correction or for
features where the correction passed the defined CV difference threshold in
case of conditional correction (conditional_correction = TRUE).
For batch-wise correction, the change is calculated per batch, with the final median CV
change being the median of these batch medians across features.
MRMhubExperiment object
The drift-correction tutorial for a worked example.
Subtract a single, user-specified interference from one feature.
Use this for a one-off correction or to validate a factor before trusting the
automatic derivation; for the metadata-driven paths use
correct_isotopic_interferences() (automatic, isotopic) or
correct_custom_interferences() (declared). The interference is subtracted as:
correct_interference_manual( data = NULL, variable, feature, interfering_feature, interference_contribution, neg_to_na = FALSE, updated_feature_id = NA )correct_interference_manual( data = NULL, variable, feature, interfering_feature, interference_contribution, neg_to_na = FALSE, updated_feature_id = NA )
data |
|
variable |
Name of the variable to be corrected, e.g.
|
feature |
Name of feature to be corrected |
interfering_feature |
Name of feature that is interfering, i.e.
contributing to the signal of |
interference_contribution |
Relative portion of the interfering feature contributing to the feature signal. Must be greater than 0; values are usually between 0 and 1, and values above 1 trigger a warning. |
neg_to_na |
If |
updated_feature_id |
Optional. New name of corrected feature. If empty then feature name will not change. |
MRMhubExperiment object
Applies the isotopic (M+2) interference corrections previously
discovered by calc_isotopic_interferences() (and any declared interferences,
see correct_custom_interferences()) to the raw feature intensities. Aborts
with guidance if no interferences have been derived yet.
The subtraction is
applied on the raw feature_intensity. For auto-derived
(source == "auto") edges the interferer is clamped at 0 before subtraction
and the result clamped at 0 (LICAR parity); declared ("manual") edges are
unclamped. See calc_isotopic_interferences() for how K is computed.
A chain (e.g. PC 34:2 > PC 34:1 > PC 34:0) is corrected sequentially by
default, each feature using its already-corrected interferer; set
sequential_correction = FALSE to correct each from the raw interferer. The
raw signal is preserved in feature_intensity_orig, and the correction is
idempotent (re-running restores from raw first).
correct_isotopic_interferences( data = NULL, variable = "feature_intensity", sequential_correction = TRUE, neg_to_na = FALSE )correct_isotopic_interferences( data = NULL, variable = "feature_intensity", sequential_correction = TRUE, neg_to_na = FALSE )
data |
|
variable |
Name of the variable to correct. Only |
sequential_correction |
Logical. If |
neg_to_na |
If |
MRMhubExperiment object with feature intensities corrected.
Gao L., Ji S, Burla B, Wenk MR, Torta F, & Cazenave-Gassiot A (2021). LICAR: An Application for Isotopic Correction of Targeted Lipidomic Data Acquired with Class-Based Chromatographic Separations Using Multiple Reaction Monitoring. Analytical Chemistry, 93(6), 3163-3171. https://doi.org/10.1021/acs.analchem.0c04565
The interference-correction guide.
This function computes the percent coefficient of variation of the values in x.
If na.rm is TRUE then missing values are removed before computation proceeds.
cv(x, na.rm = FALSE, use_robust_cv = FALSE, min_n = 1L)cv(x, na.rm = FALSE, use_robust_cv = FALSE, min_n = 1L)
x |
a numeric vector with untransformed data |
na.rm |
logical, if |
use_robust_cv |
logical, if |
min_n |
integer, the minimum number of observations (non-missing ones
when |
a numeric value. If the mean (or the median, for robust CV) is zero, or x is not numeric, NA_real_ is returned
cv(c(5, 6, 3, 4, 5, NA), na.rm = TRUE)cv(c(5, 6, 3, 4, 5, NA), na.rm = TRUE)
Computes the percent coefficient of variation (CV) based on the log-transformation of the input data. This can be more robust in certain cases, especially when the data is not normally distributed.
cv_log(x, na.rm = FALSE)cv_log(x, na.rm = FALSE)
x |
a numeric vector with untransformed data |
na.rm |
logical, if |
a numeric value. If x contains a zero, then NaN is returned
Canchola et al. (2017) Correct use of percent coefficient of variation (% CV) formula for log-transformed data. MOJ Proteomics Bioinform. 2017;6(4):316‒317. DOI: 10.15406/mojpb.2017.06.00200
cv_log(c(5, 6, 3, 4, 5, NA), na.rm = TRUE)cv_log(c(5, 6, 3, 4, 5, NA), na.rm = TRUE)
MRMhubExperiment datasetLoad an example MRMhubExperiment dataset: a small, preprocessed subset of a
plasma lipidomics dataset (Tan et al., ATVB, 2022).
data_load_example(data = NULL, dataset = 1)data_load_example(data = NULL, dataset = 1)
data |
|
dataset |
Which example dataset to load. Currently only |
MRMhubExperiment object
myexp <- MRMhubExperiment() myexp <- data_load_example(myexp) myexpmyexp <- MRMhubExperiment() myexp <- data_load_example(myexp) myexp
This function sums up feature intensities per analyte_id.
This is useful when you have multiple features (e.g. adducts, isotopes, in-source fragments) or isomers that you want to combine into a single analyte intensity value, such as LPC sn1 and sn2 species.
data_sum_features(data, qualifier_action = "include")data_sum_features(data, qualifier_action = "include")
data |
|
qualifier_action |
Character. How to handle qualifier features. To sum them up separately select "separate", to include them in the sum if quantifier select "include", to not sum them up select "exclude". |
Features are summed when they share an analyte_id (an empty one counts as
missing): with qualifier_action = "include" all of them, with "separate"
quantifiers and qualifiers each into their own feature (the qualifier sum is
named <analyte_id>_qual), and with "exclude" only the quantifiers, while
qualifiers are kept as they are. An analyte with a single feature in its group
keeps its feature_id. Only features present in the dataset are summed:
excluded features and features listed only in the metadata keep their
feature_id and do not affect the sum.
Only raw signal variables are aggregated across the transitions of an analyte:
feature_intensity, feature_height and feature_area are summed, and
feature_rt is averaged. A sum is NA in an analysis where a constituent is
missing, since a partial sum would look like a valid value; a warning reports
these analyses. A transition without a value in any analysis is left out of
its sum. feature_fwhm, feature_width, feature_int_start and
feature_int_end are set to NA for merged analytes: the constituents are
separate chromatographic peaks, so no aggregate of their peak widths or
borders describes the merged quantity.
Summing transitions redefines feature_intensity, so all values derived
from the pre-merge intensities are invalidated and removed: normalized
intensities, concentrations, drift/batch correction results and QC metrics.
Re-run normalize_by_istd() and the quantitation/correction steps after
merging. A message reports this when such values were present.
The summed features must be measured and quantified alike: an error is raised
when they combine internal standards with analytes, or differ in
istd_feature_id, quant_istd_feature_id, response_factor or
interference_feature_id. An error is also raised when a summed id equals
the feature_id of another feature. Transitions of one internal standard can
be summed; references to summed features in the feature, ISTD and
interference metadata are updated, and interferences between transitions
summed into one feature are removed. Other metadata (feature_class,
feature_label) comes from the first constituent, with a warning when the
constituents disagree.
is_quantifier is not inherited but determined by the merge: the merged
analyte is a quantifier if any of its constituents is one.
MRMhubExperiment object
This function is experimental and its behaviour may change. It overwrites the
feature_id of features sharing an analyte_id in both the dataset and the
feature metadata, and the original feature_id is not backed up anywhere. Run
it after importing metadata and after any exclusions, set_analysis_order()
or set_intensity_var(), and before normalization/quantitation: these steps
rebuild the dataset from the imported data and stop with an error once
features were summed. Running it on a processed object drops the derived
variables (see Details).
Retrieves analysis IDs of data outliers based on the principal components (PCA) with SD or MAD fences
detect_outlier_pca( data = NULL, variable, filter_data, pca_component, qc_types = NA, fence_multiplicator, summarize_fun = c("pca", "rma"), outlier_detection = c("sd", "mad"), log_transform = TRUE )detect_outlier_pca( data = NULL, variable, filter_data, pca_component, qc_types = NA, fence_multiplicator, summarize_fun = c("pca", "rma"), outlier_detection = c("sd", "mad"), log_transform = TRUE )
data |
|
variable |
Feature variable used for outlier detection |
filter_data |
Use all (default) or qc-filtered data |
pca_component |
PCA component to be used |
qc_types |
QC types included in the outlier detection |
fence_multiplicator |
Multiplier for SD or MAD. |
summarize_fun |
Function used to summarize the features, either "pca" based on PCA, or "rma" based on Relative Mean Abundance (RMA) of all features |
outlier_detection |
Outlier detection method, either based on "sd" or "mad" |
log_transform |
Log-transform data for outlier detection |
MRMhubExperiment object
This function excludes specified analyses from a MRMhubExperiment object, either by
marking them as invalid for downstream processing.
The function also allows to reset the exclusions.
exclude_analyses(data = NULL, analyses, clear_existing)exclude_analyses(data = NULL, analyses, clear_existing)
data |
A |
analyses |
A character vector of analysis IDs (case-sensitive) to be excluded from the dataset.
If this is |
clear_existing |
A logical value. If |
A modified MRMhubExperiment object with the specified analyses defined as excluded.
This function excludes specified features from a MRMhubExperiment object, either by
marking them as invalid for downstream processing.
The function also allows to reset the exclusions.
exclude_features(data = NULL, features, clear_existing)exclude_features(data = NULL, features, clear_existing)
data |
A |
features |
A character vector of feature IDs (case-sensitive) to be excluded from the dataset.
If this is |
clear_existing |
A logical value. If |
A modified MRMhubExperiment object with the specified features defined as excluded.
Filters a dataset based on quality control (QC) criteria, including intensity, coefficient of variation (CV), signal-to-blank ratios, D-ratio, response curve properties, and proportion of missing values. Criteria apply to different QC types (BQC, TQC) and measurement variables (concentration, intensity, and normalized intensity).
To clear all existing filters, run filter_features_qc() with clear_existing = TRUE
and without any filtering criteria.
filter_features_qc( data = NULL, clear_existing = TRUE, recalc_metrics = FALSE, use_batch_medians = FALSE, use_robust_cv = FALSE, include_qualifier = FALSE, include_istd = FALSE, features.to.keep = NA, max.prop.missing.intensity.spl = NA, max.prop.missing.normintensity.spl = NA, max.prop.missing.conc.spl = NA, min.intensity.lowest.bqc = NA, min.intensity.lowest.tqc = NA, min.intensity.lowest.spl = NA, min.intensity.median.bqc = NA, min.intensity.median.tqc = NA, min.intensity.median.spl = NA, min.intensity.highest.spl = NA, min.signalblank.median.spl.pblk = NA, min.signalblank.median.spl.ublk = NA, min.signalblank.median.spl.sblk = NA, max.cv.intensity.bqc = NA, max.cv.intensity.tqc = NA, max.cv.normintensity.bqc = NA, max.cv.normintensity.tqc = NA, max.cv.conc.bqc = NA, max.cv.conc.tqc = NA, response.curves.selection = NA, response.curves.summary = NA, min.rsquare.response = NA, min.slope.response = NA, max.slope.response = NA, max.yintercept.response = NA, max.dratio.sd.conc.bqc = NA, max.dratio.sd.conc.tqc = NA, max.dratio.mad.conc.bqc = NA, max.dratio.mad.conc.tqc = NA, max.dratio.sd.normint.bqc = NA, max.dratio.sd.normint.tqc = NA, max.dratio.mad.normint.bqc = NA, max.dratio.mad.normint.tqc = NA )filter_features_qc( data = NULL, clear_existing = TRUE, recalc_metrics = FALSE, use_batch_medians = FALSE, use_robust_cv = FALSE, include_qualifier = FALSE, include_istd = FALSE, features.to.keep = NA, max.prop.missing.intensity.spl = NA, max.prop.missing.normintensity.spl = NA, max.prop.missing.conc.spl = NA, min.intensity.lowest.bqc = NA, min.intensity.lowest.tqc = NA, min.intensity.lowest.spl = NA, min.intensity.median.bqc = NA, min.intensity.median.tqc = NA, min.intensity.median.spl = NA, min.intensity.highest.spl = NA, min.signalblank.median.spl.pblk = NA, min.signalblank.median.spl.ublk = NA, min.signalblank.median.spl.sblk = NA, max.cv.intensity.bqc = NA, max.cv.intensity.tqc = NA, max.cv.normintensity.bqc = NA, max.cv.normintensity.tqc = NA, max.cv.conc.bqc = NA, max.cv.conc.tqc = NA, response.curves.selection = NA, response.curves.summary = NA, min.rsquare.response = NA, min.slope.response = NA, max.slope.response = NA, max.yintercept.response = NA, max.dratio.sd.conc.bqc = NA, max.dratio.sd.conc.tqc = NA, max.dratio.mad.conc.bqc = NA, max.dratio.mad.conc.tqc = NA, max.dratio.sd.normint.bqc = NA, max.dratio.sd.normint.tqc = NA, max.dratio.mad.normint.bqc = NA, max.dratio.mad.normint.tqc = NA )
data |
|
clear_existing |
Logical. If |
recalc_metrics |
Logical. If |
use_batch_medians |
Logical. If |
use_robust_cv |
Logical. If |
include_qualifier |
Logical. If |
include_istd |
Logical. If |
features.to.keep |
A vector of feature identifiers to retain, even if they do not meet the filtering criteria. |
max.prop.missing.intensity.spl |
Maximum proportion of missing intensity values among study samples (SPL). Default is |
max.prop.missing.normintensity.spl |
Maximum proportion of missing normalized intensity values among study samples (SPL). Default is |
max.prop.missing.conc.spl |
Maximum proportion of missing concentration values among study samples (SPL). Default is |
min.intensity.lowest.bqc |
Minimum intensity of the lowest BQC sample. Default is |
min.intensity.lowest.tqc |
Minimum intensity of the lowest TQC sample. Default is |
min.intensity.lowest.spl |
Minimum intensity of the lowest study sample (SPL). Default is |
min.intensity.median.bqc |
Minimum median intensity of BQC samples. Default is |
min.intensity.median.tqc |
Minimum median intensity of TQC samples. Default is |
min.intensity.median.spl |
Minimum median intensity of study samples (SPL). Default is |
min.intensity.highest.spl |
Minimum intensity of the highest intensity study sample (SPL). Default is |
min.signalblank.median.spl.pblk |
Minimum signal-to-blank ratio for SPL samples and PBLK. Default is |
min.signalblank.median.spl.ublk |
Minimum signal-to-blank ratio for SPL samples and UBLK. Default is |
min.signalblank.median.spl.sblk |
Minimum signal-to-blank ratio for SPL samples and SBLK. Default is |
max.cv.intensity.bqc |
Maximum CV for intensity in BQC samples. Default is |
max.cv.intensity.tqc |
Maximum CV for intensity in TQC samples. Default is |
max.cv.normintensity.bqc |
Maximum CV for normalized intensity in BQC samples. Default is |
max.cv.normintensity.tqc |
Maximum CV for normalized intensity in TQC samples. Default is |
max.cv.conc.bqc |
Maximum CV for concentration in BQC samples. Default is |
max.cv.conc.tqc |
Maximum CV for concentration in TQC samples. Default is |
response.curves.selection |
Select specific response curves by ID. Default is |
response.curves.summary |
Define the method to summarize multiple response curves. Default is |
min.rsquare.response |
Minimum R² value for the response curves. Default is |
min.slope.response |
Minimum slope for the response curve. Default is |
max.slope.response |
Maximum slope for the response curve. Default is |
max.yintercept.response |
Maximum y-intercept of the response curve. Default is |
max.dratio.sd.conc.bqc |
Maximum allowed D-ratio (SD of BQC / SD of SPL) using standard deviation for BQC samples. Default is |
max.dratio.sd.conc.tqc |
Maximum allowed D-ratio (SD of TQC / SD of SPL) using standard deviation for TQC samples. Default is |
max.dratio.mad.conc.bqc |
Maximum allowed D-ratio (MAD of BQC / MAD of SPL) using median absolute deviation for BQC samples. Default is |
max.dratio.mad.conc.tqc |
Maximum allowed D-ratio (MAD of TQC / MAD of SPL) using median absolute deviation for TQC samples. Default is |
max.dratio.sd.normint.bqc |
Maximum allowed D-ratio (SD of normalized intensity in BQC / SD of SPL) using standard deviation. Default is |
max.dratio.sd.normint.tqc |
Maximum allowed D-ratio (SD of normalized intensity in TQC / SD of SPL) using standard deviation. Default is |
max.dratio.mad.normint.bqc |
Maximum allowed D-ratio (MAD of normalized intensity in BQC / MAD of SPL) using median absolute deviation. Default is |
max.dratio.mad.normint.tqc |
Maximum allowed D-ratio (MAD of normalized intensity in TQC / MAD of SPL) using median absolute deviation. Default is |
This function implements filtering criteria based on quality control (QC) samples and additional analytical parameters, following recommendations outlined by Broadhurst et al. (2018). The implemented criteria evaluate data quality through analysis of QC samples, blanks, and study samples.
The input MRMhubExperiment object with the feature filtering criteria applied.
Per-criterion verdicts are stored in metrics_qc: pass_minint (the
min.intensity.* criteria), pass_sb, pass_cva, pass_dratio,
pass_linearity and pass_missingval, combined in all_filter_pass.
With a response-curve criterion, a feature without response-curve results
fails pass_linearity; ISTDs without results are not failed.
Broadhurst, D., Goodacre, R., Reinke, S. N., Kuligowski, J., Wilson, I. D., Lewis, M. R., & Dunn, W. B. (2018). Guidelines and considerations for the use of system suitability and quality control samples in mass spectrometry assays applied in clinical studies. Metabolomics, 14(6), 72. doi:10.1007/s11306-018-1367-3
Function for cubic spline-based smoothing with optional cross-validation, for use by correct_drift
fun_cspline(tbl, ref_qc_types, log_transform_internal, ...)fun_cspline(tbl, ref_qc_types, log_transform_internal, ...)
tbl |
Table ( |
ref_qc_types |
QC types used for the smoothing (fit) by cubic spline |
log_transform_internal |
Apply log transformation internally for smoothing if |
... |
Additional arguments forwarded to |
List with a data.frame containing original x and the smoothed y values, and a boolean value indicating whether the fit failed or not.
Function for penalized spline-based smoothing using GAM, for use by correct_drift
fun_gam_smooth(tbl, ref_qc_types, log_transform_internal = TRUE, ...)fun_gam_smooth(tbl, ref_qc_types, log_transform_internal = TRUE, ...)
tbl |
Table ( |
ref_qc_types |
QC types used for the smoothing (fit) by GAM |
log_transform_internal |
Apply log transformation internally for smoothing if |
... |
Additional arguments forwarded to |
List with a data.frame containing original x and the smoothed y values, and a boolean value indicating whether the fit failed or not.
Function for Gaussian kernel-based smoothing, for use by correct_drift.
fun_gauss.kernel.smooth(tbl, ref_qc_types, log_transform_internal, ...)fun_gauss.kernel.smooth(tbl, ref_qc_types, log_transform_internal, ...)
tbl |
Table ( |
ref_qc_types |
QC types used for the smoothing (fit) by loess |
log_transform_internal |
Apply log transformation internally for smoothing if |
... |
Additional arguments |
List with a data.frame containing original x and the smoothed y values, and a boolean value indicting whether the fit failed or not.
Hyung Won Choi
Function for loess-based smoothing, for use by correct_drift
fun_loess(tbl, ref_qc_types, log_transform_internal, ...)fun_loess(tbl, ref_qc_types, log_transform_internal, ...)
tbl |
Table ( |
ref_qc_types |
QC types used for the smoothing (fit) by loess |
log_transform_internal |
Apply log transformation internally for smoothing if |
... |
Additional arguments forwarded to Loess |
List with a data.frame containing original x and the smoothed y values, and a boolean value indicting whether the fit failed or not.
Assembles a self-contained Quarto document that imports data and metadata and
runs the selected processing steps, in canonical order, using the same
function calls and defaults as the package tutorials. This is a pure function
(no file I/O, no Shiny) so it can be tested and scripted directly; the
interactive build_workflow() app calls it to power its live preview.
generate_workflow_qmd(spec)generate_workflow_qmd(spec)
spec |
A list describing the workflow. Recognised fields:
|
A length-1 character string containing the .qmd source.
cat(generate_workflow_qmd(list( importer = "mrmhub", data_path = "MRMhub_demo.tsv", steps = c("normalize_istd", "quantify_istd") )))cat(generate_workflow_qmd(list( importer = "mrmhub", data_path = "MRMhub_demo.tsv", steps = c("normalize_istd", "quantify_istd") )))
Returns the end time of the analysis, corresponding to the last acquisition_time_stamp from the dataset.
Note: if estimate_sequence_end is set to FALSE, the function will return
the timestamp of the last analysis in the dataset, corresponding to the start of
the last analysis. Set estimate_sequence_end to TRUE to estimate the end
time of the analysis sequence, based on the median runtime.
get_analyis_end(data, estimate_sequence_end)get_analyis_end(data, estimate_sequence_end)
data |
A |
estimate_sequence_end |
If |
A POSIXct timestamp, or NA_POSIXct_ if the dataset is empty.
Returns the start time of the analysis, corresponding to the earliest acquisition_time_stamp from the dataset.
get_analyis_start(data)get_analyis_start(data)
data |
A |
A POSIXct timestamp, or NA_POSIXct_ if the dataset is empty.
Counts the number of interruptions in the analysis, where an interruption is
defined as a time gap between consecutive acquisition timestamps that
exceeds a given threshold (break_duration_minutes).
get_analysis_breaks(data, break_duration_minutes)get_analysis_breaks(data, break_duration_minutes)
data |
A |
break_duration_minutes |
A numeric value specifying the minimum duration (in minutes) between two consecutive analyses that qualifies as an interruption. |
An integer with the number of interruptions, or NA_integer_ if the dataset is empty.
Returns the number of analyses in the dataset, with an optional
filter based on qc_types.
get_analysis_count(data, qc_types = NULL)get_analysis_count(data, qc_types = NULL)
data |
A |
qc_types |
Defines the |
An integer with the analysis count
This function returns the total duration of the analysis, which is the time difference between the timestamps of the first and last analyses in the sequence.
get_analysis_duration(data, estimate_sequence_end)get_analysis_duration(data, estimate_sequence_end)
data |
A |
estimate_sequence_end |
If |
If estimate_sequence_end is TRUE, the function will estimate the end time of the analysis sequence
by adding the median runtime to the timestamp of the last analysis, instead of simply using the timestamp
of the last analysis.
Get the annotated or the originally imported analytical data
get_analyticaldata(data = NULL, annotated)get_analyticaldata(data = NULL, annotated)
data |
|
annotated |
Boolean indicating whether to return the annotated data
( |
A tibble with the analytical data in the long format
Returns the lower and upper analysis number (sequence position) spanned by the specified batch or range of batches.
get_batch_boundaries(data = NULL, batch_indices = NULL)get_batch_boundaries(data = NULL, batch_indices = NULL)
data |
|
batch_indices |
A numeric vector with one or two elements, representing the first and/or last batch index (i.e., sequential batch number). If NULL or invalid, the function will abort. |
A vector with two elements: the lower and upper analysis number for the specified batch(es).
Extracts calibration fit metrics from a MRMhubExperiment object.
get_calibration_metrics( data = NULL, include_qualifier = TRUE, with_lod = TRUE, with_loq = TRUE, with_coefficients = TRUE, with_sigma = TRUE, summary_table = FALSE )get_calibration_metrics( data = NULL, include_qualifier = TRUE, with_lod = TRUE, with_loq = TRUE, with_coefficients = TRUE, with_sigma = TRUE, summary_table = FALSE )
data |
A |
include_qualifier |
Whether to include qualifier features. When |
with_lod |
Whether to include LoD in output. Default is |
with_loq |
Whether to include LoQ in output. Default is |
with_coefficients |
Whether to include regression coefficients. Default is |
with_sigma |
Whether to include sigma in output. Default is |
summary_table |
When |
Requires prior computation of regression results using calc_calibration_results().
See its documentation for details.
feature_id: Feature identifier.
is_quantifier: Logical, indicates if the feature is a quantifier.
fit_model: Regression model used for fitting.
fit_weighting: Weighting method used in fitting.
lowest_cal: Lowest non-zero calibrator concentration with a response.
highest_cal: Highest calibrator concentration with a response.
r2: R² value, indicating goodness of fit. For a weighted
fit this is the weighted coefficient of determination (computed from weighted
sums of squares), matching the value reported by vendor software such as
Agilent MassHunter for the same weighted curve.
coef_a: Intercept (0th-order term, x^0) of the fitted curve.
coef_b: 1st-order (linear, x^1) coefficient — the slope in a linear fit, or the linear term in a quadratic fit.
coef_c: 2nd-order (quadratic, x^2) coefficient in quadratic fits. Returns NA for linear fits.
sigma: Standard deviation of residuals.
reg_failed: TRUE if regression fitting failed.
LoD = 3.3× the sample standard error of residuals / slope of the regression (see Notes).
LoQ = 10× the sample standard error of residuals / slope of the regression (see Notes).
The coefficients describe the curve in ascending power order (R's
lm() / poly() convention): response = coef_a + coef_b * x + coef_c * x^2.
This is the reverse of the descending a*x^2 + b*x + c form used by some
vendor software (e.g. Agilent MassHunter, where a is the x^2 term), so
when comparing against such an export, match by power, not by letter.
Note: LoD/LoQ follow the ICH Q2(R1/R2) approach (3.3 sigma / S and
10 sigma / S). The slope S is the slope of the calibration curve at zero
concentration (the linear coefficient coef_b); for a quadratic fit the
quadratic term does not contribute to this slope. The response sigma is
selectable in calc_calibration_results() via lod_sigma (residual
standard error, the default, or the standard error of the intercept); the
sigma column reported here is always the residual standard error.
For a weighted fit (1/x, 1/x^2, 1/sqrt(x)) sigma is R's weighted
residual standard error, which is not on the raw response scale that the ICH
3.3 sigma / S formula assumes, so the reported LoD/LoQ are approximate
(typically slightly optimistic for 1/x). Use fit_weighting = "none" if you
require the strict ICH response-scale Sy/x; the back-calculated
concentrations themselves are unaffected.
A tibble with exported calibration metrics.
Returns the number of features in the dataset, with optional filters whether counted features must be internal standard and/or quantifier.
get_feature_count(data, is_istd = NA, is_quantifier = NA)get_feature_count(data, is_istd = NA, is_quantifier = NA)
data |
A |
is_istd |
If set, then defines whether to include or exclude internal standard features. Default is |
is_quantifier |
If set, then defines whether to include or exclude quantifier features. Default is |
An integer with the feature count
Returns a vector of annotated feature IDs (feature_id) present in the dataset
get_featurelist(data, is_istd = NA, is_quantifier = NA)get_featurelist(data, is_istd = NA, is_quantifier = NA)
data |
A |
is_istd |
If set, then defines whether to include or exclude internal standard features. Default is |
is_quantifier |
If set, then defines whether to include or exclude quantifier features. Default is |
A character vector with feature_id values
Computes the lower and upper boundaries based on Tukey's Interquartile Range (IQR) fences from a numeric vector.
get_iqr_tails(x, k = 1.5, na.rm = FALSE)get_iqr_tails(x, k = 1.5, na.rm = FALSE)
x |
A numeric vector. |
k |
A numeric multiplier for the IQR. Default is |
na.rm |
Logical. Should missing values be removed? Default is |
A numeric vector of length 2: c(lower_tail, upper_tail).
Computes the lower and upper boundaries based on Median Absolute Deviation (MAD) from a numeric vector. Returns c(NA_real_, NA_real_) if the input vector has less than 2 elements or if no values fall within the computed fences.
get_mad_tails(x, k, na.rm = FALSE)get_mad_tails(x, k, na.rm = FALSE)
x |
a numeric vector |
k |
multiplier for the MAD |
na.rm |
if |
a numeric vector of length 2 with the lower and upper boundaries.
Computes lower and upper bounds for a numeric vector using one of several methods:
get_outlier_bounds( x, method = c("iqr", "mad", "sd", "quantile", "z_normal", "z_robust", "fold_change"), k = NULL, outlier_log = FALSE, na.rm = FALSE )get_outlier_bounds( x, method = c("iqr", "mad", "sd", "quantile", "z_normal", "z_robust", "fold_change"), k = NULL, outlier_log = FALSE, na.rm = FALSE )
x |
A numeric vector. |
method |
Character string: one of |
k |
Numeric multiplier or threshold. Defaults depend on method:
|
outlier_log |
Logical. If |
na.rm |
Logical. Should missing values be removed? Default is |
"iqr": Tukey's Interquartile Range fences
"mad": Median Absolute Deviation
"sd": Standard deviation from mean
"quantile": Fixed percentile cutoffs
"z_normal": Standard Z-score using mean & SD
"z_robust": Modified Z-score using median & MAD
"fold_change": Median ± log10(k), assumes log-transformed data
A numeric vector of length 2: c(lower_bound, upper_bound) representing
the smallest and largest observed values within the computed fences.
get_outlier_bounds(c(1, 2, 3, 4, 100), "iqr") get_outlier_bounds(c(1, 2, 3, 4, 100), "mad") get_outlier_bounds(c(1, 2, 3, 4, 100), "sd") get_outlier_bounds(c(1, 2, 3, 4, 100), "quantile", k = 0.05) get_outlier_bounds(c(1, 2, 3, 4, 100), "z_normal") get_outlier_bounds(c(1, 2, 3, 4, 100), "z_robust") get_outlier_bounds(log10(c(1, 2, 4, 8)), "fold_change") # default 2× get_outlier_bounds(log10(c(1, 2, 4, 8)), "fold_change", k = 3) # 3× fold-changeget_outlier_bounds(c(1, 2, 3, 4, 100), "iqr") get_outlier_bounds(c(1, 2, 3, 4, 100), "mad") get_outlier_bounds(c(1, 2, 3, 4, 100), "sd") get_outlier_bounds(c(1, 2, 3, 4, 100), "quantile", k = 0.05) get_outlier_bounds(c(1, 2, 3, 4, 100), "z_normal") get_outlier_bounds(c(1, 2, 3, 4, 100), "z_robust") get_outlier_bounds(log10(c(1, 2, 4, 8)), "fold_change") # default 2× get_outlier_bounds(log10(c(1, 2, 4, 8)), "fold_change", k = 3) # 3× fold-change
This function retrieves quality control (QC) bias and variability metrics from a MRMhubExperiment object.
It returns a summary of QC metrics for specified QC samples,
including bias, absolute bias, and intra-assay coefficient of variation (CV).
The standard deviation of the concentration ratio is also included unless
it is NA for all analytes, i.e. when no replicates were measured.
get_qc_bias_variability( data, qc_types = NA, sample_ids = NA, wide_format = "none", include_qualifier = FALSE, with_conc = TRUE, with_conc_target = TRUE, with_bias = TRUE, with_bias_abs = FALSE, with_conc_ratio = FALSE, with_cv_intra = TRUE, with_conc_out_of_range = TRUE, summary_table = FALSE )get_qc_bias_variability( data, qc_types = NA, sample_ids = NA, wide_format = "none", include_qualifier = FALSE, with_conc = TRUE, with_conc_target = TRUE, with_bias = TRUE, with_bias_abs = FALSE, with_conc_ratio = FALSE, with_cv_intra = TRUE, with_conc_out_of_range = TRUE, summary_table = FALSE )
data |
A |
qc_types |
A character vector specifying the QC types to include in the results, in addition to |
sample_ids |
A character vector specifying the sample IDs to include in the results. If not specified, all analyses regardless of their sample IDs are included by default. |
wide_format |
Format of the output table. Must be one of |
include_qualifier |
Logical. If |
with_conc |
Logical. If |
with_conc_target |
Logical. If |
with_bias |
Logical. If |
with_bias_abs |
Logical. If |
with_conc_ratio |
Logical. If |
with_cv_intra |
Logical. If |
with_conc_out_of_range |
Logical. If |
summary_table |
Logical. If |
The standard deviation of concentration is also included unless the number of replicates was 1.
The function uses data from the MRMhubExperiment object and filters it according to the specified QC types and other parameters. It then calculates summary statistics for each feature, such as bias and CV, and organizes the data into a user-specified format.
A data frame containing the calibration results, including metrics such as bias, percentage bias, and intra-assay CV based on specified parameters.
This function calculates linear regression statistics (R², slope, and intercept)
for each response curve in the provided MRMhubExperiment object. Each curve
is fitted on its points with a non-missing intensity, with a warning when some
are missing; a curve with 2 such points has a slope and intercept but no R²
(NA), and a curve with fewer gives NA throughout. Before fitting,
the analyzed sample amount (x) and feature intensity (y) of these points
are each scaled to their maximum (set to 1), so the returned slopenorm and
y0norm are on this normalized scale.
Optionally, it can include
additional statistics from the lancer package (if installed) when with_saturation_stats is set to TRUE.
get_response_curve_stats( data = NULL, with_saturation_stats = FALSE, limit_to_rqc = FALSE, silent_invalid_data = FALSE )get_response_curve_stats( data = NULL, with_saturation_stats = FALSE, limit_to_rqc = FALSE, silent_invalid_data = FALSE )
data |
A |
with_saturation_stats |
Logical, if |
limit_to_rqc |
Logical, if |
silent_invalid_data |
Logical, if |
A tibble with linear regression statistics (r2, slopenorm, y0norm) for each curve,
or NULL if no data matches the criteria.
Calculates the median run time (in seconds) based of the timestamps differences between consecutive analyses in the sequence.
get_runtime_median(data)get_runtime_median(data)
data |
A |
A lubridate time period object, or NA if the dataset is empty.
This function imports analysis results from CSV files in long table format, where each row represents a unique observation of a feature-value pair for an analysis (sample), along with associated feature variables and other metadata. See "Details" below for more information on using this function.
import_data_csv_long( data = NULL, path, import_metadata = TRUE, column_mapping = NULL, na_strings = "NA", warn_unrecognized_columns = TRUE, silent = FALSE )import_data_csv_long( data = NULL, path, import_metadata = TRUE, column_mapping = NULL, na_strings = "NA", warn_unrecognized_columns = TRUE, silent = FALSE )
data |
A |
path |
A single file path, multiple file paths, or a directory path. If
a directory is provided, all |
import_metadata |
Logical indicating whether to import additional
metadata columns (e.g., batch ID, sample type) into the
|
column_mapping |
A named character vector mapping internal column names
to CSV column names. Should include keys such as |
na_strings |
Character vector of strings to interpret as missing values
( |
warn_unrecognized_columns |
Logical indicating whether to issue a warning when unknown columns are encountered in the dataset. |
silent |
Logical indicating whether to suppress most notifications and messages. |
When no column mapping is provided via the column_mapping argument, the
function will automatically detect and import columns with the following
names:
| CSV Column Name | MRMhub Internal Name | Required |
analysis_id |
analysis_id |
Yes |
feature_id |
feature_id |
Yes |
qc_type |
qc_type |
No |
batch_id |
batch_id |
No |
istd_feature_id |
istd_feature_id |
No |
feature_class |
feature_class |
No |
precursor_mz |
method_precursor_mz |
No |
product_mz |
method_product_mz |
No |
area |
feature_area |
No |
height |
feature_height |
No |
intensity |
feature_intensity |
No |
response |
feature_response |
No |
conc |
feature_conc |
No |
rt |
feature_rt |
No |
fwhm |
feature_fwhm |
No |
width |
feature_width |
No |
Detection of these columns is case-insensitive. Additionally, if feature
variable columns use the internal naming convention with prefixes
"feature_" or "method_" (e.g. feature_area instead of area), the
function will detect and import them automatically.
To import data with different column names, provide a named vector mapping
CSV column names to the internal column names used by MRMhubExperiment.
The mapping should be in the format:
c("analysis_id" = "[CSV column name for analysis]", "feature_id" = "[CSV column name for feature]", ...), where the right-hand side refers to the
exact column name in the CSV file header. Columns matching internal names
do not require mapping and will be imported automatically. The mapping is
case-insensitive.
Note that the dataset must contain an analysis identifier, either as an
analysis_id column or via a mapped column.
The function processes all CSV files in the specified directory or the given file(s), combining them into a single dataset. This supports datasets split across multiple files during preprocessing. Each feature and raw data file pair should appear only once to avoid duplication.
The na_strings parameter allows specifying character strings that should
be interpreted as NA, ensuring proper handling of missing values.
A MRMhubExperiment object containing the imported data.
All imported identifiers are whitespace-normalized on import: leading and
trailing spaces are removed and internal runs of whitespace are collapsed to
a single space (for example "QC 01" becomes "QC 01"). Raw-data file
extensions (.mzML, .d, .raw, .wiff, .wiff2, .lcd, .chrom,
case-insensitive) are stripped from analysis_id.
The same normalization is applied to both the data and the metadata, which is
what lets an analysis_id typed into metadata match the one derived from a
data-file name instead of silently failing to join. A consequence is that two
identifiers differing only by whitespace collapse to one and are then reported
as duplicates.
file_path <- system.file("extdata", "plain_long_dataset.csv", package = "mrmhub") mexp <- MRMhubExperiment() # Define the column mapping; right side is the CSV column name col_map <- c( "analysis_id" = "raw_data_filename", "qc_type" = "qc_type", "feature_id" = "feature_id", "feature_class" = "feature_class", "istd_feature_id" = "istd_feature_id", "feature_rt" = "rt", "feature_area" = "area" ) mexp <- import_data_csv_long( data = mexp, path = file_path, column_mapping = col_map, import_metadata = TRUE ) print(mexp)file_path <- system.file("extdata", "plain_long_dataset.csv", package = "mrmhub") mexp <- MRMhubExperiment() # Define the column mapping; right side is the CSV column name col_map <- c( "analysis_id" = "raw_data_filename", "qc_type" = "qc_type", "feature_id" = "feature_id", "feature_class" = "feature_class", "istd_feature_id" = "istd_feature_id", "feature_rt" = "rt", "feature_area" = "area" ) mexp <- import_data_csv_long( data = mexp, path = file_path, column_mapping = col_map, import_metadata = TRUE ) print(mexp)
Imports analysis result data from wide-format .csv files, where each row corresponds
to a single analysis and each feature is stored in its own column. All feature columns
hold the same variable type, given by variable_name.
import_data_csv_wide( data = NULL, path, variable_name, analysis_id_col = NA, import_metadata = TRUE, first_feature_column = NA, na_strings = "NA" )import_data_csv_wide( data = NULL, path, variable_name, analysis_id_col = NA, import_metadata = TRUE, first_feature_column = NA, na_strings = "NA" )
data |
A |
path |
A file path or vector of file paths, or a directory path. If a directory is
provided, all |
variable_name |
A character string specifying the variable type contained in the
data. Must be one of |
analysis_id_col |
The column name or index to be used as |
import_metadata |
Logical indicating whether to import additional metadata columns
(e.g., batch ID, sample type) into the |
first_feature_column |
Integer indicating the column number where feature value columns start. |
na_strings |
Character vector of strings to interpret as NA values. Blank fields are also treated as NA. |
Each row must be identified by an "analysis_id" column (or, if absent, the first
column, provided it holds unique values). Every feature is stored in a separate column;
the feature columns all contain the single variable type specified by variable_name.
Use first_feature_column to mark where the feature columns begin so that leading
metadata columns are not mistaken for features.
The variable_name argument specifies the data type represented in the table, which
must be one of: "area", "height", "intensity", "norm_intensity", "response",
"conc", "conc_raw", "rt", or "fwhm".
If there is no column named analysis_id, it will be inferred from the first column,
provided it contains unique values.
When import_metadata is set to TRUE, the following metadata columns will be imported
if present:
analysis_order
qc_type
batch_id
is_quantifier
To prevent additional non-metadata columns from being misinterpreted as features,
use the first_feature_column parameter to specify the column where feature data starts.
If a directory path is provided to path, all .csv files in that directory will be
processed and merged into a single dataset. This facilitates handling datasets split
into multiple files during preprocessing. Ensure each feature and raw data file pair
appears only once to avoid duplication errors.
The na_strings parameter allows specifying character strings to be interpreted as
missing values (NA). Blank fields are also treated as missing.
A MRMhubExperiment object containing the imported dataset.
All imported identifiers are whitespace-normalized on import: leading and
trailing spaces are removed and internal runs of whitespace are collapsed to
a single space (for example "QC 01" becomes "QC 01"). Raw-data file
extensions (.mzML, .d, .raw, .wiff, .wiff2, .lcd, .chrom,
case-insensitive) are stripped from analysis_id.
The same normalization is applied to both the data and the metadata, which is
what lets an analysis_id typed into metadata match the one derived from a
data-file name instead of silently failing to join. A consequence is that two
identifiers differing only by whitespace collapse to one and are then reported
as duplicates.
file_path <- system.file("extdata", "plain_wide_dataset.csv", package = "mrmhub") mexp <- MRMhubExperiment() mexp <- import_data_csv_wide( data = mexp, path = file_path, variable_name = "conc", import_metadata = TRUE ) print(mexp)file_path <- system.file("extdata", "plain_wide_dataset.csv", package = "mrmhub") mexp <- MRMhubExperiment() mexp <- import_data_csv_wide( data = mexp, path = file_path, variable_name = "conc", import_metadata = TRUE ) print(mexp)
Imports .csv files exported from Agilent MassHunter Quantitative
Analysis software, containing peak integration results. The input files must
have analyses (samples) in rows, features/compounds in columns, and either
peak areas, peak heights, or response as the values. Additional columns, such
as retention time (RT), full-width at half-maximum (FWHM), precursor m/z
(PrecursorMZ), and collision energy (CE), will also be imported and made
available in the MRMhubExperiment object for downstream analyses.
When a directory path is provided, all matching .csv files in that directory will be imported and merged into a single dataset. This is useful when importing datasets that were pre-processed in blocks, resulting in multiple files. Each unique combination of feature and raw data file must only occur once across all source data files. Duplicate combinations will result in an error.
import_data_masshunter( data = NULL, path, import_metadata = TRUE, expand_qualifier_names = TRUE, conc_column = "conc_final", silent = FALSE )import_data_masshunter( data = NULL, path, import_metadata = TRUE, expand_qualifier_names = TRUE, conc_column = "conc_final", silent = FALSE )
data |
|
path |
One or more file paths, or a directory path (in which case all matching files will be imported) |
import_metadata |
Logical, whether to extract and add metadata from the analysis result file |
expand_qualifier_names |
Logical, whether to add the quantifier name in front of the qualifier name (the latter only has the m/z transition values) |
conc_column |
Which concentration field of the masshunter data to use, in case "Calc. Conc." and "Final Conc" are present. Default is "conc_final". Must be one of "conc_calc" or "conc_final" (default). |
silent |
Logical, whether to suppress most notifications |
MRMhubExperiment object with the imported data
All imported identifiers are whitespace-normalized on import: leading and
trailing spaces are removed and internal runs of whitespace are collapsed to
a single space (for example "QC 01" becomes "QC 01"). Raw-data file
extensions (.mzML, .d, .raw, .wiff, .wiff2, .lcd, .chrom,
case-insensitive) are stripped from analysis_id.
The same normalization is applied to both the data and the metadata, which is
what lets an analysis_id typed into metadata match the one derived from a
data-file name instead of silently failing to join. A consequence is that two
identifiers differing only by whitespace collapse to one and are then reported
as duplicates.
mexp <- MRMhubExperiment() file_path = system.file("extdata", "MHQuant_demo.csv", package = "mrmhub") mexp <- import_data_masshunter( data = mexp, path = file_path, import_metadata = TRUE, expand_qualifier_names = TRUE) print(mexp)mexp <- MRMhubExperiment() file_path = system.file("extdata", "MHQuant_demo.csv", package = "mrmhub") mexp <- import_data_masshunter( data = mexp, path = file_path, import_metadata = TRUE, expand_qualifier_names = TRUE) print(mexp)
Imports tabular data files (*.tsv) generated from MRMhub containing peak
integration results. The input files must be in a long format with columns
for the raw data file name, feature ID, peak intensity, and other columns.
Additional information, such as retention time, FWHM, precursor/product m/z,
and CE will also be imported and made available in the MRMhubExperiment
object for downstream analyses.
When a directory path is provided, all matching files in that directory will be imported and merged into a single dataset. This is useful when importing datasets that were pre-processed in blocks, resulting in multiple files. Each unique combination of feature and raw data file must only occur once across all source data files. Duplicate combinations will result in an error.
import_data_mrmhub(data = NULL, path, import_metadata = TRUE, silent = FALSE)import_data_mrmhub(data = NULL, path, import_metadata = TRUE, silent = FALSE)
data |
|
path |
One or more file paths, or a directory path (in which case all matching files will be imported) |
import_metadata |
Logical, whether to import additional metadata columns (e.g., |
silent |
Logical, whether to suppress most notifications |
MRMhubExperiment object with the imported data
All imported identifiers are whitespace-normalized on import: leading and
trailing spaces are removed and internal runs of whitespace are collapsed to
a single space (for example "QC 01" becomes "QC 01"). Raw-data file
extensions (.mzML, .d, .raw, .wiff, .wiff2, .lcd, .chrom,
case-insensitive) are stripped from analysis_id.
The same normalization is applied to both the data and the metadata, which is
what lets an analysis_id typed into metadata match the one derived from a
data-file name instead of silently failing to join. A consequence is that two
identifiers differing only by whitespace collapse to one and are then reported
as duplicates.
mexp <- MRMhubExperiment() file_path = system.file("extdata", "MRMhub_demo.tsv", package = "mrmhub") mexp <- import_data_mrmhub( data = mexp, path = file_path, import_metadata = TRUE) print(mexp)mexp <- MRMhubExperiment() file_path = system.file("extdata", "MRMhub_demo.tsv", package = "mrmhub") mexp <- import_data_mrmhub( data = mexp, path = file_path, import_metadata = TRUE) print(mexp)
Imports quantitative results from an
mzTab-M file (e.g. produced by
Lipid Data Analyzer, MS-DIAL or MZmine) into an MRMhubExperiment. Each
Small Molecule Feature (SMF) becomes an mrmhub feature and each assay an
analysis; the per-assay abundances are imported as feature_intensity.
import_data_mztab(data = NULL, path, import_metadata = TRUE, silent = FALSE)import_data_mztab(data = NULL, path, import_metadata = TRUE, silent = FALSE)
data |
An |
path |
Path to a |
import_metadata |
If |
silent |
Suppress messages. |
mzTab-M is a quantification report, so an import is necessarily partial:
the single reported abundance per feature is mapped to feature_intensity,
and feature identities (name, formula, neutral mass, m/z, retention time)
are taken from the SMF/SML sections where available. Internal-standard
relationships, QC-type assignments and calibration metadata are not
part of mzTab-M and must be supplied afterwards with add_metadata().
study_variable groups are not imported; all analyses are in one batch.
The updated MRMhubExperiment.
All imported identifiers are whitespace-normalized on import: leading and
trailing spaces are removed and internal runs of whitespace are collapsed to
a single space (for example "QC 01" becomes "QC 01"). Raw-data file
extensions (.mzML, .d, .raw, .wiff, .wiff2, .lcd, .chrom,
case-insensitive) are stripped from analysis_id.
The same normalization is applied to both the data and the metadata, which is
what lets an analysis_id typed into metadata match the one derived from a
data-file name instead of silently failing to join. A consequence is that two
identifiers differing only by whitespace collapse to one and are then reported
as duplicates.
import_data_mrmhub(), save_dataset_mztab(), add_metadata()
## Not run: mexp <- MRMhubExperiment() mexp <- import_data_mztab(mexp, "LDA_export.mzTab") ## End(Not run)## Not run: mexp <- MRMhubExperiment() mexp <- import_data_mztab(mexp, "LDA_export.mzTab") ## End(Not run)
This function imports tabular data files (*.csv) exported from Skyline,
containing peak integration results.
import_data_skyline( data = NULL, path, transition_id_columns = c("name", "mz", "none"), import_metadata = TRUE, silent = FALSE )import_data_skyline( data = NULL, path, transition_id_columns = c("name", "mz", "none"), import_metadata = TRUE, silent = FALSE )
data |
A |
path |
One or more file paths, or a directory path from which all matching files will be imported. |
transition_id_columns |
A character vector specifying the columns that
define the transition (precursor and product) to use for unique |
import_metadata |
Logical; whether to import additional metadata columns (e.g., precursor/product m/z values). |
silent |
Logical; whether to suppress most notifications. |
In Skyline, transitions are defined by
the Molecule Name and corresponding precursor and product m/z values,
rather than any identifier. When importing this data, the feature_id is
generated using the Molecule Name with either precursor/product names or
m/z values, unless Molecule Name uniquely identifies the features (refer to
the transition_id_columns argument below).
The following supported columns from Skyline can be imported:
| Skyline Column Name | MRMhub Column Name | Required |
Replicate Name |
analysis_id |
Yes |
Molecule List Name |
feature_class |
No |
Molecule Name |
feature_id |
Yes |
Precursor Name |
feature_id |
Yes* |
Product Name |
feature_id |
Yes* |
Precursor Mz |
method_precursor_mz |
Yes* |
Product Mz |
method_product_mz |
Yes* |
Area |
feature_area |
Yes |
Retention Time |
feature_rt |
No |
*Requirements for these columns are described in transition_id_columns.
To export results from Skyline, use the 'Molecule Transition Results' format
and include Replicate Name, Molecule Name, and either
Precursor Mz/Product Mz or Precursor Name/Product Name columns.
At least one feature variable, such as Area or RT, must also be exported.
A MRMhubExperiment object containing the imported data.
All imported identifiers are whitespace-normalized on import: leading and
trailing spaces are removed and internal runs of whitespace are collapsed to
a single space (for example "QC 01" becomes "QC 01"). Raw-data file
extensions (.mzML, .d, .raw, .wiff, .wiff2, .lcd, .chrom,
case-insensitive) are stripped from analysis_id.
The same normalization is applied to both the data and the metadata, which is
what lets an analysis_id typed into metadata match the one derived from a
data-file name instead of silently failing to join. A consequence is that two
identifiers differing only by whitespace collapse to one and are then reported
as duplicates.
mexp <- MRMhubExperiment() file_path <- system.file("extdata", "Skyline_MoleculeTransitionResults.csv", package = "mrmhub") mexp <- import_data_skyline( data = mexp, path = file_path, transition_id_columns = "mz", import_metadata = TRUE ) print(mexp)mexp <- MRMhubExperiment() file_path <- system.file("extdata", "Skyline_MoleculeTransitionResults.csv", package = "mrmhub") mexp <- import_data_skyline( data = mexp, path = file_path, transition_id_columns = "mz", import_metadata = TRUE ) print(mexp)
Imports analysis metadata (annotation) from a preloaded data frame or tibble via the data argument, or from data from a file (CSV or Excel) via the path argument.
The analysis metadata must contain following columns: analysis_id and qc_type. Additional analysis metadata columns are described under details below.
import_metadata_analyses( data = NULL, table = NULL, path = NULL, sheet = NULL, ignore_warnings = FALSE, excl_unmatched_analyses = FALSE )import_metadata_analyses( data = NULL, table = NULL, path = NULL, sheet = NULL, ignore_warnings = FALSE, excl_unmatched_analyses = FALSE )
data |
A |
table |
A data frame or tibble with analysis (sample) metadata. If |
path |
A character string specifying the path to a CSV (.csv) or Excel (.xlsx) file. If |
sheet |
Defines the sheet name in case an Excel file is provided. |
ignore_warnings |
Ignore warnings from data validation and proceed with importing metadata |
excl_unmatched_analyses |
Exclude analyses (samples) that have no matching metadata |
An updated MRMhubExperiment object
All imported identifiers are whitespace-normalized on import: leading and
trailing spaces are removed and internal runs of whitespace are collapsed to
a single space (for example "QC 01" becomes "QC 01"). Raw-data file
extensions (.mzML, .d, .raw, .wiff, .wiff2, .lcd, .chrom,
case-insensitive) are stripped from analysis_id.
The same normalization is applied to both the data and the metadata, which is
what lets an analysis_id typed into metadata match the one derived from a
data-file name instead of silently failing to join. A consequence is that two
identifiers differing only by whitespace collapse to one and are then reported
as duplicates.
mexp <- MRMhubExperiment() file_path = system.file("extdata", "MHQuant_demo.csv", package = "mrmhub") mexp <- import_data_masshunter( data = mexp, path = file_path, import_metadata = FALSE) meta_path = system.file("extdata", "MHQuant_demo_metadata_analyses.csv", package = "mrmhub") mexp <- import_metadata_analyses( data = mexp, path = meta_path, excl_unmatched_analyses = TRUE) print(mexp)mexp <- MRMhubExperiment() file_path = system.file("extdata", "MHQuant_demo.csv", package = "mrmhub") mexp <- import_data_masshunter( data = mexp, path = file_path, import_metadata = FALSE) meta_path = system.file("extdata", "MHQuant_demo_metadata_analyses.csv", package = "mrmhub") mexp <- import_metadata_analyses( data = mexp, path = meta_path, excl_unmatched_analyses = TRUE) print(mexp)
Imports feature metadata (annotation) from a preloaded data frame or tibble via the data argument, or from data from a file (CSV or Excel) via the path argument.
The feature metadata must contain following column: feature_id. Additional feature metadata columns are described under details below.
import_metadata_features( data = NULL, table = NULL, path = NULL, sheet = NULL, ignore_warnings = FALSE )import_metadata_features( data = NULL, table = NULL, path = NULL, sheet = NULL, ignore_warnings = FALSE )
data |
A |
table |
A data frame or tibble with feature metadata. If |
path |
A character string specifying the path to a CSV (.csv) or Excel (.xlsx) file. If |
sheet |
Defines the sheet name in case an Excel file is provided. |
ignore_warnings |
Ignore warnings from data validation and proceed with importing metadata |
An updated MRMhubExperiment object
All imported identifiers are whitespace-normalized on import: leading and
trailing spaces are removed and internal runs of whitespace are collapsed to
a single space (for example "QC 01" becomes "QC 01"). Raw-data file
extensions (.mzML, .d, .raw, .wiff, .wiff2, .lcd, .chrom,
case-insensitive) are stripped from analysis_id.
The same normalization is applied to both the data and the metadata, which is
what lets an analysis_id typed into metadata match the one derived from a
data-file name instead of silently failing to join. A consequence is that two
identifiers differing only by whitespace collapse to one and are then reported
as duplicates.
Retrieves available metadata from the imported analysis data and
associates it with the provided MRMhubExperiment object.
import_metadata_from_data(data = NULL, qc_type_column_name = "qc_type")import_metadata_from_data(data = NULL, qc_type_column_name = "qc_type")
data |
A |
qc_type_column_name |
Column name in the imported raw data representing
the |
An updated MRMhubExperiment object
Imports ISTD metadata (annotation) from a preloaded data frame or tibble via the data argument, or from data from a file (CSV or Excel) via the path argument.
The ISTD metadata must contain following columns: istd_feature_id and one of istd_conc_nmolar or istd_conc_ngml.
import_metadata_istds( data = NULL, table = NULL, path = NULL, sheet = NULL, ignore_warnings = FALSE )import_metadata_istds( data = NULL, table = NULL, path = NULL, sheet = NULL, ignore_warnings = FALSE )
data |
A |
table |
A data frame or tibble with ISTD metadata. If |
path |
A character string specifying the path to a CSV (.csv) or Excel (.xlsx) file. If |
sheet |
Defines the sheet name in case an Excel file is provided. |
ignore_warnings |
Ignore warnings from data validation and proceed with importing metadata |
An updated MRMhubExperiment object
All imported identifiers are whitespace-normalized on import: leading and
trailing spaces are removed and internal runs of whitespace are collapsed to
a single space (for example "QC 01" becomes "QC 01"). Raw-data file
extensions (.mzML, .d, .raw, .wiff, .wiff2, .lcd, .chrom,
case-insensitive) are stripped from analysis_id.
The same normalization is applied to both the data and the metadata, which is
what lets an analysis_id typed into metadata match the one derived from a
data-file name instead of silently failing to join. A consequence is that two
identifiers differing only by whitespace collapse to one and are then reported
as duplicates.
Imports metadata from a 'MRMhub Metadata Organizer' file (.xlsx) file and associates it with analysis data.
import_metadata_msorganiser( data = NULL, path, ignore_warnings = FALSE, excl_unmatched_analyses = FALSE )import_metadata_msorganiser( data = NULL, path, ignore_warnings = FALSE, excl_unmatched_analyses = FALSE )
data |
A |
path |
File name and path of the 'MRMhub Metadata Organizer' file (.xlsx) file |
ignore_warnings |
Ignore warnings from data validation and proceed with importing metadata |
excl_unmatched_analyses |
Exclude analyses (samples) that have no matching metadata |
An updated MRMhubExperiment object
All imported identifiers are whitespace-normalized on import: leading and
trailing spaces are removed and internal runs of whitespace are collapsed to
a single space (for example "QC 01" becomes "QC 01"). Raw-data file
extensions (.mzML, .d, .raw, .wiff, .wiff2, .lcd, .chrom,
case-insensitive) are stripped from analysis_id.
The same normalization is applied to both the data and the metadata, which is
what lets an analysis_id typed into metadata match the one derived from a
data-file name instead of silently failing to join. A consequence is that two
identifiers differing only by whitespace collapse to one and are then reported
as duplicates.
mexp <- MRMhubExperiment() mexp <- import_data_mrmhub( data = mexp, path = system.file("extdata", "MRMhub_demo.tsv", package = "mrmhub"), import_metadata = TRUE) mexp <- import_metadata_msorganiser( data = mexp, path = system.file("extdata", "Example_Metadata_1.xlsx", package = "mrmhub"), excl_unmatched_analyses = FALSE, ignore_warnings = TRUE) print(mexp)mexp <- MRMhubExperiment() mexp <- import_data_mrmhub( data = mexp, path = system.file("extdata", "MRMhub_demo.tsv", package = "mrmhub"), import_metadata = TRUE) mexp <- import_metadata_msorganiser( data = mexp, path = system.file("extdata", "Example_Metadata_1.xlsx", package = "mrmhub"), excl_unmatched_analyses = FALSE, ignore_warnings = TRUE) print(mexp)
Imports calibration curve metadata (annotation) from a preloaded data frame or tibble via the data argument, or from data from a file (CSV or Excel) via the path argument.
The calibration curve metadata must contain following columns: sample_id, analyte_id, concentration, and concentration_unit.
import_metadata_qcconcentrations( data = NULL, table = NULL, path = NULL, sheet = NULL, ignore_warnings = FALSE )import_metadata_qcconcentrations( data = NULL, table = NULL, path = NULL, sheet = NULL, ignore_warnings = FALSE )
data |
A |
table |
A data frame or tibble with calibration curve metadata. If |
path |
A character string specifying the path to a CSV (.csv) or Excel (.xlsx) file. If |
sheet |
Defines the sheet name in case an Excel file is provided. |
ignore_warnings |
Ignore warnings from data validation and proceed with importing metadata |
An updated MRMhubExperiment object
All imported identifiers are whitespace-normalized on import: leading and
trailing spaces are removed and internal runs of whitespace are collapsed to
a single space (for example "QC 01" becomes "QC 01"). Raw-data file
extensions (.mzML, .d, .raw, .wiff, .wiff2, .lcd, .chrom,
case-insensitive) are stripped from analysis_id.
The same normalization is applied to both the data and the metadata, which is
what lets an analysis_id typed into metadata match the one derived from a
data-file name instead of silently failing to join. A consequence is that two
identifiers differing only by whitespace collapse to one and are then reported
as duplicates.
Imports response curve metadata (annotation) from a preloaded data frame or tibble via the data argument, or from data from a file (CSV or Excel) via the path argument.
The response curve metadata must contain following columns: analysis_id, curve_id, analyzed_amount and analyzed_amount_unit.
import_metadata_responsecurves( data = NULL, table = NULL, path = NULL, sheet = NULL, ignore_warnings = FALSE )import_metadata_responsecurves( data = NULL, table = NULL, path = NULL, sheet = NULL, ignore_warnings = FALSE )
data |
A |
table |
A data frame or tibble with response curve metadata. If |
path |
A character string specifying the path to a CSV (.csv) or Excel (.xlsx) file. If |
sheet |
Defines the sheet name in case an Excel file is provided. |
ignore_warnings |
Ignore warnings from data validation and proceed with importing metadata |
An updated MRMhubExperiment object
All imported identifiers are whitespace-normalized on import: leading and
trailing spaces are removed and internal runs of whitespace are collapsed to
a single space (for example "QC 01" becomes "QC 01"). Raw-data file
extensions (.mzML, .d, .raw, .wiff, .wiff2, .lcd, .chrom,
case-insensitive) are stripped from analysis_id.
The same normalization is applied to both the data and the metadata, which is
what lets an analysis_id typed into metadata match the one derived from a
data-file name instead of silently failing to join. A consequence is that two
identifiers differing only by whitespace collapse to one and are then reported
as duplicates.
The labels a feature's mrm_pattern may take, optionally for one
product-ion origin. Single source of truth shared by metadata validation and
the Excel template dropdown (so they cannot drift).
licar_pattern_choices(origin = NULL)licar_pattern_choices(origin = NULL)
origin |
Optional origin filter ( |
A character vector of labels.
This demo dataset is included for use in function examples and user testing. It is a small, preprocessed subset of a plasma lipidomics dataset, containing raw peak areas and analytical metadata. The original dataset was published in Tan et al., ATVB, 2022.
lipidomics_datasetlipidomics_dataset
A MRMhubExperiment object with the following data and metadata:
A tibble containing the original peak data.
A tibble with annotated lipidomics data.
Analysis-level metadata
Feature-level metadata
Batch annotations.
ISTD concentrations
Response curves metadata
mrmhub's console feedback is coloured with cli. In an interactive session this
works out of the box, but in a non-interactive render (Quarto or R Markdown)
cli suppresses colour by default, and its alerts travel on the message
stream, which knitr does not colour-convert. Call this once in a setup chunk
to (1) advertise colour support to cli via cli.num_colors / crayon.enabled
and (2), when rendering to HTML, register a knitr message hook that converts
the emitted ANSI sequences to coloured HTML using the fansi package. For
PDF and Word the same hook strips the ANSI so messages stay clean plain text.
Advertising colour also tints ordinary output (e.g. tibble prints) on the
output stream, which knitr leaves untouched, so an output hook strips that
ANSI to keep printed data plain text; only the message-stream alerts colour.
mrmhub_enable_cli_color(num_colors = 256L)mrmhub_enable_cli_color(num_colors = 256L)
num_colors |
Number of colours to advertise to cli. Defaults to |
Invisibly, the previous values of the options it changed (as returned
by options()), so the caller can restore them.
## Not run: # In a Quarto / R Markdown setup chunk: mrmhub_enable_cli_color() ## End(Not run)## Not run: # In a Quarto / R Markdown setup chunk: mrmhub_enable_cli_color() ## End(Not run)
Returns the currently set mrmhub.* plot-appearance options as a named list.
Options that are not set are omitted.
mrmhub_get_plot_defaults()mrmhub_get_plot_defaults()
A named list of the active plot defaults (empty if none are set).
mrmhub_set_plot_defaults(font_base_size = 8) mrmhub_get_plot_defaults() mrmhub_reset_plot_defaults()mrmhub_set_plot_defaults(font_base_size = 8) mrmhub_get_plot_defaults() mrmhub_reset_plot_defaults()
Removes all mrmhub.* plot-appearance options set by
mrmhub_set_plot_defaults(), restoring the built-in per-function defaults.
mrmhub_reset_plot_defaults()mrmhub_reset_plot_defaults()
Invisibly, the previous option values (as returned by options()).
mrmhub_set_plot_defaults(font_base_size = 8) mrmhub_reset_plot_defaults()mrmhub_set_plot_defaults(font_base_size = 8) mrmhub_reset_plot_defaults()
Sets session-wide defaults for the shared appearance arguments of the
plot_*() functions, so common choices such as a smaller base font or point
size can be made once at the top of a notebook instead of on every call.
Defaults are stored as mrmhub.* options. The precedence for every argument
is: a value passed explicitly to a plotting function wins, then the global
default set here, then the function's built-in default (including automatic
cols_page-based sizing on faceted plots).
mrmhub_set_plot_defaults( font_base_size = NULL, point_size = NULL, legend_position = NULL, legend_size = NULL, show_legend_title = NULL, strip_bg_color = NULL, units = NULL, dpi = NULL )mrmhub_set_plot_defaults( font_base_size = NULL, point_size = NULL, legend_position = NULL, legend_size = NULL, show_legend_title = NULL, strip_bg_color = NULL, units = NULL, dpi = NULL )
font_base_size |
Base font size in points; all plot text scales from it. |
point_size |
Point/marker size. |
legend_position |
Legend placement: a keyword ( |
legend_size |
Scales the whole legend (text, title, key and glyphs); a
value |
show_legend_title |
|
strip_bg_color |
Facet strip background fill (strip text auto-contrasts). |
units |
Default unit for the |
dpi |
Default resolution in dots per inch for the raster formats of
|
Only the arguments you supply are changed; the rest are left untouched. Pass
NULL (the default) to leave a setting as it is, and use
mrmhub_reset_plot_defaults() to clear them all. The previous option values
are returned invisibly, so a set can be undone with options(old) or scoped
to a block with withr::local_options().
Invisibly, a named list of the option values as they were before this
call (as returned by options()).
mrmhub_reset_plot_defaults(), mrmhub_get_plot_defaults(),
save_plot() and the vignette("manual-08-visualization") article.
old <- mrmhub_set_plot_defaults(font_base_size = 8, point_size = 0.8) # ... make plots with the smaller defaults ... options(old) # restoreold <- mrmhub_set_plot_defaults(font_base_size = 8, point_size = 0.8) # ... make plots with the smaller defaults ... options(old) # restore
MRMhubExperiment
Prints the full status dashboard for a MRMhubExperiment: sample and feature
composition, which metadata tables are populated, the state of each processing
step, and any manually excluded analyses or features. Printing the object
directly gives the compact one-screen overview instead.
mrmhub_status(object)mrmhub_status(object)
object |
A |
The object, invisibly.
mrmhub_status(MRMhubExperiment(title = "Test", analysis_type = "lipidomics"))mrmhub_status(MRMhubExperiment(title = "Test", analysis_type = "lipidomics"))
MRMhubExperiment objectConstructor for the MRMhubExperiment object
MRMhubExperiment(title = "", analysis_type = NA_character_)MRMhubExperiment(title = "", analysis_type = NA_character_)
title |
Title of experiment |
analysis_type |
Analysis type, one of "lipidomics", "metabolomics", "externalcalib", "others" |
MRMhubExperiment object
The MRMhubExperiment object is the core data structure utilized within the MRMhub workflow, encapsulating all relevant experimental data and metadata.
It also includes processing results, details of the applied processing steps, and the current status of the data.
titleTitle of the experiment
analysis_typeAnalysis type, one of "lipidomics", "metabolomics", "externalcalib", "others"
feature_intensity_varFeature variable used as default for calculations
conc_analyte_unitUnit of the analyte amount underlying feature_conc,
set when the data are quantitated. "pmol" or "ng" for ISTD quantitation
(see quantify_by_istd()), or the calibrant concentration unit (e.g.
"nmol/L") for calibration quantitation. Divided by sample_amount_unit by
get_conc_unit() to name the unit of feature_conc. NA when not quantitated.
dataset_origOriginal imported analysis data.
datasetProcessed analysis data.
dataset_filteredQC-filtered processed analysis data.
annot_analysesAnnotation of analyses/runs
annot_featuresAnnotation of measured features.
annot_istdsAnnotation of Internal Standard concs.
annot_responsecurvesAnnotation of response curves (RQC).
annot_qcconcentrationsAnnotation of calibration curves.
annot_studysamplesAnnotation of study samples.
annot_batchesAnnotation of batches.
annot_interferencesInterference relationships (feature_id, interference_feature_id, interference_contribution, overlap_type, source) feeding the correction engine; derived (auto) and/or manual.
metrics_qcQC information for each measured feature
metrics_calibrationCalibration metrics calculated from external calibration curves for each measured feature
status_processingStatus within the data processing workflow
is_istd_normalizedFlag if data has been ISTD normalized
is_quantitatedFlag if data has been quantitated using ISTD and sample amount
is_filteredFlag if data has been filtered based on QC parameters
is_isotope_corrFlag if one or more features have been isotope corrected
analyses_excludedAnalyses excluded from processing, plots and reporting, unless explicitly requested
features_excludedFeatures excluded from processing, plots and reporting, unless explicitly requested
var_drift_correctedList indicating which variables are drift corrected
var_batch_correctedList indicating which variables are batch corrected
Normalize feature intensities by dividing them by the intensities
of the corresponding internal standards (ISTDs). Each feature
must have a defined internal standard (ISTD) in the feature metadata.
normalize_by_istd(data = NULL, ignore_missing_annotation = FALSE)normalize_by_istd(data = NULL, ignore_missing_annotation = FALSE)
data |
A |
ignore_missing_annotation |
If |
A MRMhubExperiment object with normalized feature intensities
This function retrieves lipid class, species and transition names from the feature_id column and adds them as columns to the dataset.
parse_lipid_feature_names( tbl, use_as_feature_class = "lipid_class_lcb", add_transition_names = FALSE, add_chain_composition = TRUE )parse_lipid_feature_names( tbl, use_as_feature_class = "lipid_class_lcb", add_transition_names = FALSE, add_chain_composition = TRUE )
tbl |
A data frame containing a |
use_as_feature_class |
Set |
add_transition_names |
add transition name and transition group, based on information in square brackets in |
add_chain_composition |
add |
The input data frame with added lipid class, species and transition name columns.
Reads and parses one Agilent MassHunter Quant CSV result file
parse_masshunter_csv( path, expand_qualifier_names = TRUE, silent = FALSE, conc_column = "conc_final" )parse_masshunter_csv( path, expand_qualifier_names = TRUE, silent = FALSE, conc_column = "conc_final" )
path |
File path of MassHunter Quant CSV file |
expand_qualifier_names |
If |
silent |
Suppress messages |
conc_column |
Which concentration field of the masshunter data to use, in case "Calc. Conc." and "Final Conc" are present. Default is "conc_final". |
A tibble with the parse results in the long format
file_path = system.file("extdata", "MHQuant_demo.csv", package = "mrmhub") tbl <- parse_masshunter_csv( path = file_path, expand_qualifier_names = TRUE) head(tbl)file_path = system.file("extdata", "MHQuant_demo.csv", package = "mrmhub") tbl <- parse_masshunter_csv( path = file_path, expand_qualifier_names = TRUE) head(tbl)
Parses MRMhub peak integration results into a tibble
parse_mrmhub_result(path, silent = FALSE)parse_mrmhub_result(path, silent = FALSE)
path |
File name of the MRMhub result file (*.tsv or *.csv) |
silent |
No comments printed |
A tibble in the long format
file_path = system.file("extdata", "MRMhub_demo.tsv", package = "mrmhub") tbl <- parse_mrmhub_result(path = file_path) head(tbl)file_path = system.file("extdata", "MRMhub_demo.tsv", package = "mrmhub") tbl <- parse_mrmhub_result(path = file_path) head(tbl)
Parses a CSV table with analysis/samples and feature pairs in rows, columns representing the feature variables.
parse_plain_long_csv( path, na_strings = "NA", silent = FALSE, column_mapping = NULL, warn_unrecognized_columns = TRUE, ... )parse_plain_long_csv( path, na_strings = "NA", silent = FALSE, column_mapping = NULL, warn_unrecognized_columns = TRUE, ... )
path |
File name (*.tsv or *.csv) |
na_strings |
A character vector of strings to be interpreted as NA values. Blank fields are also considered to be missing values. |
silent |
No comments printed |
column_mapping |
A named character vector with the mapping of the columns in the input file to the columns in the output table.
If NULL (default), the function will use the default mapping. See |
warn_unrecognized_columns |
Logical indicating whether to issue a warning for unknown columns in the dataset. |
... |
Additional arguments passed to the function. Currently only |
A tibble in the long format
file_path = system.file("extdata", "plain_long_dataset.csv", package = "mrmhub") tbl <- parse_plain_long_csv(path = file_path) head(tbl)file_path = system.file("extdata", "plain_long_dataset.csv", package = "mrmhub") tbl <- parse_plain_long_csv(path = file_path) head(tbl)
Parses a CSV table with analysis/samples in rows, features values in columns.
parse_plain_wide_csv( path, variable_name, analysis_id_col = NA, import_metadata = TRUE, first_feature_column = NA, na_strings = "NA" )parse_plain_wide_csv( path, variable_name, analysis_id_col = NA, import_metadata = TRUE, first_feature_column = NA, na_strings = "NA" )
path |
File name and path of a plain wide-format CSV file |
variable_name |
Name of the variable representing the values in the table. Must be one of "intensity", "norm_intensity", "conc", "area", "height", "response". |
analysis_id_col |
Column to be used as analysis_id |
import_metadata |
Import additional metadata columns (e.g. batch ID, sample type) and add to the |
first_feature_column |
Column number of the first column representing the feature values |
na_strings |
A character vector of strings which are to be interpreted as NA values. Blank fields are also considered to be missing values. |
A tibble in the long format
file_path <- system.file("extdata", "plain_wide_dataset.csv", package = "mrmhub") tbl <- parse_plain_wide_csv( path = file_path, variable_name = "conc", analysis_id_col = "analysis_id", import_metadata = TRUE) head(tbl)file_path <- system.file("extdata", "plain_wide_dataset.csv", package = "mrmhub") tbl <- parse_plain_wide_csv( path = file_path, variable_name = "conc", analysis_id_col = "analysis_id", import_metadata = TRUE) head(tbl)
Parses skyline peak integration results into a tibble
parse_skyline_result(path, na_strings, silent = FALSE, ...)parse_skyline_result(path, na_strings, silent = FALSE, ...)
path |
File name of the Skyline result file (*.tsv or *.csv) |
na_strings |
A character vector of strings to be interpreted as NA values. |
silent |
No comments printed |
... |
Additional arguments passed to the function. Currently only |
A tibble in the long format
file_path = system.file("extdata", "Skyline_MoleculeTransitionResults.csv", package = "mrmhub") tbl <- parse_skyline_result(path = file_path, na_strings = "NA") head(tbl)file_path = system.file("extdata", "Skyline_MoleculeTransitionResults.csv", package = "mrmhub") tbl <- parse_skyline_result(path = file_path, na_strings = "NA") head(tbl)
Creates a profile plot showing the abundance distribution of features across different classes.
plot_abundanceprofile( data, variable, qc_types, log_scale, use_qc_metrics = FALSE, feature_map = NA, show_sum = NA, exclude_classes = NA, filter_data = FALSE, include_qualifier = FALSE, include_istd = FALSE, include_feature_filter = NA, exclude_feature_filter = NA, analysis_range = NA, drop_empty_classes = TRUE, density_strip = FALSE, scale_factor = 1, x_lim = NA, x_label = NA, y_axis_position = "right", segment_width = 0.25, font_base_size = NULL, grid_major_color = "grey50", grid_major_linewidth = 0.1, grid_minor_color = "grey50", grid_minor_linewidth = 0.1 )plot_abundanceprofile( data, variable, qc_types, log_scale, use_qc_metrics = FALSE, feature_map = NA, show_sum = NA, exclude_classes = NA, filter_data = FALSE, include_qualifier = FALSE, include_istd = FALSE, include_feature_filter = NA, exclude_feature_filter = NA, analysis_range = NA, drop_empty_classes = TRUE, density_strip = FALSE, scale_factor = 1, x_lim = NA, x_label = NA, y_axis_position = "right", segment_width = 0.25, font_base_size = NULL, grid_major_color = "grey50", grid_major_linewidth = 0.1, grid_minor_color = "grey50", grid_minor_linewidth = 0.1 )
data |
A |
variable |
A character string indicating the variable to plot. For |
qc_types |
A character vector specifying the QC types to be averaged and plotted.
Ignored if |
log_scale |
A logical value indicating whether to use a log10 scale for the x-axis. |
use_qc_metrics |
A logical value. If |
feature_map |
A named character vector specifying feature classes, their order, and color. The order of the vector determines the y-axis order.
Alternatively, can be a single string: |
show_sum |
A logical value indicating whether to plot a summary point (diamond shape)
representing the mean of the summed abundances for each class. Defaults to |
exclude_classes |
A character vector of feature classes to be excluded from the plot. |
filter_data |
A logical value indicating whether to use all data ( |
include_qualifier |
A logical value indicating whether to include qualifier features. Default is |
include_istd |
A logical value indicating whether to include internal standard (ISTD) features. Default is |
include_feature_filter |
Feature(s) to include by |
exclude_feature_filter |
Feature(s) to exclude by |
analysis_range |
A numeric vector of length 2 specifying the inclusive range of |
drop_empty_classes |
A logical value. If |
density_strip |
A logical value. If |
scale_factor |
A numeric value to scale the selected variable. Default is 1. |
x_lim |
A numeric vector of length 2 specifying the x-axis limits. If |
x_label |
A character string for the x-axis label. If |
y_axis_position |
A character string specifying the y-axis position ("left" or "right"). Default is "right". |
segment_width |
A numeric value for the linewidth of the feature segments. Default is 0.25. |
font_base_size |
Numeric. Base font size (in points) for plot text; all
plot text scales proportionally with this value. |
grid_major_color |
Color for major grid lines. Default is "grey50". |
grid_major_linewidth |
Linewidth for major grid lines. Default is 0.1. |
grid_minor_color |
Color for minor grid lines. Default is "grey50". |
grid_minor_linewidth |
Linewidth for minor grid lines. Default is 0.1. |
A ggplot object representing the abundance profile plot.
This function plots calibration curves of each feature where defined
and displays QC samples with defined concentrations within the plot.
Users can select a regression model (linear or quadratic) and apply
weighting (none, "1/x", "1/x^2", or "1/sqrt(x)"), either through function arguments
or feature metadata.
plot_calibrationcurves( data = NULL, variable = "norm_intensity", qc_types = NA, fit_overwrite, fit_model = c("linear", "quadratic"), fit_weighting = c(NA, "none", "1/x", "1/x^2", "1/sqrt(x)"), ci_show = NA, ci_clip = TRUE, zoom_n_points = NA, log_scale = FALSE, filter_data = FALSE, include_qualifier = TRUE, include_istd = FALSE, include_feature_filter = NA, exclude_feature_filter = NA, output_pdf = FALSE, path = NA, create_dir = TRUE, return_plots = FALSE, point_size = NULL, point_color = NA, point_fill = NA, point_shape = NA, line_width = 0.7, line_color = "#4575b4", ribbon_fill = "#e6f6ff", font_base_size = NULL, rows_page = 4, cols_page = 5, specific_page = NA, page_orientation = "LANDSCAPE", page_width = NULL, page_height = NULL, page_units = "mm", show_progress = TRUE )plot_calibrationcurves( data = NULL, variable = "norm_intensity", qc_types = NA, fit_overwrite, fit_model = c("linear", "quadratic"), fit_weighting = c(NA, "none", "1/x", "1/x^2", "1/sqrt(x)"), ci_show = NA, ci_clip = TRUE, zoom_n_points = NA, log_scale = FALSE, filter_data = FALSE, include_qualifier = TRUE, include_istd = FALSE, include_feature_filter = NA, exclude_feature_filter = NA, output_pdf = FALSE, path = NA, create_dir = TRUE, return_plots = FALSE, point_size = NULL, point_color = NA, point_fill = NA, point_shape = NA, line_width = 0.7, line_color = "#4575b4", ribbon_fill = "#e6f6ff", font_base_size = NULL, rows_page = 4, cols_page = 5, specific_page = NA, page_orientation = "LANDSCAPE", page_width = NULL, page_height = NULL, page_units = "mm", show_progress = TRUE )
data |
A |
variable |
Variable to plot on the y-axis, usually intensity. Default
is |
qc_types |
A character vector specifying the QC types to plot. It must contain
at least |
fit_overwrite |
If |
fit_model |
A character string specifying the default regression fit
method to use for the calibration curve. Must be one of |
fit_weighting |
A character string specifying the default weighting
method for the regression points in the calibration curve. Must be one of
|
ci_show |
Logical, if |
ci_clip |
Logical, if |
zoom_n_points |
Number of x lowest concentration points to display, used for zooming. Set to |
log_scale |
Logical. Determines whether the x and y axes are displayed in a logarithmic scale (log-log scale).
Set to |
filter_data |
Logical, if |
include_qualifier |
Logical, whether to include qualifier features. Default is |
include_istd |
Logical, whether to include internal standard (ISTD) features. Default is |
include_feature_filter |
Feature(s) to include by |
exclude_feature_filter |
Feature(s) to exclude by |
output_pdf |
Logical, if |
path |
File path for saving the PDF. Default is an empty string. |
create_dir |
A logical value. If |
return_plots |
Logical, if |
point_size |
Size of points in the plot. Default is 1.5. |
point_color |
A vector specifying the colors for points corresponding
to different QC types. This can be either an unnamed vector or a named
vector, with names corresponding to QC types. Unused colors will be ignored.
Default is |
point_fill |
A vector specifying the fill colors for points corresponding
to different QC types. This can be either an unnamed vector or a named
vector, with names corresponding to QC types. Unused fill colors will be ignored.
Default is |
point_shape |
A vector specifying the shapes for points corresponding
to different QC types. This can be either an unnamed vector or a named
vector, with names corresponding to QC types. Unused shapes will be ignored.
Default is |
line_width |
Width of regression lines. Default is 0.7. |
line_color |
Color of the regression line. Default is |
ribbon_fill |
Color for the confidence interval ribbon. Default is
|
font_base_size |
Numeric. Base font size (in points) for plot text; all
plot text scales proportionally with this value. |
rows_page |
Number of plot rows. Default is 4. |
cols_page |
Number of plot columns. Default is 5. |
specific_page |
Show/save a specific page number only. |
page_orientation |
Orientation of PDF, either |
page_width, page_height
|
Size of a PDF page, in |
page_units |
Unit of |
show_progress |
Logical. If |
Features for plotting can be filtered using QC filters defined via
filter_features_qc() or through include_feature_filter and
exclude_feature_filter arguments. The resulting plots offer extensive
customization options, including point size, line width, point color, point
fill, point shape, line color, ribbon fill, and font base size.
Plots will be divided into multiple pages if the number of features exceeds
the product of rows_page and cols_page settings. The function supports
both direct plotting within R and saving plots as PDF files. Additionally,
plots can be returned as a list of ggplot2 objects for further manipulation
or integration into other analyses.
A list of ggplot objects if return_plots = TRUE, otherwise
NULL (the plots are drawn to the active device or written to a PDF).
| Purpose | Format | Device used | Typical dpi |
| Journal figure, vector (default choice) | "pdf" |
grDevices::cairo_pdf, else grDevices::pdf |
n/a |
| Figure for further editing (Illustrator, Inkscape) | "svg" |
svglite::svglite, else grDevices::svg |
n/a |
| Slides, Quarto HTML, GitHub | "png" |
ragg::agg_png, else grDevices::png |
150-300 |
| Journal requiring raster submission | "tiff" |
ragg::agg_tiff, else grDevices::tiff |
300-600 |
Prefer a vector format (pdf, svg) for publication: text stays
selectable and searchable, and lines stay sharp at any magnification.
Prefer a raster format (png, tiff) when a plot draws very many marks
– a plot_runscatter() page covering several thousand analyses, or a dense
plot_pca() score plot. Every point becomes a separate object in a PDF, so
such figures produce very large files that are slow to open and to typeset.
Saving them at 300-600 dpi instead keeps the file small with no visible loss.
The optional packages ragg and svglite are used automatically when
installed, giving better text rendering, system-font support and smaller SVG
files. When they are absent the equivalent grDevices device is used and the
output is still correct. Installing both is recommended:
install.packages(c("ragg", "svglite")).
PDF output uses the cairo device wherever R was built with cairo support
(capabilities("cairo")), because plain grDevices::pdf() writes text in a
single-byte encoding and silently transliterates anything outside it – an en
dash becomes -, >= replaces the proper symbol. Unit labels such as
umol/L and statistical annotations routinely depend on those glyphs.
Multi-page output from the paged plot functions (plot_runscatter(),
plot_calibrationcurves(), plot_responsecurves(),
plot_feature_correlations()) is PDF only, which is the only format that
holds many pages in one file. Use save_plot() for single figures in any of
the other formats.
save_plot() to save a single figure in any format.
Other calibration plots:
plot_responsecurves()
Creates scatter plots for pairs of features that have correlations outside specified thresholds. Each pair is displayed in a separate facet with its correlation coefficient.
This plot can be used to visually inspect highly correlated features, that may represent duplicate identifications or represent isomers.
Correlations are Pearson's r over the analyses where both features have values; pairs sharing values in fewer than half of the analyses are skipped.
plot_feature_correlations( data, variable, qc_types = NA, cor_min, cor_min_neg = -0.99, log_scale = FALSE, sort_by_corr = TRUE, filter_data = FALSE, include_qualifier = FALSE, include_istd = FALSE, include_feature_filter = NA, exclude_feature_filter = NA, min_median_value = NA, output_pdf = FALSE, path = NA, create_dir = TRUE, return_plots = FALSE, rows_page = 4, cols_page = 5, specific_page = NA, page_orientation = "LANDSCAPE", page_width = NULL, page_height = NULL, page_units = "mm", point_size = NULL, point_alpha = 0.8, point_stroke = 0.3, line_width = 0.5, line_color = "orange", line_alpha = 0.5, font_base_size = NULL, show_progress = TRUE )plot_feature_correlations( data, variable, qc_types = NA, cor_min, cor_min_neg = -0.99, log_scale = FALSE, sort_by_corr = TRUE, filter_data = FALSE, include_qualifier = FALSE, include_istd = FALSE, include_feature_filter = NA, exclude_feature_filter = NA, min_median_value = NA, output_pdf = FALSE, path = NA, create_dir = TRUE, return_plots = FALSE, rows_page = 4, cols_page = 5, specific_page = NA, page_orientation = "LANDSCAPE", page_width = NULL, page_height = NULL, page_units = "mm", point_size = NULL, point_alpha = 0.8, point_stroke = 0.3, line_width = 0.5, line_color = "orange", line_alpha = 0.5, font_base_size = NULL, show_progress = TRUE )
data |
A |
variable |
A character string indicating the signal variable to plot. Must be one of: "area", "height", "intensity", "norm_intensity", "response", "conc", "conc_raw", "rt", "fwhm". |
qc_types |
A character vector specifying the QC types to plot. It must
contain at least one element. The default |
cor_min |
Numeric. Minimum correlation threshold. Only feature pairs with positive correlations above this value will be shown. Set to Inf to exclude positive correlations. |
cor_min_neg |
Numeric. Minimum negative correlation threshold. Only feature pairs with negative correlations above this value will be shown. Set to -Inf to exclude negative correlations. |
log_scale |
A logical value indicating whether to use a log10 scale for
both axes. Default is |
sort_by_corr |
A logical value indicating whether to sort the features in
the plot by correlation or alphabetically by feature ID. Default is |
filter_data |
A logical value indicating whether to use all data
(default) or only QC-filtered data (filtered via |
include_qualifier |
A logical value indicating whether to include
qualifier features. Default is |
include_istd |
A logical value indicating whether to include internal
standard (ISTD) features. Default is |
include_feature_filter |
Feature(s) to include by |
exclude_feature_filter |
Feature(s) to exclude by |
min_median_value |
Minimum median feature value across the selected
QC-type samples required for a feature to be included. |
output_pdf |
If |
path |
The file path for saving the PDF. Must be defined if
|
create_dir |
A logical value. If |
return_plots |
Logical. If |
rows_page |
Number of rows of plots per page. |
cols_page |
Number of columns of plots per page. |
specific_page |
An integer specifying a specific page to plot. If
|
page_orientation |
Orientation of the PDF paper: |
page_width, page_height
|
Size of a PDF page, in |
page_units |
Unit of |
point_size |
A numeric value indicating the size of points in millimeters. Default is 1. |
point_alpha |
A numeric value indicating the transparency of points (0-1). Default is 0.8. |
point_stroke |
A numeric value indicating the stroke width of the points. Default is 0.3. |
line_width |
A numeric value indicating the size of the correlation line. Default is 0.5. |
line_color |
A character string indicating the color of the correlation line. Default is orange. |
line_alpha |
A numeric value indicating the transparency of the correlation line (0-1). Default is 0.5. |
font_base_size |
Numeric. Base font size (in points) for plot text; all
plot text scales proportionally with this value. |
show_progress |
Logical. If |
A ggplot object showing scatter plots of highly correlated feature pairs.
Returns NULL if no correlations meet the threshold criteria.
| Purpose | Format | Device used | Typical dpi |
| Journal figure, vector (default choice) | "pdf" |
grDevices::cairo_pdf, else grDevices::pdf |
n/a |
| Figure for further editing (Illustrator, Inkscape) | "svg" |
svglite::svglite, else grDevices::svg |
n/a |
| Slides, Quarto HTML, GitHub | "png" |
ragg::agg_png, else grDevices::png |
150-300 |
| Journal requiring raster submission | "tiff" |
ragg::agg_tiff, else grDevices::tiff |
300-600 |
Prefer a vector format (pdf, svg) for publication: text stays
selectable and searchable, and lines stay sharp at any magnification.
Prefer a raster format (png, tiff) when a plot draws very many marks
– a plot_runscatter() page covering several thousand analyses, or a dense
plot_pca() score plot. Every point becomes a separate object in a PDF, so
such figures produce very large files that are slow to open and to typeset.
Saving them at 300-600 dpi instead keeps the file small with no visible loss.
The optional packages ragg and svglite are used automatically when
installed, giving better text rendering, system-font support and smaller SVG
files. When they are absent the equivalent grDevices device is used and the
output is still correct. Installing both is recommended:
install.packages(c("ragg", "svglite")).
PDF output uses the cairo device wherever R was built with cairo support
(capabilities("cairo")), because plain grDevices::pdf() writes text in a
single-byte encoding and silently transliterates anything outside it – an en
dash becomes -, >= replaces the proper symbol. Unit labels such as
umol/L and statistical annotations routinely depend on those glyphs.
Multi-page output from the paged plot functions (plot_runscatter(),
plot_calibrationcurves(), plot_responsecurves(),
plot_feature_correlations()) is PDF only, which is the only format that
holds many pages in one file. Use save_plot() for single figures in any of
the other formats.
save_plot() to save a single figure in any format.
Other QC plots:
plot_interference_correction(),
plot_matrixeffects(),
plot_normalization_qc(),
plot_pca(),
plot_pca_loading(),
plot_qc_interference_impact(),
plot_qc_summary_byclass(),
plot_qc_summary_overall(),
plot_qcmetrics_comparison(),
plot_rla_boxplot(),
plot_rt_vs_chain(),
plot_runscatter(),
plot_runsequence()
This function generates grouped standardized beeswarm plots to visualize the results of interference correction across different QC types.
plot_interference_correction( data, qc_types = c("SPL", "TQC", "PBLK", "BQC"), include_qualifier = FALSE, include_istd = TRUE, include_feature_filter = NA, exclude_feature_filter = NA, min_median_value = NA, min_correction_pct = NA, sort_by_effect = c("none", "desc", "asc"), top_n = NA, y_lim = c(-NA, NA), point_size = NULL, dodge_width = 0.6, point_alpha = 0.3, box_alpha = 0.3, box_linewidth = 0.5, font_base_size = NULL, legend_position = NULL, legend_size = NULL, show_legend_title = NULL, title = NULL, angle_x = 45 )plot_interference_correction( data, qc_types = c("SPL", "TQC", "PBLK", "BQC"), include_qualifier = FALSE, include_istd = TRUE, include_feature_filter = NA, exclude_feature_filter = NA, min_median_value = NA, min_correction_pct = NA, sort_by_effect = c("none", "desc", "asc"), top_n = NA, y_lim = c(-NA, NA), point_size = NULL, dodge_width = 0.6, point_alpha = 0.3, box_alpha = 0.3, box_linewidth = 0.5, font_base_size = NULL, legend_position = NULL, legend_size = NULL, show_legend_title = NULL, title = NULL, angle_x = 45 )
data |
A |
qc_types |
A character vector specifying the QC types to plot. It must
contain at least one element. The default |
include_qualifier |
A logical value indicating whether to include
qualifier features. Default is |
include_istd |
A logical value indicating whether to include internal
standards (ISTD) features. Default is |
include_feature_filter |
Feature(s) to include by |
exclude_feature_filter |
Feature(s) to exclude by |
min_median_value |
Median raw-signal abundance floor: drop features whose
median |
min_correction_pct |
Keep only features whose median correction (percent
of raw signal removed, across the selected QC types) is at least this value.
|
sort_by_effect |
Order the x-axis by correction effect, defined per
feature as the deviation of its median % change from 100% (pooled across the
displayed QC-type points). One of |
top_n |
Keep only the |
y_lim |
A numeric vector of length 2 specifying the y-axis limits. |
point_size |
A numeric value indicating the size of points in
millimeters. Default is |
dodge_width |
Numeric. Width used to dodge overlapping points by |
point_alpha |
Numeric. Transparency of the plotted points. Default is |
box_alpha |
Numeric. Transparency of the boxplot. Default is |
box_linewidth |
Numeric. Width of the boxplot lines. Default is |
font_base_size |
Numeric. Base font size (in points) for plot text; all
plot text scales proportionally with this value. |
legend_position |
Optional legend placement. One of |
legend_size |
Optional single multiplier of |
show_legend_title |
Logical. |
title |
Optional plot title. |
angle_x |
Numeric. Angle of the x-axis text labels. Default is |
A ggplot object showing the grouped standardized beeswarm plot.
Other QC plots:
plot_feature_correlations(),
plot_matrixeffects(),
plot_normalization_qc(),
plot_pca(),
plot_pca_loading(),
plot_qc_interference_impact(),
plot_qc_summary_byclass(),
plot_qc_summary_overall(),
plot_qcmetrics_comparison(),
plot_rla_boxplot(),
plot_rt_vs_chain(),
plot_runscatter(),
plot_runsequence()
This function creates a grouped beeswarm plot of standardized feature intensities,
where each value is shown as a percentage of the feature's median over the
plotted non-blank analyses (per batch with batchwise_normalization = TRUE).
Points are grouped by qc_type and spread using quasirandom jitter. An ISTD
signal higher in process blanks (ISTD without matrix) than in the samples may
indicate ion suppression by the sample matrix. The spread between study
samples and pooled QCs can reflect sample-to-sample differences in matrix
effects.
plot_matrixeffects( data, variable = "intensity", qc_types = c("SPL", "TQC", "PBLK", "BQC"), batchwise_normalization = TRUE, include_qualifier = FALSE, only_istd = TRUE, include_feature_filter = NA, exclude_feature_filter = NA, min_median_value = NA, y_lim = c(-NA, NA), point_size = NULL, dodge_width = 0.6, point_alpha = 0.3, box_alpha = 0.3, box_linewidth = 0.5, font_base_size = NULL, legend_position = NULL, legend_size = NULL, show_legend_title = NULL, title = NULL, angle_x = 45 )plot_matrixeffects( data, variable = "intensity", qc_types = c("SPL", "TQC", "PBLK", "BQC"), batchwise_normalization = TRUE, include_qualifier = FALSE, only_istd = TRUE, include_feature_filter = NA, exclude_feature_filter = NA, min_median_value = NA, y_lim = c(-NA, NA), point_size = NULL, dodge_width = 0.6, point_alpha = 0.3, box_alpha = 0.3, box_linewidth = 0.5, font_base_size = NULL, legend_position = NULL, legend_size = NULL, show_legend_title = NULL, title = NULL, angle_x = 45 )
data |
A |
variable |
A character string indicating the signal variable to plot. Must be one of: "area", "height", "intensity", "norm_intensity", "response", "conc", "conc_raw", "rt", "fwhm". |
qc_types |
A character vector specifying the QC types to plot. It must
contain at least one element. The default |
batchwise_normalization |
A logical value indicating whether to normalize the signals by batch instead of globally. |
include_qualifier |
A logical value indicating whether to include
qualifier features. Default is |
only_istd |
A logical value indicating whether to show only internal
standard (ISTD) features. Default is |
include_feature_filter |
Feature(s) to include by |
exclude_feature_filter |
Feature(s) to exclude by |
min_median_value |
Minimum median feature value across the selected
QC-type samples required for a feature to be included. |
y_lim |
A numeric vector of length 2 specifying the y-axis limits. |
point_size |
A numeric value indicating the size of points in
millimeters. Default is |
dodge_width |
Numeric. Width used to dodge overlapping points by |
point_alpha |
Numeric. Transparency of the plotted points. Default is |
box_alpha |
Numeric. Transparency of the boxplot. Default is |
box_linewidth |
Numeric. Width of the boxplot lines. Default is |
font_base_size |
Numeric. Base font size (in points) for plot text; all
plot text scales proportionally with this value. |
legend_position |
Optional legend placement. One of |
legend_size |
Optional single multiplier of |
show_legend_title |
Logical. |
title |
Optional plot title. |
angle_x |
Numeric. Angle of the x-axis text labels. Default is |
Include at least one QC type besides the study samples: the reference is computed from the plotted analyses, so with study samples only they centre on 100% by construction. The plot compares ISTD signals between samples; it does not measure the matrix effect itself.
A ggplot object showing the grouped standardized beeswarm plot.
Other QC plots:
plot_feature_correlations(),
plot_interference_correction(),
plot_normalization_qc(),
plot_pca(),
plot_pca_loading(),
plot_qc_interference_impact(),
plot_qc_summary_byclass(),
plot_qc_summary_overall(),
plot_qcmetrics_comparison(),
plot_rla_boxplot(),
plot_rt_vs_chain(),
plot_runscatter(),
plot_runsequence()
Evaluates the effectiveness of normalization by comparing feature variability (measured as %CV) in QC and/or study samples before and after normalization. The comparison is visualized through one of three plot types:
Scatter plot: CV values before vs after normalization
Difference plot: (CV after - CV before) vs mean CV
Ratio plot: log2 of (CV after / CV before) vs mean CV
Features can be grouped and visualized by their feature class using facets.
The resulting visualization helps assess whether normalization improved measurement precision across different features and sample/QC types.
plot_normalization_qc( data = NULL, before_norm_var, after_norm_var, plot_type, qc_types = NA, facet_by_class = FALSE, y_shared = FALSE, filter_data = FALSE, include_qualifier = FALSE, include_istd = FALSE, cv_threshold_value = 25, x_lim = c(NA_real_, NA_real_), y_lim = c(NA_real_, NA_real_), cols_page = 5, point_size = NULL, point_alpha = 0.5, font_base_size = NULL, autoscale = TRUE, legend_position = NULL, legend_size = NULL, show_legend_title = NULL, title = NULL, strip_text_size = NULL, strip_bg_color = NULL, legend_bg_alpha = NULL )plot_normalization_qc( data = NULL, before_norm_var, after_norm_var, plot_type, qc_types = NA, facet_by_class = FALSE, y_shared = FALSE, filter_data = FALSE, include_qualifier = FALSE, include_istd = FALSE, cv_threshold_value = 25, x_lim = c(NA_real_, NA_real_), y_lim = c(NA_real_, NA_real_), cols_page = 5, point_size = NULL, point_alpha = 0.5, font_base_size = NULL, autoscale = TRUE, legend_position = NULL, legend_size = NULL, show_legend_title = NULL, title = NULL, strip_text_size = NULL, strip_bg_color = NULL, legend_bg_alpha = NULL )
data |
A |
before_norm_var |
A string specifying the variable from the QC metrics table to be used for the x-axis (before normalization). |
after_norm_var |
A string specifying the variable from the QC metrics table to be used for the y-axis (after normalization). |
plot_type |
A character string specifying the type of plot to generate. Must be one of "scatter", "diff", or "ratio". Selecting "scatter" plots the before and after normalization CV values as a scatter plot, "diff" plots the difference between the two CV values against the average CV, and "ratio" plots the log2 ratio of the two CV values against the average CV. |
qc_types |
A character vector specifying the QC types to plot. It must
contain at least one element. The default |
facet_by_class |
If |
y_shared |
Logical; if |
filter_data |
Whether to use all data (default) or only
QC-filtered data (filtered via |
include_qualifier |
Whether to include qualifier features
(default is |
include_istd |
Whether to include internal standards (ISTDs) (default
is |
cv_threshold_value |
Numerical threshold value to be shown as dashed
lines in the plot (default is |
x_lim |
Numeric vector of length 2 for x-axis limits. Use |
y_lim |
Numeric vector of length 2 for y-axis limits. Use |
cols_page |
Number of facet columns per page, representing
different feature classes (default is |
point_size |
Size of points in millimeters (default is |
point_alpha |
Transparency of points (default is |
font_base_size |
Numeric. Base font size (in points) for plot text; all
plot text scales proportionally with this value. |
autoscale |
Logical. When |
legend_position |
Optional legend placement. One of |
legend_size |
Optional single multiplier of |
show_legend_title |
Logical. |
title |
Optional plot title. |
strip_text_size |
Optional facet strip text size, as a multiplier of
|
strip_bg_color |
Optional facet strip background fill colour. The strip
text colour is set automatically for contrast (white on a dark fill, black
on a light one). |
legend_bg_alpha |
Optional opacity ( |
The function preselects the corresponding variables from the QC metrics and uses
plot_qcmetrics_comparison() to visualize the results.
The data must be normalized before using normalize_by_istd() followed by
calculation of the QC metrics table via calc_qc_metrics() or
filter_features_qc(), see examples below.
When facet_by_class = TRUE, then the feature_class must be defined in the
metadata or retrieved via specific functions, e.g., parse_lipid_feature_names().
A ggplot object representing the scatter plot comparing CV values
before and after normalization.
plot_qcmetrics_comparison(), calc_qc_metrics(), filter_features_qc(),
Other QC plots:
plot_feature_correlations(),
plot_interference_correction(),
plot_matrixeffects(),
plot_pca(),
plot_pca_loading(),
plot_qc_interference_impact(),
plot_qc_summary_byclass(),
plot_qc_summary_overall(),
plot_qcmetrics_comparison(),
plot_rla_boxplot(),
plot_rt_vs_chain(),
plot_runscatter(),
plot_runsequence()
# Example usage: mexp <- lipidomics_dataset mexp <- normalize_by_istd(mexp) mexp <- calc_qc_metrics(mexp) plot_normalization_qc( data = mexp, before_norm_var = "intensity", after_norm_var = "norm_intensity", plot_type = "scatter", qc_types = "SPL", filter_data = FALSE, facet_by_class = TRUE, cv_threshold_value = 25 )# Example usage: mexp <- lipidomics_dataset mexp <- normalize_by_istd(mexp) mexp <- calc_qc_metrics(mexp) plot_normalization_qc( data = mexp, before_norm_var = "intensity", after_norm_var = "norm_intensity", plot_type = "scatter", qc_types = "SPL", filter_data = FALSE, facet_by_class = TRUE, cv_threshold_value = 25 )
Generates a Principal Component Analysis (PCA) plot for visualizing samples including quality control (QC) samples. This function provides options for filtering data, applying transformations, and labelling of outliers.
Experimental batches can be visualized as ellipses to assess batch effects.
This function returns a ggplot object. Identified outliers can be printed to the console.
plot_pca( data = NULL, variable, qc_types = NA, ellipse_variable = "qc_type", ellipse_levels = NA, pca_dims = c(1, 2), log_transform = TRUE, filter_data = FALSE, include_qualifier = FALSE, include_istd = FALSE, include_feature_filter = NA, exclude_feature_filter = NA, min_median_value = NA, show_labels = TRUE, labels_column = "analysis_id", labels_threshold_mad = 3, shared_labeltext_hide = NA, label_font_size = 3, point_size = NULL, point_alpha = 0.7, font_base_size = NULL, legend_position = NULL, legend_size = NULL, show_legend_title = NULL, title = NULL, strip_text_size = NULL, strip_bg_color = NULL, legend_bg_alpha = NULL, aspect_ratio = 1, ellipse_confidence_level = 0.95, ellipse_linewidth = 1, ellipse_fill = TRUE, ellipse_fillcolor = NA, ellipse_alpha = 0.1 )plot_pca( data = NULL, variable, qc_types = NA, ellipse_variable = "qc_type", ellipse_levels = NA, pca_dims = c(1, 2), log_transform = TRUE, filter_data = FALSE, include_qualifier = FALSE, include_istd = FALSE, include_feature_filter = NA, exclude_feature_filter = NA, min_median_value = NA, show_labels = TRUE, labels_column = "analysis_id", labels_threshold_mad = 3, shared_labeltext_hide = NA, label_font_size = 3, point_size = NULL, point_alpha = 0.7, font_base_size = NULL, legend_position = NULL, legend_size = NULL, show_legend_title = NULL, title = NULL, strip_text_size = NULL, strip_bg_color = NULL, legend_bg_alpha = NULL, aspect_ratio = 1, ellipse_confidence_level = 0.95, ellipse_linewidth = 1, ellipse_fill = TRUE, ellipse_fillcolor = NA, ellipse_alpha = 0.1 )
data |
A |
variable |
A character string indicating the variable to use for PCA analysis. Must be one of: "area", "height", "intensity", "norm_intensity", "response", "conc", "conc_raw", "rt", "fwhm". |
qc_types |
A character vector specifying the QC types to plot. It must
contain at least one element. The default |
ellipse_variable |
String specifying which sample variable to show as ellipses. Must be one of: "none", "qc_type", "batch_id". "none" omits ellipses. |
ellipse_levels |
A character vector specifying the levels of
|
pca_dims |
A numeric vector of length 2 indicating the PCA dimensions to plot. Default is c(1, 2). |
log_transform |
A logical value indicating whether to log-transform
the data before the PCA. Default is |
filter_data |
A logical value indicating whether to use all data
(default) or only QC-filtered data (filtered via |
include_qualifier |
A logical value indicating whether to include
qualifier features. Default is |
include_istd |
A logical value indicating whether to include internal
standard (ISTD) features. Default is |
include_feature_filter |
Feature(s) to include by |
exclude_feature_filter |
Feature(s) to exclude by |
min_median_value |
Minimum median feature value across the selected
QC-type samples required for a feature to be included. |
show_labels |
A logical value indicating whether to show analysis_id
labels for points outside k * MAD of the selected PCA dimensions. Default
is |
labels_column |
A character string indicating the column to be used for the point labels. Typically "analysis_id" or "analysis_order". Default is "analysis_id". |
labels_threshold_mad |
A numeric value determining the threshold
for showing labels based on the median absolute deviation (MAD): samples
whose score on either shown PC lies more than this many MADs from the
median are labelled. Default is 3. Set to |
shared_labeltext_hide |
A character string representing text shared across labels to be hidden (case-sensitive). If this results in non-unique analysis_id's, an error will be raised. |
label_font_size |
Number indicating the font size for labels in 'mm'. Note the unit is different from font_base_size that is in 'pt'. |
point_size |
A numeric value indicating the size of points in millimeters. Default is 2. |
point_alpha |
A numeric value indicating the transparency of points (0-1). Default is 0.5. |
font_base_size |
Numeric. Base font size (in points) for plot text; all
plot text scales proportionally with this value. |
legend_position |
Optional legend placement. One of |
legend_size |
Optional single multiplier of |
show_legend_title |
Logical. |
title |
Optional plot title. |
strip_text_size |
Optional facet strip text size, as a multiplier of
|
strip_bg_color |
Optional facet strip background fill colour. The strip
text colour is set automatically for contrast (white on a dark fill, black
on a light one). |
legend_bg_alpha |
Optional opacity ( |
aspect_ratio |
Panel aspect ratio (height/width). Default |
ellipse_confidence_level |
A numeric value indicating the confidence level for the ellipses. Default is 0.95. |
ellipse_linewidth |
A numeric value indicating the line width of the ellipses. Default is 1. |
ellipse_fill |
A logical value indicating whether to fill the ellipses. |
ellipse_fillcolor |
A vector specifying the fill colors for ellipse corresponding
to different |
ellipse_alpha |
A numeric value indicating the transparency of the ellipse fill (0-1). Default is 0.3. |
A ggplot object with the PCA plot
Other QC plots:
plot_feature_correlations(),
plot_interference_correction(),
plot_matrixeffects(),
plot_normalization_qc(),
plot_pca_loading(),
plot_qc_interference_impact(),
plot_qc_summary_byclass(),
plot_qc_summary_overall(),
plot_qcmetrics_comparison(),
plot_rla_boxplot(),
plot_rt_vs_chain(),
plot_runscatter(),
plot_runsequence()
Generates a plot of PCA loadings, illustrating the contribution of features to each principal component. This function can be used to investigate which feature (groups) are contributing to the variance seen in the plot and which need further investigation.
plot_pca_loading( data = NULL, variable, qc_types = NA, pca_dims = c(1, 2, 3, 4), log_transform = TRUE, top_n = 30, vertical_bars = FALSE, abs_loading = TRUE, filter_data = FALSE, include_qualifier = FALSE, include_istd = FALSE, include_feature_filter = NA, exclude_feature_filter = NA, min_median_value = NA, font_base_size = NULL, legend_position = NULL, legend_size = NULL, show_legend_title = NULL, title = NULL, strip_text_size = NULL, strip_bg_color = NULL, legend_bg_alpha = NULL )plot_pca_loading( data = NULL, variable, qc_types = NA, pca_dims = c(1, 2, 3, 4), log_transform = TRUE, top_n = 30, vertical_bars = FALSE, abs_loading = TRUE, filter_data = FALSE, include_qualifier = FALSE, include_istd = FALSE, include_feature_filter = NA, exclude_feature_filter = NA, min_median_value = NA, font_base_size = NULL, legend_position = NULL, legend_size = NULL, show_legend_title = NULL, title = NULL, strip_text_size = NULL, strip_bg_color = NULL, legend_bg_alpha = NULL )
data |
A |
variable |
A character string indicating the variable to use for PCA analysis. Must be one of: "area", "height", "intensity", "norm_intensity", "response", "conc", "conc_raw", "rt", "fwhm". |
qc_types |
A character vector specifying the QC types to plot. It must
contain at least one element. The default |
pca_dims |
A numeric vector indicating for which PCA dimensions the loadings should be shown. Default is c(1, 2, 3, 4). |
log_transform |
A logical value indicating whether to log-transform
the data before the PCA. Default is |
top_n |
Number of top features with highest absolute loading that will be shown for each PC dimension. Default is 30. |
vertical_bars |
Show vertical bars instead of horizontal bars in the plot. Default is |
abs_loading |
Show absolute loading values instead of signed loadings. Default is |
filter_data |
A logical value indicating whether to use all data
(default) or only QC-filtered data (filtered via |
include_qualifier |
A logical value indicating whether to include
qualifier features. Default is |
include_istd |
A logical value indicating whether to include internal
standard (ISTD) features. Default is |
include_feature_filter |
Feature(s) to include by |
exclude_feature_filter |
Feature(s) to exclude by |
min_median_value |
Minimum median feature value across the selected
QC-type samples required for a feature to be included. |
font_base_size |
Numeric. Base font size (in points) for plot text; all
plot text scales proportionally with this value. |
legend_position |
Optional legend placement. One of |
legend_size |
Optional single multiplier of |
show_legend_title |
Logical. |
title |
Optional plot title. |
strip_text_size |
Optional facet strip text size, as a multiplier of
|
strip_bg_color |
Optional facet strip background fill colour. The strip
text colour is set automatically for contrast (white on a dark fill, black
on a light one). |
legend_bg_alpha |
Optional opacity ( |
A ggplot object with PCA loadings plot
Other QC plots:
plot_feature_correlations(),
plot_interference_correction(),
plot_matrixeffects(),
plot_normalization_qc(),
plot_pca(),
plot_qc_interference_impact(),
plot_qc_summary_byclass(),
plot_qc_summary_overall(),
plot_qcmetrics_comparison(),
plot_rla_boxplot(),
plot_rt_vs_chain(),
plot_runscatter(),
plot_runsequence()
Shows how many features were affected by which magnitude of interference correction, as a histogram of the per-feature correction impact (percent of raw signal removed) within one or more QC types (study samples by default). The data must already be interference-corrected. Features with no impact are excluded and reported.
plot_qc_interference_impact( data, qc_types = "SPL", include_qualifier = FALSE, include_istd = TRUE, include_feature_filter = NA, exclude_feature_filter = NA, min_correction_pct = NA, binwidth = NA, font_base_size = 8 )plot_qc_interference_impact( data, qc_types = "SPL", include_qualifier = FALSE, include_istd = TRUE, include_feature_filter = NA, exclude_feature_filter = NA, min_correction_pct = NA, binwidth = NA, font_base_size = 8 )
data |
A |
qc_types |
QC type(s) to summarize. Default |
include_qualifier |
Include qualifier features. Default |
include_istd |
Include internal standards. Default |
include_feature_filter |
Feature(s) to include by |
exclude_feature_filter |
Feature(s) to exclude by |
min_correction_pct |
Keep only features whose median correction (percent
of raw signal removed) is at least this value. |
binwidth |
Histogram bin width (percent). Default |
font_base_size |
Base font size. Default |
A ggplot object: feature count vs. percent of signal removed.
Other QC plots:
plot_feature_correlations(),
plot_interference_correction(),
plot_matrixeffects(),
plot_normalization_qc(),
plot_pca(),
plot_pca_loading(),
plot_qc_summary_byclass(),
plot_qc_summary_overall(),
plot_qcmetrics_comparison(),
plot_rla_boxplot(),
plot_rt_vs_chain(),
plot_runscatter(),
plot_runsequence()
This function provides a summary of feature QC filtering based on feature class,
showing the number of features that passed or failed various quality control criteria.
It visualizes the filtering in a hierarchical sequence. Features are first evaluated
against lower-level filters such as signal-to-blank (S/B) ratios and minimum intensity,
followed by higher-level filters like the coefficient of variation (CV) or linear regression results.
This means that a feature is classified as failing a given criterion (e.g., CV)
only if it has passed all hierarchically lower filters (e.g., S/B ratio and minimum intensity).
Each feature is counted once; features retained via features.to.keep
despite failing are shown as "QC failed, kept".
plot_qc_summary_byclass( data = NULL, font_base_size = NULL, legend_position = NULL, legend_size = NULL, show_legend_title = NULL, title = NULL )plot_qc_summary_byclass( data = NULL, font_base_size = NULL, legend_position = NULL, legend_size = NULL, show_legend_title = NULL, title = NULL )
data |
A |
font_base_size |
Numeric. Base font size (in points) for plot text; all
plot text scales proportionally with this value. |
legend_position |
Optional legend placement. One of |
legend_size |
Optional single multiplier of |
show_legend_title |
Logical. |
title |
Optional plot title. |
A ggplot object showing the feature QC filtering summary by feature class.
plot_qc_summary_overall() for an overall summary plot
filter_features_qc() for comparing QC metrics
Other QC plots:
plot_feature_correlations(),
plot_interference_correction(),
plot_matrixeffects(),
plot_normalization_qc(),
plot_pca(),
plot_pca_loading(),
plot_qc_interference_impact(),
plot_qc_summary_overall(),
plot_qcmetrics_comparison(),
plot_rla_boxplot(),
plot_rt_vs_chain(),
plot_runscatter(),
plot_runsequence()
This function generates a summary of the feature QC filtering process, visualizing the number of features that passed or failed the various QC criteria.
The bars apply the criteria hierarchically: a feature is counted once, under
the first criterion it fails, and features retained via features.to.keep
despite failing are shown as "QC failed, kept". See plot_qc_summary_byclass()
for more information.
The optional Venn diagram shows, for the features passing the missing-value
and minimum-intensity criteria, the overlap of features failing the
signal-to-blank, CV and linearity criteria; unlike the bars, it is not
hierarchical.
plot_qc_summary_overall(data = NULL, with_venn = TRUE, font_base_size = NULL)plot_qc_summary_overall(data = NULL, with_venn = TRUE, font_base_size = NULL)
data |
A |
with_venn |
Whether to include a Venn diagram summarizing the features excluded due to different QC criteria. Default is |
font_base_size |
Numeric. Base font size (in points) for plot text; all
plot text scales proportionally with this value. |
The QC filtering process follows a hierarchical structure, where features are first evaluated against lower-level filters such as signal-to-blank ratios and minimum intensity.
Only features that pass these basic criteria are then subjected to higher-level filters like the coefficient of variation (CV) or linear regression results.
A feature will only fail a higher-level filter (such as CV or R²) if it has passed all previous lower-level filters.
This ensures that features are evaluated progressively, starting from fundamental quality checks up to more stringent filtering criteria.
Note: The function currently shows a warning Using size aesthetic for lines was deprecated in ggplot2 3.4.0. which can be ignored.
A ggplot object showing the feature QC filtering summary with or without a Venn diagram.
Other QC plots:
plot_feature_correlations(),
plot_interference_correction(),
plot_matrixeffects(),
plot_normalization_qc(),
plot_pca(),
plot_pca_loading(),
plot_qc_interference_impact(),
plot_qc_summary_byclass(),
plot_qcmetrics_comparison(),
plot_rla_boxplot(),
plot_rt_vs_chain(),
plot_runscatter(),
plot_runsequence()
This function generates scatter plots comparing two QC metrics variables
across feature classes. A list of available QC metrics is available from the
calc_qc_metrics() documentation.
plot_qcmetrics_comparison( data = NULL, plot_type, x_variable, y_variable, qc_types = NA, facet_by_class = FALSE, y_shared = FALSE, filter_data = FALSE, include_qualifier = FALSE, include_istd = FALSE, equality_line = FALSE, threshold_values = NA_real_, log_scale = FALSE, x_lim = c(NA_real_, NA_real_), y_lim = c(NA_real_, NA_real_), cols_page = 5, point_size = NULL, point_alpha = 0.5, point_color = "#0460acff", point_fill = "#4da2e7ff", point_shape = 21, point_stroke = 0.5, font_base_size = NULL, autoscale = TRUE, legend_position = NULL, legend_size = NULL, show_legend_title = NULL, title = NULL, strip_text_size = NULL, strip_bg_color = NULL, legend_bg_alpha = NULL )plot_qcmetrics_comparison( data = NULL, plot_type, x_variable, y_variable, qc_types = NA, facet_by_class = FALSE, y_shared = FALSE, filter_data = FALSE, include_qualifier = FALSE, include_istd = FALSE, equality_line = FALSE, threshold_values = NA_real_, log_scale = FALSE, x_lim = c(NA_real_, NA_real_), y_lim = c(NA_real_, NA_real_), cols_page = 5, point_size = NULL, point_alpha = 0.5, point_color = "#0460acff", point_fill = "#4da2e7ff", point_shape = 21, point_stroke = 0.5, font_base_size = NULL, autoscale = TRUE, legend_position = NULL, legend_size = NULL, show_legend_title = NULL, title = NULL, strip_text_size = NULL, strip_bg_color = NULL, legend_bg_alpha = NULL )
data |
A |
plot_type |
A character string specifying the type of plot to generate. Must be one of "scatter", "diff", or "ratio". Selecting "scatter" plots the "y_variable" against the "x_variable" values as a scatter plot, "diff" plots the difference between the two values against the average value, and "ratio" plots the log2 ratio of the two values against the average value. |
x_variable |
The name of the QC metric variable to be plotted on the x-axis. |
y_variable |
The name of the QC metric variable to be plotted on the y-axis. |
qc_types |
A character vector specifying the QC types to plot. |
facet_by_class |
Logical; if |
y_shared |
Logical; if |
filter_data |
Logical; whether to use all data (default) or only
QC-filtered data (filtered via |
include_qualifier |
Logical; whether to include qualifier features
(default is |
include_istd |
Logical; whether to include internal standards (ISTDs)
(default is |
equality_line |
Logical; whether to show a line indicating
identical values in both compared variables (default is |
threshold_values |
Numeric single value or vector with 2 elements; threshold valus to be shown as dashed lines
from both axes on the plot (default is |
log_scale |
Logical, whether to use a log10 scale the axes. |
x_lim |
Numeric vector of length 2 for x-axis limits. Use |
y_lim |
Numeric vector of length 2 for y-axis limits. Use |
cols_page |
Integer; number of facet columns per page (default is |
point_size |
Numeric; size of points in millimeters (default is |
point_alpha |
Numeric; transparency of points (default is |
point_color |
A vector specifying the colors for points corresponding
to different QC types. This can be either an unnamed vector or a named
vector, with names corresponding to QC types. Unused colors will be ignored.
Default is |
point_fill |
A vector specifying the fill colors for points corresponding
to different QC types. This can be either an unnamed vector or a named
vector, with names corresponding to QC types. Unused fill colors will be ignored.
Default is |
point_shape |
A vector specifying the shapes for points corresponding
to different QC types. This can be either an unnamed vector or a named
vector, with names corresponding to QC types. Unused shapes will be ignored.
Default is |
point_stroke |
Numeric; thickness of point borders (default is |
font_base_size |
Numeric. Base font size (in points) for plot text; all
plot text scales proportionally with this value. |
autoscale |
Logical. When |
legend_position |
Optional legend placement. One of |
legend_size |
Optional single multiplier of |
show_legend_title |
Logical. |
title |
Optional plot title. |
strip_text_size |
Optional facet strip text size, as a multiplier of
|
strip_bg_color |
Optional facet strip background fill colour. The strip
text colour is set automatically for contrast (white on a dark fill, black
on a light one). |
legend_bg_alpha |
Optional opacity ( |
The comparison is visualized through one of three plot types:
Scatter plot: Values of y_variable vs x_variable
Difference plot: (y_variable - x_variable) vs mean of both values
Ratio plot: log2(y_variable / x_variable) vs mean of both values
x_variable and y_variable must be available in the QC metrics table.
Please refer to the help page of calc_qc_metrics() for more information on
the available QC metric variables.
When facet_by_class = TRUE, then the feature_class must be defined in the
metadata or retrieved via specific functions, e.g., parse_lipid_feature_names().
A ggplot object representing the scatter plot.
calc_qc_metrics(), filter_features_qc(), plot_normalization_qc(), normalize_by_istd()
Other QC plots:
plot_feature_correlations(),
plot_interference_correction(),
plot_matrixeffects(),
plot_normalization_qc(),
plot_pca(),
plot_pca_loading(),
plot_qc_interference_impact(),
plot_qc_summary_byclass(),
plot_qc_summary_overall(),
plot_rla_boxplot(),
plot_rt_vs_chain(),
plot_runscatter(),
plot_runsequence()
This function plots response curves for each feature. Multiple response curves, each with a linear regression line, can be plotted on the same graph. Each feature is displayed as a separate facet.
plot_responsecurves( data = NULL, variable = "intensity", filter_data = FALSE, include_qualifier = TRUE, include_istd = TRUE, include_feature_filter = NA, exclude_feature_filter = NA, max_regression_value = NA, output_pdf = FALSE, path = NA, create_dir = TRUE, return_plots = FALSE, color_curves = NULL, point_size = NULL, line_width = 0.7, label_wrap = FALSE, label_wrap_width = 25, font_base_size = NULL, autoscale = TRUE, legend_position = NULL, legend_size = NULL, show_legend_title = NULL, title = NULL, strip_text_size = NULL, strip_bg_color = NULL, rows_page = 4, cols_page = 5, curve_layout = "overlay", fixed_scale_curves = FALSE, r2_vstep = 0.06, specific_page = NA, page_orientation = "LANDSCAPE", page_width = NULL, page_height = NULL, page_units = "mm", show_progress = TRUE )plot_responsecurves( data = NULL, variable = "intensity", filter_data = FALSE, include_qualifier = TRUE, include_istd = TRUE, include_feature_filter = NA, exclude_feature_filter = NA, max_regression_value = NA, output_pdf = FALSE, path = NA, create_dir = TRUE, return_plots = FALSE, color_curves = NULL, point_size = NULL, line_width = 0.7, label_wrap = FALSE, label_wrap_width = 25, font_base_size = NULL, autoscale = TRUE, legend_position = NULL, legend_size = NULL, show_legend_title = NULL, title = NULL, strip_text_size = NULL, strip_bg_color = NULL, rows_page = 4, cols_page = 5, curve_layout = "overlay", fixed_scale_curves = FALSE, r2_vstep = 0.06, specific_page = NA, page_orientation = "LANDSCAPE", page_width = NULL, page_height = NULL, page_units = "mm", show_progress = TRUE )
data |
A |
variable |
The variable to plot on the y-axis. |
filter_data |
Whether to use all data (default) or only
QC-filtered data (filtered via |
include_qualifier |
Logical, whether to include qualifier features. Default is |
include_istd |
Logical, whether to include internal standard (ISTD) features. Default is |
include_feature_filter |
Feature(s) to include by |
exclude_feature_filter |
Feature(s) to exclude by |
max_regression_value |
The maximum sample_amount (x) value for fitting
the regression line. If |
output_pdf |
If |
path |
The file path for saving the PDF. Must be defined if
|
create_dir |
A logical value. If |
return_plots |
Logical. If |
color_curves |
A vector of colors for the curves. If |
point_size |
Size of points in millimeters. |
line_width |
Width of regression lines. |
label_wrap |
Logical. If |
label_wrap_width |
Integer. Maximum width in characters for wrapped labels when
|
font_base_size |
Numeric. Base font size (in points) for plot text; all
plot text scales proportionally with this value. |
autoscale |
Logical. When |
legend_position |
Optional legend placement. One of |
legend_size |
Optional single multiplier of |
show_legend_title |
Logical. |
title |
Optional plot title. |
strip_text_size |
Optional facet strip text size, as a multiplier of
|
strip_bg_color |
Optional facet strip background fill colour. The strip
text colour is set automatically for contrast (white on a dark fill, black
on a light one). |
rows_page |
Number of rows of plots per page. Used for pagination in
|
cols_page |
Number of columns of plots per page. Used for pagination in
|
curve_layout |
Controls how multiple curves are displayed. One of:
|
fixed_scale_curves |
Logical. If |
r2_vstep |
Numeric. Vertical step between stacked R² labels when multiple
curves are plotted in the same panel ( |
specific_page |
An integer specifying a specific page to plot. If
|
page_orientation |
Orientation of the PDF paper: |
page_width, page_height
|
Size of a PDF page, in |
page_units |
Unit of |
show_progress |
Logical. If |
Features for plotting can be filtered using QC filters defined via
filter_features_qc() or through include_feature_filter and
exclude_feature_filter arguments. The resulting plots offer extensive
customization options, including point size, line width, point color, point
fill, point shape, line color, ribbon fill, and font base size.
Plots will be divided into multiple pages if the number of features exceeds
the product of rows_page and cols_page settings. The function supports
both direct plotting within R and saving plots as PDF files. Additionally,
plots can be returned as a list of ggplot2 objects for further manipulation
or integration into other analyses.
If return_plots is TRUE, a list of ggplot objects is
returned. Otherwise, the function saves the plot output or does not return
anything.
| Purpose | Format | Device used | Typical dpi |
| Journal figure, vector (default choice) | "pdf" |
grDevices::cairo_pdf, else grDevices::pdf |
n/a |
| Figure for further editing (Illustrator, Inkscape) | "svg" |
svglite::svglite, else grDevices::svg |
n/a |
| Slides, Quarto HTML, GitHub | "png" |
ragg::agg_png, else grDevices::png |
150-300 |
| Journal requiring raster submission | "tiff" |
ragg::agg_tiff, else grDevices::tiff |
300-600 |
Prefer a vector format (pdf, svg) for publication: text stays
selectable and searchable, and lines stay sharp at any magnification.
Prefer a raster format (png, tiff) when a plot draws very many marks
– a plot_runscatter() page covering several thousand analyses, or a dense
plot_pca() score plot. Every point becomes a separate object in a PDF, so
such figures produce very large files that are slow to open and to typeset.
Saving them at 300-600 dpi instead keeps the file small with no visible loss.
The optional packages ragg and svglite are used automatically when
installed, giving better text rendering, system-font support and smaller SVG
files. When they are absent the equivalent grDevices device is used and the
output is still correct. Installing both is recommended:
install.packages(c("ragg", "svglite")).
PDF output uses the cairo device wherever R was built with cairo support
(capabilities("cairo")), because plain grDevices::pdf() writes text in a
single-byte encoding and silently transliterates anything outside it – an en
dash becomes -, >= replaces the proper symbol. Unit labels such as
umol/L and statistical annotations routinely depend on those glyphs.
Multi-page output from the paged plot functions (plot_runscatter(),
plot_calibrationcurves(), plot_responsecurves(),
plot_feature_correlations()) is PDF only, which is the only format that
holds many pages in one file. Use save_plot() for single figures in any of
the other formats.
save_plot() to save a single figure in any format.
Other calibration plots:
plot_calibrationcurves()
The Relative Log Abundance (RLA) plot visualizes standardized feature abundances distributions across samples. RLA standardization involves subtracting either the within-batch or across-batch median from each feature's log-transformed abundance. These plots are effective for identifying systematic technical variations, such as batch effects, instrument drift, or sample handling inconsistencies, by providing a robust representation less susceptible to global intensity shifts.
The function also incorporates optional outlier detection and visualization functionalities to identify anomalous samples based on their median RLA values.
This function returns a list with the ggplot object representing the RLA plot and a table with detected outliers (if outlier_detection = TRUE).
plot_rla_boxplot( data = NULL, variable, rla_type_batch, qc_types = NA, plot_range = NA, rla_limit_to_range = FALSE, collapse_excluded = FALSE, remove_gaps = FALSE, gap_line_color = "#e34a33", gap_line_width = 0.3, gap_label_size = 2.5, gap_scale = 1, filter_data = FALSE, include_qualifier = TRUE, include_istd = TRUE, include_feature_filter = NA, exclude_feature_filter = NA, show_timestamp = FALSE, min_feature_intensity = 0, y_lim = NA, outlier_detection = TRUE, outlier_exclude = FALSE, outlier_method = "mad", outlier_qctypes = c("SPL", "TQC", "BQC", "LTR", "NIST"), outlier_k = NULL, show_batches = TRUE, batch_zebra_stripe = FALSE, batch_line_color = "#b6f0c5", batch_fill_color = "grey93", x_gridlines = FALSE, linewidth = 0.2, font_base_size = NULL, legend_position = NULL, legend_size = NULL, show_legend_title = NULL, title = NULL, strip_text_size = NULL, strip_bg_color = NULL, legend_bg_alpha = NULL, relative_log_abundances = TRUE, show_plot = TRUE )plot_rla_boxplot( data = NULL, variable, rla_type_batch, qc_types = NA, plot_range = NA, rla_limit_to_range = FALSE, collapse_excluded = FALSE, remove_gaps = FALSE, gap_line_color = "#e34a33", gap_line_width = 0.3, gap_label_size = 2.5, gap_scale = 1, filter_data = FALSE, include_qualifier = TRUE, include_istd = TRUE, include_feature_filter = NA, exclude_feature_filter = NA, show_timestamp = FALSE, min_feature_intensity = 0, y_lim = NA, outlier_detection = TRUE, outlier_exclude = FALSE, outlier_method = "mad", outlier_qctypes = c("SPL", "TQC", "BQC", "LTR", "NIST"), outlier_k = NULL, show_batches = TRUE, batch_zebra_stripe = FALSE, batch_line_color = "#b6f0c5", batch_fill_color = "grey93", x_gridlines = FALSE, linewidth = 0.2, font_base_size = NULL, legend_position = NULL, legend_size = NULL, show_legend_title = NULL, title = NULL, strip_text_size = NULL, strip_bg_color = NULL, legend_bg_alpha = NULL, relative_log_abundances = TRUE, show_plot = TRUE )
data |
A |
variable |
Variable to plot, must be one of "intensity", "norm_intensity", "conc", "area", "height", "fwhm", or one of "intensity_raw", "intensity_before", "norm_intensity_raw", "norm_intensity_before", "conc_raw", "conc_before" |
rla_type_batch |
Character, must be either "within" or "across", defining whether to use within-batch or across-batch RLA |
qc_types |
QC types to be plotted. Can be a vector of QC types or a regular expression pattern. |
plot_range |
Numeric vector of length 2, specifying the start and end indices of the analysis order to be plotted. |
rla_limit_to_range |
Logical, whether to limit the RLA values to the specified |
collapse_excluded |
Logical, whether to collapse gaps in the x-axis caused by QC types that were not selected, re-indexing x to a contiguous sequence. Default is |
remove_gaps |
Logical. If |
gap_line_color |
Color of the vertical gap-indicator lines. Default is |
gap_line_width |
Line width of the vertical gap-indicator lines. Default is |
gap_label_size |
Font size of the gap-boundary labels. Default is |
gap_scale |
Numeric multiplication factor for the gap band width.
Default is |
filter_data |
Logical, whether to use QC-filtered data based on criteria set via |
include_qualifier |
Logical, whether to include qualifier features. Default is |
include_istd |
Logical, whether to include internal standard (ISTD) features. Default is |
include_feature_filter |
Feature(s) to include by |
exclude_feature_filter |
Feature(s) to exclude by |
show_timestamp |
Logical, whether to use the acquisition timestamp as the x-axis instead of the run sequence number |
min_feature_intensity |
Numeric, exclude features with overall median intensity below this value |
y_lim |
Numeric vector of length 2, specifying the lower and upper y-axis limits. Default is |
outlier_detection |
Logical, whether to show outlier fences on the plot and return a table with detect outliers based on the method defined by |
outlier_exclude |
Logical, whether to exclude outlier values from the plot. Default is |
outlier_method |
Character, method used for outlier detection. Default is "mad" (median absolute deviation). Other possible values are "iqr", "sd", "z_normal", "z_robust", "quantile", and "fold". See get_outlier_bounds() for details. |
outlier_qctypes |
Character vector, QC types to use for outlier detection. Default is |
outlier_k |
Numeric, multiplier for the outlier detection method. Default is |
show_batches |
Logical, whether to show batch separators in the plot |
batch_zebra_stripe |
Logical, whether to show batches as shaded areas instead of line separators |
batch_line_color |
Character, color of the batch separator lines |
batch_fill_color |
Character, color of the batch shaded areas |
x_gridlines |
Logical, whether to show major x-axis gridlines |
linewidth |
Numeric, line width used for whiskers of the boxplot |
font_base_size |
Numeric. Base font size (in points) for plot text; all
plot text scales proportionally with this value. |
legend_position |
Optional legend placement. One of |
legend_size |
Optional single multiplier of |
show_legend_title |
Logical. |
title |
Optional plot title. |
strip_text_size |
Optional facet strip text size, as a multiplier of
|
strip_bg_color |
Optional facet strip background fill colour. The strip
text colour is set automatically for contrast (white on a dark fill, black
on a light one). |
legend_bg_alpha |
Optional opacity ( |
relative_log_abundances |
Logical, whether to use relative log abundances (RLA) or just log-transformed values |
show_plot |
Logical, whether to display the plot. Default is |
A list with the ggplot object representing the RLA plot and a table with detected outliers if outlier_detection = TRUE.
De Livera et al. (2012) Normalizing and integrating metabolomics data. Analytical Chemistry 10768-10776 DOI: 10.1021/ac302748b De Livera et al. (2015) Statistical Methods for Handling Unwanted Variation in Metabolomics Data. Analytical Chemistry 87(7):3606-3615 DOI: 10.1021/ac502439y
Other QC plots:
plot_feature_correlations(),
plot_interference_correction(),
plot_matrixeffects(),
plot_normalization_qc(),
plot_pca(),
plot_pca_loading(),
plot_qc_interference_impact(),
plot_qc_summary_byclass(),
plot_qc_summary_overall(),
plot_qcmetrics_comparison(),
plot_rt_vs_chain(),
plot_runscatter(),
plot_runsequence()
Generates scatter plots of retention time (RT) versus either chain length, degree of saturation (double bonds), or equivalent carbon number (ECN) of lipid features of different feature classes. This visualization can be useful in identifying annotation (peak picking) errors in reversed-phase (RP)-LC lipidomics dataset arising from isotopic, isobaric, isomeric, or unknown interferences.
plot_rt_vs_chain( data = NULL, x_var = c("total_c", "total_db", "ecn"), qc_types = NA, outliers_highlight = TRUE, outlier_residual_min = 0.15, outlier_print = TRUE, ecn_k = 1.5, include_qualifier = FALSE, robust_regression = TRUE, cols_page = 5, point_size = NULL, point_alpha = 0.9, line_transparency = 0.5, font_base_size = NULL, autoscale = TRUE, legend_position = NULL, legend_size = NULL, show_legend_title = NULL, title = NULL, strip_text_size = NULL, strip_bg_color = NULL )plot_rt_vs_chain( data = NULL, x_var = c("total_c", "total_db", "ecn"), qc_types = NA, outliers_highlight = TRUE, outlier_residual_min = 0.15, outlier_print = TRUE, ecn_k = 1.5, include_qualifier = FALSE, robust_regression = TRUE, cols_page = 5, point_size = NULL, point_alpha = 0.9, line_transparency = 0.5, font_base_size = NULL, autoscale = TRUE, legend_position = NULL, legend_size = NULL, show_legend_title = NULL, title = NULL, strip_text_size = NULL, strip_bg_color = NULL )
data |
A |
x_var |
Variable to use for the x-axis. One of "total_c", "total_db", or "ecn". |
qc_types |
A character vector specifying the QC types to plot. It must
contain at least one element. The default |
outliers_highlight |
Whether to highlight potential outliers in the plot. Default is |
outlier_residual_min |
Minimum value for the residuals to be considered an outlier (default is |
outlier_print |
Whether to print the features that are flagged as potential outliers to the console. Default is |
ecn_k |
Constant for ECN calculation (ECN = C - ecn_k* DB), see Details. Default is |
include_qualifier |
Whether to include qualifier features. |
robust_regression |
Whether to use robust regression, which is less sensitive to outlier (default is |
cols_page |
Number of facet columns, representing different feature classes, shown per page (default is |
point_size |
Size of the data points. Default is 2 |
point_alpha |
Alpha transparency of the data point. Default is 0.9 |
line_transparency |
Alpha transparency of the regression lines. Default is 0.9 |
font_base_size |
Numeric. Base font size (in points) for plot text; all
plot text scales proportionally with this value. |
autoscale |
Logical. When |
legend_position |
Optional legend placement. One of |
legend_size |
Optional single multiplier of |
show_legend_title |
Logical. |
title |
Optional plot title. |
strip_text_size |
Optional facet strip text size, as a multiplier of
|
strip_bg_color |
Optional facet strip background fill colour. The strip
text colour is set automatically for contrast (white on a dark fill, black
on a light one). |
The retention time can be either plotted against the total number of carbon atoms with
the total number of double bonds as curves, or opposite, with the total double bond
number as x axis and the total number of carbon atoms as curves. Alternatively,
the retention time can be plotted against the ECN, which is calculated as
, where is a constant that may need
to be adjusted to the specific chromatographic properties. The default value is
.
A ggplot object representing faceted scatter plots
Other QC plots:
plot_feature_correlations(),
plot_interference_correction(),
plot_matrixeffects(),
plot_normalization_qc(),
plot_pca(),
plot_pca_loading(),
plot_qc_interference_impact(),
plot_qc_summary_byclass(),
plot_qc_summary_overall(),
plot_qcmetrics_comparison(),
plot_rla_boxplot(),
plot_runscatter(),
plot_runsequence()
The runscatter function visualizes raw or processed feature signals across
different sample/QC types along the analysis sequence. It helps identify
trends, detect outliers, and assess analytical performance. Available
feature variables, such as retention time (RT) and full width at
half maximum (FWHM), can be plotted against analysis order or timestamps.
By default, all QC types present in the dataset will be plotted. User-defined
QC types that have no predefined color or shape in mrmhub are assigned black
shapes. To show specific QC types, use the qc_types argument.
To plot the feature values before the last applied drift/batch correction,
add *_before to the variable name, e.g., intensity_before or conc_before.
To plot the uncorrected feature values (before any drift/batch correction),
add *_raw to the variable name, e.g., intensity_raw or conc_raw. To show
corresponding fit curves, set show_trend = TRUE.
The function also supports visualizing analysis batches, reference lines
(mean SD), and trends. It offers customization options to display batch
separators, apply outlier capping, show smoothed trend curves, add reference
lines, and incorporate other features. Outlier capping is particularly useful
to focus on QC or study sample trends that might otherwise be obscured by
extreme values or high variability.
The runscatter function serves as a central QC tool in the workflow,
providing critical insights into data quality.
plot_runscatter( data = NULL, variable, qc_types = NA, filter_data = FALSE, include_qualifier = TRUE, include_istd = TRUE, include_feature_filter = NA, exclude_feature_filter = NA, plot_range = NA, output_pdf = FALSE, path = NA, create_dir = TRUE, multithreading = FALSE, return_plots = FALSE, show_batches = TRUE, batch_zebra_stripe = FALSE, batch_line_color = "#b6f0c5", batch_fill_color = "grey93", cap_outliers = FALSE, cap_sample_k_mad = 4, cap_qc_k_mad = 4, cap_top_n_outliers = NA, show_reference_lines = FALSE, ref_qc_types = NA, reference_k_sd = 2, reference_batchwise = FALSE, reference_line_color = "#04bf9a", reference_sd_shade = FALSE, reference_fill_color = NA, reference_linewidth = 0.75, show_trend = FALSE, trend_color = "#22e06b", y_lim = c(0, NA), log_scale = FALSE, show_gridlines = FALSE, point_size = NULL, point_alpha = 1, point_border_width = NA, font_base_size = NULL, autoscale = TRUE, legend_position = NULL, legend_size = NULL, show_legend_title = NULL, title = NULL, strip_text_size = NULL, strip_bg_color = NULL, legend_bg_alpha = NULL, rows_page = 3, cols_page = 3, specific_page = NA, page_orientation = "LANDSCAPE", page_width = NULL, page_height = NULL, page_units = "mm", y_label_text = NA, pages_per_core = 1, use_dingbats = TRUE, show_progress = TRUE, remove_gaps = FALSE, collapse_excluded = FALSE, gap_line_color = "#e34a33", gap_line_width = 0.3, gap_label_size = 2.5, gap_scale = 1, label_wrap = FALSE, label_wrap_width = 25 )plot_runscatter( data = NULL, variable, qc_types = NA, filter_data = FALSE, include_qualifier = TRUE, include_istd = TRUE, include_feature_filter = NA, exclude_feature_filter = NA, plot_range = NA, output_pdf = FALSE, path = NA, create_dir = TRUE, multithreading = FALSE, return_plots = FALSE, show_batches = TRUE, batch_zebra_stripe = FALSE, batch_line_color = "#b6f0c5", batch_fill_color = "grey93", cap_outliers = FALSE, cap_sample_k_mad = 4, cap_qc_k_mad = 4, cap_top_n_outliers = NA, show_reference_lines = FALSE, ref_qc_types = NA, reference_k_sd = 2, reference_batchwise = FALSE, reference_line_color = "#04bf9a", reference_sd_shade = FALSE, reference_fill_color = NA, reference_linewidth = 0.75, show_trend = FALSE, trend_color = "#22e06b", y_lim = c(0, NA), log_scale = FALSE, show_gridlines = FALSE, point_size = NULL, point_alpha = 1, point_border_width = NA, font_base_size = NULL, autoscale = TRUE, legend_position = NULL, legend_size = NULL, show_legend_title = NULL, title = NULL, strip_text_size = NULL, strip_bg_color = NULL, legend_bg_alpha = NULL, rows_page = 3, cols_page = 3, specific_page = NA, page_orientation = "LANDSCAPE", page_width = NULL, page_height = NULL, page_units = "mm", y_label_text = NA, pages_per_core = 1, use_dingbats = TRUE, show_progress = TRUE, remove_gaps = FALSE, collapse_excluded = FALSE, gap_line_color = "#e34a33", gap_line_width = 0.3, gap_label_size = 2.5, gap_scale = 1, label_wrap = FALSE, label_wrap_width = 25 )
data |
A |
variable |
The variable to plot on the y-axis, one of 'intensity',
'norm_intensity', 'conc', 'rt', 'fwhm', 'area', 'height', 'response'.
Add |
qc_types |
QC types to be plotted. Can be a vector of QC types or a regular expression pattern. |
filter_data |
Logical, whether to use QC-filtered data based on criteria set via |
include_qualifier |
Logical, whether to include qualifier features. Default is |
include_istd |
Logical, whether to include internal standard (ISTD) features. Default is |
include_feature_filter |
Feature(s) to include by |
exclude_feature_filter |
Feature(s) to exclude by |
plot_range |
Numeric vector of length 2, specifying the start and end indices of the analysis order to be plotted. |
output_pdf |
Logical, whether to save the plot as a PDF file. |
path |
File name for the PDF output. |
create_dir |
A logical value. If |
multithreading |
Logical, whether to use parallel processing to speed up plot generation. |
return_plots |
Logical, whether to return the list of ggplot objects. |
show_batches |
Logical, whether to show batch separators in the plot. |
batch_zebra_stripe |
Logical, whether to display batches with alternating shaded and non-shaded areas. |
batch_line_color |
Color of the batch separator lines. |
batch_fill_color |
Color for the shaded areas representing batches. |
cap_outliers |
Logical, whether to cap upper outliers based on MAD fences of SPL and QC samples. |
cap_sample_k_mad |
Numeric, k * MAD (median absolute deviation) for outlier capping of SPL samples. |
cap_qc_k_mad |
Numeric, k * MAD (median absolute deviation) for outlier capping of QC samples. |
cap_top_n_outliers |
Numeric, cap the top n outliers regardless of MAD fences. |
show_reference_lines |
Whether to display reference lines (mean |
ref_qc_types |
QC type for which the reference lines are calculated. |
reference_k_sd |
Multiplier for standard deviations to define SD reference lines. |
reference_batchwise |
Whether to calculate reference lines per batch. |
reference_line_color |
Color of the reference lines. |
reference_sd_shade |
|
reference_fill_color |
Fill color of the batch-wise reference ranges.
If |
reference_linewidth |
Width of the reference lines. |
show_trend |
If |
trend_color |
Color of the trend curve. |
y_lim |
Numeric vector of length 2, specifying the lower and upper y-axis limits. Default is |
log_scale |
Logical, whether to use a log10 scale for the y-axis. |
show_gridlines |
Whether to show major x and y gridlines. |
point_size |
Size of the data points. Default is |
point_alpha |
Alpha transparency of the data points. |
point_border_width |
Width of the data point borders. |
font_base_size |
Numeric. Base font size (in points) for plot text; all
plot text scales proportionally with this value. |
autoscale |
Logical. When |
legend_position |
Optional legend placement. One of |
legend_size |
Optional single multiplier of |
show_legend_title |
Logical. |
title |
Optional plot title. |
strip_text_size |
Optional facet strip text size, as a multiplier of
|
strip_bg_color |
Optional facet strip background fill colour. The strip
text colour is set automatically for contrast (white on a dark fill, black
on a light one). |
legend_bg_alpha |
Optional opacity ( |
rows_page |
Number of rows per page. |
cols_page |
Number of columns per page. |
specific_page |
Show/save a specific page number only. |
page_orientation |
Page orientation, "LANDSCAPE" or "PORTRAIT". Ignored
when |
page_width, page_height
|
Size of a PDF page, in |
page_units |
Unit of |
y_label_text |
Override the default y-axis label text. |
pages_per_core |
Number of pages to be plotted by core when multithreading is enabled. Default is |
use_dingbats |
Logical, whether to use Dingbats font in the PDF output for improved plotting speed. Default is |
show_progress |
Logical, whether to show a progress bar. Default is |
remove_gaps |
Logical. If |
collapse_excluded |
Logical. If |
gap_line_color |
Color of the vertical gap-indicator lines. Default is |
gap_line_width |
Line width of the vertical gap-indicator lines. Default is |
gap_label_size |
Font size of the gap-boundary labels. Default is |
gap_scale |
Numeric multiplication factor for the gap band width.
Default is |
label_wrap |
Logical. If |
label_wrap_width |
Integer. Maximum width in characters for wrapped labels when
|
The outlier capping feature (cap_outliers) allows you to cap upper outliers
based on median absolute deviation (MAD) fences of SPL and QC samples, or to
remove the top n points. This can help to focus on the trends of interest when
there are outlier or a high variability in the data, e.g. in the study samples.
When using log-scale (log_scale = TRUE), zero or negative values will
be replaced with the minimum positive value divided by 5 to avoid log 0 errors
Reference lines/ranges corresponding to mean k x SD can be shown across
or within batches as lines or shaded stripes.
Trend curves can be displayed before or after drift/batch correction. In
either case, a drift and/or batch correction must be applied to the data
to enable plotting of trend curves. To show trend curves used for the last drift or batch correction,
add "_before" to the variable name, e.g. conc_before or intensity_before
and set show_trend = TRUE.
A list of ggplot objects if return_plots = TRUE, otherwise
NULL (the plots are drawn to the active device or written to a PDF).
| Purpose | Format | Device used | Typical dpi |
| Journal figure, vector (default choice) | "pdf" |
grDevices::cairo_pdf, else grDevices::pdf |
n/a |
| Figure for further editing (Illustrator, Inkscape) | "svg" |
svglite::svglite, else grDevices::svg |
n/a |
| Slides, Quarto HTML, GitHub | "png" |
ragg::agg_png, else grDevices::png |
150-300 |
| Journal requiring raster submission | "tiff" |
ragg::agg_tiff, else grDevices::tiff |
300-600 |
Prefer a vector format (pdf, svg) for publication: text stays
selectable and searchable, and lines stay sharp at any magnification.
Prefer a raster format (png, tiff) when a plot draws very many marks
– a plot_runscatter() page covering several thousand analyses, or a dense
plot_pca() score plot. Every point becomes a separate object in a PDF, so
such figures produce very large files that are slow to open and to typeset.
Saving them at 300-600 dpi instead keeps the file small with no visible loss.
The optional packages ragg and svglite are used automatically when
installed, giving better text rendering, system-font support and smaller SVG
files. When they are absent the equivalent grDevices device is used and the
output is still correct. Installing both is recommended:
install.packages(c("ragg", "svglite")).
PDF output uses the cairo device wherever R was built with cairo support
(capabilities("cairo")), because plain grDevices::pdf() writes text in a
single-byte encoding and silently transliterates anything outside it – an en
dash becomes -, >= replaces the proper symbol. Unit labels such as
umol/L and statistical annotations routinely depend on those glyphs.
Multi-page output from the paged plot functions (plot_runscatter(),
plot_calibrationcurves(), plot_responsecurves(),
plot_feature_correlations()) is PDF only, which is the only format that
holds many pages in one file. Use save_plot() for single figures in any of
the other formats.
save_plot() to save a single figure in any format.
Other QC plots:
plot_feature_correlations(),
plot_interference_correction(),
plot_matrixeffects(),
plot_normalization_qc(),
plot_pca(),
plot_pca_loading(),
plot_qc_interference_impact(),
plot_qc_summary_byclass(),
plot_qc_summary_overall(),
plot_qcmetrics_comparison(),
plot_rla_boxplot(),
plot_rt_vs_chain(),
plot_runsequence()
The RunSequence plot provides an overview of the analysis design and timelines, which can be useful for subsequent processing steps. The plot illustrates the batch structure, the quality control (QC) samples included with their respective positions, and additional information regarding the date, duration, and run time of the analysis.
Setting show_timestamp = TRUE allows you to check for any interruptions in
the analysis timeline.
plot_runsequence( data = NULL, qc_types = NA, show_batches = TRUE, show_timestamp = FALSE, add_info_title = TRUE, single_row = FALSE, segment_linewidth = 0.5, batch_zebra_stripe = FALSE, batch_line_color = "#b6f0c5", batch_fill_color = "grey93", font_base_size = NULL, legend_position = NULL, legend_size = NULL, show_legend_title = NULL, title = NULL )plot_runsequence( data = NULL, qc_types = NA, show_batches = TRUE, show_timestamp = FALSE, add_info_title = TRUE, single_row = FALSE, segment_linewidth = 0.5, batch_zebra_stripe = FALSE, batch_line_color = "#b6f0c5", batch_fill_color = "grey93", font_base_size = NULL, legend_position = NULL, legend_size = NULL, show_legend_title = NULL, title = NULL )
data |
A |
qc_types |
QC types to be plotted. Can be a vector of QC types or a
regular expression pattern. |
show_batches |
Logical, whether to show batch separators in the plot. |
show_timestamp |
Logical, whether to use the acquisition timestamp as the x-axis instead of the run sequence number. |
add_info_title |
Logical, whether to add a title with the experiment title, analysis date, and analysis times. |
single_row |
Logical, whether to show all QC types in a single row. |
segment_linewidth |
Width of the segment lines, default is 0.5. |
batch_zebra_stripe |
Logical, whether to show batches as shaded areas instead of line separators. |
batch_line_color |
Color of the batch separator lines. |
batch_fill_color |
Color of the batch shaded areas. |
font_base_size |
Numeric. Base font size (in points) for plot text; all
plot text scales proportionally with this value. |
legend_position |
Optional legend placement. One of |
legend_size |
Optional single multiplier of |
show_legend_title |
Logical. |
title |
Optional plot title. |
A ggplot object representing the run sequence plot.
Other QC plots:
plot_feature_correlations(),
plot_interference_correction(),
plot_matrixeffects(),
plot_normalization_qc(),
plot_pca(),
plot_pca_loading(),
plot_qc_interference_impact(),
plot_qc_summary_byclass(),
plot_qc_summary_overall(),
plot_qcmetrics_comparison(),
plot_rla_boxplot(),
plot_rt_vs_chain(),
plot_runscatter()
pooled_sd() expressed as a percentage of the grand mean of x, i.e. a
batch-pooled %CV. The pooled SD weights each group by its degrees of freedom
and the grand mean weights each value equally, so both are consistently
weighted by group size. See pooled_sd() for how groups are pooled.
pooled_rsd(x, group, na.rm = FALSE, min_n = 2L)pooled_rsd(x, group, na.rm = FALSE, min_n = 2L)
x |
a numeric vector |
group |
a vector the same length as |
na.rm |
logical, if |
min_n |
integer, the minimum number of non-missing values a group must
have to contribute. Groups with fewer than |
a single numeric value. NA_real_ if the grand mean is zero or NA,
x is not numeric, or no group has enough replicates.
pooled_rsd(c(5, 6, 4, 15, 16, 14), group = c(1, 1, 1, 2, 2, 2))pooled_rsd(c(5, 6, 4, 15, 16, 14), group = c(1, 1, 1, 2, 2, 2))
Pools the within-group variances of x across the levels of group,
weighting each group by its degrees of freedom (n_i - 1), and returns the
square root. This is the within-group precision estimate: unlike a plain
sd(x) it is not inflated by systematic shifts between groups (e.g. batch
offsets or drift), so it is the appropriate spread for a batch-pooled %RSD.
pooled_sd(x, group, na.rm = FALSE, min_n = 2L)pooled_sd(x, group, na.rm = FALSE, min_n = 2L)
x |
a numeric vector |
group |
a vector the same length as |
na.rm |
logical, if |
min_n |
integer, the minimum number of non-missing values a group must
have to contribute. Groups with fewer than |
a single numeric value. NA_real_ if x is not numeric or no group
has enough replicates to pool.
pooled_sd(c(5, 6, 4, 15, 16, 14), group = c(1, 1, 1, 2, 2, 2))pooled_sd(c(5, 6, 4, 15, 16, 14), group = c(1, 1, 1, 2, 2, 2))
This demo dataset is included for use in function examples and user testing. It is a subset of an LC-MS analysis of plasma steroids, containing an external calibration curve for each analyte, QC samples with known concentrations, and unknown samples.
quant_lcms_datasetquant_lcms_dataset
A MRMhubExperiment object with the following data and metadata:
Original data (peak data).
Annotated data
Analysis-level metadata
Feature-level annotations
ISTD concentrations
Calibrant (CAL) and QC concentrations
Concentrations of all features in all analyses are determined using ISTD-normalized intensities and corresponding external calibration curves.
Calibration curves are calculated for each feature based on calibration sample concentrations defined in the qc_concentrations metadata.
The regression fit model (linear or quadratic) and the weighting method (either "none", "1/x", "1/x^2", or "1/sqrt(x)") can be defined globally via
the arguments fit_model and fit_weighting for all features, if fit_overwrite is TRUE.
Alternatively, the model and weighting can be defined individually for each feature in the feature metadata (columns curve_fit_model and curve_fit_weighting).
If these details are missing in the metadata, the default values provided via fit_model and fit_weighting will be used.
quantify_by_calibration( data = NULL, include_qualifier = TRUE, fit_overwrite, fit_model = c("linear", "quadratic"), fit_weighting = c("none", "1/x", "1/x^2", "1/sqrt(x)"), ignore_failed_calibration = FALSE, ignore_missing_annotation = FALSE, lod_sigma = c("residual", "intercept") )quantify_by_calibration( data = NULL, include_qualifier = TRUE, fit_overwrite, fit_model = c("linear", "quadratic"), fit_weighting = c("none", "1/x", "1/x^2", "1/sqrt(x)"), ignore_failed_calibration = FALSE, ignore_missing_annotation = FALSE, lod_sigma = c("residual", "intercept") )
data |
A |
include_qualifier |
A logical value. If |
fit_overwrite |
If |
fit_model |
A character string specifying the default regression fit
method to use for the calibration curve. Must be one of |
fit_weighting |
A character string specifying the default weighting
method for the regression points in the calibration curve. Must be one of
|
ignore_failed_calibration |
If |
ignore_missing_annotation |
If |
lod_sigma |
A character string selecting the standard deviation of the
response (sigma) used in the ICH Q2 LoD/LoQ formulas. Must be one of
|
The concentrations are added to the dataset table as feature_conc column. The results of the regression and the calculated LoD and LoQ values are stored in the metrics_calibration table of the returned MRMhubExperiment object.
A modified MRMhubExperiment object with updated concentration values.
calc_calibration_results() for calculating the calibration curve results including LoD and LoQ.
quantify_by_istd() for calculation of concentrations based on spiked-in internal standard concentration.
This function calculates analyte concentrations based on internal standard (ISTD) normalized intensities,
the corresponding spiked-in ISTD amount, and the per-feature response factor
(response_factor, from the feature metadata), normalized by the sample amount.
quantify_by_istd( data = NULL, concentration_unit = "molar", ignore_missing_annotation = FALSE, ignore_istds = FALSE )quantify_by_istd( data = NULL, concentration_unit = "molar", ignore_missing_annotation = FALSE, ignore_istds = FALSE )
data |
A |
concentration_unit |
Character string indicating the type of concentration to calculate and export.
Must be either |
ignore_missing_annotation |
If |
ignore_istds |
If |
The ISTD used for quantitation is taken from the quant_istd_feature_id
column, which is currently always derived from the feature's normalization
ISTD (istd_feature_id).
By default, concentrations are returned in molar units (e.g., µmol/L). To return concentrations in mass units
(e.g., µg/L), set concentration_unit = "mass". This requires either the chemical formula or molecular weight
for each feature to be specified in the feature metadata.
Internal standard concentrations can also be provided in ng/mL. In such cases, the function will convert these
concentrations to molar units for internal calculations. Here too, either the chemical formula or the molecular
weight must be defined for each ISTD in the feature metadata.
The unit of the calculated concentrations is determined by the concentration_unit argument and the sample_amount_unit
field in the analysis metadata of the MRMhubExperiment object. The function will automatically adjust the sample amount
to the appropriate unit based on the provided concentration_unit. For example, if concentration_unit = "molar"
and sample_amount_unit = "uL", the calculated concentrations will be in µmol/L. If concentration_unit = "mass", the
concentrations will be in µg/L.
The calculated concentrations are added to the dataset table as a new column named feature_conc,
along with the intermediate total amount per analysis in feature_pmol_total.
A MRMhubExperiment object with the calculated analyte concentrations added to the
dataset table in the feature_conc column (and the intermediate feature_pmol_total).
quantify_by_calibration() for calculating concentrations based on external calibration curves.
MRMhubExperiment from an RDS fileReads an .rds file written by save_dataset_rds() (or a bare saveRDS()) back
into an MRMhubExperiment, with feedback and a class
check. The .rds is a self-contained snapshot of a complete analysis project, so
the reloaded object can be inspected, re-plotted or re-processed with mrmhub
without the original input files or metadata.
If the file carries an embedded content fingerprint (see save_dataset_rds()),
it is verified against the reloaded object: a match confirms the file holds the
object it was saved from, and the fingerprint is printed so it can be compared
with a recorded value.
This function only adds the class check, fingerprint verification and console
feedback on top of readRDS(); the file itself is a plain R serialization.
It can therefore always be reopened with base R's readRDS() without
mrmhub, and every slot (the dataset, the annot_* metadata tables, the
QC and calibration metrics) is stored as an ordinary tibble that can be
inspected via the @ slots or attributes(). mrmhub is only required to
re-plot or re-process the object — which makes the .rds a convenient
self-contained archive of a complete analysis.
read_dataset_rds(path, verify = TRUE, show_status = FALSE)read_dataset_rds(path, verify = TRUE, show_status = FALSE)
path |
A character string with the path to the |
verify |
A logical value. If |
show_status |
A logical value. If |
The loaded MRMhubExperiment object.
save_dataset_rds(), mrmhub_status()
mexp <- data_load_example() path <- file.path(tempdir(), "example_mexp.rds") save_dataset_rds(mexp, path) mexp2 <- read_dataset_rds(path)mexp <- data_load_example() path <- file.path(tempdir(), "example_mexp.rds") save_dataset_rds(mexp, path) mexp2 <- read_dataset_rds(path)
This function exports specific unprocessed or processed feature variable
(e.g. intensities or concentrations) from a MRMhubExperiment object to a CSV file.
Allows selection of features and optional QC filtering.
save_dataset_csv( data = NULL, path, variable, qc_types = NA, filter_data = FALSE, include_qualifier = NA, include_istd = NA, include_feature_filter = NA, exclude_feature_filter = NA, add_qctype = NA, create_dir = TRUE )save_dataset_csv( data = NULL, path, variable, qc_types = NA, filter_data = FALSE, include_qualifier = NA, include_istd = NA, include_feature_filter = NA, exclude_feature_filter = NA, add_qctype = NA, create_dir = TRUE )
data |
|
path |
File name with path of exported CSV file |
variable |
Variable to be exported, must be present in the data and any of "area", "height", "intensity", "norm_intensity", "response", "conc", "conc_raw", "rt", "fwhm". |
qc_types |
QC types to be exported. Can be a vector of QC types or a regular expression pattern. |
filter_data |
A logical value indicating whether to use all data
(default) or only QC-filtered data (filtered via |
include_qualifier |
A logical value indicating whether to include
qualifier features. Default is |
include_istd |
A logical value indicating whether to include internal
standard (ISTD) features. Default is |
include_feature_filter |
Feature(s) to include by |
exclude_feature_filter |
Feature(s) to exclude by |
add_qctype |
Add the QC type as column |
create_dir |
A logical value. If |
normalize_by_istd(), quantify_by_istd(), quantify_by_calibration(), calibrate_by_reference()
Writes an MRMhubExperiment to an
mzTab-M 2.0.0-M file, the HUPO-PSI
community standard for reporting quantitative metabolomics / lipidomics
results (and the format expected by repositories such as MetaboLights).
save_dataset_mztab( data = NULL, path, variable = "conc", instrument = NULL, contact = NULL, publication = NULL, rt_in_minutes = TRUE, overwrite = TRUE )save_dataset_mztab( data = NULL, path, variable = "conc", instrument = NULL, contact = NULL, publication = NULL, rt_in_minutes = TRUE, overwrite = TRUE )
data |
An |
path |
Output file path. A |
variable |
Feature variable used as abundance. One of |
instrument, contact, publication
|
Optional single strings used to
enrich the |
rt_in_minutes |
Logical; are |
overwrite |
Logical; overwrite an existing file. Default |
The full dataset is exported: every analysis becomes an assay (QC,
blank and calibration samples included), every feature a Small Molecule
Feature (SMF) row, and features are grouped by analyte into Small Molecule
Summary (SML) rows. A minimal Small Molecule Evidence (SME) row is
emitted per feature so all three table types are present.
Abundance. variable selects which feature_* value is written to the
abundance_assay[n] columns. The default "conc" uses final concentrations
and declares the matching concentration unit; if the experiment has not been
quantified, the exporter falls back to raw feature_intensity with an
"Arbitrary quantification unit".
What is not exported. mzTab-M is a quantification report, not a
processing-state container. Internal-standard relationships, QC/calibration
metrics, drift/batch-correction state and the qc_type/batch structure are
not representable and are therefore not written (ISTD features are merely
flagged via an opt_global_is_internal_standard column). See the
mzTab-M export recipe article for the full mapping.
Invisibly returns the (normalised) output path. Called for its
side effect of writing the file.
save_report_xlsx(), save_dataset_csv()
## Not run: save_dataset_mztab(mexp, "experiment.mzTab") save_dataset_mztab(mexp, "raw.mzTab", variable = "area") ## End(Not run)## Not run: save_dataset_mztab(mexp, "experiment.mzTab") save_dataset_mztab(mexp, "raw.mzTab", variable = "area") ## End(Not run)
MRMhubExperiment as an RDS fileWrites the whole MRMhubExperiment to a single .rds
file: raw data, metadata joins, calibration fits, quantification results and
processing history all travel together. This makes the .rds a self-contained,
portable snapshot of a complete analysis project — a collaborator can open it
with readRDS() to inspect, or load mrmhub to re-plot and re-process,
without reconstructing the original file paths, input files or metadata versions.
By default a content fingerprint of the object (rlang::hash()) is embedded in
the saved file and printed. Record it (or compare printed fingerprints) to
confirm that a reloaded file — or a copy shared with a colleague — holds the
identical object. read_dataset_rds() reads the file back and verifies the
fingerprint.
save_dataset_rds( data = NULL, path, hash = TRUE, compress = TRUE, overwrite = TRUE, create_dir = TRUE )save_dataset_rds( data = NULL, path, hash = TRUE, compress = TRUE, overwrite = TRUE, create_dir = TRUE )
data |
A |
path |
A character string with the file path. If it does not end in
|
hash |
A logical value. If |
compress |
A logical value passed to |
overwrite |
A logical value indicating whether to overwrite the file if it
already exists. Default is |
create_dir |
A logical value. If |
The path written to, invisibly.
The file is a plain R serialization, so it can always be reopened with base R's
readRDS() — mrmhub is not required just to read it. Every slot (the
dataset, the annot_* metadata tables, and the QC and calibration metrics)
is stored as an ordinary tibble and can be inspected via the @ slots or
attributes(), which makes the .rds a convenient self-contained archive of a
complete analysis. mrmhub (a compatible version) is only needed to
re-plot or re-process the object through its methods. For long-term, cross-tool
preservation, complement the .rds with an open-standard export
(save_dataset_mztab(), save_dataset_summarizedexperiment() or
save_dataset_csv()).
read_dataset_rds(), save_report_xlsx(),
save_dataset_summarizedexperiment()
mexp <- data_load_example() path <- file.path(tempdir(), "example_mexp.rds") save_dataset_rds(mexp, path)mexp <- data_load_example() path <- file.path(tempdir(), "example_mexp.rds") save_dataset_rds(mexp, path)
Converts an MRMhubExperiment to a
SummarizedExperiment,
the Bioconductor container for feature x sample data, and optionally to a
LipidomicsExperiment for use with
lipidr. This opens the experiment to the
Bioconductor ecosystem - limma for differential abundance, POMA and pmp
for preprocessing.
save_dataset_summarizedexperiment( data = NULL, path = NULL, variable = NULL, as = c("SummarizedExperiment", "LipidomicsExperiment"), filter_data = FALSE, overwrite = TRUE )save_dataset_summarizedexperiment( data = NULL, path = NULL, variable = NULL, as = c("SummarizedExperiment", "LipidomicsExperiment"), filter_data = FALSE, overwrite = TRUE )
data |
An |
path |
Optional file path. When given, the object is written there with
|
variable |
Feature variables to export as assays, e.g. |
as |
Class to produce. |
filter_data |
Use QC-filtered data ( |
overwrite |
Overwrite an existing file at |
Layout. Features are rows and analyses are columns, following the
SummarizedExperiment convention. Each feature variable becomes one assay, so
feature_intensity, feature_norm_intensity and feature_conc sit
side-by-side in the same object and are addressed with
SummarizedExperiment::assay(se, "conc"). Assay names drop the feature_
prefix. annot_features becomes rowData(), annot_analyses becomes
colData(), and the processing state (status, flags, concentration unit)
becomes metadata().
Everything is exported. Internal standards, QC samples, blanks and
calibrants are all included and flagged rather than dropped, because
downstream tools need them: lipidr requires the istd annotation and
pmp's blank filter needs blanks present. Subset when you need to:
se[!rowData(se)$is_istd, se$qc_type == "SPL"]
Most statistical tools will otherwise happily include blanks and calibrants and return nonsense.
QC metrics are not written to rowData(). To filter features by QC
criteria, use filter_features_qc() and export with filter_data = TRUE.
save_feature_qc_metrics() exports the metrics themselves.
A SummarizedExperiment (or LipidomicsExperiment). Returned
invisibly when path is given.
Morgan M, Obenchain V, Hester J, & Pagès H (2026). SummarizedExperiment: A container (S4 class) for matrix-like assays. R package version 1.42.0. doi:10.18129/B9.bioc.SummarizedExperiment https://bioconductor.org/packages/SummarizedExperiment
Mohamed A, Molendijk J, & Hill MM (2020). lipidr: A Software Tool for Data Mining and Analysis of Lipidomics Datasets. Journal of Proteome Research, 19(7), 2890-2897. doi:10.1021/acs.jproteome.0c00082
save_dataset_csv(), save_dataset_mztab(), save_report_xlsx()
mexp <- normalize_by_istd(lipidomics_dataset) mexp <- quantify_by_istd(mexp) se <- save_dataset_summarizedexperiment(mexp) SummarizedExperiment::assayNames(se) # study samples only, internal standards dropped se[!SummarizedExperiment::rowData(se)$is_istd, se$qc_type == "SPL"]mexp <- normalize_by_istd(lipidomics_dataset) mexp <- quantify_by_istd(mexp) se <- save_dataset_summarizedexperiment(mexp) SummarizedExperiment::assayNames(se) # study samples only, internal standards dropped se[!SummarizedExperiment::rowData(se)$is_istd, se$qc_type == "SPL"]
This function exports the feature information and QC (Quality Control) metrics
from a MRMhubExperiment object to a CSV file.
save_feature_qc_metrics(data = NULL, path)save_feature_qc_metrics(data = NULL, path)
data |
A |
path |
A string specifying the file path where the CSV file will be saved. |
A tibble with the QC metrics that have been exported.
This function saves a XLSX file with metadata template to the specified location.
save_metadata_msorganiser_template(path = "metadata_msorganiser_template.xlsx")save_metadata_msorganiser_template(path = "metadata_msorganiser_template.xlsx")
path |
File path where the MRMhub Metadata Organizer file will be saved. If left empty (default), the file will be saved in the current working directory under the file "metadata_msorganiser_template.xlsx" |
This function saves a XLSX file with metadata template to the specified location.
save_metadata_templates(path = "metadata_template.xlsx")save_metadata_templates(path = "metadata_template.xlsx")
path |
File path where the XLSX file with templates will be saved. If left empty (default), the file will be saved in the current working directory under the file "metadata_template.xlsx" |
Writes a plot created by any of the plot_*() functions to a file at a
defined physical size and resolution, so figures do not have to be exported
with hand-written ggplot2::ggsave() calls. Dimensions can be given in
millimetres, centimetres, inches, points or pixels, and the same figure can be
written in several formats in one call.
save_plot( plot, path, width, height, units = NULL, dpi = NULL, format = NULL, scale = 1, bg = NULL, create_dir = TRUE, overwrite = TRUE, show_plot = TRUE, ... )save_plot( plot, path, width, height, units = NULL, dpi = NULL, format = NULL, scale = 1, bg = NULL, create_dir = TRUE, overwrite = TRUE, show_plot = TRUE, ... )
plot |
The plot to save. A |
path |
Output file path. The extension selects the format unless
|
width, height
|
Figure size, in |
units |
Unit of |
dpi |
Resolution in dots per inch for the raster formats ( |
format |
Output format(s): one or more of |
scale |
Multiplicative scaling factor applied to the plot, as in
|
bg |
Background colour. |
create_dir |
A logical value. If |
overwrite |
A logical value indicating whether existing files may be
overwritten. Default is |
show_plot |
A logical value. If |
... |
Further arguments passed to the graphics device. |
If show_plot = TRUE, the plot itself, visibly, with the written
paths in its "paths" attribute. If show_plot = FALSE, invisibly, a
character vector of the paths written. For multi-page output the list of
plots is returned in place of a single plot.
| Purpose | Format | Device used | Typical dpi |
| Journal figure, vector (default choice) | "pdf" |
grDevices::cairo_pdf, else grDevices::pdf |
n/a |
| Figure for further editing (Illustrator, Inkscape) | "svg" |
svglite::svglite, else grDevices::svg |
n/a |
| Slides, Quarto HTML, GitHub | "png" |
ragg::agg_png, else grDevices::png |
150-300 |
| Journal requiring raster submission | "tiff" |
ragg::agg_tiff, else grDevices::tiff |
300-600 |
Prefer a vector format (pdf, svg) for publication: text stays
selectable and searchable, and lines stay sharp at any magnification.
Prefer a raster format (png, tiff) when a plot draws very many marks
– a plot_runscatter() page covering several thousand analyses, or a dense
plot_pca() score plot. Every point becomes a separate object in a PDF, so
such figures produce very large files that are slow to open and to typeset.
Saving them at 300-600 dpi instead keeps the file small with no visible loss.
The optional packages ragg and svglite are used automatically when
installed, giving better text rendering, system-font support and smaller SVG
files. When they are absent the equivalent grDevices device is used and the
output is still correct. Installing both is recommended:
install.packages(c("ragg", "svglite")).
PDF output uses the cairo device wherever R was built with cairo support
(capabilities("cairo")), because plain grDevices::pdf() writes text in a
single-byte encoding and silently transliterates anything outside it – an en
dash becomes -, >= replaces the proper symbol. Unit labels such as
umol/L and statistical annotations routinely depend on those glyphs.
Multi-page output from the paged plot functions (plot_runscatter(),
plot_calibrationcurves(), plot_responsecurves(),
plot_feature_correlations()) is PDF only, which is the only format that
holds many pages in one file. Use save_plot() for single figures in any of
the other formats.
mrmhub_set_plot_defaults() to set units and dpi once for a
whole notebook, plot_runscatter() and the other paged plot functions for
multi-page PDF output, and save_report_xlsx() to export the data.
## Not run: p <- plot_pca(mexp, variable = "norm_intensity", qc_types = c("BQC", "SPL")) # A single figure, sized in mm (the default unit) save_plot(p, "output/pca.pdf", width = 180, height = 120) # In a notebook: save and show the figure in one statement plot_pca(mexp, variable = "norm_intensity") |> save_plot("output/pca.pdf", width = 180, height = 120) # The same figure as vector and raster in one call save_plot(p, "output/pca", format = c("pdf", "png"), width = 180, height = 120) # In a script or loop, skip the re-draw and collect the paths paths <- save_plot(p, "output/pca.pdf", width = 180, height = 120, show_plot = FALSE) # Every runscatter page in one multi-page PDF pages <- plot_runscatter(mexp, variable = "conc", return_plots = TRUE) save_plot(pages, "output/runscatter.pdf", width = 280, height = 200, show_plot = FALSE) ## End(Not run)## Not run: p <- plot_pca(mexp, variable = "norm_intensity", qc_types = c("BQC", "SPL")) # A single figure, sized in mm (the default unit) save_plot(p, "output/pca.pdf", width = 180, height = 120) # In a notebook: save and show the figure in one statement plot_pca(mexp, variable = "norm_intensity") |> save_plot("output/pca.pdf", width = 180, height = 120) # The same figure as vector and raster in one call save_plot(p, "output/pca", format = c("pdf", "png"), width = 180, height = 120) # In a script or loop, skip the re-draw and collect the paths paths <- save_plot(p, "output/pca.pdf", width = 180, height = 120, show_plot = FALSE) # Every runscatter page in one multi-page PDF pages <- plot_runscatter(mexp, variable = "conc", return_plots = TRUE) save_plot(pages, "output/runscatter.pdf", width = 280, height = 200, show_plot = FALSE) ## End(Not run)
Generates a data processing report from a MRMhubExperiment object and writes it to an Excel file.
The report includes information on the data processing steps, quality control metrics, feature concentrations, and metadata.
Following tables will be created as sheets in the EXCEL file, in this order:
save_report_xlsx( data = NULL, path, filtered_variable = "conc", normalized_variable = NA, overwrite = TRUE, create_dir = TRUE )save_report_xlsx( data = NULL, path, filtered_variable = "conc", normalized_variable = NA, overwrite = TRUE, create_dir = TRUE )
data |
A |
path |
A character string specifying the file name and path for the Excel file.
If the path does not include an |
filtered_variable |
A character string specifying the variable name in the filtered data to be exported. It must be one of "conc", "intensity", "norm_intensity", "response", "area", "height", "conc_raw", "rt", or "fwhm". The defined variable name will be included in the sheet name. Default is "conc". |
normalized_variable |
A character string indicating if and which normalized feature values (by reference sample) to include in the report.See also |
overwrite |
A logical value indicating whether to overwrite the file if it already exists. Default is |
create_dir |
A logical value. If |
Info: Report date, author, MRMhub version and the concentration unit.
Feature_QC_metrics: Quality control metrics of all features. An infinite
signal-to-blank ratio (feature not detected in the blank) is written as the
text Inf.
Calibration_metrics: External calibration results per feature.
QCfilt_x_StudySamples: Feature (QC)-filtered data (variable defined via filtered_variable) in study samples ('SPL'). Filter have to be set via filter_features_qc(). The x corresponds to the filtered_variable argument.
QCfilt_x_AllSamples: Feature (QC)-filtered data (variable defined via filtered_variable) in all samples. Filter have to be set via filter_features_qc(). The x corresponds to the filtered_variable argument.
Raw_Intensity_FullDataset: Raw feature intensities from the full, non-filtered dataset.
Norm_Intensity_FullDataset: Normalized feature intensities from the full, non-filtered dataset.
Conc_FullDataset: Final feature concentrations from the full, non-filtered dataset.
x_NormalizedByRef_Full: Study-sample values normalized by a reference
sample (see calibrate_by_reference()), if available.
SampleMetadata: Analysis metadata that was imported and used for processing steps
FeatureMetadata: Feature metadata that was imported and used for processing steps
InternalStandards: Internal standards metadata with concentrations
BatchInfo: Information on batches and positions of first and last analysis/sample in each batch
Interferences: Derived and declared interference relationships (interfering feature, contribution factor, overlap type, source) with the per-feature correction impact when the correction has been applied.
Internal standards are not included in the concentration and QC-filtered
sheets. For reference-normalized variables, sheet names use short labels
to stay within Excel's 31 characters, with "Ref" marking values normalized
by a reference sample (e.g. QCfilt_ConcRef_StudySamples).
If certain data sets are not available, the function includes empty tables for the corresponding dataset.
Concentration corresponds to the final concentration values after applying isotope correction, and drift and batch correction, if applicable. If any corrections, such as drift or batch correction, were applied to raw or normalized intensities, the exported values will reflect these corrections.
The function does not return a value. It writes the report to the specified Excel file.
normalize_by_istd(), quantify_by_istd(), quantify_by_calibration(), calibrate_by_reference()
## Not run: # Assuming `mrmhubexp` is a MRMhubExperiment object and `output_path` is a valid path save_report_xlsx(data = mrmhubexp, path = "output_path/report.xlsx") ## End(Not run)## Not run: # Assuming `mrmhubexp` is a MRMhubExperiment object and `output_path` is a valid path save_report_xlsx(data = mrmhubexp, path = "output_path/report.xlsx") ## End(Not run)
Determines the sequence of analyses using either instrument timestamps, the order in the imported raw data file, or the order defined in the Analysis metadata. Note: After changing the analysis order, all post processing steps must be rerun.
set_analysis_order( data = NULL, order_by = c("timestamp", "resultfile", "metadata") )set_analysis_order( data = NULL, order_by = c("timestamp", "resultfile", "metadata") )
data |
A |
order_by |
Character string specifying the ordering method. Must be one of "timestamp" (requires timestamp data in imported results), "resultfile" (uses order from imported data file), or "metadata" (uses order from analysis metadata) |
An updated MRMhubExperiment object with ordered analyses
file_path <- system.file("extdata", "MRMhub_demo.tsv", package = "mrmhub") mexp <- MRMhubExperiment() mexp <- import_data_mrmhub(mexp, path = file_path, import_metadata = TRUE) # Order by timestamp (if available) mexp <- set_analysis_order(mexp, "timestamp") # Order by metadata definition mexp <- set_analysis_order(mexp, "metadata")file_path <- system.file("extdata", "MRMhub_demo.tsv", package = "mrmhub") mexp <- MRMhubExperiment() mexp <- import_data_mrmhub(mexp, path = file_path, import_metadata = TRUE) # Order by timestamp (if available) mexp <- set_analysis_order(mexp, "timestamp") # Order by metadata definition mexp <- set_analysis_order(mexp, "metadata")
Sets the raw signal variable used for calculations starting from raw signal values (i.e., normalization) Note that this set variable must be part of the orginally imported data. Processed data variables (e.g., normalized intensities and concentrations) can not be set as default feature intensity variable.
set_intensity_var( data = NULL, variable_name, auto_select = FALSE, warnings = TRUE, ... )set_intensity_var( data = NULL, variable_name, auto_select = FALSE, warnings = TRUE, ... )
data |
|
variable_name |
Feature variable to be used as default feature intensity for downstream processing. |
auto_select |
If |
warnings |
Suppress warnings |
... |
Feature variables to search for one-by-one when |
MRMhubExperiment object
Derives lipid classes from the feature_ids with the Goslin lipid name
parser and writes them to feature_class in the feature metadata, the
dataset and the QC metrics. For sphingolipids, the class includes the number
of oxygens on the sphingoid base (e.g. Cer;O2, SM;O2). Requires the
Bioconductor package rgoslin (BiocManager::install("rgoslin")).
set_lipid_class(data = NULL, overwrite = FALSE)set_lipid_class(data = NULL, overwrite = FALSE)
data |
A |
overwrite |
Logical. If |
MRMhubExperiment object with updated
feature_class.
Prints and returns a rollup of the interference relationships
defined for the experiment – automatically derived
(calc_isotopic_interferences()) and declared (custom) – so they can be
reviewed before, and after, applying a correction. Reports the affected
features, a split by source and overlap type, the contribution-factor range
and, once the data are corrected, the per-feature median impact.
summarize_interferences(data = NULL)summarize_interferences(data = NULL)
data |
Invisibly, a tibble of the assembled, de-duplicated interference edges
(with a pct_impact column when the data are already corrected). Called
mainly for the printed summary.
calc_isotopic_interferences(), correct_isotopic_interferences(),
correct_custom_interferences()