| Title: | Antimicrobial Resistance Surveillance Preprocessing and Burden Estimation |
|---|---|
| Description: | anumaan provides a preprocessing pipeline for antimicrobial resistance (AMR) surveillance data, exploratory data analysis (EDA) tools for reviewing cohorts prior to modelling, and burden estimation. Supports polymicrobial weighting, MDR/XDR classification, resistance profile estimation, and burden estimation calculations. |
| Authors: | Nilanjana Dey [aut], Nima Jijo [aut], Namrata Kharat [aut], Saket Choudhary [aut, cre] |
| Maintainer: | Saket Choudhary <[email protected]> |
| License: | MIT + file LICENSE |
| Version: | 0.1.0.9036 |
| Built: | 2026-10-08 09:26:02 UTC |
| Source: | https://github.com/saketlab/anumaan |
Summarises draw-level R_ALL, R_KNOWN_OUTCOME, and R_NF values from
compute_event_profile_probabilities() into posterior mean and
credible interval per hospital x pathogen x profile combination, and
derives explicit eligible_for_YLL/eligible_for_YLD flags
(with reasons) rather than asserting universal usability.
aggregate_profiles_for_daly( profile_output, hospital_col = "hospital", pathogen_col = "pathogen", estimand = "observed_stewardship_event_mix", ci_level = 0.95, min_n_events = 10L, min_n_draws = 100L, sampler_acceptable = TRUE )aggregate_profiles_for_daly( profile_output, hospital_col = "hospital", pathogen_col = "pathogen", estimand = "observed_stewardship_event_mix", ci_level = 0.95, min_n_events = 10L, min_n_draws = 100L, sampler_acceptable = TRUE )
profile_output |
List returned by |
hospital_col |
Character. Hospital column in |
pathogen_col |
Character. Pathogen column. Default |
estimand |
Character. Estimand label to attach to output.
Default |
ci_level |
Numeric. Credible interval coverage. Default |
min_n_events |
Integer. Minimum events in the relevant cohort
(known-outcome for YLL, nonfatal for YLD) for eligibility. Default |
min_n_draws |
Integer. Minimum valid posterior draws in the relevant
summary for eligibility. Default |
sampler_acceptable |
Logical, scalar or one value per row of
|
Cohort definitions: R_ALL is the mean over truly all events
in the hospital-pathogen-panel cohort (no outcome filter). R_KNOWN_OUTCOME
restricts to events with a known patient outcome (this is what earlier
versions of this function called R_ALL – renamed because it is not
actually all events). R_NF restricts to the non-fatal subset of the
known-outcome cohort. All three are computed per posterior draw and then
summarised here; n_draws_all/n_draws_known_outcome/n_draws_nf
count only the non-NA draws feeding each summary (a cohort that is
empty for a given hospital-pathogen pair yields NA draws, which must
not be silently counted as valid support).
Eligibility: eligible_for_profile_inference is a hard
boolean, TRUE only for rows generated by a conditional
(observed-plus-imputed) method – "conditional_analytic_identity"
or "conditional_gibbs_correlated"; see
compute_event_profile_probabilities(). FALSE for any other
profile_generation_method value, including the legacy
"unconditional_simulation_correlated_not_daly_eligible" tag from an
older profile_output – callers must not rely on the descriptive
profile_generation_method string alone.
eligible_for_YLL/eligible_for_YLD additionally require:
sampler_acceptable (passed in by the caller, e.g. from
fitted_model$diagnostics$converged_structural); the relevant event
cohort has at least min_n_events events; and at least
min_n_draws valid posterior draws contributed to the relevant
summary. exclusion_reason_YLL/exclusion_reason_YLD record
why, distinguishing a cohort that is completely empty
("no_known_outcome_events" / "no_nonfatal_events") from one
that is merely small ("too_few_known_outcome_events" /
"too_few_nonfatal_events").
Tibble with one row per hospital x pathogen x profile: R_ALL,
R_KNOWN_OUTCOME, and R_NF posterior mean and credible interval, panel
composition (n_profile_classes, panel_eligibility_method,
classes_excluded, classes_excluded_reason), event and draw
counts, and profile/YLL/YLD eligibility flags with reasons.
Creates a configuration object that controls the behavior of the preprocessing pipeline. Users can override default settings for their specific use case.
amr_config( column_mappings = NULL, fuzzy_match = TRUE, strict_validation = FALSE, date_columns = NULL, hai_cutoff = 2, infer_department = TRUE, event_gap_days = 14, mortality_window = 14, age_bins = "GBD_standard", contaminant_method = "auto", mdr_definition = "CDC", intermediate_as_resistant = TRUE, verbose = TRUE )amr_config( column_mappings = NULL, fuzzy_match = TRUE, strict_validation = FALSE, date_columns = NULL, hai_cutoff = 2, infer_department = TRUE, event_gap_days = 14, mortality_window = 14, age_bins = "GBD_standard", contaminant_method = "auto", mdr_definition = "CDC", intermediate_as_resistant = TRUE, verbose = TRUE )
column_mappings |
Named list of column name mappings. Default uses
|
fuzzy_match |
Logical. Enable fuzzy matching for column names. Default TRUE. |
strict_validation |
Logical. If TRUE, stops execution if required fields are missing. If FALSE, issues warnings. Default FALSE. |
date_columns |
Character vector of date column names to parse. Default NULL auto-detects date-like columns by name pattern. |
hai_cutoff |
Numeric. Number of days after admission to classify as Hospital-Acquired Infection (HAI). Default 2. |
infer_department |
Logical. Attempt to infer hospital department from other variables if missing. Default TRUE. |
event_gap_days |
Numeric. Minimum days between events to create new event_id. Default 14. |
mortality_window |
Numeric. Days after culture to classify death as infection-related. Default 14. |
age_bins |
Character. Age binning strategy: "GBD_standard", "pediatric", or "geriatric". Can also be a custom vector. Default "GBD_standard". |
contaminant_method |
Character. Method for contaminant classification: "auto" (cascade through available methods), "device_based", "heuristic", "provided". Default "auto". |
mdr_definition |
Character or numeric. MDR/XDR definition (used for both): "CDC", "WHO", or numeric threshold for number of resistant classes. Default "CDC". |
intermediate_as_resistant |
Logical. Treat Intermediate (I) as Resistant (R) except for special cases like Colistin. Default TRUE. |
verbose |
Logical. Print progress messages during processing. Default TRUE. |
An amr_config object (list with class)
## Not run: # Use defaults config <- amr_config() # Customize for specific hospital config <- amr_config( hai_cutoff = 3, mdr_definition = 5, strict_validation = FALSE ) ## End(Not run)## Not run: # Use defaults config <- amr_config() # Customize for specific hospital config <- amr_config( hai_cutoff = 3, mdr_definition = 5, strict_validation = FALSE ) ## End(Not run)
Repeats the existing conditional truncated-MVN Gibbs profile completion for fixed posterior draws and a fixed, reproducibly selected subset of incomplete events. It does not refit Stan or alter the fitted model. The comparison therefore isolates finite Gibbs-chain length. The conditional completion algorithm is the correct profile-completion algorithm; this diagnostic checks whether its finite Monte Carlo run length is adequate for a particular fit, especially when posterior residual correlations are high.
assess_gibbs_profile_stability( fitted_model, schedules = list(baseline = list(burnin = 30L, kept = 50L), medium = list(burnin = 60L, kept = 100L), long = list(burnin = 100L, kept = 250L)), n_posterior_draws = 200L, max_events = 250L, seed = 123L, tolerance = 0.01, event_selection = c("stratified", "all") )assess_gibbs_profile_stability( fitted_model, schedules = list(baseline = list(burnin = 30L, kept = 50L), medium = list(burnin = 60L, kept = 100L), long = list(burnin = 100L, kept = 250L)), n_posterior_draws = 200L, max_events = 250L, seed = 123L, tolerance = 0.01, event_selection = c("stratified", "all") )
fitted_model |
Object returned by [fit_bayesian_multivariate_probit()]. |
schedules |
Named list of 'list(burnin=, kept=)' schedules. It must contain 'baseline', 'medium', and 'long'. |
n_posterior_draws |
Number of fixed posterior draws to use. |
max_events |
Maximum number of incomplete events to assess. |
seed |
Seed used once to select draws/events and then reset before each schedule. Thus schedules share posterior draws, events, and RNG streams. |
tolerance |
Maximum aggregate difference for status '"pass"'; twice this value is the '"warning"' upper bound. |
event_selection |
Currently '"stratified"' or '"all"'. |
The default 0.01/0.02 thresholds are numerical-stability conventions for this diagnostic, not universal statistical thresholds.
A structured list with summary, event/aggregate comparisons, selected events, schedules, posterior draw indices, and a separate stability status.
Quantifies uncertainty in resistance-profile probability estimates by
repeatedly resampling isolate counts from a binomial distribution implied
by the observed n_tested and n_resistant values, refitting
the convex optimisation QP for each replicate, and returning percentile
confidence intervals across replicates.
bootstrap_profiles_convex( marginals, coresistance_output = NULL, B = 500L, seed = 123L, alpha = 0.05, n_cores = 1L, exclude_near_zero = TRUE, top_n_classes = NULL, sigma_sq = 1, ridge = 1e-08, pathogen_col = "organism_name", class_col = "antibiotic_class", n_tested_col = "n_tested", n_resistant_col = "n_resistant", org_group_col = "org_group" )bootstrap_profiles_convex( marginals, coresistance_output = NULL, B = 500L, seed = 123L, alpha = 0.05, n_cores = 1L, exclude_near_zero = TRUE, top_n_classes = NULL, sigma_sq = 1, ridge = 1e-08, pathogen_col = "organism_name", class_col = "antibiotic_class", n_tested_col = "n_tested", n_resistant_col = "n_resistant", org_group_col = "org_group" )
marginals |
Data frame. Marginal resistance rates with at minimum
columns |
coresistance_output |
Named list or |
B |
Integer. Number of bootstrap replicates. Default |
seed |
Integer. Random seed for reproducibility. Default |
alpha |
Numeric. Two-sided interval width. Default |
n_cores |
Integer. Parallel cores via |
exclude_near_zero |
Logical. Passed to |
top_n_classes |
Integer or |
sigma_sq |
Numeric. QP constraint variance. Default |
ridge |
Numeric. QP Hessian ridge term. Default |
pathogen_col |
Character. Pathogen column in |
class_col |
Character. Class column in |
n_tested_col |
Character. Tested-count column. Default |
n_resistant_col |
Character. Resistant-count column. Default
|
org_group_col |
Character. Organism-group column (passed through to
QP engine). Default |
Resampling mechanism:
For each bootstrap replicate and each (pathogen, class) cell:
The bootstrap marginal is then
.
Pairwise co-resistance rates (if supplied) are resampled analogously.
The QP is re-solved on each bootstrap marginal using the existing
compute_resistance_profiles() engine.
Performance:
For classes the QP solves in milliseconds; B = 500
replicates will complete in seconds. For classes use
n_cores > 1 or reduce B.
A named list, one entry per pathogen. Each entry is a tibble with columns:
profileProfile label (e.g. "RSS").
probability_meanMean profile probability across B replicates.
probability_medianMedian across replicates.
lowerLower percentile (alpha / 2).
upperUpper percentile (1 - alpha / 2).
n_replicates_convergedNumber of replicates for which the QP converged (non-uniform solution).
convergence_rateProportion of replicates that converged.
The point-estimate profiles tibble (from a single run on the
original marginals) is stored as the attribute "point_estimate".
## Not run: marg <- compute_marginal_resistance(amr_clean) co_res <- compute_pairwise_coresistance(marg) boot <- bootstrap_profiles_convex( marginals = marg$marginal, coresistance_output = co_res, B = 500, seed = 42 ) # 95% intervals for K. pneumoniae boot[["Klebsiella pneumoniae"]] # Point estimate attr(boot[["Klebsiella pneumoniae"]], "point_estimate") ## End(Not run)## Not run: marg <- compute_marginal_resistance(amr_clean) co_res <- compute_pairwise_coresistance(marg) boot <- bootstrap_profiles_convex( marginals = marg$marginal, coresistance_output = co_res, B = 500, seed = 42 ) # 95% intervals for K. pneumoniae boot[["Klebsiella pneumoniae"]] # Point estimate attr(boot[["Klebsiella pneumoniae"]], "point_estimate") ## End(Not run)
Constructs the constraint matrix M and target vector v used in the simplex-constrained weighted least-squares QP:
build_constraint_matrix(profiles_enum, r_marg, co_mat = NULL)build_constraint_matrix(profiles_enum, r_marg, co_mat = NULL)
profiles_enum |
Tibble from |
r_marg |
Named numeric vector. Marginal resistance rates, one per
class. Names must match column names in |
co_mat |
Numeric matrix or |
Marginal rows: iff class is resistant in
profile .
Pairwise rows: iff both classes are resistant.
When a pairwise value is unavailable (too few co-tested isolates), the
product of marginals (independence assumption) is substituted.
Pairwise values that exceed are capped.
Named list:
MNumeric matrix .
vNumeric vector of constraint targets.
constraint_namesCharacter vector labelling each row of M.
fallback_pairsCharacter vector of class pairs that used the independence fallback.
capped_pairsNamed numeric vector of pairs whose pairwise value was capped, showing original and capped values.
Validates that the profile probability distributions returned by
compute_resistance_profiles() satisfy all mathematical requirements:
non-negativity, sum-to-one, and reconstruction of the input marginal and
pairwise resistance rates within a specified tolerance.
check_profile_constraints( profiles_output, marginals = NULL, pairwise = NULL, tolerance = 1e-06, pathogen_col = "pathogen", class_col = "antibiotic_class", rate_col = "marginal_resistance", class1_col = "antibiotic_class_1", class2_col = "antibiotic_class_2", pairwise_rate_col = "pairwise_resistance_prevalence" )check_profile_constraints( profiles_output, marginals = NULL, pairwise = NULL, tolerance = 1e-06, pathogen_col = "pathogen", class_col = "antibiotic_class", rate_col = "marginal_resistance", class1_col = "antibiotic_class_1", class2_col = "antibiotic_class_2", pairwise_rate_col = "pairwise_resistance_prevalence" )
profiles_output |
Named list returned by
|
marginals |
Data frame or |
pairwise |
Data frame or |
tolerance |
Numeric. Maximum absolute residual considered a pass.
Default |
pathogen_col |
Character. Pathogen column in |
class_col |
Character. Class column in |
rate_col |
Character. Marginal rate column in |
class1_col |
Character. First class column in |
class2_col |
Character. Second class column in |
pairwise_rate_col |
Character. Pairwise rate column.
Default |
The function uses two complementary sources of evidence:
Constraint residuals already stored in
profiles_output[[pathogen]]$constraint_residuals – these are
computed at solve time and are available without
re-supplying the original rates.
Direct reconstruction from the binary class-indicator
columns in the profiles data frame when marginals and/or
pairwise are supplied – independently verifies the residuals
and catches any post-solve modifications to the probability vector.
A tibble with one row per constraint per pathogen:
pathogenPathogen name.
constraint_typeOne of "nonneg", "sum_to_one",
"marginal", "pairwise".
constraint_nameSpecific label (e.g. "marg_3GC",
"pair_3GC_Carbapenems").
targetThe constraint target value (NA for
nonneg).
reconstructedThe value implied by .
abs_residualAbsolute difference between target and reconstructed.
passLogical. TRUE if abs_residual < tolerance
or the structural check passed.
sourceEither "stored_residuals" (from solve-time
values) or "recomputed" (from direct reconstruction).
Also prints a per-pathogen summary of passed and failed checks.
## Not run: marg <- compute_marginal_resistance(amr_clean) co_res <- compute_pairwise_coresistance(marg) rp <- compute_resistance_profiles(marg, co_res) # Using stored constraint residuals only checks <- check_profile_constraints(rp) # Full re-verification with original rates checks <- check_profile_constraints( rp, marginals = marg$marginal, pairwise = NULL, tolerance = 1e-5 ) # Inspect failures checks[!checks$pass, ] ## End(Not run)## Not run: marg <- compute_marginal_resistance(amr_clean) co_res <- compute_pairwise_coresistance(marg) rp <- compute_resistance_profiles(marg, co_res) # Using stored constraint residuals only checks <- check_profile_constraints(rp) # Full re-verification with original rates checks <- check_profile_constraints( rp, marginals = marg$marginal, pairwise = NULL, tolerance = 1e-5 ) # Inspect failures checks[!checks$pass, ] ## End(Not run)
Looks up inst/extdata/class_display_labels.csv; falls back to
replacing underscores with spaces for any class not in the table (e.g. a
pathogen-specific class not yet added there), so this never errors on an
unmapped class – it just degrades to a readable-if-generic label.
class_display_label(x)class_display_label(x)
x |
Character vector of raw class names (e.g. |
Character vector of display labels, same length as x.
Human-readable class-pair label
class_pair_label(class_1, class_2, short = TRUE)class_pair_label(class_1, class_2, short = TRUE)
class_1, class_2
|
Character vectors of raw class names. |
short |
Logical; use |
Character vector, e.g. "AMG x CARB".
Same lookup/fallback behaviour as class_display_label(), but
returns the abbreviated form (e.g. "3GC"). Falls back to the first
4 characters of the underscore-cleaned name, upper-cased, for any class
not in the reference table.
class_short_label(x)class_short_label(x)
x |
Character vector of raw class names. |
Character vector of short labels, same length as x.
Fits Weibull, Lognormal, and Gamma distributions to a numeric vector and returns their AIC values for comparison.
compare_distribution_aic(x, fits = NULL)compare_distribution_aic(x, fits = NULL)
x |
Numeric vector of positive values (e.g., LOS in days). |
fits |
Optional. Pre-computed fits from |
Data frame with columns Weibull_AIC, Lognormal_AIC,
Gamma_AIC.
compare_distribution_aic(rlnorm(200, meanlog = 2, sdlog = 0.5))compare_distribution_aic(rlnorm(200, meanlog = 2, sdlog = 0.5))
For each event, retains every observed (tested) AST cell exactly and
computes a probability distribution only over the genuinely untested
(NA) antibiotic-class cells in that event's profile panel. Any
enumerated profile inconsistent with the event's observed cells receives
probability 0 – this function never overwrites an observed R/S result.
compute_event_profile_probabilities( fitted_model, n_posterior_draws_for_profiles = 2000L, outcome_col = NULL, nonfatal_values = c("Discharged", "Survived", "Alive", "discharged", "survived", "alive"), seed = 123L, n_gibbs_burnin = 10L, n_gibbs_kept = 20L, posterior_draw_indices = NULL, event_indices = NULL )compute_event_profile_probabilities( fitted_model, n_posterior_draws_for_profiles = 2000L, outcome_col = NULL, nonfatal_values = c("Discharged", "Survived", "Alive", "discharged", "survived", "alive"), seed = 123L, n_gibbs_burnin = 10L, n_gibbs_kept = 20L, posterior_draw_indices = NULL, event_indices = NULL )
fitted_model |
List returned by |
n_posterior_draws_for_profiles |
Integer. Number of posterior draws
averaged over for both the event-level profile probabilities and the
draw-level aggregates. Subsampled without replacement when total draws
exceed this value. Default |
outcome_col |
Character or |
nonfatal_values |
Character vector. Outcome values for the non-fatal cohort (R_NF). Default covers common discharge/survival labels. |
seed |
Integer. Random seed. Default |
n_gibbs_burnin, n_gibbs_kept
|
Integer. Only used when
|
posterior_draw_indices |
Optional unique indices into the fitted posterior draws. When supplied, these replace random draw subsampling. |
event_indices |
Optional canonical event indices to include. When supplied, only observed events with these indices are processed. |
Identity residual structure (fitted_model$residual_structure
== "identity"): classes are conditionally independent given the linear
predictor, so the missing-cell probabilities are computed analytically as
for each missing class
, and the profile probability over the missing dimensions is the
exact product of per-class Bernoulli probabilities – no latent-variable
simulation is used, so there is no added latent-profile-simulation noise.
Rows carry profile_generation_method = "conditional_analytic_identity".
Correlated residual structure: the missing latent
dimensions are sampled conditional on the observed resistance SIGNS of the
tested classes via a Gibbs sampler on the truncated multivariate normal –
see .gibbs_conditional_profile_probs(). This replaces the earlier
unconditional latent- simulation, which resampled tested cells
along with untested ones and was therefore not observed-plus-imputed.
Rows carry profile_generation_method = "conditional_gibbs_correlated"
and ARE eligible for downstream DALY use (subject to the same panel-support
and sampler-acceptability gates as identity-residual profiles – see
aggregate_profiles_for_daly()). Because Gibbs is only run for
n_gibbs_burnin + n_gibbs_kept iterations per draw rather than to
full convergence, correlated-residual profiles carry additional Monte
Carlo error beyond identity-residual profiles at the same
n_posterior_draws_for_profiles; increase n_gibbs_kept (and/or
n_gibbs_burnin) for lower-noise estimates at higher compute cost.
Both residual structures produce, per event per posterior draw, a profile
probability vector over the panel's enumerated profiles that
(a) sums to exactly 1 and (b) assigns exactly 0 to any profile
inconsistent with that event's observed cells – enforced by construction
in both cases (an exact product for identity; Gibbs never visiting an
inconsistent pattern for correlated), and checked with a hard
stop() for the identity path since it has no other source of
Monte Carlo noise to blur a genuine bug.
Class panels: the antibiotic-class panel enumerated for each
hospital x pathogen pair is drawn from the approved eligibility rules
computed at fit time (fitted_model$eligibility_report: marginal
n_tested/n_resistant/n_susceptible thresholds, plus pairwise co-testing
sufficiency for correlated-residual fits) – not from "tested at least
once". See .resolve_profile_class_panel().
Estimand: The posterior distribution over the observed event
case-mix, conditional on each event's own observed AST results. This is
labelled "observed_stewardship_event_mix".
Named list: event_profiles (event-level posterior mean
observed-plus-imputed profile probabilities, with
n_classes_observed/n_classes_missing per event) and
aggregate_draws (per-draw R_ALL [truly all events in the
hp pair], R_KNOWN_OUTCOME [known-outcome cohort], and R_NF
[nonfatal cohort], used by aggregate_profiles_for_daly() for
credible intervals). Both tibbles contain all profiles per
hospital-pathogen pair and carry profile_generation_method and
panel_reason columns.
Distributes pooled YLL/YLD totals to individual hospitals proportionally by deaths and discharges, and computes per-1 000 rates.
compute_hospital_daly( hospital_counts, total_deaths, total_discharged, yll_base, yll_associated, yll_attributable, yld_base, yld_associated, yld_attributable )compute_hospital_daly( hospital_counts, total_deaths, total_discharged, yll_base, yll_associated, yll_attributable, yld_base, yld_associated, yld_attributable )
hospital_counts |
Data frame with columns: |
total_deaths |
Numeric. Pooled total deaths across all hospitals. |
total_discharged |
Numeric. Pooled total discharges. |
yll_base |
Numeric. Total baseline YLL. |
yll_associated |
Numeric. Total YLL associated with resistance. |
yll_attributable |
Numeric. Total YLL attributable to resistance. |
yld_base |
Numeric. Total baseline YLD. |
yld_associated |
Numeric. Total YLD associated. |
yld_attributable |
Numeric. Total YLD attributable. |
Data frame with hospital-level YLL, YLD, DALY (absolute and per 1 000 cases) columns.
Collapses drug-level susceptibility data to antibiotic-class level per
isolate ( if resistant to any drug in class
), then computes marginal resistance for every pathogen x class
combination found in the data.
compute_marginal_resistance( data, pathogen_col = "organism_name", org_group_col = "org_group", isolate_col = "isolate_id", antibiotic_class_col = "antibiotic_class", antibiotic_value_col = "antibiotic_value", zero_threshold = 0, min_n_tested = 30, facility_col = NULL, facility_name = NULL, outcome_col = NULL, outcome_value = NULL )compute_marginal_resistance( data, pathogen_col = "organism_name", org_group_col = "org_group", isolate_col = "isolate_id", antibiotic_class_col = "antibiotic_class", antibiotic_value_col = "antibiotic_value", zero_threshold = 0, min_n_tested = 30, facility_col = NULL, facility_name = NULL, outcome_col = NULL, outcome_value = NULL )
data |
Data frame. Pre-processed AMR data at isolate x antibiotic
level (one row per isolate-antibiotic combination). Results must already
be binary ( |
pathogen_col |
Character. Column with pathogen names.
Default |
org_group_col |
Character. Column with organism group labels.
Default |
isolate_col |
Character. Column uniquely identifying each isolate.
Default |
antibiotic_class_col |
Character. Column with the antibiotic class
for each drug. Default |
antibiotic_value_col |
Character. Column with susceptibility result
( |
zero_threshold |
Numeric. Classes with
|
min_n_tested |
Integer or |
facility_col |
Character or |
facility_name |
Character or |
outcome_col |
Character or |
outcome_value |
Character or |
Classes whose marginal resistance is at or below zero_threshold are
listed in $near_zero as a flag for downstream use – they are
not removed here.
Named list:
marginalData frame with columns: pathogen_col,
org_group_col, antibiotic_class_col, n_tested,
n_resistant, marginal_resistance. Sorted descending by
marginal_resistance within each pathogen.
near_zeroSubset of marginal where
marginal_resistance <= zero_threshold. These classes are
candidates for exclusion in downstream profiling.
class_longCollapsed isolate x pathogen x class data frame
(columns: isolate_col, pathogen_col, org_group_col,
antibiotic_class_col, class_result). Pass this directly
to compute_pairwise_coresistance().
## Not run: marg <- compute_marginal_resistance( data = amr_clean, pathogen_col = "organism_name", org_group_col = "org_group", isolate_col = "isolate_id", antibiotic_class_col = "antibiotic_class", antibiotic_value_col = "antibiotic_value" ) marg$marginal # full marginal resistance table marg$near_zero # classes flagged as near-zero ## End(Not run)## Not run: marg <- compute_marginal_resistance( data = amr_clean, pathogen_col = "organism_name", org_group_col = "org_group", isolate_col = "isolate_id", antibiotic_class_col = "antibiotic_class", antibiotic_value_col = "antibiotic_value" ) marg$marginal # full marginal resistance table marg$near_zero # classes flagged as near-zero ## End(Not run)
Takes the wide-format tibble produced by preprocess_for_profiles()
and computes marginal resistance rates per pathogen x antibiotic class,
optionally stratified by geography, year, and/or patient outcome. The
counting unit is always isolate_id: a patient with multiple isolates
contributes one count per isolate.
compute_marginals_from_data( data_wide, col_map, panel_map, stratify_by = NULL, outcome_col = NULL, min_n_tested = 30L, external_marginals = NULL, ext_col_map = list(pathogen_col = "pathogen", class_col = "antibiotic_class", geography_col = "geography", year_col = "year", rate_col = "resistance_prevalence") )compute_marginals_from_data( data_wide, col_map, panel_map, stratify_by = NULL, outcome_col = NULL, min_n_tested = 30L, external_marginals = NULL, ext_col_map = list(pathogen_col = "pathogen", class_col = "antibiotic_class", geography_col = "geography", year_col = "year", rate_col = "resistance_prevalence") )
data_wide |
Tibble. Output of |
col_map |
Named list. |
panel_map |
Named list. Same panel used in |
stratify_by |
Character vector or |
outcome_col |
Character or |
min_n_tested |
Integer. Minimum tested-isolate count per
(stratum x pathogen x class) cell. Cells below this threshold are dropped
with a logged reason. Default |
external_marginals |
Data frame or |
ext_col_map |
Named list. Column names in |
Optionally, externally modelled marginals (e.g. from GBD ST-GPR) can be supplied to override the locally computed values while retaining the pairwise correlation structure from the local data.
Tibble with columns: pathogen, antibiotic_class,
[stratum columns], n_tested, n_resistant,
marginal_resistance, marginal_source
("computed" or "external").
For every pathogen and every pair of antibiotic classes
that were both tested:
compute_pairwise_coresistance( marginal_output, pathogen_col = "organism_name", org_group_col = "org_group", isolate_col = "isolate_id", antibiotic_class_col = "antibiotic_class", min_co_tested = 10, facility_col = NULL, facility_name = NULL, outcome_col = NULL, outcome_value = NULL )compute_pairwise_coresistance( marginal_output, pathogen_col = "organism_name", org_group_col = "org_group", isolate_col = "isolate_id", antibiotic_class_col = "antibiotic_class", min_co_tested = 10, facility_col = NULL, facility_name = NULL, outcome_col = NULL, outcome_value = NULL )
marginal_output |
The list returned by
|
pathogen_col |
Character. Must match the column name used in Step 1.
Default |
org_group_col |
Character. Default |
isolate_col |
Character. Default |
antibiotic_class_col |
Character. Default |
min_co_tested |
Integer. Pairwise cells with fewer than
|
facility_col |
Character or |
facility_name |
Character or |
outcome_col |
Character or |
outcome_value |
Character or |
Matrices are computed for all tested classes – no filtering by marginal resistance or GBD core list is applied here.
Named list. One entry per pathogen (keyed by pathogen name), each containing:
prevalenceSquare symmetric matrix of pairwise co-resistance
rates. Diagonal and cells with n < min_co_tested are NA.
T_matrixInteger matrix of co-tested isolate counts.
R_matrixInteger matrix of co-resistant isolate counts.
classesCharacter vector of class names (row/column order).
## Not run: marg <- compute_marginal_resistance(amr_clean, ...) co_res <- compute_pairwise_coresistance(marg) # Prevalence matrix for K. pneumoniae co_res[["Klebsiella pneumoniae"]]$prevalence # Co-tested counts co_res[["Klebsiella pneumoniae"]]$T_matrix ## End(Not run)## Not run: marg <- compute_marginal_resistance(amr_clean, ...) co_res <- compute_pairwise_coresistance(marg) # Prevalence matrix for K. pneumoniae co_res[["Klebsiella pneumoniae"]]$prevalence # Co-tested counts co_res[["Klebsiella pneumoniae"]]$T_matrix ## End(Not run)
For each antibiotic-class pair (A, B) and each pathogen [x stratum], this function:
Computes the Pearson correlation between binary
resistance indicators across co-tested isolates.
Back-calculates pairwise prevalence using the GBD formula:
where and come from marginals
(which may include externally overridden values).
Caps the result to and floors it to 0.
Cells below the floor use the independence product as fallback.
compute_pairwise_from_data( data_wide, marginals, col_map, panel_map, stratify_by = NULL, outcome_col = NULL, min_co_tested = 10L )compute_pairwise_from_data( data_wide, marginals, col_map, panel_map, stratify_by = NULL, outcome_col = NULL, min_co_tested = 10L )
data_wide |
Tibble. Output of |
marginals |
Tibble. Output of |
col_map |
Named list. |
panel_map |
Named list. Same panel as used in preprocessing. |
stratify_by |
Character vector or |
outcome_col |
Character or |
min_co_tested |
Integer. Pairs with fewer co-tested isolates are
reported with |
Tibble with one row per pathogen x class-pair [x stratum]:
pathogen, antibiotic_class_1, antibiotic_class_2
Keys.
n_co_testedIsolates tested for both classes.
rhoPearson correlation between binary resistance indicators.
pairwise_prevalenceBack-calculated P(AnB), capped and floored.
method"pearson_back_calc" or "independence_fallback".
Does NOT classify from a single tail probability. Groups supported
statistics into families (marginal, pairwise, profile
[complete-profile and resistant-count statistics – both address joint
multidrug-resistance burden], hospital_heterogeneity, cluster
[admission and patient clustering]) and flags a family when either (a) any
statistic in it is SEVERE (ppc_tail_probability < tail_severe or
> 1 - tail_severe), or (b) the FRACTION of that family's supported
statistics that are extreme exceeds max_fraction_core_extreme.
Thresholds are configurable, not universal hardcoded truths, and are
applied as discrepancy FLAGS, not frequentist rejection tests.
compute_posterior_predictive_status(ppc_statistics, thresholds = list())compute_posterior_predictive_status(ppc_statistics, thresholds = list())
ppc_statistics |
Tibble returned by
|
thresholds |
Named list overriding any of the defaults:
|
Statistics with essentially ZERO posterior-predictive variance
(replicated_sd at or near 0 – e.g. a discrete statistic that
lands on the same value in every replicated state, such as
max(resistant_count) pinned at its ceiling for a small class
panel) are excluded from extreme/severe classification (though still
returned in ppc_statistics with their true, unmodified
ppc_tail_probability): mean(T_rep >= T_obs) is exactly 1
whenever every replicate exactly EQUALS the observed value, which is a
well-known degeneracy of posterior-predictive tail probabilities for
near-constant discrete statistics, not evidence of misfit – a
discrepancy statistic that cannot vary under the posterior predictive
distribution carries no discriminating information about model fit.
List with status (one of "pass",
"warning_marginal_ppc", "warning_pairwise_ppc",
"warning_profile_ppc", "warning_hospital_heterogeneity_ppc",
"warning_cluster_ppc", "fail_major_ppc_misfit",
"insufficient_ppc_support"), reasons (character vector of
every triggered family-level flag), thresholds_used, and
family_status (per-family n/n_extreme/n_severe/fraction_extreme).
Two experiments that share the same prior-generative structure (same
residual structure, same beta/tau/LKJ priors, same declared random-effect
block structure, same fixed-effect design-column definitions, same
D) can safely REUSE a prior predictive check's results rather than
rerunning simulate_probit_prior_predictive for every
experiment – prior predictive checking depends only on the generative
structure, never on the fitted posterior. If ANY component changes
(a prior, a scaling, the declared block structure), the fingerprint
changes and any cached result must be invalidated.
compute_prior_predictive_fingerprint(fitted_model)compute_prior_predictive_fingerprint(fitted_model)
fitted_model |
A fitted model object as returned by
|
List with fingerprint (a single character hash via
rlang::hash(), already an anumaan dependency – no new
package dependency introduced) and components (the exact named
list that was hashed, for audit/debugging).
Unlike posterior predictive checking, the goal here is NOT to make the
simulated distribution match the observed data closely – it is to flag
obviously implausible/extreme implications of the CHOSEN priors, before
conditioning on any outcomes. Computes, per prior state and averaged
across states: the fraction of event-class probabilities
below 0.001 or above 0.999 (near-deterministic
implied resistance), the fraction of generated events that are
degenerate (all classes resistant or all susceptible), and the spread of
per-"hospital" (the model's primary declared random-effect grouping)
mean implied probability – a very large spread implies an implausibly
extreme facility-to-facility prior.
compute_prior_predictive_status(prior_draws, thresholds = list())compute_prior_predictive_status(prior_draws, thresholds = list())
prior_draws |
An |
thresholds |
Named list overriding any of the defaults:
|
List with status (one of "pass",
"warning_extreme_prior_predictions",
"warning_excessive_hospital_heterogeneity",
"warning_degenerate_profiles",
"fail_implausible_prior_predictive",
"insufficient_prior_check"), reasons, thresholds_used,
and summary (the averaged plausibility fractions).
Drives ppc_draws$generate_state(s) once per posterior state (see
simulate_probit_posterior_predictive), streaming each
state's complete and observation-masked replicate through every requested
discrepancy statistic and accumulating only the compact per-state scalar
contributions – never an S x N_events x D array. Statistic
families (Stan User's Guide-style posterior predictive checks, adapted to
AMR resistance data):
Per-class resistance rate, pooled and per eligible
hospital x pathogen x class cell (reusing
fitted_model$eligibility_report$marginal).
Number of resistant classes per event, among whatever was tested for that event, summarised (mean/variance/median/ p90/max); plus, for fully-observed eligible panels, the full count distribution.
RR/RS/SR/SS co-resistance proportions for every
sufficiently co-tested class pair (reusing
fitted_model$eligibility_report$pairwise).
All-susceptible/all-resistant/most-common-profile
frequency, distinct-profile count, Shannon entropy, Simpson
concentration, and the top-3 most frequent OBSERVED profiles
(profile_top_observed_frequency – a purely data-dominant
descriptive summary, deliberately NOT a claim of clinical importance;
see the file header of probit_posterior_predictive.R for the
distinction and the deferred clinical_priority_profiles
extension point), restricted to adequately-supported fully-observed
hospital x pathogen panels (enumerate_binary_profiles-
style class panel via .resolve_profile_class_panel()).
SD/IQR/MAD/range of per-hospital
resistance proportions among hospitals meeting
min_hospital_support, per class.
Within-/between-group
same-class agreement and Hamming distance, only when the relevant role
is declared eligible (see random_effect_roles and
random_effect_eligibility_audit below); skipped cleanly
(support_status != "supported"), never as a failure, when
unsupported.
compute_probit_ppc_statistics( fitted_model_or_ppc_draws, n_states = 500L, seed = 123L, preserve_observation_mask = TRUE, statistics = c("marginal", "resistant_count", "pairwise", "complete_profile", "hospital_heterogeneity", "admission_clustering", "patient_clustering"), random_effect_roles = NULL, random_effect_eligibility_audit = NULL, min_hospital_support = 30L, min_complete_profile_events = 30L, ci_level = 0.95 )compute_probit_ppc_statistics( fitted_model_or_ppc_draws, n_states = 500L, seed = 123L, preserve_observation_mask = TRUE, statistics = c("marginal", "resistant_count", "pairwise", "complete_profile", "hospital_heterogeneity", "admission_clustering", "patient_clustering"), random_effect_roles = NULL, random_effect_eligibility_audit = NULL, min_hospital_support = 30L, min_complete_profile_events = 30L, ci_level = 0.95 )
fitted_model_or_ppc_draws |
Either a fitted model object (as for
|
n_states, seed, preserve_observation_mask
|
See
|
statistics |
Character vector of statistic families to compute.
Default: all of |
random_effect_roles |
Optional named character vector/list mapping
the name of a GROUPING COLUMN present in
|
random_effect_eligibility_audit |
Optional data frame with columns
|
min_hospital_support |
Integer; minimum tested events for a hospital to enter the hospital-heterogeneity comparison. Default 30. |
min_complete_profile_events |
Integer; minimum fully-observed events for a hospital x pathogen panel to enter complete-profile / full resistant-count-distribution statistics. Default 30. |
ci_level |
Numeric; determines the |
A tibble with columns statistic_name, stratum,
observed_value, replicated_mean, replicated_sd,
replicated_q025, replicated_q50, replicated_q975,
ppc_tail_probability, ppc_two_sided, n_replications,
support_status.
Stan Development Team. "Posterior and Prior Predictive Checks." Stan User's Guide. https://mc-stan.org/docs/stan-users-guide/posterior-predictive-checks.html
Calculates performance and processing statistics.
compute_processing_statistics(raw_data, processed_data, preprocessing_log)compute_processing_statistics(raw_data, processed_data, preprocessing_log)
raw_data |
Original data |
processed_data |
Processed data |
preprocessing_log |
Full log |
List with statistics
Combines the outputs of validate_marginal_calibration(),
validate_pairwise_calibration(),
validate_complete_profile_calibration(), and
mask_and_validate_ast() into a single profile_validation_status
field. This is deliberately separate from diagnostic_status
(see fit_bayesian_multivariate_probit()): diagnostic_status
describes HMC sampler/model-fitting health (R-hat, ESS, divergences,
E-BFMI, tree-depth); profile_validation_status describes predictive
agreement with the observed data and data support for that agreement. A
model can converge cleanly (diagnostic_status = "pass") while its
profile predictions are poorly calibrated, or vice versa, and the two
should never be merged into one flag.
compute_profile_validation_status( marginal_tbl = NULL, pairwise_tbl = NULL, complete_profile_tbl = NULL, masked_summary = NULL, thresholds = list() )compute_profile_validation_status( marginal_tbl = NULL, pairwise_tbl = NULL, complete_profile_tbl = NULL, masked_summary = NULL, thresholds = list() )
marginal_tbl |
Tibble from |
pairwise_tbl |
Tibble from |
complete_profile_tbl |
Tibble from
|
masked_summary |
Tibble ( |
thresholds |
Named list overriding any of: |
All thresholds are explicit parameters with documented defaults – none
are silently hard-coded elsewhere. Pass thresholds to override any
subset; unspecified entries keep their default.
In-sample masked validation can never produce a bare "pass"
on its own. When masked_summary$validation_mode ==
"in_sample_no_refit" (see mask_and_validate_ast()), the masked
cells were already seen during fitting, so predicting them well is not
genuine validation. If every threshold is otherwise cleared, the status
becomes "in_sample_validation_only" rather than "pass" –
a real "pass" requires either validation_mode ==
"refit_masked" (a genuine holdout) or no masked-AST check at all (the
other observed-versus-model checks being used purely descriptively).
Named list: status (one of "pass",
"in_sample_validation_only",
"warning_marginal_miscalibration",
"warning_pairwise_miscalibration",
"warning_sparse_complete_profiles",
"fail_masked_ast_validation", or "not_evaluated" when no
inputs were supplied), reasons (character vector of every
triggered condition – including "masked_validation_in_sample_only"
as an informational reason even when a more severe status wins –
the most severe status is returned but all are listed),
and thresholds_used (the resolved threshold list, for audit trail).
For each pathogen with antibiotic classes, enumerates all
binary resistance profiles and
estimates their probabilities by solving a simplex-constrained weighted
least-squares Quadratic Programme (GBD equation 7.5.1.3):
compute_resistance_profiles( marginal_output, coresistance_output, pathogens = NULL, top_n_pathogens = NULL, exclude_near_zero = TRUE, top_n_classes = NULL, sigma_sq = 1, ridge = 1e-08, pathogen_col = "organism_name", antibiotic_class_col = "antibiotic_class", facility_col = NULL, facility_name = NULL, outcome_col = NULL, outcome_value = NULL, n_cores = 1L )compute_resistance_profiles( marginal_output, coresistance_output, pathogens = NULL, top_n_pathogens = NULL, exclude_near_zero = TRUE, top_n_classes = NULL, sigma_sq = 1, ridge = 1e-08, pathogen_col = "organism_name", antibiotic_class_col = "antibiotic_class", facility_col = NULL, facility_name = NULL, outcome_col = NULL, outcome_value = NULL, n_cores = 1L )
marginal_output |
List returned by |
coresistance_output |
List returned by
|
pathogens |
Character vector. Pathogen(s) to process.
|
top_n_pathogens |
Integer or |
exclude_near_zero |
Logical. If |
top_n_classes |
Integer or |
sigma_sq |
Positive numeric. Assumed variance for each
constraint (uniform). Default |
ridge |
Positive numeric. Ridge term added to the QP
Hessian for numerical stability. Default |
pathogen_col |
Character. Column name for pathogens. Must match
the column used in Steps 1-2. Default |
antibiotic_class_col |
Character. Column name for antibiotic classes.
Default |
facility_col |
Character or |
facility_name |
Character or |
outcome_col |
Character or |
outcome_value |
Character or |
n_cores |
Integer. Number of CPU cores for parallel computation.
Default |
where data-derived linear constraints encode
n marginal resistance rates and n(n-1)/2 pairwise
co-resistance rates, and is the standard probability simplex.
Row : iff
(i.e., class is resistant in profile ).
Constraint: .
Row : iff
.
Constraint: .
When a pairwise estimate is unavailable (too few co-tested isolates),
the product of marginals (independence assumption) is used as fallback.
The QP is solved via quadprog::solve.QP. A small ridge term
(ridge) is added to the Hessian to guarantee strict
positive-definiteness. On solver failure the pathogen gets a uniform
distribution over all profiles.
This function has been optimized for speed with vectorized profile generation and label creation (10-100x faster than previous versions). However, computational complexity is still exponential in the number of classes:
n <= 14: Fast (seconds to minutes)
n = 15: Moderate (minutes)
n >= 16: Slow and memory-intensive (use top_n_classes)
For large datasets with many pathogens, consider using top_n_classes
to limit each pathogen to its most-tested classes (e.g., top_n_classes = 12).
Named list, one entry per pathogen, each a list with:
profilesData frame: profile (character label,
e.g.\ "RSR"), probability (), and
one binary (0/1) integer column per antibiotic class indicating whether
that class is resistant (1) or susceptible (0) in each
profile.
classesCharacter vector of antibiotic class names used (alphabetical; bit 0 = classes[1]).
n_classesInteger. Number of classes used.
constraint_residualsNamed numeric vector of
for each constraint. Small absolute
values indicate good constraint satisfaction.
## Not run: marg <- compute_marginal_resistance(amr_clean) co_res <- compute_pairwise_coresistance(marg) rp <- compute_resistance_profiles(marg, co_res) # All profiles and probabilities for K. pneumoniae rp[["Klebsiella pneumoniae"]]$profiles # Constraint residuals (quality check) rp[["Klebsiella pneumoniae"]]$constraint_residuals # Single pathogen rp_kp <- compute_resistance_profiles( marg, co_res, pathogens = "Klebsiella pneumoniae" ) ## End(Not run)## Not run: marg <- compute_marginal_resistance(amr_clean) co_res <- compute_pairwise_coresistance(marg) rp <- compute_resistance_profiles(marg, co_res) # All profiles and probabilities for K. pneumoniae rp[["Klebsiella pneumoniae"]]$profiles # Constraint residuals (quality check) rp[["Klebsiella pneumoniae"]]$constraint_residuals # Single pathogen rp_kp <- compute_resistance_profiles( marg, co_res, pathogens = "Klebsiella pneumoniae" ) ## End(Not run)
Maps organism names to GBD RR pathogen categories and antibiotic class names
to RR drug categories in a single pass. Either mapping is skipped silently
when the corresponding column is absent from data.
daly_add_rr_mappings( data, organism_col = "organism_normalized", class_col = "antibiotic_class" )daly_add_rr_mappings( data, organism_col = "organism_normalized", class_col = "antibiotic_class" )
data |
Data frame with organism and/or antibiotic class columns. |
organism_col |
Character. Column with organism names to map to
|
class_col |
Character. Column with antibiotic class names to map to
|
Pathogen mapping uses the organism taxonomy (get_organism_taxonomy());
drug class mapping uses inst/extdata/WHO_aware_class.csv.
Data frame with rr_pathogen and/or rr_drug columns
appended.
For each resistance profile delta (from compute_resistance_profiles()), determines the profile-level RR_kd_LOS using the GBD max rule: RR_kd_LOS = max over c in C_R(d) of RR_kc_LOS [if C_R(d) non-empty] = 1 [if d = all-susceptible] where C_R(d) = {c : d_c = 1}. The CI reported for each profile is that of its dominant (max-RR) class.
daly_assign_rr_to_profiles( profiles_output, rr_table, pathogen_col = "pathogen", class_col = "antibiotic_class", rr_col = "RR_LOS", fallback_rr = 1, los_r_col = NULL, los_s_col = NULL, los_unit = c("years", "days") )daly_assign_rr_to_profiles( profiles_output, rr_table, pathogen_col = "pathogen", class_col = "antibiotic_class", rr_col = "RR_LOS", fallback_rr = 1, los_r_col = NULL, los_s_col = NULL, los_unit = c("years", "days") )
profiles_output |
Named list from compute_resistance_profiles(). |
rr_table |
Data frame from daly_fit_los_rr() or daly_fit_los_rr_distribution(). Must have columns pathogen_col, class_col, rr_col, and optionally CI_lower / CI_upper. |
pathogen_col |
Character. Default |
class_col |
Character. Default |
rr_col |
Character. Default |
fallback_rr |
Numeric. RR for resistant classes with no match.
Default |
los_r_col |
Character or |
los_s_col |
Character or |
los_unit |
Character. Unit of |
If rr_table was fit with a syndrome_name filter, its RR
values are syndrome-specific but get applied here to all profiles of a
pathogen – i.e. it assumes syndrome-invariant LOS prolongation. Refit
with syndrome_name = NULL for a RR pooled across syndromes.
Optionally, when los_r_col and los_s_col are supplied, also
propagates the absolute mean LOS for the profile's dominant class
(resistant and susceptible) as LOSR_years / LOSS_years. This
does not change the RR assignment above; it is an additive lookup against
the dominant class already selected by the max rule, using whichever
absolute-LOS columns are present in rr_table (e.g. mean_LOS_R
/ mean_LOS_S from daly_fit_los_rr_distribution(), or
mean_los_resistant / mean_los_susceptible from
daly_fit_los_rr()). LOSR_years/LOSS_years are set to
NA for the all-susceptible profile, which has no dominant class.
Named list (one entry per pathogen): original profiles data frame
augmented with RR_LOS_profile, dominant_class, (if available)
CI_lower_profile / CI_upper_profile, and (when los_r_col /
los_s_col are supplied) LOSR_years / LOSS_years.
Computes the case fatality ratio (CFR) for each pathogen (k) within a specified infectious syndrome (L) using facility-level microbiology data.
daly_calc_case_fatality( data, syndrome_col, syndrome_name, specimen_col, specimen_name, polymicrobial_col, patient_col, pathogen_col, outcome_col, death_value = "Died", glass_ref = NULL, facility_col = NULL, facility_name = NULL, pathogen_name = NULL )daly_calc_case_fatality( data, syndrome_col, syndrome_name, specimen_col, specimen_name, polymicrobial_col, patient_col, pathogen_col, outcome_col, death_value = "Died", glass_ref = NULL, facility_col = NULL, facility_name = NULL, pathogen_name = NULL )
data |
Data frame of facility-level microbiology records. |
syndrome_col |
Character. Column containing infectious syndrome labels (L). |
syndrome_name |
Character. Syndrome to analyse. |
specimen_col |
Character. Column containing specimen type. |
specimen_name |
Character. Specimen to restrict to (e.g., |
polymicrobial_col |
Character. Column flagging polymicrobial patients (1 = polymicrobial, 0 = monomicrobial). |
patient_col |
Character. Unique patient identifier column. |
pathogen_col |
Character. Pathogen (organism) column (k). |
outcome_col |
Character. Final patient outcome column. |
death_value |
Character. Value indicating death. Default |
glass_ref |
Character vector of valid pathogen names, or a data
frame with columns |
facility_col |
Character or NULL. Facility identifier column. |
facility_name |
Character or NULL. Restricts to a single facility. |
pathogen_name |
Character vector or NULL. Filter to specific pathogen(s). |
The unit of analysis is the patient. Each patient contributes
total weight 1, distributed equally across their valid pathogens via a
fractional weight (where is the number of distinct
valid pathogens for patient r). This ensures polymicrobial patients are
not double-counted.
For polymicrobial patients (polymicrobial_col == 1), only
pathogens listed in the GLASS reference (glass_ref) for the given
specimen type are retained before weighting. Monomicrobial patients
(polymicrobial_col == 0) are never filtered.
When facility_col is supplied and facility_name is NULL,
both per-facility and pooled CFR are returned. The pooled CFR sums
weighted deaths and totals across facilities before dividing.
A list:
Pooled CFR: pathogen_col, weighted_deaths,
weighted_total, CFR_LK.
Per-facility CFR (only when facility_col is
supplied and facility_name is NULL).
Computes CR_L, the factor that adjusts a hospital-derived CFR to account for
infection cases managed outside the inpatient setting. The adjustment type
for each syndrome is looked up from the adjustment_ref table
(loaded from ‘inst/extdata/adjustment_for_CFR’).
daly_calc_cr_l( data, syndrome_col, syndrome_name, patient_col, visit_type_col, inpatient_value = "Inpatient", outpatient_value = "Outpatient", adjustment_ref, facility_col = NULL, facility_name = NULL )daly_calc_cr_l( data, syndrome_col, syndrome_name, patient_col, visit_type_col, inpatient_value = "Inpatient", outpatient_value = "Outpatient", adjustment_ref, facility_col = NULL, facility_name = NULL )
data |
Data frame of facility-level records. |
syndrome_col |
Character. Column containing infectious syndrome labels. |
syndrome_name |
Character. Syndrome to compute CR_L for. |
patient_col |
Character. Unique patient identifier column. |
visit_type_col |
Character. Column indicating visit type per record (inpatient / outpatient). |
inpatient_value |
Character. Value in |
outpatient_value |
Character. Value in |
adjustment_ref |
Data frame with columns |
facility_col |
Character or NULL. Facility identifier column. When
provided (and |
facility_name |
Character or NULL. If provided, restricts to that facility only. |
Three adjustment types are supported:
CR_L = 1. The hospital CFR applies directly (e.g., BSI, Meningitis, hospital-acquired infections).
CR_L = (patients with 1 inpatient visit) / (all patients).
Used when community cases are captured partly in outpatient data
(e.g., community-acquired LRI, UTI).
CR_L = (patients with 1 outpatient AND 1 inpatient
visit) / (patients with 1 outpatient visit).
Used for syndromes where OP-to-IP transition captures disease severity
(e.g., STI, Skin, Eye, Oral, Bone/joint infections).
Data frame with columns syndrome (= syndrome_name),
adjustment_type, CR_L, and (when facility_col is
supplied) facility_col. Additional columns
(n_inpatient, n_total, etc.) give the raw counts used.
Computes D_J, the number of deaths for each underlying cause J from population-level vital registration or mortality data. Optionally stratified by grouping variables such as age group, sex, year, or location.
daly_calc_deaths_by_cause( pop_data, cause_col = "cause_of_death", deaths_col = NULL, groupby_cols = NULL )daly_calc_deaths_by_cause( pop_data, cause_col = "cause_of_death", deaths_col = NULL, groupby_cols = NULL )
pop_data |
Data frame. Population-level vital registration or mortality data. Required – this function does not accept facility-level data. |
cause_col |
Character. Column containing the underlying cause of death
(cause J), e.g. an ICD-10 code or cause name. Default |
deaths_col |
Character. Column with pre-aggregated death counts. Set to
|
groupby_cols |
Character vector. Additional stratification columns
(e.g., |
This function requires population-level data. If only facility-level data
are available, use daly_calc_deaths_by_syndrome() with
facility_data instead, which directly counts deaths by syndrome.
Data frame with columns: cause_col, any groupby_cols,
D_J (death count), D_J_method ("population"),
D_J_confidence ("high").
Antimicrobial Resistance Collaborators. Global burden of bacterial antimicrobial resistance in 2019. Lancet. 2022.
## Not run: # One row per death record d_j <- daly_calc_deaths_by_cause( pop_data = vital_reg, cause_col = "icd10_cause" ) # Pre-aggregated counts, stratified by age and sex d_j <- daly_calc_deaths_by_cause( pop_data = vital_reg, cause_col = "icd10_cause", deaths_col = "n_deaths", groupby_cols = c("Age_bin", "gender") ) ## End(Not run)## Not run: # One row per death record d_j <- daly_calc_deaths_by_cause( pop_data = vital_reg, cause_col = "icd10_cause" ) # Pre-aggregated counts, stratified by age and sex d_j <- daly_calc_deaths_by_cause( pop_data = vital_reg, cause_col = "icd10_cause", deaths_col = "n_deaths", groupby_cols = c("Age_bin", "gender") ) ## End(Not run)
Computes D_L, the number of deaths due to each infectious syndrome L.
daly_calc_deaths_by_syndrome( d_j = NULL, s_j = NULL, m_lj = NULL, pop_data = NULL, facility_data = NULL, cause_col = "cause_of_death", syndrome_col = "syndrome", syndrome = NULL, deaths_col = NULL, infection_flag_col = "is_infection_death", outcome_col = "final_outcome", death_value = "Died", patient_col = "patient_id", facility_col = NULL, facility_name = NULL, groupby_cols = NULL )daly_calc_deaths_by_syndrome( d_j = NULL, s_j = NULL, m_lj = NULL, pop_data = NULL, facility_data = NULL, cause_col = "cause_of_death", syndrome_col = "syndrome", syndrome = NULL, deaths_col = NULL, infection_flag_col = "is_infection_death", outcome_col = "final_outcome", death_value = "Died", patient_col = "patient_id", facility_col = NULL, facility_name = NULL, groupby_cols = NULL )
d_j |
Data frame. Output of |
s_j |
Data frame. Output of |
m_lj |
Data frame. Output of |
pop_data |
Data frame. Raw population-level data for Mode 2.
Default |
facility_data |
Data frame. Facility-level data for Mode 3 fallback.
Default |
cause_col |
Character. Underlying cause column used in Modes 1 and 2.
Default |
syndrome_col |
Character. Column containing syndrome labels in both
population and facility data. Default |
syndrome |
Character. Optional. Name of a specific syndrome to filter
results to (e.g., |
deaths_col |
Character. Pre-aggregated deaths column in |
infection_flag_col |
Character. Binary infection flag column in
|
outcome_col |
Character. Outcome column in |
death_value |
Character. Value in |
patient_col |
Character. Unique patient identifier column in
|
facility_col |
Character. Column containing facility names in
|
facility_name |
Character. Name of a specific facility to restrict the
analysis to. |
groupby_cols |
Character vector. Additional stratification columns
(e.g., |
Three operating modes, evaluated in priority order:
Pre-computed components (HIGH confidence): pass the outputs
of daly_calc_deaths_by_cause(), daly_calc_infection_fraction(),
and daly_calc_syndrome_fraction() via d_j, s_j, and
m_lj. Computes: D_L = sum_J(D_J * S_J * M_LJ).
Raw population data (HIGH confidence): pass pop_data
and all three components are computed internally before combining.
Computes: D_L = sum_J(D_J * S_J * M_LJ).
Facility fallback (LOW confidence): when no population
inputs are available, counts the number of unique patients who
died for each syndrome directly from facility_data.
Use syndrome to restrict results to a single syndrome of interest.
Use facility_col and facility_name to restrict the facility
fallback to a specific site.
Data frame with columns: syndrome_col, any groupby_cols,
D_L (deaths by syndrome), D_L_method, D_L_confidence.
Antimicrobial Resistance Collaborators. Global burden of bacterial antimicrobial resistance in 2019. Lancet. 2022.
## Not run: # Mode 1: pass pre-computed components, all syndromes d_j <- daly_calc_deaths_by_cause(pop_data = vr, cause_col = "icd10") s_j <- daly_calc_infection_fraction(pop_data = vr, cause_col = "icd10") m_lj <- daly_calc_syndrome_fraction( pop_data = vr, cause_col = "icd10", syndrome_col = "syndrome" ) d_l <- daly_calc_deaths_by_syndrome( d_j = d_j, s_j = s_j, m_lj = m_lj, cause_col = "icd10", syndrome_col = "syndrome" ) # Mode 2: raw population data, filter to one syndrome d_l <- daly_calc_deaths_by_syndrome( pop_data = vital_reg, cause_col = "icd10_cause", syndrome_col = "infectious_syndrome", syndrome = "Bloodstream infection" ) # Mode 3: facility fallback, one facility, all syndromes d_l <- daly_calc_deaths_by_syndrome( facility_data = amr_data, syndrome_col = "specimen_normalized", outcome_col = "final_outcome", death_value = "Died", patient_col = "patient_id", facility_col = "location", facility_name = "Mumbai" ) # Mode 3: facility fallback, all facilities, one syndrome, stratified by age d_l <- daly_calc_deaths_by_syndrome( facility_data = amr_data, syndrome_col = "specimen_normalized", syndrome = "Blood", death_value = "Died", groupby_cols = c("Age_bin") ) ## End(Not run)## Not run: # Mode 1: pass pre-computed components, all syndromes d_j <- daly_calc_deaths_by_cause(pop_data = vr, cause_col = "icd10") s_j <- daly_calc_infection_fraction(pop_data = vr, cause_col = "icd10") m_lj <- daly_calc_syndrome_fraction( pop_data = vr, cause_col = "icd10", syndrome_col = "syndrome" ) d_l <- daly_calc_deaths_by_syndrome( d_j = d_j, s_j = s_j, m_lj = m_lj, cause_col = "icd10", syndrome_col = "syndrome" ) # Mode 2: raw population data, filter to one syndrome d_l <- daly_calc_deaths_by_syndrome( pop_data = vital_reg, cause_col = "icd10_cause", syndrome_col = "infectious_syndrome", syndrome = "Bloodstream infection" ) # Mode 3: facility fallback, one facility, all syndromes d_l <- daly_calc_deaths_by_syndrome( facility_data = amr_data, syndrome_col = "specimen_normalized", outcome_col = "final_outcome", death_value = "Died", patient_col = "patient_id", facility_col = "location", facility_name = "Mumbai" ) # Mode 3: facility fallback, all facilities, one syndrome, stratified by age d_l <- daly_calc_deaths_by_syndrome( facility_data = amr_data, syndrome_col = "specimen_normalized", syndrome = "Blood", death_value = "Died", groupby_cols = c("Age_bin") ) ## End(Not run)
Estimates the number of incident cases of syndrome L using:
daly_calc_incidence_from_cfr( deaths_L, cfr_lk_tbl, P_Lk_prime_tbl, CR_L = 1, pathogen_col = "pathogen", cfr_col = "CFR_LK", plk_col = "P_Lk_prime", facility_col = NULL, deaths_col = "deaths" )daly_calc_incidence_from_cfr( deaths_L, cfr_lk_tbl, P_Lk_prime_tbl, CR_L = 1, pathogen_col = "pathogen", cfr_col = "CFR_LK", plk_col = "P_Lk_prime", facility_col = NULL, deaths_col = "deaths" )
deaths_L |
Numeric scalar (pooled mode) or data frame with a
|
cfr_lk_tbl |
Data frame with at minimum columns |
P_Lk_prime_tbl |
Data frame with |
CR_L |
Numeric scalar. CFR adjustment factor from
|
pathogen_col |
Character. Pathogen column in both tables.
Default |
cfr_col |
Character. CFR column in |
plk_col |
Character. P'LK column in |
facility_col |
Character or NULL. Facility identifier. When provided,
|
deaths_col |
Character. Column in |
where the syndrome-level CFR is the pathogen-weighted average:
Use this when you have population- or facility-level death counts and want
to back-calculate incidence. For a direct patient count from facility data,
use count_incident_cases() instead.
Data frame with columns deaths, CFR_L, CR_L,
I_L (incident cases), and facility_col when applicable.
Computes S_J, the fraction of deaths for underlying cause J that were related to infection. Values range from 0 (no infection involvement) to 1 (all deaths for cause J involved infection).
daly_calc_infection_fraction( pop_data, cause_col = "cause_of_death", infection_flag_col = "is_infection_death", groupby_cols = NULL )daly_calc_infection_fraction( pop_data, cause_col = "cause_of_death", infection_flag_col = "is_infection_death", groupby_cols = NULL )
pop_data |
Data frame. Population-level mortality data. Required. |
cause_col |
Character. Underlying cause of death column (cause J).
Default |
infection_flag_col |
Character. Binary column (TRUE/FALSE or 1/0) in
|
groupby_cols |
Character vector. Stratification columns present in
|
This function requires population-level data where each death record carries
a binary flag indicating whether infection was involved. If only facility
data are available, use daly_calc_deaths_by_syndrome() with
facility_data instead.
Data frame with columns: cause_col, any groupby_cols,
D_J (total deaths), infection_deaths (infection-related
death count), S_J (infection fraction 0-1), S_J_method,
S_J_confidence.
Antimicrobial Resistance Collaborators. Global burden of bacterial antimicrobial resistance in 2019. Lancet. 2022.
## Not run: s_j <- daly_calc_infection_fraction( pop_data = vital_reg, cause_col = "icd10_cause", infection_flag_col = "is_infectious", groupby_cols = c("Age_bin", "gender") ) ## End(Not run)## Not run: s_j <- daly_calc_infection_fraction( pop_data = vital_reg, cause_col = "icd10_cause", infection_flag_col = "is_infectious", groupby_cols = c("Age_bin", "gender") ) ## End(Not run)
Computes the population attributable fraction (PAF) for length of stay from a named list of profile data frames, each containing resistance-profile probabilities and profile-level relative risk of LOS.
daly_calc_paf_los( profiles_with_rr, probability_col = "probability", rr_profile_col = "RR_LOS_profile", profile_col = "profile" )daly_calc_paf_los( profiles_with_rr, probability_col = "probability", rr_profile_col = "RR_LOS_profile", profile_col = "profile" )
profiles_with_rr |
Named list returned by |
probability_col |
Character. Column name for profile probability
(must sum to 1 within each pathogen). Default |
rr_profile_col |
Character. Column name for profile-level LOS relative
risk. Default |
profile_col |
Character. Column name for the profile identifier.
Default |
For each pathogen the formula is: PAF = sum_d R'_kd * (RR_kd - 1) / (1 + sum_d R'_kd * (RR_kd - 1))
where R'_kd is the probability of resistance profile d and RR_kd is the corresponding relative LOS multiplier.
Named list (one entry per pathogen) with columns profile,
probability, rr_profile_col, numerator, PAF_LOS,
and denominator added to the input profile data frame.
Computes PAF_kd_mortality for each pathogen k and resistance profile delta
using the GBD multi-exposure Levin formula, substituting the mortality
odds ratio (OR_death) from fit_mortality_rr_logistic() in place of
the LOS relative risk used by compute_paf_los():
daly_calc_paf_mortality( profiles_with_rr, probability_col = "probability", rr_profile_col = "RR_LOS_profile", profile_col = "profile" )daly_calc_paf_mortality( profiles_with_rr, probability_col = "probability", rr_profile_col = "RR_LOS_profile", profile_col = "profile" )
profiles_with_rr |
Named list from |
probability_col |
Character. Profile probability column name.
Default |
rr_profile_col |
Character. Profile-level OR column as produced by
|
profile_col |
Character. Profile label column.
Default |
The all-susceptible profile carries OR = 1 and contributes 0.
The denominator equals
,
numerically identical to the denominator produced by compute_paf_los().
Overall mortality PAF for pathogen k:
Usage pipeline:
# 1. Fit mortality OR per class
mort_or <- fit_mortality_rr_logistic(data, ...)
# 2. Assign OR to profiles via max rule (rr_col = "OR_death")
profiles_with_or <- assign_rr_to_profiles(
profiles_output,
rr_table = mort_or,
rr_col = "OR_death"
)
# 3. Compute per-profile and overall mortality PAF
paf_mort <- daly_calc_paf_mortality(profiles_with_or)
Named list (one entry per pathogen) containing:
per_profile: profile data frame augmented with
numerator_mort (= ),
PAF_mortality (= numerator / denominator), and
denominator_mort (= numerator).
PAF_k_mort: overall mortality PAF for pathogen k.
denominator_mort: shared denominator .
Computes the fatal pathogen distribution for a given infectious syndrome (L) using facility-level microbiology data. This quantity represents the fractional contribution of each pathogen (k) to fatal infection cases, and is used in YLL / mortality burden estimation.
daly_calc_pathogen_fraction_fatal( data, syndrome_col, syndrome_name, specimen_col = NULL, specimen_name = NULL, polymicrobial_col, patient_col, pathogen_col, outcome_col, death_value = "Death", glass_ref = NULL, facility_col = NULL, facility_name = NULL, pathogen_name = NULL )daly_calc_pathogen_fraction_fatal( data, syndrome_col, syndrome_name, specimen_col = NULL, specimen_name = NULL, polymicrobial_col, patient_col, pathogen_col, outcome_col, death_value = "Death", glass_ref = NULL, facility_col = NULL, facility_name = NULL, pathogen_name = NULL )
data |
Data frame of facility-level microbiology records. |
syndrome_col |
Character. Column containing infectious syndrome labels (L). |
syndrome_name |
Character. Syndrome to analyse. |
specimen_col |
Character or NULL. Column containing specimen type.
If |
specimen_name |
Character or NULL. Specimen to restrict to (e.g.,
|
polymicrobial_col |
Character. Column flagging polymicrobial patients (1 = polymicrobial, 0 = monomicrobial). |
patient_col |
Character. Unique patient identifier column. |
pathogen_col |
Character. Pathogen (organism) column (k). |
outcome_col |
Character. Final patient outcome column. |
death_value |
Character. Value indicating a fatal outcome.
Default |
glass_ref |
Character vector of valid pathogen names, or a data
frame with columns |
facility_col |
Character or NULL. Facility identifier column. When
provided without |
facility_name |
Character or NULL. Restricts to a single facility. |
pathogen_name |
Character vector or NULL. Filter to specific pathogen(s). |
The unit of analysis is the patient. Each patient contributes
total weight 1, distributed equally across their valid pathogens.
For a patient with valid pathogens, each pathogen receives
weight .
For polymicrobial patients (polymicrobial_col == 1),
only pathogens listed in the GLASS reference (glass_ref) for the
given specimen type are retained before weighting. Monomicrobial patients
(polymicrobial_col == 0) are never filtered.
The pooled formula across facilities is:
A list:
Pooled P_LK data frame: pathogen_col,
N_F_LK, N_F_L, P_Lk_fatal.
Per-facility P_LK (only when facility_col
is supplied and facility_name is NULL).
Computes the profile-weighted expected proportion of deaths attributable to resistance (R_k) and the expected odds ratio of death (E[OR_death]) for each pathogen.
daly_calc_resistance_prevalence_fatal( profiles_with_rr, probability_col = "probability", rr_profile_col = "RR_LOS_profile" )daly_calc_resistance_prevalence_fatal( profiles_with_rr, probability_col = "probability", rr_profile_col = "RR_LOS_profile" )
profiles_with_rr |
Named list returned by
|
probability_col |
Character. Profile probability column.
Default |
rr_profile_col |
Character. Profile-level OR column.
Default |
Named list (one entry per pathogen) each containing
per_profile data frame, R_k, and E_OR_k.
Computes M_LJ, the fraction of infection-related deaths for underlying cause J that are attributed to infectious syndrome L. This distributes infection deaths across clinical syndrome categories (e.g., bloodstream infection, pneumonia, urinary tract infection).
daly_calc_syndrome_fraction( pop_data, cause_col = "cause_of_death", syndrome_col = "syndrome", infection_flag_col = "is_infection_death", groupby_cols = NULL )daly_calc_syndrome_fraction( pop_data, cause_col = "cause_of_death", syndrome_col = "syndrome", infection_flag_col = "is_infection_death", groupby_cols = NULL )
pop_data |
Data frame. Population-level mortality data with cause and syndrome columns. Required. |
cause_col |
Character. Underlying cause of death column (cause J).
Default |
syndrome_col |
Character. Infectious syndrome column (syndrome L),
e.g., |
infection_flag_col |
Character. Binary column (TRUE/FALSE or 1/0)
indicating infection involvement in |
groupby_cols |
Character vector. Additional stratification columns.
Default |
This function requires population-level data. If only facility data are
available, use daly_calc_deaths_by_syndrome() with facility_data
instead.
Data frame with columns: cause_col, syndrome_col,
any groupby_cols, infection_deaths_LJ (deaths for syndrome L
given cause J), infection_deaths_J (total infection deaths for
cause J), M_LJ (syndrome fraction 0-1), M_LJ_method,
M_LJ_confidence.
Antimicrobial Resistance Collaborators. Global burden of bacterial antimicrobial resistance in 2019. Lancet. 2022.
## Not run: m_lj <- daly_calc_syndrome_fraction( pop_data = vital_reg, cause_col = "icd10_cause", syndrome_col = "infectious_syndrome", infection_flag_col = "is_infectious", groupby_cols = c("Age_bin") ) ## End(Not run)## Not run: m_lj <- daly_calc_syndrome_fraction( pop_data = vital_reg, cause_col = "icd10_cause", syndrome_col = "infectious_syndrome", infection_flag_col = "is_infectious", groupby_cols = c("Age_bin") ) ## End(Not run)
Primary, direct implementation of the profile-specific associated-YLD equation:
daly_calc_yld_associated( profiles_with_los, P_Lk_prime_tbl, yld_ref = NULL, DW_sepsis = NULL, pathogen_col = "pathogen", plk_col = "P_Lk_prime", incidence_col = "N_NF_L", facility_col = NULL, facility_name = NULL, facility_state_map = NULL, state_col = "state", state_name = NULL, probability_col = "probability", dominant_class_col = "dominant_class", losr_col = "LOSR_years" )daly_calc_yld_associated( profiles_with_los, P_Lk_prime_tbl, yld_ref = NULL, DW_sepsis = NULL, pathogen_col = "pathogen", plk_col = "P_Lk_prime", incidence_col = "N_NF_L", facility_col = NULL, facility_name = NULL, facility_state_map = NULL, state_col = "state", state_name = NULL, probability_col = "probability", dominant_class_col = "dominant_class", losr_col = "LOSR_years" )
profiles_with_los |
Named list (one entry per pathogen) from
|
P_Lk_prime_tbl |
Data frame: the |
yld_ref |
Data frame with columns |
DW_sepsis |
Numeric scalar or |
pathogen_col |
Character. Default |
plk_col |
Character. P'_Lk column in |
incidence_col |
Character. I_L column in |
facility_col |
Character or |
facility_name |
Character or |
facility_state_map |
Data frame with |
state_col |
Character. Default |
state_name |
Character or |
probability_col |
Character. R'_k_delta column in
|
dominant_class_col |
Character. d*(delta) column. Default
|
losr_col |
Character. LOSR_k,d*(delta) column (years). Default
|
YLD_assoc_k = I_L * P'_Lk * DW_L * sum_{delta in D_k} [R'_k_delta * LOSR_k,d*(delta)]
where D_k is the set of RESISTANT resistance profiles for pathogen k (the
all-susceptible profile has no dominant class and is excluded – see
"Details"). d*(delta) is the dominant drug class of profile delta (GBD max
rule, assigned by daly_assign_rr_to_profiles()).
This does not require computing a baseline/pooled YLD first:
unlike the pre-existing multiplicative pathway (a pooled baseline YLD
multiplied by an associated-burden fraction), this is the direct
equation, evaluated per pathogen (and per facility, if
P_Lk_prime_tbl is facility-level) from its own inputs.
Component sourcing:
I_L and P'_Lk: read directly from
P_Lk_prime_tbl – the P_Lk_prime (pooled) or
facility_level element already returned by
daly_calc_pathogen_fraction_nonfatal(), which computes both the
non-fatal incidence count and the pathogen fraction from the same
observed cohort. Incidence is never back-calculated from deaths, CFR,
or LOS.
DW_L: resolved exactly as in the package's pre-existing
YLD weight mechanism – either the DW_sepsis scalar, or a
lookup in yld_ref (loaded from
inst/extdata/Proxy_YLD_per_case.csv) by state/facility. See
"Disability weight caveat" below.
R'_k_delta, d*(delta), and LOSR: read
from profiles_with_los, the list returned by
daly_assign_rr_to_profiles() when called with
los_r_col/los_s_col set.
Why D_k excludes the all-susceptible profile: this matches the
pre-existing convention elsewhere in this package that "associated"
burden is a partition over resistant profiles only (the removed
daly_calc_fraction_associated_yld()'s Fraction_k summed over
resistant profiles only; daly_calc_paf_los()'s all-susceptible term
already contributes exactly zero by construction, since RR=1 there).
YLD_associated therefore represents the burden occurring
specifically among pathogen-k patients with a resistant profile, not the
total burden across all pathogen-k patients.
Disability weight caveat: Proxy_YLD_per_case.csv's
DW_sepsis column is empirically a duration-inclusive "YLD per case"
proxy (proxy_yld_per_case == yld_days_per_case / 365), not a pure
disability weight. Because this function already multiplies by
profile-specific LOSR_years separately, sourcing DW_L from
yld_ref risks double-counting duration; a warning is emitted when
DW_sepsis is not supplied directly. Prefer supplying a pure
disability weight via the DW_sepsis scalar for this pathway.
P_Lk_prime_tbl augmented with I_L, DW_L,
profile_term (= sum_delta R'_k_delta * LOSR_k_delta), and
YLD_associated.
Primary, direct implementation of the profile-specific attributable-YLD equation:
daly_calc_yld_attributable( profiles_with_los, P_Lk_prime_tbl, yld_ref = NULL, DW_sepsis = NULL, pathogen_col = "pathogen", plk_col = "P_Lk_prime", incidence_col = "N_NF_L", facility_col = NULL, facility_name = NULL, facility_state_map = NULL, state_col = "state", state_name = NULL, probability_col = "probability", dominant_class_col = "dominant_class", losr_col = "LOSR_years", loss_col = "LOSS_years" )daly_calc_yld_attributable( profiles_with_los, P_Lk_prime_tbl, yld_ref = NULL, DW_sepsis = NULL, pathogen_col = "pathogen", plk_col = "P_Lk_prime", incidence_col = "N_NF_L", facility_col = NULL, facility_name = NULL, facility_state_map = NULL, state_col = "state", state_name = NULL, probability_col = "probability", dominant_class_col = "dominant_class", losr_col = "LOSR_years", loss_col = "LOSS_years" )
profiles_with_los |
Named list (one entry per pathogen) from
|
P_Lk_prime_tbl |
Data frame: the |
yld_ref |
Data frame with columns |
DW_sepsis |
Numeric scalar or |
pathogen_col |
Character. Default |
plk_col |
Character. P'_Lk column in |
incidence_col |
Character. I_L column in |
facility_col |
Character or |
facility_name |
Character or |
facility_state_map |
Data frame with |
state_col |
Character. Default |
state_name |
Character or |
probability_col |
Character. R'_k_delta column in
|
dominant_class_col |
Character. d*(delta) column. Default
|
losr_col |
Character. LOSR_k,d*(delta) column (years). Default
|
loss_col |
Character. LOSS_k,d*(delta) column (years) in
|
YLD_attrib_k = I_L * P'_Lk * DW_L * sum_{delta in D_k} [R'_k_delta * (LOSR_k,d*(delta) - LOSS_k,d*(delta))]
The excess (LOSR - LOSS) term makes this a genuine counterfactual:
how much MORE disability burden exists because these infections were
resistant, versus if they had been susceptible to the same (dominant)
class. D_k excludes the all-susceptible profile from the sum entirely
(rather than including a zero LOSR - LOSS term for it) – see
daly_calc_yld_associated() for why.
Obtains I_L, P'_Lk, DW_L, R'_k_delta, d*(delta), LOSR, and LOSS the same
way as daly_calc_yld_associated() – see that function's
documentation for full component-by-component sourcing and the
disability-weight caveat. Does not require a baseline YLD or a
PAF_LOS computed first; unlike the pre-existing multiplicative pathway
(daly_calc_paf_los() multiplied against a pooled baseline YLD),
this is the direct equation. daly_calc_paf_los() remains available
standalone for diagnostics / comparison against this direct calculation.
P_Lk_prime_tbl augmented with I_L, DW_L,
profile_term (= sum_delta R'_k_delta * (LOSR_k_delta -
LOSS_k_delta)), and YLD_attributable.
Computes years of life lost (YLL) associated with AMR directly from patient-level facility records, without requiring population-level P_LK (syndrome fractions) or R_kd (resistance profile scalars).
daly_calc_yll_associated( data, outcome_col, death_value = "Death", pathogen_col, patient_col, age_bin_col, sex_col, facility_col = NULL, syndrome_col = NULL, syndrome_name = NULL, date_culture_col = NULL, specimen_col = NULL, poly_weight_method = "monomicrobial_proportion", min_mono_per_facility = 30L, gap_days = 14, le_path = system.file("extdata", "life_expectancy_all.xlsx", package = "anumaan"), male_value = "Male", female_value = "Female", age_bin_map = c(`<1` = "0-1"), stratify_by = NULL )daly_calc_yll_associated( data, outcome_col, death_value = "Death", pathogen_col, patient_col, age_bin_col, sex_col, facility_col = NULL, syndrome_col = NULL, syndrome_name = NULL, date_culture_col = NULL, specimen_col = NULL, poly_weight_method = "monomicrobial_proportion", min_mono_per_facility = 30L, gap_days = 14, le_path = system.file("extdata", "life_expectancy_all.xlsx", package = "anumaan"), male_value = "Male", female_value = "Female", age_bin_map = c(`<1` = "0-1"), stratify_by = NULL )
data |
Data frame of patient-level facility records. |
outcome_col |
Character. Final outcome column. |
death_value |
Character. Value(s) indicating a fatal outcome.
Default |
pathogen_col |
Character. Pathogen / organism column (k). |
patient_col |
Character. Unique patient identifier column. |
age_bin_col |
Character. Column containing GBD-standard age
bin labels (e.g. |
sex_col |
Character. Column containing patient sex. |
facility_col |
Character or |
syndrome_col |
Character or |
syndrome_name |
Character or |
date_culture_col |
Character or |
specimen_col |
Character or |
poly_weight_method |
Character. Method for computing polymicrobial
death weights. Default |
min_mono_per_facility |
Integer. Minimum monomicrobial records per
facility to use facility-specific weights; smaller facilities fall back
to global weights. Default |
gap_days |
Integer. Window (days) used for polymicrobial
episode detection. Default |
le_path |
Character. Path to the India life expectancy
xlsx file. Defaults to the bundled |
male_value |
Character. Value in |
female_value |
Character. Value in |
age_bin_map |
Named character vector remapping non-standard
age bin labels to LE-table labels. Default |
stratify_by |
Character vector or |
For every fatal patient with pathogen k (and optionally syndrome L) the individual YLL contribution is:
where is the polymicrobial death weight for patient r and
pathogen k (= 1 for monomicrobial, 0-1 for polymicrobial episodes).
Total YLL associated:
Polymicrobial weights are computed via
prep_flag_polymicrobial() + prep_compute_poly_weights().
When facility_col is provided the weights
are derived per facility (reflecting local organism distributions), with
automatic fallback to globally-pooled proportions for facilities whose
monomicrobial reference pool is smaller than min_mono_per_facility.
If date_culture_col is NULL polymicrobial flagging is
skipped and all weights default to 1.
A named list:
totalScalar: total YLL associated across all pathogens and facilities.
per_pathogenData frame: YLL summed per pathogen k, pooled
across facilities. Columns: pathogen_col, n_patients,
YLL_associated_k.
by_age_sexData frame: YLL by age_bin_col x sex.
by_pathogen_age_sexData frame: YLL by pathogen x
age_bin_col x sex.
by_facilityData frame (only when facility_col is
supplied): per-facility YLL, one row per facility x pathogen.
by_syndromeData frame (only when syndrome_col is
supplied and syndrome_name is NULL): YLL by syndrome.
by_syndrome_pathogenData frame (only when
syndrome_col supplied): YLL by syndrome x pathogen.
stratifiedData frame (only when stratify_by is
supplied): YLL aggregated by the requested columns.
patient_dataThe death-cohort data frame used for
computation, with polymicrobial_weight, life_expectancy,
and yll_contribution columns attached.
## Not run: yll <- daly_calc_yll_associated( data = cohort_df, outcome_col = "final_outcome", death_value = "Death", pathogen_col = "organism_name", patient_col = "PatientInformation_id", age_bin_col = "Age_bin", sex_col = "gender", facility_col = "center_name", syndrome_col = "infectious_syndrome", date_culture_col = "culture_date", specimen_col = "sample_type", stratify_by = c("location", "infectious_syndrome") ) yll$total yll$per_pathogen yll$by_age_sex yll$stratified ## End(Not run)## Not run: yll <- daly_calc_yll_associated( data = cohort_df, outcome_col = "final_outcome", death_value = "Death", pathogen_col = "organism_name", patient_col = "PatientInformation_id", age_bin_col = "Age_bin", sex_col = "gender", facility_col = "center_name", syndrome_col = "infectious_syndrome", date_culture_col = "culture_date", specimen_col = "sample_type", stratify_by = c("location", "infectious_syndrome") ) yll$total yll$per_pathogen yll$by_age_sex yll$stratified ## End(Not run)
Takes the per-patient YLL data produced by daly_calc_yll_associated()
(which already contains life_expectancy, death_weight, and
yll_contribution) and multiplies by the mortality PAF from
daly_calc_paf_mortality() to produce AMR-attributable YLL.
daly_calc_yll_attributable( yll_patient_data, paf_mort, pathogen_col, patient_col, age_bin_col, sex_col = ".sex_norm", resistance_profile_col = NULL, profile_col = "profile", facility_col = NULL, syndrome_col = NULL, stratify_by = NULL )daly_calc_yll_attributable( yll_patient_data, paf_mort, pathogen_col, patient_col, age_bin_col, sex_col = ".sex_norm", resistance_profile_col = NULL, profile_col = "profile", facility_col = NULL, syndrome_col = NULL, stratify_by = NULL )
yll_patient_data |
Data frame: the |
paf_mort |
Named list returned by
|
pathogen_col |
Character. Pathogen column. |
patient_col |
Character. Patient identifier column. |
age_bin_col |
Character. Age bin column. |
sex_col |
Character. Normalised sex column.
Default |
resistance_profile_col |
Character or |
profile_col |
Character. Profile identifier column in the
|
facility_col |
Character or |
syndrome_col |
Character or |
stratify_by |
Character vector or |
Two PAF modes:
When resistance_profile_col is
NULL, the overall mortality PAF per pathogen k (PAF_k_mort)
from paf_mort is used as a scalar multiplier.
When resistance_profile_col is supplied,
each patient row is matched to its resistance profile delta and the
profile-specific PAF_mortality is applied. Patients whose
profile does not appear in paf_mort receive NA and a
warning is issued.
A list:
Scalar: total AMR-attributable YLL.
One row per pathogen: pathogen_col,
n_patients, YLL_associated_k, PAF_k_mort,
YLL_attributable_k.
YLL attributable stratified by age_bin x sex.
YLL attributable by pathogen x age_bin x sex.
Per-facility breakdown (when facility_col
supplied).
Per-syndrome breakdown (when syndrome_col
supplied).
Per-syndrome x pathogen (when
syndrome_col supplied).
User-defined stratification (when stratify_by
supplied).
Patient-level data augmented with PAF_kd
and YLL_attributable_contribution.
## Not run: yll_assoc <- daly_calc_yll_associated(data = cohort, ...) mort_or <- fit_mortality_rr_logistic(data = rr_data, ...) profiles_or <- assign_rr_to_profiles(profiles_out, rr_table = mort_or, rr_col = "OR_death" ) paf_mort <- daly_calc_paf_mortality(profiles_or) yll_attr <- daly_calc_yll_attributable( yll_patient_data = yll_assoc$patient_data, paf_mort = paf_mort, pathogen_col = "organism_name", patient_col = "PatientInformation_id", age_bin_col = "Age_bin", sex_col = ".sex_norm", facility_col = "center_name", syndrome_col = "infectious_syndrome", stratify_by = c("location", "infectious_syndrome") ) ## End(Not run)## Not run: yll_assoc <- daly_calc_yll_associated(data = cohort, ...) mort_or <- fit_mortality_rr_logistic(data = rr_data, ...) profiles_or <- assign_rr_to_profiles(profiles_out, rr_table = mort_or, rr_col = "OR_death" ) paf_mort <- daly_calc_paf_mortality(profiles_or) yll_attr <- daly_calc_yll_attributable( yll_patient_data = yll_assoc$patient_data, paf_mort = paf_mort, pathogen_col = "organism_name", patient_col = "PatientInformation_id", age_bin_col = "Age_bin", sex_col = ".sex_norm", facility_col = "center_name", syndrome_col = "infectious_syndrome", stratify_by = c("location", "infectious_syndrome") ) ## End(Not run)
Computes LOS with infection-type-specific clock start:
CAI: LOS = date_discharge - date_admission
HAI: LOS = date_discharge - date_culture
Unknown / Not known: LOS = date_discharge - date_culture (if culture date present), else date_discharge - date_admission. If neither reference date is available the patient is excluded.
Only discharged patients are retained. A checkpoint reports how many are
missing a discharge date; those patients fall back to los_col when
provided, otherwise they are excluded. Rows with LOS <= 0 or
LOS > max_los are dropped. Returns one row per patient.
daly_compute_patient_los( data, patient_id_col = "PatientInformation_id", facility_col = "center_name", facility_name = NULL, organism_col = "organism_name", syndrome_col = "syndrome", syndrome_name = NULL, date_admission_col = "date_of_admission", date_discharge_col = "final_outcome_date", date_culture_col = "date_of_first_positive_culture", final_outcome_col = "final_outcome", final_outcome_value = "Discharged", infection_type_derived_col = "infection_type_derived", los_col = NULL, max_los = 200 )daly_compute_patient_los( data, patient_id_col = "PatientInformation_id", facility_col = "center_name", facility_name = NULL, organism_col = "organism_name", syndrome_col = "syndrome", syndrome_name = NULL, date_admission_col = "date_of_admission", date_discharge_col = "final_outcome_date", date_culture_col = "date_of_first_positive_culture", final_outcome_col = "final_outcome", final_outcome_value = "Discharged", infection_type_derived_col = "infection_type_derived", los_col = NULL, max_los = 200 )
data |
Data frame with an |
patient_id_col |
Character. Default |
facility_col |
Character. Default |
facility_name |
Character or |
organism_col |
Character. Column containing organism/pathogen names.
Used for episode grouping: a new episode is only created when the culture
date gap exceeds 14 days AND the organism differs from the episode's first
organism. Default |
syndrome_col |
Character. Syndrome column name. Only used when
|
syndrome_name |
Character or |
date_admission_col |
Character. Default |
date_discharge_col |
Character. Default |
date_culture_col |
Character. Default
|
final_outcome_col |
Character. Default |
final_outcome_value |
Character. Default |
infection_type_derived_col |
Character. Column holding each patient's
HAI/CAI classification (e.g. copied from |
los_col |
Character or |
max_los |
Numeric. Upper cap on LOS in days; patients exceeding this
are excluded. Default |
Data frame: one row per patient with patient_id_col,
facility_col, infection_type_derived_col, LOS_days.
Counts the number of unique patients per infectious syndrome directly from
facility-level data. This is the direct-count approach to incidence –
no CFR, no CR_L adjustment, no pathogen weighting. Use this when you
want raw facility-reported case counts rather than the formula-derived
estimate from calculate_incidence_L().
daly_count_incident_cases( data, syndrome_col, syndrome_name, patient_col, facility_col = NULL, facility_name = NULL, pathogen_col = NULL, pathogen_name = NULL )daly_count_incident_cases( data, syndrome_col, syndrome_name, patient_col, facility_col = NULL, facility_name = NULL, pathogen_col = NULL, pathogen_name = NULL )
data |
Data frame of facility-level records. |
syndrome_col |
Character. Column containing infectious syndrome labels. |
syndrome_name |
Character. Syndrome to count cases for
(e.g., |
patient_col |
Character. Unique patient identifier column. Cases are counted as distinct patients, not rows. |
facility_col |
Character or NULL. Facility identifier column.
When provided without |
facility_name |
Character or NULL. If provided, restricts the count
to that facility only. Default |
pathogen_col |
Character or NULL. Pathogen identifier column.
Required when |
pathogen_name |
Character or NULL. If provided, restricts the count
to the specified pathogen(s). Default |
Results are returned facility-wise when facility_col is supplied
and facility_name is NULL. When facility_name is specified,
only that facility is returned. When no facility information is provided,
a single pooled count across all records is returned.
Data frame with columns:
syndrome_col, n_cases (unique patient count),
and facility_col if supplied.
Derives the healthcare-associated infection (HAI) vs community-acquired infection (CAI) classification for each patient record in the mortality cohort, using admission-to-culture date differences. Also performs a data-quality check for deceased patients missing an outcome date.
daly_derive_hai_cai_for_mortality( data, infection_type_col = "type_of_infection", date_admission_col = "date_of_admission", date_culture_col = "date_of_first_positive_culture", final_outcome_col = "final_outcome", final_outcome_date_col = "final_outcome_date", death_value = "Death", hai_threshold_hours = 48, patient_id_col = "PatientInformation_id" )daly_derive_hai_cai_for_mortality( data, infection_type_col = "type_of_infection", date_admission_col = "date_of_admission", date_culture_col = "date_of_first_positive_culture", final_outcome_col = "final_outcome", final_outcome_date_col = "final_outcome_date", death_value = "Death", hai_threshold_hours = 48, patient_id_col = "PatientInformation_id" )
data |
Data frame of patient-level records. |
infection_type_col |
Character. Column containing the raw infection
type label. Default |
date_admission_col |
Character. Admission date column.
Default |
date_culture_col |
Character. First positive culture date column.
Default |
final_outcome_col |
Character. Final outcome column.
Default |
final_outcome_date_col |
Character. Final outcome date column.
Default |
death_value |
Character. Value in |
hai_threshold_hours |
Numeric. Hours after admission at which a
positive culture is classified as HAI. Default |
patient_id_col |
Character. Patient identifier column.
Default |
The input data frame with a derived infection_type column
(values "HAI" or "CAI").
Drops profiles whose resistant classes have no RR estimate in
rr_table and re-normalises the remaining probabilities. The
all-susceptible reference profile is always kept.
daly_filter_profiles_to_rr_classes( profiles_with_rr, rr_table, pathogen_col = "pathogen", class_col = "antibiotic_class", probability_col = "probability", fallback_rr = 1 )daly_filter_profiles_to_rr_classes( profiles_with_rr, rr_table, pathogen_col = "pathogen", class_col = "antibiotic_class", probability_col = "probability", fallback_rr = 1 )
profiles_with_rr |
Named list returned by
|
rr_table |
Data frame of RR estimates. |
pathogen_col |
Character. Default |
class_col |
Character. Default |
probability_col |
Character. Default |
fallback_rr |
Numeric. Default |
Named list (one entry per pathogen) with filtered and re-normalised profiles.
Estimates class-specific relative length of stay (RR_LOS) for each pathogen using a Gamma generalized linear model with log link:
daly_fit_los_rr( data, patient_id_col = "PatientInformation_id", facility_col = "center_name", organism_col = "organism_name", syndrome_col = "syndrome", infection_type_col = "infection_type", antibiotic_class_col = "antibiotic_class", antibiotic_name_col = "antibiotic_name", antibiotic_value_col = "antibiotic_value", date_admission_col = "date_of_admission", date_discharge_col = "final_outcome_date", date_culture_col = "date_of_first_positive_culture", final_outcome_col = "final_outcome", final_outcome_value = "Discharged", age_col = "Age", sex_col = "Gender", unit_type_col = NULL, comorbidity_col = NULL, syndrome_name = NULL, organism_name = NULL, hai_threshold_hours = 48, max_los = 365, min_n = 20L, min_resistant = 5L, min_susceptible = 5L )daly_fit_los_rr( data, patient_id_col = "PatientInformation_id", facility_col = "center_name", organism_col = "organism_name", syndrome_col = "syndrome", infection_type_col = "infection_type", antibiotic_class_col = "antibiotic_class", antibiotic_name_col = "antibiotic_name", antibiotic_value_col = "antibiotic_value", date_admission_col = "date_of_admission", date_discharge_col = "final_outcome_date", date_culture_col = "date_of_first_positive_culture", final_outcome_col = "final_outcome", final_outcome_value = "Discharged", age_col = "Age", sex_col = "Gender", unit_type_col = NULL, comorbidity_col = NULL, syndrome_name = NULL, organism_name = NULL, hai_threshold_hours = 48, max_los = 365, min_n = 20L, min_resistant = 5L, min_susceptible = 5L )
data |
Data frame. |
patient_id_col |
Character. Patient identifier column. |
facility_col |
Character or NULL. Facility / centre column. When
|
organism_col |
Character. Pathogen column. |
syndrome_col |
Character. Syndrome column. |
infection_type_col |
Character. Column already holding the final
HAI/CAI classification (e.g. |
antibiotic_class_col |
Character. Antibiotic class column. |
antibiotic_name_col |
Character. Antibiotic name column. |
antibiotic_value_col |
Character. Antibiotic susceptibility column. |
date_admission_col |
Character. Admission date column. |
date_discharge_col |
Character. Discharge / final outcome date column. |
date_culture_col |
Character. First positive culture date column. |
final_outcome_col |
Character. Final outcome column. |
final_outcome_value |
Character. Value indicating discharged patients. |
age_col |
Character. Age column. |
sex_col |
Character. Sex column. |
unit_type_col |
Character or NULL. ICU / ward location column. |
comorbidity_col |
Character or NULL. Comorbidity column. |
syndrome_name |
Character or NULL. Restrict to one syndrome. |
organism_name |
Character vector or NULL. Restrict to these pathogens. |
hai_threshold_hours |
Numeric. Unused – retained only for backward
API compatibility. HAI/CAI is read directly from |
max_los |
Numeric. Maximum retained LOS in days. |
min_n |
Integer. Minimum patients required in a class model. |
min_resistant |
Integer. Minimum resistant patients required. |
min_susceptible |
Integer. Minimum susceptible patients required. |
E(LOS_i) = exp(beta0 + beta1*Resistance_ci + beta2*HAI_i + beta3*Age_i + beta4*Sex_i + beta5*ICU_i + beta6*Comorbidity_i + centre fixed effects)
RR_LOS for a resistance class is exp(beta1).
Data frame with pathogen, antibiotic_class, hospital (NA when
facility_col is NULL), RR_LOS, CI_lower,
CI_upper, beta_log_rr, mean_los_resistant, mean_los_susceptible,
n_patients, n_resistant, n_susceptible, model_family, link_function,
and syndrome_scope.
For each pathogen x antibiotic class, splits patients into resistant (R) and susceptible (S) groups, fits a parametric distribution (default: gamma) to each group's LOS, and returns: RR_LOS = mean_LOS(R) / mean_LOS(S)
daly_fit_los_rr_distribution( data, patient_id_col = "PatientInformation_id", facility_col = "center_name", organism_col = "organism_name", syndrome_col = "syndrome", infection_type_col = "infection_type", antibiotic_class_col = "antibiotic_class", antibiotic_name_col = "antibiotic_name", antibiotic_value_col = "antibiotic_value", date_admission_col = "date_of_admission", date_discharge_col = "final_outcome_date", date_culture_col = "date_of_first_positive_culture", final_outcome_col = "final_outcome", final_outcome_value = "Discharged", syndrome_name = NULL, organism_name = NULL, facility_name = NULL, hai_threshold_hours = 48, distributions = "gamma", max_los = 365, min_n = 10L )daly_fit_los_rr_distribution( data, patient_id_col = "PatientInformation_id", facility_col = "center_name", organism_col = "organism_name", syndrome_col = "syndrome", infection_type_col = "infection_type", antibiotic_class_col = "antibiotic_class", antibiotic_name_col = "antibiotic_name", antibiotic_value_col = "antibiotic_value", date_admission_col = "date_of_admission", date_discharge_col = "final_outcome_date", date_culture_col = "date_of_first_positive_culture", final_outcome_col = "final_outcome", final_outcome_value = "Discharged", syndrome_name = NULL, organism_name = NULL, facility_name = NULL, hai_threshold_hours = 48, distributions = "gamma", max_los = 365, min_n = 10L )
data |
Data frame of isolate/patient rows (long format). |
patient_id_col |
Character. Patient identifier column. |
facility_col |
Character. Facility/centre column. |
organism_col |
Character. Organism name column. |
syndrome_col |
Character. Syndrome column (used only when
|
infection_type_col |
Character. Column already holding the final
HAI/CAI classification (e.g. |
antibiotic_class_col |
Character. Antibiotic class column. |
antibiotic_name_col |
Character. Antibiotic name column. |
antibiotic_value_col |
Character. Antibiotic value column (S/I/R). |
date_admission_col |
Character. Date of admission column. |
date_discharge_col |
Character. Date of discharge column. |
date_culture_col |
Character. Date of culture column. |
final_outcome_col |
Character. Final outcome column. |
final_outcome_value |
Character. Value indicating discharge. |
syndrome_name |
Character or |
organism_name |
Character vector or |
facility_name |
Character or |
hai_threshold_hours |
Numeric. Unused – retained only for backward
API compatibility. HAI/CAI is read directly from |
distributions |
Character vector. Candidate distributions to fit.
Default |
max_los |
Numeric. Maximum plausible LOS in days. Default |
min_n |
Integer. Minimum patients required in both R and S groups.
Default |
This is an alternative to daly_fit_los_rr() that avoids regression
and models the full LOS distribution per group. The output flat data frame
is fully compatible with assign_rr_to_profiles() and
filter_profiles_to_rr_classes().
A data frame with one row per pathogen x class:
Pathogen name.
Antibiotic class name.
Fitted mean ratio: mean_LOS(R) / mean_LOS(S).
Fitted mean LOS for resistant patients.
Fitted mean LOS for susceptible patients.
Distribution fitted to the R group.
Distribution fitted to the S group.
Number of resistant patients.
Number of susceptible patients.
Syndrome filter applied, or "all".
daly_fit_los_rr, daly_assign_rr_to_profiles
Fits a pathogen-class specific mixed-effects logistic regression model:
daly_fit_mortality_rr( data, patient_id_col = "PatientInformation_id", facility_col = "center_name", organism_col = "organism_name", syndrome_col = "syndrome", infection_type_col = "type_of_infection", antibiotic_class_col = "antibiotic_class", antibiotic_name_col = "antibiotic_name", antibiotic_value_col = "antibiotic_value", unit_type_col = "unit_type", date_admission_col = "date_of_admission", date_culture_col = "date_of_first_positive_culture", final_outcome_col = "final_outcome", final_outcome_date_col = "final_outcome_date", age_col = "Age", sex_col = "Gender", comorbidity_col = NULL, death_value = "Death", syndrome_name = NULL, organism_name = NULL, hai_threshold_hours = 48, icu_values = c("ICU", "Intensive Care", "Critical Care", "PICU", "NICU"), phi_threshold = 0.7, min_n = 20L, min_deaths = 10L )daly_fit_mortality_rr( data, patient_id_col = "PatientInformation_id", facility_col = "center_name", organism_col = "organism_name", syndrome_col = "syndrome", infection_type_col = "type_of_infection", antibiotic_class_col = "antibiotic_class", antibiotic_name_col = "antibiotic_name", antibiotic_value_col = "antibiotic_value", unit_type_col = "unit_type", date_admission_col = "date_of_admission", date_culture_col = "date_of_first_positive_culture", final_outcome_col = "final_outcome", final_outcome_date_col = "final_outcome_date", age_col = "Age", sex_col = "Gender", comorbidity_col = NULL, death_value = "Death", syndrome_name = NULL, organism_name = NULL, hai_threshold_hours = 48, icu_values = c("ICU", "Intensive Care", "Critical Care", "PICU", "NICU"), phi_threshold = 0.7, min_n = 20L, min_deaths = 10L )
data |
Data frame. |
patient_id_col |
Character. Patient identifier column. |
facility_col |
Character or NULL. Facility / centre column. When
|
organism_col |
Character. Pathogen column. |
syndrome_col |
Character. Syndrome column. |
infection_type_col |
Character. Raw infection-type column. |
antibiotic_class_col |
Character. Antibiotic class column. |
antibiotic_name_col |
Character. Antibiotic name column. |
antibiotic_value_col |
Character. Antibiotic susceptibility column. |
unit_type_col |
Character or NULL. ICU / ward location column. |
date_admission_col |
Character. Admission date column. |
date_culture_col |
Character. First positive culture date column. |
final_outcome_col |
Character. Final outcome column. |
final_outcome_date_col |
Character. Final outcome date column. |
age_col |
Character. Age column. |
sex_col |
Character. Sex column. |
comorbidity_col |
Character or NULL. Comorbidity column. |
death_value |
Character. Value indicating death. |
syndrome_name |
Character or NULL. Restrict to one syndrome. |
organism_name |
Character vector or NULL. Restrict to these pathogens. |
hai_threshold_hours |
Numeric. HAI derivation threshold. |
icu_values |
Character vector. Values treated as ICU. |
phi_threshold |
Numeric. HAI / ICU collinearity warning threshold. |
min_n |
Integer. Minimum patients per fitted model. |
min_deaths |
Integer. Minimum deaths per fitted model. |
Death_i ~ Bernoulli(pi_i) logit(pi_i) = beta0 + beta_kd * Resistant_id + beta_age * Age_i + beta_sex * Sex_i + beta_hai * HAI_i + beta_icu * ICU_i + beta_comorb * Comorbidity_i + beta_syn * Syndrome_i + u_facility
where u_facility is a random intercept when more than one facility is present.
The function returns both: - OR_death = exp(beta_kd) - RR_death = mean(p_resistant_cf) / mean(p_susceptible_cf)
RR_death is derived from model-based predicted probabilities under resistant and susceptible counterfactual scenarios, as required by the burden methodology.
Data frame with hospital (NA when facility_col is
NULL), adjusted OR and adjusted RR of death.
Ranks pathogens by the number of records (rows) in the dataset, optionally filtered to a specific syndrome, specimen, facility, or outcome. Returns the top N pathogens overall or broken down per facility.
daly_get_top_pathogens( data, pathogen_col, n = 5L, syndrome_col = NULL, syndrome_name = NULL, specimen_col = NULL, specimen_name = NULL, outcome_col = NULL, outcome_name = NULL, facility_col = NULL, facility_name = NULL )daly_get_top_pathogens( data, pathogen_col, n = 5L, syndrome_col = NULL, syndrome_name = NULL, specimen_col = NULL, specimen_name = NULL, outcome_col = NULL, outcome_name = NULL, facility_col = NULL, facility_name = NULL )
data |
Data frame of facility-level records. |
pathogen_col |
Character. Pathogen column. |
n |
Integer. Number of top pathogens to return. Default 5. |
syndrome_col |
Character or NULL. Filter to this syndrome column. |
syndrome_name |
Character or NULL. Syndrome value to filter to. |
specimen_col |
Character or NULL. Filter to this specimen column. |
specimen_name |
Character or NULL. Specimen value to filter to. |
outcome_col |
Character or NULL. Filter to this outcome column. |
outcome_name |
Character or NULL. Outcome value to filter to
(e.g., |
facility_col |
Character or NULL. Facility identifier column.
When provided without |
facility_name |
Character or NULL. If provided, restricts to that facility only before ranking. |
Use this to decide which pathogens to focus on before calling
calculate_P_Lk_prime_BSI(), calculate_cfr_lk(), or
calculate_YLD().
Data frame with columns: pathogen_col, n_records,
rank (1 = most common), and facility_col if supplied.
Loads the rr_list_gbd.xlsx file containing pathogen-drug combinations with relative risk values for burden estimation.
daly_load_rr_reference()daly_load_rr_reference()
Data frame with Pathogen, Drug, and RR columns
## Not run: rr_data <- daly_load_rr_reference() head(rr_data) ## End(Not run)## Not run: rr_data <- daly_load_rr_reference() head(rr_data) ## End(Not run)
Default column name mappings for fuzzy matching
default_column_mappingsdefault_column_mappings
A named list with elements mapping standard names to character vectors of acceptable aliases.
Inspects a data frame (after column mapping) and returns a named logical vector indicating which preprocessing steps can be executed given the columns that are present.
detect_preprocessing_capabilities(data)detect_preprocessing_capabilities(data)
data |
Data frame after column mapping. |
This is used by run_preprocess() to decide which layers to run and
which to skip gracefully.
Named logical vector. TRUE means the step can run; FALSE means required inputs are absent and the step will be skipped with a warning.
Consistent theme used across all EDA plot functions in this file.
Uses ggpubr::theme_pubr() when ggpubr is installed and falls back to
ggplot2::theme_bw() otherwise.
eda_theme(base_size = 14, legend_position = "top")eda_theme(base_size = 14, legend_position = "top")
base_size |
Numeric. Base font size. Default 14. |
legend_position |
Character. Legend position ("top", "bottom", "left", "right", "none"). Default "top". |
A ggplot2 theme object.
Generates all binary resistance profiles for n antibiotic
classes using vectorised bit manipulation. Each row is one profile; each
class column contains 1 (resistant) or 0 (susceptible).
enumerate_binary_profiles(classes)enumerate_binary_profiles(classes)
classes |
Character vector. Ordered antibiotic class names. The order determines which bit position each class occupies and must be consistent across all calls within a single analysis. |
Tibble with 2^n rows and n + 1 columns:
profile_delta (character label, e.g. "RSS") and one integer
column per class (0 / 1).
The public-facing solver for Pathway 1. Accepts pre-computed marginal and
pairwise resistance rates (from compute_marginals_from_data() /
compute_pairwise_from_data(), or from validate_aggregate_inputs()
for GBD-style pre-computed inputs), enumerates all binary
resistance profiles, builds the constraint matrix, and solves the
simplex-constrained weighted least-squares QP:
estimate_profiles_convex( marginals, pairwise = NULL, panel_map = NULL, exclude_near_zero = TRUE, zero_threshold = 0, top_n_classes = NULL, lambda = 1e-08, sigma_sq = 1, solver = c("osqp", "quadprog"), n_cores = 1L, pathogen_col = "pathogen", class_col = "antibiotic_class", rate_col = "marginal_resistance", n_tested_col = "n_tested" )estimate_profiles_convex( marginals, pairwise = NULL, panel_map = NULL, exclude_near_zero = TRUE, zero_threshold = 0, top_n_classes = NULL, lambda = 1e-08, sigma_sq = 1, solver = c("osqp", "quadprog"), n_cores = 1L, pathogen_col = "pathogen", class_col = "antibiotic_class", rate_col = "marginal_resistance", n_tested_col = "n_tested" )
marginals |
Tibble. Output of |
pairwise |
Tibble or |
panel_map |
Named list or |
exclude_near_zero |
Logical. Drop classes with
|
zero_threshold |
Numeric. Classes at or below this value are
considered near-zero. Default |
top_n_classes |
Integer or |
lambda |
Numeric. Ridge regularisation added to QP Hessian diagonal.
Default |
sigma_sq |
Numeric. Uniform constraint variance. Default |
solver |
Character. |
n_cores |
Integer. Parallel cores. Default |
pathogen_col |
Character. Default |
class_col |
Character. Default |
rate_col |
Character. Default |
n_tested_col |
Character. Default |
Stratification columns (geography, year, outcome) present in marginals
are detected automatically and carried through to the output.
Tibble with one row per (stratum x) pathogen x profile:
Any geography / year / outcome columns from marginals.
pathogenPathogen name.
profile_set_type"aggregate_convex".
profile_class_setOrdered class names joined by "|".
profile_deltaBinary profile label, e.g. "RSS".
profile_probabilityEstimated probability .
estimator"convex".
convergence_flagLogical; FALSE if QP failed and
uniform distribution was returned.
identifiability_flagLogical; TRUE when the constraint
matrix is rank-deficient (system is underdetermined).
max_abs_residualMaximum absolute constraint residual.
notesSemicolon-separated notes: capped pairs, fallback pairs.
## Not run: marg <- compute_marginals_from_data(result$data_wide, result$col_map_resolved, panel_map) pw <- compute_pairwise_from_data(result$data_wide, marg, result$col_map_resolved, panel_map) out <- estimate_profiles_convex(marg, pw, panel_map) ## End(Not run)## Not run: marg <- compute_marginals_from_data(result$data_wide, result$col_map_resolved, panel_map) pw <- compute_pairwise_from_data(result$data_wide, marg, result$col_map_resolved, panel_map) out <- estimate_profiles_convex(marg, pw, panel_map) ## End(Not run)
Top-level dispatcher. Runs either the convex optimisation pathway (Pathway 1, aggregate surveillance data) or the Bayesian hierarchical multivariate probit pathway (Pathway 2, facility-level AST data).
estimate_resistance_profiles( data, method = c("convex", "bayesian"), pairwise = NULL, panel_map = NULL, class_cols = NULL, fixed_effects = NULL, random_effects = list(), profile_group_col = NULL, pathogen = NULL, pathogen_col = "pathogen", eligible_pairs = NULL, outcome_col = NULL, nonfatal_values = c("Discharged", "Survived", "Alive", "discharged", "survived", "alive"), panel_eligibility = list(), residual_structure = c("identity", "correlated"), estimand = "observed_stewardship_event_mix", prior_config = list(), sampler_config = list(), n_posterior_draws_for_profiles = 2000L )estimate_resistance_profiles( data, method = c("convex", "bayesian"), pairwise = NULL, panel_map = NULL, class_cols = NULL, fixed_effects = NULL, random_effects = list(), profile_group_col = NULL, pathogen = NULL, pathogen_col = "pathogen", eligible_pairs = NULL, outcome_col = NULL, nonfatal_values = c("Discharged", "Survived", "Alive", "discharged", "survived", "alive"), panel_eligibility = list(), residual_structure = c("identity", "correlated"), estimand = "observed_stewardship_event_mix", prior_config = list(), sampler_config = list(), n_posterior_draws_for_profiles = 2000L )
data |
For Pathway 1: marginals tibble from
|
method |
Character. |
pairwise |
Tibble or |
panel_map |
Named list or |
class_cols |
Character vector. Pathway 2 only. Required. |
fixed_effects |
Character vector. Pathway 2 only. Required. |
random_effects |
Character vector or named list of random-intercept
blocks. Pathway 2 only. Use |
profile_group_col |
Character scalar or |
pathogen |
Character or |
pathogen_col |
Character. Default |
eligible_pairs |
Tibble or |
outcome_col |
Character or |
nonfatal_values |
Character vector. Outcome values for R_NF cohort. |
panel_eligibility |
Named list. Eligibility thresholds; passed to
|
residual_structure |
Character. Pathway 2. |
estimand |
Character. Estimand label. Default
|
prior_config |
Named list. Pathway 2 only. Priors. |
sampler_config |
Named list. Pathway 2 only. Structured sampler
settings: |
n_posterior_draws_for_profiles |
Integer. Pathway 2. Number of posterior
draws used for MVN simulation of profiles. Default |
For Pathway 2, pass pathogen to fit one pathogen at a time – the
recommended workflow. Run this function once per pathogen and collect the
results in the analysis repository.
Named list: profiles, eligibility, diagnostics,
fitted_models, config_used.
Saves preprocessing report to HTML, PDF, TXT, or RDS format.
export_report(report, file)export_report(report, file)
report |
An amr_preprocessing_report object |
file |
Path to output file |
Invisibly returns file path
Accepts wide-format event-level AST data (one row per organism-event, one
column per antibiotic class with 0 / 1 / NA values) and fits a
hierarchical Bayesian multivariate probit model via cmdstanr.
fit_bayesian_multivariate_probit( event_class_data, class_cols, fixed_effects, random_effects = list(), profile_group_col = NULL, pathogen = NULL, pathogen_col = "pathogen", event_id_col = "event_id", eligible_pairs = NULL, outcome_col = NULL, reserve_drug_cols = NULL, panel_eligibility = list(), residual_structure = c("identity", "correlated"), estimand = "observed_stewardship_event_mix", prior_config = list(), sampler_config = list(), compute = list(), show_messages = TRUE, save_full_latent_diagnostics = FALSE, ... )fit_bayesian_multivariate_probit( event_class_data, class_cols, fixed_effects, random_effects = list(), profile_group_col = NULL, pathogen = NULL, pathogen_col = "pathogen", event_id_col = "event_id", eligible_pairs = NULL, outcome_col = NULL, reserve_drug_cols = NULL, panel_eligibility = list(), residual_structure = c("identity", "correlated"), estimand = "observed_stewardship_event_mix", prior_config = list(), sampler_config = list(), compute = list(), show_messages = TRUE, save_full_latent_diagnostics = FALSE, ... )
event_class_data |
Data frame. One row per organism-event. Antibiotic
class columns hold 0 (susceptible), 1 (resistant), or |
class_cols |
Character vector. Names of the antibiotic class columns. Required. |
fixed_effects |
Character vector. Event-level covariate column names. Required. |
random_effects |
Character vector or named list of random-intercept
blocks. Use |
profile_group_col |
Character scalar or |
pathogen |
Character or |
pathogen_col |
Character. Column identifying the pathogen.
Default |
event_id_col |
Character. Column in |
eligible_pairs |
Tibble or |
outcome_col |
Character or |
reserve_drug_cols |
Character vector or |
panel_eligibility |
Named list. Eligibility thresholds per
hospital x class cell: |
residual_structure |
Character. Controls the residual covariance structure.
|
estimand |
Character. Identifies the target quantity. Only
|
prior_config |
Named list. Any subset of |
sampler_config |
Named list. Sampler settings forwarded to
|
compute |
Named list controlling the Stan execution backend. Supported
fields are |
show_messages |
Logical. Print sampling progress. Default |
save_full_latent_diagnostics |
Logical. When |
... |
Additional arguments forwarded to |
Model (per pathogen):
The per-event latent noise makes (and therefore
) identifiable from the observed binary
outcomes. Hospital (and lower-level) effects use a
parameterisation so
the D-dim random effect vectors are correlated across antibiotic classes.
Single-pathogen design: pass pathogen to restrict the fit.
Run once per pathogen and orchestrate in the analysis repository.
Random effects (random_effects): an optional character
vector or list of grouping blocks defining the clustering hierarchy. Use
list() for a fixed-effects-only model. When blocks are present, the
first element is the upper-most level;
subsequent elements are nested within it. Nested levels receive globally unique
composite keys built internally. Any hierarchical grouping variable can occupy
any slot – the labels hospital/patient/admission are semantic conventions, not
constraints. Isolate- or sample-event-level effects can be passed as the second
or third element, but note the returned object uses generic level names
(upper_re_col, middle_re_col, lower_re_col).
Missing-AST handling: Observed AST cells impose sign constraints on
the latent variables; untested cells impose no sign constraint and are
represented as unconstrained latent values. The model assumes testing is
conditionally ignorable given included covariates and random effects. It does
NOT correct for selective testing bias. See residual_structure for
control over residual covariance complexity.
Fixed-effect missingness: the function warns but does NOT silently impute covariates. Imputation is the caller's responsibility; columns with any remaining NA values after the call will cause Stan to fail.
Named list with elements: draws, diagnostics,
diagnostics_detail, fit, data_long, index_maps,
X_event, event_re_idx, class_cols,
event_metadata, n_re_levels, upper_re_col,
middle_re_col, lower_re_col, patient_key_col,
admission_key_col, pathogen_col, pathogen_fitted,
residual_structure, estimand, prior_config_used,
sampler_config_used, compute_config_used, and
eligibility_report.
diagnostics is a one-row monitored summary. The main diagnostic
fields max_rhat, min_ess_bulk, and min_ess_tail
are computed over the monitored parameters retained in draws.
These exclude the latent z_free nuisance parameters used for
probit data augmentation. converged_structural/converged_full
incorporate tree-depth saturation as well as R-hat/ESS/divergences/E-BFMI
(a run that repeatedly saturates max_treedepth is not reported as
converged). diagnostic_status is a canonical multi-level status –
one of "pass", "warning_rhat", "warning_low_bulk_ess",
"warning_low_tail_ess", "warning_treedepth",
"fail_rhat", "fail_energy", or "fail_divergent" (most
severe first) – intended as the single authoritative status field for
callers, replacing ad hoc re-derivations downstream.
Full-fit diagnostic fields, including max_rhat_all,
min_ess_bulk_all, and min_ess_tail_all, are reported
separately for visibility and include all Stan parameters, including
z_free.
diagnostics_detail contains monitored_parameters,
all_parameters (per-parameter Rhat/ESS with parameter_group),
grouped (per-parameter_group Rhat/ESS quantiles and
percentage-over-threshold, not only the single worst parameter), and
chains (per-chain n_sampling, n_divergent,
n_treedepth_sat, ebfmi, mean_accept_stat,
mean_stepsize, mean_treedepth, max_treedepth) – the
canonical diagnostic tables; callers should not recompute these
independently from fit$fit$sampler_diagnostics().
Fits Weibull, Lognormal, and Gamma distributions to a numeric vector,
returning all fit objects. Failed fits are NULL.
fit_distributions(x)fit_distributions(x)
x |
Numeric vector of positive values (e.g., LOS in days). |
Named list with elements weibull, lnorm, gamma,
each a fitdist object or NULL.
fits <- fit_distributions(rlnorm(200, 2, 0.5)) fits$lnorm$estimatefits <- fit_distributions(rlnorm(200, 2, 0.5)) fits$lnorm$estimate
Creates a comprehensive report documenting all transformations applied during preprocessing, including column mappings, data quality metrics, and transformation summaries.
generate_preprocessing_report( raw_data, processed_data, preprocessing_log, config, output_file = NULL, include_plots = TRUE )generate_preprocessing_report( raw_data, processed_data, preprocessing_log, config, output_file = NULL, include_plots = TRUE )
raw_data |
Original input data frame (before preprocessing) |
processed_data |
Final output data frame (after preprocessing) |
preprocessing_log |
List containing logs from each preprocessing step |
config |
AMR configuration object used |
output_file |
Optional. Path to save report. If NULL, returns list. Supports .html, .pdf, .txt, .rds formats. |
include_plots |
Logical. Include data quality plots. Default TRUE. |
If output_file is NULL, returns a list with report components. Otherwise, saves report to file and returns file path.
## Not run: # Generate report report <- generate_preprocessing_report( raw_data = my_raw_data, processed_data = result$data, preprocessing_log = result$log, config = result$config, output_file = "preprocessing_report.html" ) ## End(Not run)## Not run: # Generate report report <- generate_preprocessing_report( raw_data = my_raw_data, processed_data = result$data, preprocessing_log = result$log, config = result$config, output_file = "preprocessing_report.html" ) ## End(Not run)
Returns predefined age bin label sets for use with prep_assign_age_bins().
get_age_bins(type = "GBD_standard")get_age_bins(type = "GBD_standard")
type |
Character. One of |
Character vector of age bin labels.
For a given organism (and optionally center), computes per-patient resistance status and returns separate LOS vectors for resistant and susceptible exposures.
get_los_by_resistance( abx_data, los_data, organism, center = NULL, patient_id_col = "PatientInformation_id", organism_col = "organism_clean", center_col = "center_name", antibiotic_col = "antibiotic_name", sus_col = "sus" )get_los_by_resistance( abx_data, los_data, organism, center = NULL, patient_id_col = "PatientInformation_id", organism_col = "organism_clean", center_col = "center_name", antibiotic_col = "antibiotic_name", sus_col = "sus" )
abx_data |
Data frame of antibiotic susceptibility results with columns for patient ID, organism, antibiotic name, and susceptibility value (already cleaned to "R"/"S"). |
los_data |
Data frame from |
organism |
Character. Organism name (lowercase, trimmed) to filter on. |
center |
Optional character. Center name to filter on. Default
|
patient_id_col |
Character. Patient ID column. Default
|
organism_col |
Character. Organism column. Default
|
center_col |
Character. Center column. Default |
antibiotic_col |
Character. Antibiotic name column. Default
|
sus_col |
Character. Susceptibility column (values "R"/"S"). Default
|
List with elements R (LOS vector for resistant exposures) and
S (LOS vector for susceptible exposures).
Replaces underscores with spaces only – does not alter the underlying 'center_name'/hospital identifier used anywhere else (joins, grouping, file paths all keep the raw value; this is a plotting-display transform only).
hospital_display_label(x)hospital_display_label(x)
x |
Character vector of raw hospital/site names (e.g. |
Character vector, e.g. "AIIMS trauma center".
Converts a wide-format data frame (one column per syndrome, values indicating presence) to long format and assigns the highest-priority syndrome per patient using the infectious syndrome hierarchy.
infer_patient_syndrome_wide( data, patient_col = "patient_id", syndrome_cols = NULL, positive_values = c(1, "1", TRUE, "TRUE", "True", "true", "Yes", "YES", "yes"), collapse_unspecified_respiratory = TRUE, keep_only_burden_syndromes = FALSE )infer_patient_syndrome_wide( data, patient_col = "patient_id", syndrome_cols = NULL, positive_values = c(1, "1", TRUE, "TRUE", "True", "true", "Yes", "YES", "yes"), collapse_unspecified_respiratory = TRUE, keep_only_burden_syndromes = FALSE )
data |
Data frame in wide format where syndrome columns contain presence
indicators ( |
patient_col |
Character. Patient ID column. Default |
syndrome_cols |
Character vector. Columns to treat as syndrome flags.
If NULL, all columns except |
positive_values |
Character/logical/numeric vector. Values treated as "syndrome present". Default covers common representations of TRUE/1/Yes. |
collapse_unspecified_respiratory |
Logical. Passed to
|
keep_only_burden_syndromes |
Logical. Passed to
|
This is a convenience wrapper around prep_assign_patient_syndrome().
All syndrome-selection logic and parameters (hierarchy, burden filter,
respiratory collapsing) are handled there.
Data frame with one row per patient and the selected syndrome.
Masks a reproducible, stratified subset of genuinely observed AST cells, predicts those cells' resistance probability from a fitted model, and scores the predictions against their true values.
mask_and_validate_ast( fitted_model, fixed_effects = NULL, event_id_col = "event_id", outcome_col = NULL, fraction_to_mask = 0.05, max_mask_per_cell = NULL, seed = 123L, refit = FALSE, n_posterior_draws_for_validation = 2000L, min_tested_after_mask = 30L, min_resistant_after_mask = 5L, min_susceptible_after_mask = 5L, panel_eligibility = NULL, prior_config = NULL, sampler_config = NULL, n_gibbs_burnin = 10L, n_gibbs_kept = 20L )mask_and_validate_ast( fitted_model, fixed_effects = NULL, event_id_col = "event_id", outcome_col = NULL, fraction_to_mask = 0.05, max_mask_per_cell = NULL, seed = 123L, refit = FALSE, n_posterior_draws_for_validation = 2000L, min_tested_after_mask = 30L, min_resistant_after_mask = 5L, min_susceptible_after_mask = 5L, panel_eligibility = NULL, prior_config = NULL, sampler_config = NULL, n_gibbs_burnin = 10L, n_gibbs_kept = 20L )
fitted_model |
List returned by |
fixed_effects |
Character vector. Required when |
event_id_col |
Character. Column in |
outcome_col |
Character or |
fraction_to_mask |
Numeric in (0, 1]. Target fraction of observed
cells to mask per hospital x pathogen x class cell, before the
eligibility floor and |
max_mask_per_cell |
Integer or |
seed |
Integer. Random seed for mask selection (and posterior draw
subsampling). Default |
refit |
Logical. See modes above. Default |
n_posterior_draws_for_validation |
Integer. Default |
min_tested_after_mask, min_resistant_after_mask, min_susceptible_after_mask
|
Integer. Panel-eligibility floors enforced during masking. Default
|
panel_eligibility |
Named list or |
prior_config, sampler_config
|
Named list or |
n_gibbs_burnin, n_gibbs_kept
|
Integer. Gibbs burn-in/kept-iteration
counts forwarded to |
Two validation modes:
refit = FALSE (default)Predicts masked cells using the
already-fitted fitted_model. Because never
depends on class 's own observed value (only on event-level
covariates and random-effect memberships), this is honestly an
in-sample conditional-prediction diagnostic
(validation_mode = "in_sample_no_refit"), not a genuine
held-out test – the masked cells still contributed to estimating
beta/hospital_effect etc. It is useful for spotting
miscalibrated subgroups quickly, but is optimistic relative to a real
holdout.
refit = TRUE (preferred, more expensive)Sets the selected
cells to NA in a copy of fitted_model$event_metadata,
re-runs fit_bayesian_multivariate_probit() on the masked data,
and predicts the held-out cells from that refit
(validation_mode = "refit_masked"). This is a genuine holdout
and is the recommended final procedure once computationally
affordable.
Masking procedure: reproducible via seed; stratified by
hospital x pathogen x class x observed R/S state; for every hospital x
pathogen x class cell, at most enough cells are masked to keep
n_tested/n_resistant/n_susceptible at or above
min_tested_after_mask/min_resistant_after_mask/
min_susceptible_after_mask (panel eligibility is not destroyed);
only observed (non-NA) cells are ever candidates; and no event is
ever left with zero observed classes across all class_cols
(which would otherwise silently drop that event from a refit).
Prediction: for fitted_model$residual_structure
== "identity", is the exact model-implied
probability for a masked cell regardless of what else is known about that
event (classes are conditionally independent given ). For
"correlated", using alone would ignore every
OTHER still-observed class for that event – wrong whenever classes are
correlated. Instead each masked event's full class_cols panel is
rebuilt with the masked cell(s) set to NA and every other class at
its true observed value, and .gibbs_conditional_profile_probs() is
used to get – the same conditional-imputation machinery
used for DALY profile generation, not a marginal prediction.
Named list: predictions (one row per masked cell: hospital,
pathogen, event id, class, true value, predicted probability, log score,
Brier score, predicted class at 0.5, calibration group, validation
mode), summary (one-row aggregate: counts, mean log/Brier score,
accuracy, AUROC \[only when both classes are present in the masked set\],
masking configuration), and refit_model (the refit
fitted_model, or NULL when refit = FALSE).
Produces a clustered ComplexHeatmap::Heatmap() of the proportion of
patients Resistant, with centres on rows and antibiotics
on columns. Unlike plot_abx_heatmap (a ggplot2 tile
heatmap with a fixed row/column order), this version hierarchically
clusters both rows and columns by default, which groups centres with
similar resistance profiles and antibiotics with similar resistance
patterns together.
plot_abx_complex_heatmap( data, patient_col = "PatientInformation_id", antibiotic_col = "antibiotic_name", value_col = "antibiotic_value", organism_col = "organism_name", center_col = "center_name", low_colour = "#1a9850", mid_colour = "#fee08b", high_colour = "#d73027", midpoint = 0.5, cluster_rows = TRUE, cluster_columns = TRUE, legend_name = "Resistance", row_title = "Centres", column_title = "Antibiotics", base_size = 14, column_names_max_height = grid::unit(10, "cm"), save_path = NULL, width = 15, height = 8, dpi = 300 )plot_abx_complex_heatmap( data, patient_col = "PatientInformation_id", antibiotic_col = "antibiotic_name", value_col = "antibiotic_value", organism_col = "organism_name", center_col = "center_name", low_colour = "#1a9850", mid_colour = "#fee08b", high_colour = "#d73027", midpoint = 0.5, cluster_rows = TRUE, cluster_columns = TRUE, legend_name = "Resistance", row_title = "Centres", column_title = "Antibiotics", base_size = 14, column_names_max_height = grid::unit(10, "cm"), save_path = NULL, width = 15, height = 8, dpi = 300 )
data |
Data frame. Long-format AMR dataset. |
patient_col |
Character. Patient ID column.
Default |
antibiotic_col |
Character. Antibiotic name column.
Default |
value_col |
Character. Susceptibility result column (R/S values).
Default |
organism_col |
Character. Organism name column.
Default |
center_col |
Character. Centre/facility column.
Default |
low_colour |
Character. Colour for proportion = 0 (fully
susceptible). Default |
mid_colour |
Character. Colour for the midpoint.
Default |
high_colour |
Character. Colour for proportion = 1 (fully
resistant). Default |
midpoint |
Numeric. Midpoint of the colour gradient (0-1).
Default |
cluster_rows |
Logical. Hierarchically cluster centres.
Default |
cluster_columns |
Logical. Hierarchically cluster antibiotics.
Default |
legend_name |
Character. Heatmap legend title.
Default |
row_title |
Character. Row-axis title. Default |
column_title |
Character. Column-axis title.
Default |
base_size |
Numeric. Base font size for titles/labels. Default 14. |
column_names_max_height |
|
save_path |
Character or |
width |
Numeric. PNG width in inches. Used only when
|
height |
Numeric. PNG height in inches. Used only when
|
dpi |
Numeric. PNG resolution. Used only when
|
Only R and S results are used. The same worst-phenotype rule as
plot_abx_heatmap() is applied: per patient x organism x antibiotic,
any single R marks the episode as R. Centre/antibiotic combinations with no
tests are shown as 0 (fully susceptible) in the underlying matrix – there
is no "no data" grey cell in this version, since Heatmap() requires
a complete numeric matrix.
Requires the Bioconductor package ComplexHeatmap and the CRAN
package circlize, neither of which is a hard dependency of
anumaan. Install with:
if (!requireNamespace("BiocManager", quietly = TRUE))
install.packages("BiocManager"); BiocManager::install("ComplexHeatmap")
and install.packages("circlize").
A ComplexHeatmap::Heatmap object (draw with
ComplexHeatmap::draw(ht) if not saving to file).
Produces a ggplot2 tile heatmap where:
x-axis – antibiotics (ordered by total patients tested, most tested on the left)
y-axis – centres
fill colour – proportion of patients who were Resistant for that antibiotic at that centre (0 = fully susceptible, 1 = fully resistant)
plot_abx_heatmap( data, n = NULL, mode = c("all", "single"), center = NULL, patient_col = "PatientInformation_id", antibiotic_col = "antibiotic_name", value_col = "antibiotic_value", organism_col = "organism_name", center_col = "center_name", show_values = TRUE, midpoint = 0.5, low_colour = "#1a9850", mid_colour = "#fee08b", high_colour = "#d73027", base_size = 14, title = NULL, syndrome_col = NULL, syndrome_name = NULL )plot_abx_heatmap( data, n = NULL, mode = c("all", "single"), center = NULL, patient_col = "PatientInformation_id", antibiotic_col = "antibiotic_name", value_col = "antibiotic_value", organism_col = "organism_name", center_col = "center_name", show_values = TRUE, midpoint = 0.5, low_colour = "#1a9850", mid_colour = "#fee08b", high_colour = "#d73027", base_size = 14, title = NULL, syndrome_col = NULL, syndrome_name = NULL )
data |
Data frame. Long-format AMR dataset. |
n |
Integer or |
mode |
Character. |
center |
Character. Required when |
patient_col |
Character. Patient ID column.
Default |
antibiotic_col |
Character. Antibiotic name column.
Default |
value_col |
Character. Susceptibility result column (R/S values).
Default |
organism_col |
Character. Organism name column.
Default |
center_col |
Character. Centre/facility column.
Default |
show_values |
Logical. Print proportion values inside tiles.
Default |
midpoint |
Numeric. Midpoint of the colour gradient (0-1).
Default |
low_colour |
Character. Colour for proportion = 0 (fully
susceptible). Default |
mid_colour |
Character. Colour for the midpoint.
Default |
high_colour |
Character. Colour for proportion = 1 (fully
resistant). Default |
base_size |
Numeric. Base font size. Default 14. |
title |
Character. Custom plot title. Auto-generated if
|
syndrome_col |
Character or |
syndrome_name |
Character or |
Only R and S results are used. The same worst-phenotype rule
as plot_abx_susceptibility() is applied: per patient x organism x
antibiotic, any single R marks the episode as R.
Cells with no data (antibiotic not tested at that centre) are shown in light grey.
Supports two display modes:
"all" (default) – all centres on the y-axis.
"single" – filter to one centre before plotting (produces a single-row heatmap useful for per-centre reports).
A ggplot object.
Produces a horizontal stacked bar chart showing the number of admissions
tested as Resistant (R) or Susceptible (S) for the top n antibiotics.
Percentage labels are shown inside each bar segment.
plot_abx_susceptibility( data, n = 5, mode = c("faceted", "overall", "single"), center = NULL, patient_col = "PatientInformation_id", antibiotic_col = "antibiotic_name", value_col = "antibiotic_value", organism_col = "organism_name", center_col = "center_name", colours = c(R = "#D73027", S = "#1A9850"), ncol = 2, base_size = 14, title = NULL, syndrome_col = NULL, syndrome_name = NULL )plot_abx_susceptibility( data, n = 5, mode = c("faceted", "overall", "single"), center = NULL, patient_col = "PatientInformation_id", antibiotic_col = "antibiotic_name", value_col = "antibiotic_value", organism_col = "organism_name", center_col = "center_name", colours = c(R = "#D73027", S = "#1A9850"), ncol = 2, base_size = 14, title = NULL, syndrome_col = NULL, syndrome_name = NULL )
data |
Data frame. Long-format AMR dataset. |
n |
Integer. Number of top antibiotics to show (ranked by total patients tested). Default 5. |
mode |
Character. One of |
center |
Character. Required when |
patient_col |
Character. Patient ID column.
Default |
antibiotic_col |
Character. Antibiotic name column.
Default |
value_col |
Character. Susceptibility result column containing
"R" and "S" values. Default |
organism_col |
Character. Organism name column (used in
worst-phenotype deduplication). Default |
center_col |
Character. Centre/facility column.
Default |
colours |
Named character vector. Fill colours for R and S.
Default |
ncol |
Integer. Facet columns ( |
base_size |
Numeric. Base font size. Default 14. |
title |
Character. Custom plot title. Auto-generated if
|
syndrome_col |
Character or |
syndrome_name |
Character or |
Worst-phenotype rule: when a patient has multiple records for the same organism-antibiotic combination, any single R result marks the whole episode as R. This prevents double-counting repeat cultures from the same infection episode.
Counting unit: bars show unique patients (not isolate rows), so a patient tested against the same antibiotic twice is counted once.
Supports three display modes:
"faceted" – top n antibiotics per centre independently, one panel per centre.
"overall" – all centres pooled; top n antibiotics globally.
"single" – one specific centre; pass the centre name via
center.
A ggplot object.
Visualises the distribution of patient age on the x-axis using either a
stacked ridge plot (mode = "all") or a single-centre density curve
(mode = "single").
plot_age_ridge( data, mode = c("all", "single"), center = NULL, patient_col = "PatientInformation_id", age_col = "age_years", center_col = "center_name", min_age = 0, max_age = 120, colours = NULL, scale = 1.2, alpha = 0.7, base_size = 14, title = NULL, syndrome_col = NULL, syndrome_name = NULL )plot_age_ridge( data, mode = c("all", "single"), center = NULL, patient_col = "PatientInformation_id", age_col = "age_years", center_col = "center_name", min_age = 0, max_age = 120, colours = NULL, scale = 1.2, alpha = 0.7, base_size = 14, title = NULL, syndrome_col = NULL, syndrome_name = NULL )
data |
A data frame. |
mode |
Character. One of |
center |
Character. Centre name required when |
patient_col |
Character. Column of patient identifiers. |
age_col |
Character. Column of patient age (numeric, in years).
Default |
center_col |
Character. Column of centre identifiers. |
min_age |
Numeric. Minimum age to include. Default |
max_age |
Numeric. Maximum age to include. Default |
colours |
Named character vector of colours for centres. If |
scale |
Numeric. |
alpha |
Numeric. Fill transparency (0-1). Default |
base_size |
Numeric. Base font size. Default |
title |
Character or |
syndrome_col |
Character or |
syndrome_name |
Character or |
One row per unique patient x centre is retained before plotting.
Rows with age outside [min_age, max_age] are dropped.
A ggplot object.
Produces a horizontal grouped bar chart comparing the associated and attributable burden (YLL or YLD) per 1 000 patients across hospitals. Bars are sorted by the associated value (largest at top by default). Each bar is labelled with its rounded value.
plot_burden_by_hospital( data, metric = c("YLL", "YLD"), facility_col = "center_name", center_col = NULL, assoc_col = NULL, attr_col = NULL, syndrome_col = NULL, syndrome_name = NULL, sort_by = c("associated", "attributable", "none"), label_digits = 1, colours = NULL, base_size = 14, title = NULL, subtitle = NULL )plot_burden_by_hospital( data, metric = c("YLL", "YLD"), facility_col = "center_name", center_col = NULL, assoc_col = NULL, attr_col = NULL, syndrome_col = NULL, syndrome_name = NULL, sort_by = c("associated", "attributable", "none"), label_digits = 1, colours = NULL, base_size = 14, title = NULL, subtitle = NULL )
data |
Data frame. One row per hospital (or one row per
hospital x syndrome). Must contain the columns named by
|
metric |
Character. |
facility_col |
Character. Column containing hospital / facility
names. Default |
center_col |
Deprecated alias for |
assoc_col |
Character or |
attr_col |
Character or |
syndrome_col |
Character or |
syndrome_name |
Character or |
sort_by |
Character. |
label_digits |
Integer. Decimal places in bar value labels. Default 1. |
colours |
Named character vector with exactly two elements:
|
base_size |
Numeric. Base font size. Default 14. |
title |
Character. Custom plot title. Auto-generated if
|
subtitle |
Character. Custom subtitle. Auto-generated if
|
The input data should be a hospital-level summary data frame
(e.g. the output of compute_hospital_daly()) that already contains
the per-1 000 columns. If the summary was computed across multiple
syndromes, use syndrome_col and syndrome_name to restrict
the plot to one syndrome before pivoting.
A ggplot object.
Produces a horizontal grouped bar chart showing the top n organisms
ranked by their associated burden (YLL or YLD), with a paired attributable
bar alongside each. Organisms are ranked by the associated value so the
highest-burden pathogen appears at the top.
plot_burden_by_organism( data, metric = c("YLL", "YLD"), n = 10, organism_col = NULL, assoc_col = NULL, attr_col = NULL, n_admissions = NULL, syndrome_col = NULL, syndrome_name = NULL, label_digits = 1, colours = NULL, base_size = 14, title = NULL, subtitle = NULL )plot_burden_by_organism( data, metric = c("YLL", "YLD"), n = 10, organism_col = NULL, assoc_col = NULL, attr_col = NULL, n_admissions = NULL, syndrome_col = NULL, syndrome_name = NULL, label_digits = 1, colours = NULL, base_size = 14, title = NULL, subtitle = NULL )
data |
Data frame. One row per organism. Must contain the
columns named by |
metric |
Character. |
n |
Integer. Number of top organisms to display. Default 10. |
organism_col |
Character or |
assoc_col |
Character or |
attr_col |
Character or |
n_admissions |
Numeric or |
syndrome_col |
Character or |
syndrome_name |
Character or |
label_digits |
Integer. Decimal places in bar value labels. Default 1. |
colours |
Named character vector with elements |
base_size |
Numeric. Base font size. Default 14. |
title |
Character. Custom plot title. Auto-generated if
|
subtitle |
Character. Custom subtitle. Auto-generated if
|
The input data should be a pathogen-level summary data frame with
one row per organism, already containing both the associated and attributable
burden columns. For YLD this is typically the output of
compute_yld_associated() left-joined with
compute_yld_attributable(). For YLL it is the
by_pathogen slot of compute_yll_associated() left-joined with
the equivalent slot from compute_yll_attributable().
A ggplot object.
Produces a side-by-side (dodged) bar chart comparing Death and Discharged
patient counts for the top n organisms. LAMA and Referred are
excluded – only the two definitive outcomes are shown.
plot_death_discharged( data, n = 5, mode = c("faceted", "overall", "single"), center = NULL, resistance_filter = NULL, patient_col = "PatientInformation_id", organism_col = "organism_name", outcome_col = "final_outcome", center_col = "center_name", antibiotic_col = "antibiotic_name", value_col = "antibiotic_value", death_label = "Death", discharged_label = "Discharged", colours = NULL, bar_width = 0.65, ncol = 2, base_size = 14, title = NULL, syndrome_col = NULL, syndrome_name = NULL )plot_death_discharged( data, n = 5, mode = c("faceted", "overall", "single"), center = NULL, resistance_filter = NULL, patient_col = "PatientInformation_id", organism_col = "organism_name", outcome_col = "final_outcome", center_col = "center_name", antibiotic_col = "antibiotic_name", value_col = "antibiotic_value", death_label = "Death", discharged_label = "Discharged", colours = NULL, bar_width = 0.65, ncol = 2, base_size = 14, title = NULL, syndrome_col = NULL, syndrome_name = NULL )
data |
Data frame. Long-format AMR dataset. |
n |
Integer. Number of top organisms to show. Default 5. |
mode |
Character. One of |
center |
Character. Required when |
resistance_filter |
Character or |
patient_col |
Character. Patient ID column.
Default |
organism_col |
Character. Organism name column.
Default |
outcome_col |
Character. Final outcome column.
Default |
center_col |
Character. Centre/facility column.
Default |
antibiotic_col |
Character. Antibiotic name column. Only used when
|
value_col |
Character. Susceptibility result column (R/S).
Only used when |
death_label |
Character. Exact string used for death in the
outcome column. Default |
discharged_label |
Character. Exact string used for discharged.
Default |
colours |
Named character vector with keys matching
|
bar_width |
Numeric. Width of each individual bar (0-1).
Default |
ncol |
Integer. Facet columns
( |
base_size |
Numeric. Base font size. Default 14. |
title |
Character. Custom title. Auto-generated if
|
syndrome_col |
Character or |
syndrome_name |
Character or |
Each bar is labelled with the count and the percentage that outcome
represents out of all Death + Discharged patients for that organism
(e.g. 45 (32%) on a Death bar means 45 patients died, which is
32% of the organism's known outcomes). This makes the mortality rate
immediately readable without a separate calculation.
Deduplication: uses
distinct(centre, patient, organism, outcome) – one record per
patient per organism per outcome – consistent with the original EDA script.
Top N organisms are ranked by total unique patients with a known
outcome (Death or Discharged). For mode = "faceted" the ranking is
done independently per centre; for "overall" it is done globally.
Supports three display modes:
"faceted" (default) – one panel per centre.
"overall" – all centres pooled into one chart.
"single" – one specific centre.
A ggplot object.
Derives Healthcare-Associated Infection (HAI) vs Community-Associated
Infection (CAI) status from dates, then produces a stacked bar chart
showing unique patient counts per centre. Each bar carries count and
percentage labels inside each segment, and an n= total label
above.
plot_hai_cai_by_facility( data, patient_col = "PatientInformation_id", center_col = "center_name", admission_col = "admission_date", culture_col = "culture_date", hai_threshold_hours = 48, hai_label = "HAI", cai_label = "CAI", colours = NULL, base_size = 14, title = NULL, syndrome_col = NULL, syndrome_name = NULL )plot_hai_cai_by_facility( data, patient_col = "PatientInformation_id", center_col = "center_name", admission_col = "admission_date", culture_col = "culture_date", hai_threshold_hours = 48, hai_label = "HAI", cai_label = "CAI", colours = NULL, base_size = 14, title = NULL, syndrome_col = NULL, syndrome_name = NULL )
data |
Data frame. Long-format AMR dataset. |
patient_col |
Character. Patient ID column.
Default |
center_col |
Character. Centre/facility column.
Default |
admission_col |
Character. Admission date column.
Default |
culture_col |
Character. Culture/specimen date column.
Default |
hai_threshold_hours |
Numeric. Hours from admission to first
culture at or above which a case is classified as HAI. Default |
hai_label |
Character. Label for HAI bars.
Default |
cai_label |
Character. Label for CAI bars.
Default |
colours |
Named character vector. Fill colours keyed
by |
base_size |
Numeric. Base font size. Default |
title |
Character. Custom title. Auto-generated if
|
syndrome_col |
Character or |
syndrome_name |
Character or |
Classification rule: for each patient x centre, the earliest
culture date is used. If the time from admission to that culture is
hai_threshold_hours (default 48 h), the patient is
classified as HAI; otherwise CAI. The existing type_of_infection
column in the dataset is ignored – classification is derived
entirely from dates.
Deduplication: one classification per patient per centre (earliest culture date).
A ggplot object.
100
types (e.g. HAI vs CAI) among patients in each location (e.g. ICU vs Ward).
Each bar is normalised within its location, so the two bars in a
panel directly compare
– i.e. whether infection type is associated with location, per hospital.
plot_infection_type_by_location( data, patient_col = "PatientInformation_id", center_col = "center_name", location_col = "location", infection_col = "infection_type", location_levels = c("ICU", "Ward"), infection_levels = c("HAI", "CAI"), style = c("bar", "heatmap"), colours = NULL, ncol = 5, base_size = 12, show_counts = TRUE, title = NULL )plot_infection_type_by_location( data, patient_col = "PatientInformation_id", center_col = "center_name", location_col = "location", infection_col = "infection_type", location_levels = c("ICU", "Ward"), infection_levels = c("HAI", "CAI"), style = c("bar", "heatmap"), colours = NULL, ncol = 5, base_size = 12, show_counts = TRUE, title = NULL )
data |
Data frame. Long-format AMR / cleaned stewardship data. |
patient_col |
Character. Patient ID column.
Default |
center_col |
Character. Centre/facility column.
Default |
location_col |
Character. Location column. Default |
infection_col |
Character. Infection-type column.
Default |
location_levels |
Character vector. Location values to keep (become the
x-axis bars). Default |
infection_levels |
Character vector. Infection-type values to keep
(become the stacked fills). Default |
style |
Character. |
colours |
Named character vector of fill colours keyed by
|
ncol |
Integer. Number of facet columns. Default |
base_size |
Numeric. Base font size. Default |
show_counts |
Logical. Print unique-patient counts inside each
segment. Default |
title |
Character. Custom title. Auto-generated if |
Deduplication: unique patients per centre x location x infection
type. Only the requested location_levels and infection_levels
are kept (other/blank/compound values are dropped).
A ggplot object (one panel per centre).
Produces a dodged bar chart showing the number of unique patients in each
location type (ICU, Ward, Other) per facility. Raw location strings are
normalised automatically via case-insensitive pattern matching, so
centre-specific ICU names (e.g. "Respiratory ICU (RICU)") all map
to "ICU".
plot_location_by_facility( data, patient_col = "PatientInformation_id", location_col = "location", center_col = "center_name", icu_pattern = "icu", ward_pattern = "ward", icu_label = "ICU", ward_label = "Ward", other_label = "Other", colours = NULL, bar_width = 0.68, base_size = 14, title = NULL, syndrome_col = NULL, syndrome_name = NULL )plot_location_by_facility( data, patient_col = "PatientInformation_id", location_col = "location", center_col = "center_name", icu_pattern = "icu", ward_pattern = "ward", icu_label = "ICU", ward_label = "Ward", other_label = "Other", colours = NULL, bar_width = 0.68, base_size = 14, title = NULL, syndrome_col = NULL, syndrome_name = NULL )
data |
Data frame. Long-format AMR dataset. |
patient_col |
Character. Patient ID column.
Default |
location_col |
Character. Location/unit column.
Default |
center_col |
Character. Centre/facility column.
Default |
icu_pattern |
Character. Case-insensitive regex pattern that
identifies ICU values. Default |
ward_pattern |
Character. Case-insensitive regex pattern that
identifies Ward values. Default |
icu_label |
Character. Display label for ICU bars.
Default |
ward_label |
Character. Display label for Ward bars.
Default |
other_label |
Character. Display label for all other locations.
Default |
colours |
Named character vector. Fill colours keyed by
|
bar_width |
Numeric. Width of each individual bar.
Default |
base_size |
Numeric. Base font size. Default |
title |
Character. Custom title. Auto-generated if
|
syndrome_col |
Character or |
syndrome_name |
Character or |
Normalisation: a location value is classified as:
ICU – if the lower-cased string contains
icu_pattern (default "icu")
Ward – else if it contains ward_pattern
(default "ward")
Other – everything else
Deduplication: distinct(patient, centre, location type) –
each unique patient-centre-location combination is counted once.
A ggplot object.
Displays the distribution of LOS (y-axis, log10 scale) across patient age
groups (x-axis) using boxplots. Supports "faceted" (one panel per
centre), "overall" (all centres pooled), and "single"
(one centre) modes.
plot_los_by_agebin( data, mode = c("faceted", "overall", "single"), center = NULL, patient_col = "PatientInformation_id", agebin_col = "Age_bin", age_col = "age_years", age_breaks = NULL, age_labels = NULL, center_col = "center_name", admission_col = "admission_date", discharge_col = "final_outcome_date", min_los = 1, max_los = 365, age_levels = NULL, fill_colour = "#2C7FB8", fill_alpha = 0.7, outlier_alpha = 0.25, box_width = 0.6, ncol = 3, base_size = 14, title = NULL, subtitle = NULL, syndrome_col = NULL, syndrome_name = NULL )plot_los_by_agebin( data, mode = c("faceted", "overall", "single"), center = NULL, patient_col = "PatientInformation_id", agebin_col = "Age_bin", age_col = "age_years", age_breaks = NULL, age_labels = NULL, center_col = "center_name", admission_col = "admission_date", discharge_col = "final_outcome_date", min_los = 1, max_los = 365, age_levels = NULL, fill_colour = "#2C7FB8", fill_alpha = 0.7, outlier_alpha = 0.25, box_width = 0.6, ncol = 3, base_size = 14, title = NULL, subtitle = NULL, syndrome_col = NULL, syndrome_name = NULL )
data |
A data frame. |
mode |
Character. One of |
center |
Character. Centre name required when |
patient_col |
Character. Column of patient identifiers. |
agebin_col |
Character. Pre-existing age group column. Used when
|
age_col |
Character. Continuous age column used when |
age_breaks |
Numeric vector or |
age_labels |
Character vector or |
center_col |
Character. Column of centre identifiers. |
admission_col |
Character. Admission date column. Default
|
discharge_col |
Character. Discharge / final outcome date column.
Default |
min_los |
Numeric. Minimum LOS (days) to include. Default |
max_los |
Numeric. Maximum LOS (days) to include. Default |
age_levels |
Character vector or |
fill_colour |
Character. Box fill colour. Default |
fill_alpha |
Numeric. Box fill transparency (0-1). Default |
outlier_alpha |
Numeric. Outlier point transparency (0-1). Default
|
box_width |
Numeric. Width of each box. Default |
ncol |
Integer. Number of facet columns ( |
base_size |
Numeric. Base font size. Default |
title |
Character or |
subtitle |
Character or |
syndrome_col |
Character or |
syndrome_name |
Character or |
LOS is computed as difftime(discharge_col, admission_col, units = "days").
One row per unique patient x centre x admission x discharge is retained.
Rows with LOS < min_los or LOS > max_los are dropped.
Two ways to supply age groups:
Pre-existing column (default) – set agebin_col to an
existing categorical column (e.g. "Age_bin"). Bins are sorted
automatically (<1, 1-5, ..., 85+); override order
with age_levels.
Custom breaks from continuous age – set age_breaks
to a numeric vector (e.g. c(0, 5, 15, 30, 50, 70, Inf)) and
age_col to the continuous age column (default "age_years").
Bins are derived via cut() and labelled automatically.
agebin_col is ignored when age_breaks is provided.
A ggplot object.
Creates a histogram of LOS values with Weibull, Lognormal, and Gamma density curves overlaid.
plot_los_distributions(los_vec, title, bins = 35, fits = NULL)plot_los_distributions(los_vec, title, bins = 35, fits = NULL)
los_vec |
Numeric vector of LOS values (days). |
title |
Character. Plot title. |
bins |
Integer. Number of histogram bins. Default 35. |
fits |
Optional. Pre-computed fits from |
A ggplot object.
plot_los_distributions(rlnorm(200, 2, 0.5), "Example LOS Distribution")plot_los_distributions(rlnorm(200, 2, 0.5), "Example LOS Distribution")
Visualises the distribution of length of stay (LOS) on a log10 x-axis using
either a stacked ridge plot (mode = "all") or a single-centre density
curve (mode = "single").
plot_los_ridge( data, mode = c("all", "single"), center = NULL, patient_col = "patient_id", center_col = "center_name", admission_col = "admission_date", discharge_col = "final_outcome_date", filter_outcome = NULL, outcome_col = "final_outcome", min_los = 1, max_los = 365, colours = NULL, scale = 1.2, alpha = 0.7, base_size = 14, title = NULL, syndrome_col = NULL, syndrome_name = NULL )plot_los_ridge( data, mode = c("all", "single"), center = NULL, patient_col = "patient_id", center_col = "center_name", admission_col = "admission_date", discharge_col = "final_outcome_date", filter_outcome = NULL, outcome_col = "final_outcome", min_los = 1, max_los = 365, colours = NULL, scale = 1.2, alpha = 0.7, base_size = 14, title = NULL, syndrome_col = NULL, syndrome_name = NULL )
data |
A data frame. |
mode |
Character. One of |
center |
Character. Centre name required when |
patient_col |
Character. Column of patient identifiers. |
center_col |
Character. Column of centre identifiers. |
admission_col |
Character. Column containing admission date/datetime.
Default |
discharge_col |
Character. Column containing discharge / final outcome
date. Default |
filter_outcome |
Character or |
outcome_col |
Character. Column of patient outcomes, used only when
|
min_los |
Numeric. Minimum LOS (days) to include. Rows below this
are removed (prevents |
max_los |
Numeric. Maximum LOS (days) to include. Default |
colours |
Named character vector of colours for centres. If |
scale |
Numeric. |
alpha |
Numeric. Fill transparency (0-1). Default |
base_size |
Numeric. Base font size. Default |
title |
Character or |
syndrome_col |
Character or |
syndrome_name |
Character or |
LOS is computed as
difftime(discharge_col, admission_col, units = "days").
One row per unique patient x centre x admission_date x discharge_date is
retained before plotting. Rows with LOS < min_los or
LOS > max_los are dropped.
A ggplot object.
Produces a dodged bar chart comparing the number of unique patients with Monomicrobial vs Polymicrobial infections at each centre. Hospitals appear on the x-axis; the two bars per hospital are coloured by infection type. Count labels are printed above each bar.
plot_mono_poly_by_facility( data, patient_col = "PatientInformation_id", poly_col = "is_polymicrobial", center_col = "center_name", mono_label = "Monomicrobial", poly_label = "Polymicrobial", colours = NULL, bar_width = 0.68, base_size = 14, title = NULL, syndrome_col = NULL, syndrome_name = NULL )plot_mono_poly_by_facility( data, patient_col = "PatientInformation_id", poly_col = "is_polymicrobial", center_col = "center_name", mono_label = "Monomicrobial", poly_label = "Polymicrobial", colours = NULL, bar_width = 0.68, base_size = 14, title = NULL, syndrome_col = NULL, syndrome_name = NULL )
data |
Data frame. Long-format AMR dataset. |
patient_col |
Character. Patient ID column.
Default |
poly_col |
Character. Column with binary infection type
( |
center_col |
Character. Centre/facility column.
Default |
mono_label |
Character. Label for monomicrobial bars.
Default |
poly_label |
Character. Label for polymicrobial bars.
Default |
colours |
Named character vector. Fill colours keyed by
|
bar_width |
Numeric. Width of each individual bar. Default |
base_size |
Numeric. Base font size. Default |
title |
Character. Custom title. Auto-generated if |
syndrome_col |
Character or |
syndrome_name |
Character or |
Deduplication: distinct(patient, centre, infection type) –
each unique patient-centre-infection type combination is counted once. A
patient who has both mono and polymicrobial episodes at the same centre
contributes to both bars, matching the original EDA script.
Infection type: the poly_col column is expected to contain
binary values (0 = Monomicrobial, 1 = Polymicrobial). The
labels shown in the legend and plot are controlled by mono_label
and poly_label.
A ggplot object.
Companion to plot_omega_correlation_heatmap() – shows Rhat for
each Omega[i,j] entry, so a reader cannot look at an attractive
correlation heatmap without also seeing whether those specific
parameters actually converged. A uniformly high correlation heatmap
alongside a uniformly poor Rhat heatmap here is the signature of a
near-degenerate, weakly-identified correlation matrix, not a settled
finding.
plot_omega_convergence_heatmap(corr_summary, class_cols, title_base = "")plot_omega_convergence_heatmap(corr_summary, class_cols, title_base = "")
corr_summary |
Tibble from |
class_cols |
Character vector of all class names, in the fit's canonical order (for consistent row/column ordering). |
title_base |
Character. Prefixed to the plot title. |
A ggplot object, or NULL if corr_summary is
NULL/empty or has no rhat column (e.g. computed by an
older summarize_fit_correlation_matrix() call).
Rows/columns are antimicrobial classes; each cell is the posterior
median of the corresponding Omega[i,j] (or R_block[r,i,j])
entry. Only meaningful for correlated-residual fits – pass NULL
(e.g. an identity-residual fit's summarize_fit_correlation_matrix()
result) to get NULL back rather than an empty/misleading plot.
plot_omega_correlation_heatmap( corr_summary, class_cols, title_base = "", rhat_flag_threshold = 1.01 )plot_omega_correlation_heatmap( corr_summary, class_cols, title_base = "", rhat_flag_threshold = 1.01 )
corr_summary |
Tibble from |
class_cols |
Character vector of all class names, in the fit's canonical order (for consistent row/column ordering). |
title_base |
Character. Prefixed to the plot title. |
rhat_flag_threshold |
Numeric. Cells with |
A ggplot object, or NULL if corr_summary is
NULL/empty.
A multivariate-probit correlated-residual fit can push Omega toward a near-singular boundary (very high pairwise correlations across the board) without that being visible from any single Omega\[i,j\] entry. For each posterior draw this computes the smallest eigenvalue of the full D x D Omega matrix – a value approaching 0 means that specific draw's correlation matrix is nearly singular – and reports the distribution across draws, plus the condition number (largest / smallest eigenvalue) as a supplementary summary.
plot_omega_degeneracy_diagnostic( fit, class_cols, title_base = "", degenerate_threshold = 0.05 )plot_omega_degeneracy_diagnostic( fit, class_cols, title_base = "", degenerate_threshold = 0.05 )
fit |
List returned by |
class_cols |
Character vector of all class names, in the fit's canonical order. |
title_base |
Character. Prefixed to the plot title. |
degenerate_threshold |
Numeric. Draws with smallest eigenvalue below
this are counted as "near-degenerate" in the subtitle. Default |
A ggplot object, or NULL if this is not a correlated-residual
fit, or Omega draws are unavailable.
The two heatmaps show the correlation estimate and its Rhat as separate pictures; this page puts every number for every class pair – median rho, credible interval, Rhat, bulk and tail ESS – in one table, for a reader who wants the exact figures rather than reading them off a colour scale.
plot_omega_summary_table(corr_summary, class_cols, title_base = "")plot_omega_summary_table(corr_summary, class_cols, title_base = "")
corr_summary |
Tibble from |
class_cols |
Character vector of all class names, in the fit's canonical order (for consistent row/column ordering). |
title_base |
Character. Prefixed to the plot title. |
A ggplot object (table page), or NULL if corr_summary
is NULL/empty.
Produces a horizontal 100% stacked bar chart showing how final outcomes
(Death, Discharged, LAMA, Referred) are distributed across age groups.
Each bar represents one age bin and sums to 100%. An n= label above
each bar shows the total patients in that age group.
plot_outcome_by_agebin( data, mode = c("faceted", "overall", "single"), center = NULL, patient_col = "PatientInformation_id", agebin_col = "Age_bin", outcome_col = "final_outcome", center_col = "center_name", merge_referred = TRUE, age_levels = NULL, palette = c(Death = "#E74C3C", Died = "#E74C3C", Discharged = "#2ECC71", LAMA = "#95A5A6", Referred = "#3498DB", `Transferred to other hospital` = "#3498DB"), ncol = 2, base_size = 14, title = NULL, syndrome_col = NULL, syndrome_name = NULL )plot_outcome_by_agebin( data, mode = c("faceted", "overall", "single"), center = NULL, patient_col = "PatientInformation_id", agebin_col = "Age_bin", outcome_col = "final_outcome", center_col = "center_name", merge_referred = TRUE, age_levels = NULL, palette = c(Death = "#E74C3C", Died = "#E74C3C", Discharged = "#2ECC71", LAMA = "#95A5A6", Referred = "#3498DB", `Transferred to other hospital` = "#3498DB"), ncol = 2, base_size = 14, title = NULL, syndrome_col = NULL, syndrome_name = NULL )
data |
Data frame. Long-format AMR dataset. |
mode |
Character. One of |
center |
Character. Required when |
patient_col |
Character. Patient ID column.
Default |
agebin_col |
Character. Age bin column. Default |
outcome_col |
Character. Final outcome column.
Default |
center_col |
Character. Centre/facility column.
Default |
merge_referred |
Logical. Recode
|
age_levels |
Character vector or |
palette |
Named character vector. Outcome -> fill colour mapping. Unmatched outcomes receive grey. Default uses red/green/grey/blue preset. |
ncol |
Integer. Facet columns ( |
base_size |
Numeric. Base font size. Default 14. |
title |
Character. Custom title. Auto-generated if
|
syndrome_col |
Character or |
syndrome_name |
Character or |
Deduplication: one record per patient per centre – first recorded outcome and age bin per patient per centre. Each patient contributes exactly one bar segment per centre.
Age bin ordering: bins are ordered numerically (<1,
1-5, 5-10, ..., 85+) automatically. Supply
age_levels to override with a custom order.
Supports three display modes:
"faceted" (default) – one panel per centre.
"overall" – all centres pooled; one chart.
"single" – one specific centre.
A ggplot object.
Produces a 100% horizontal stacked bar chart showing the distribution of
final outcomes (Death, Discharged, LAMA, Referred) for the top n
organisms, split by whether the patient had a Resistant or Susceptible
result.
plot_outcome_by_organism( data, n = 5, resistance_filter = c("R", "S"), mode = c("faceted", "overall", "single"), center = NULL, patient_col = "PatientInformation_id", organism_col = "organism_name", antibiotic_col = "antibiotic_name", value_col = "antibiotic_value", outcome_col = "final_outcome", center_col = "center_name", merge_referred = TRUE, palette = c(Death = "#E74C3C", Died = "#E74C3C", Discharged = "#2ECC71", LAMA = "#95A5A6", Referred = "#3498DB", `Transferred to other hospital` = "#3498DB"), ncol = 2, base_size = 14, title = NULL, syndrome_col = NULL, syndrome_name = NULL )plot_outcome_by_organism( data, n = 5, resistance_filter = c("R", "S"), mode = c("faceted", "overall", "single"), center = NULL, patient_col = "PatientInformation_id", organism_col = "organism_name", antibiotic_col = "antibiotic_name", value_col = "antibiotic_value", outcome_col = "final_outcome", center_col = "center_name", merge_referred = TRUE, palette = c(Death = "#E74C3C", Died = "#E74C3C", Discharged = "#2ECC71", LAMA = "#95A5A6", Referred = "#3498DB", `Transferred to other hospital` = "#3498DB"), ncol = 2, base_size = 14, title = NULL, syndrome_col = NULL, syndrome_name = NULL )
data |
Data frame. Long-format AMR dataset. |
n |
Integer. Number of top organisms to show. Default 5. |
resistance_filter |
Character. |
mode |
Character. One of |
center |
Character. Required when |
patient_col |
Character. Patient ID column.
Default |
organism_col |
Character. Organism name column.
Default |
antibiotic_col |
Character. Antibiotic name column.
Default |
value_col |
Character. Susceptibility result column (R/S).
Default |
outcome_col |
Character. Final outcome column.
Default |
center_col |
Character. Centre/facility column.
Default |
merge_referred |
Logical. Recode
|
palette |
Named character vector mapping outcome values to colours. Unmatched outcomes get grey automatically. |
ncol |
Integer. Facet columns
( |
base_size |
Numeric. Base font size. Default 14. |
title |
Character. Custom title. Auto-generated if
|
syndrome_col |
Character or |
syndrome_name |
Character or |
Each bar represents one organism. The fill shows outcome proportions.
A n= label is printed above each bar showing the total number of
unique patients in that organism x resistance group.
Resistance grouping: resistance_filter = "R" shows patients
who had at least one R result for the given organism. "S" shows
patients with only S results. Because these groups overlap (a patient
resistant to one antibiotic may be susceptible to another), calling the
function twice – once for "R" and once for "S" – gives the most complete
picture.
Top N organisms are ranked by total unique patients per centre
(or globally for mode = "overall"), calculated before the R/S
split so the same organisms appear in both R and S plots.
Supports three display modes:
"faceted" (default) – one panel per centre.
"overall" – all centres pooled.
"single" – one specific centre.
A ggplot object.
Produces a stacked bar chart where the x-axis shows the year derived from
date_col, the y-axis shows the number of unique patients, and bars
are filled by final outcome category. Each bar segment is labelled with
count and percentage; a total n= label sits above each bar.
plot_outcome_by_year( data, mode = c("faceted", "overall", "single"), center = NULL, patient_col = "PatientInformation_id", outcome_col = "final_outcome", date_col = "final_outcome_date", center_col = "center_name", merge_referred = TRUE, palette = c(Death = "#E74C3C", Died = "#E74C3C", Discharged = "#2ECC71", LAMA = "#95A5A6", Referred = "#3498DB", `Transferred to other hospital` = "#3498DB"), ncol = 2, base_size = 14, title = NULL, syndrome_col = NULL, syndrome_name = NULL )plot_outcome_by_year( data, mode = c("faceted", "overall", "single"), center = NULL, patient_col = "PatientInformation_id", outcome_col = "final_outcome", date_col = "final_outcome_date", center_col = "center_name", merge_referred = TRUE, palette = c(Death = "#E74C3C", Died = "#E74C3C", Discharged = "#2ECC71", LAMA = "#95A5A6", Referred = "#3498DB", `Transferred to other hospital` = "#3498DB"), ncol = 2, base_size = 14, title = NULL, syndrome_col = NULL, syndrome_name = NULL )
data |
Data frame. Long-format AMR dataset. |
mode |
Character. One of |
center |
Character. Required when |
patient_col |
Character. Patient ID column.
Default |
outcome_col |
Character. Final outcome column.
Default |
date_col |
Character. Date column used to extract the year
(must be a |
center_col |
Character. Centre/facility column.
Default |
merge_referred |
Logical. Recode
|
palette |
Named character vector mapping outcome values to colours. Unmatched outcomes get a default ggplot colour. |
ncol |
Integer. Facet columns ( |
base_size |
Numeric. Base font size. Default 14. |
title |
Character. Custom plot title. Auto-generated if
|
syndrome_col |
Character or |
syndrome_name |
Character or |
One outcome is taken per patient per centre (the first recorded value) to avoid double-counting long-format rows.
Supports three display modes:
"faceted" (default) – one panel per centre.
"overall" – all centres pooled into a single chart.
"single" – one specific centre; pass its name via
center.
A ggplot object.
Produces a bar chart of final outcome counts per centre, with each bar labelled with the count and percentage of that centre's (or overall) unique patients. Bars are coloured by outcome category.
plot_outcome_distribution( data, mode = c("faceted", "overall", "single"), center = NULL, patient_col = "PatientInformation_id", outcome_col = "final_outcome", center_col = "center_name", merge_referred = TRUE, palette = c(Death = "#E74C3C", Died = "#E74C3C", Discharged = "#2ECC71", LAMA = "#95A5A6", Referred = "#3498DB", `Transferred to other hospital` = "#3498DB"), ncol = 2, base_size = 14, title = NULL, syndrome_col = NULL, syndrome_name = NULL )plot_outcome_distribution( data, mode = c("faceted", "overall", "single"), center = NULL, patient_col = "PatientInformation_id", outcome_col = "final_outcome", center_col = "center_name", merge_referred = TRUE, palette = c(Death = "#E74C3C", Died = "#E74C3C", Discharged = "#2ECC71", LAMA = "#95A5A6", Referred = "#3498DB", `Transferred to other hospital` = "#3498DB"), ncol = 2, base_size = 14, title = NULL, syndrome_col = NULL, syndrome_name = NULL )
data |
Data frame. Long-format AMR dataset. |
mode |
Character. One of |
center |
Character. Required when |
patient_col |
Character. Patient ID column.
Default |
outcome_col |
Character. Final outcome column.
Default |
center_col |
Character. Centre/facility column.
Default |
merge_referred |
Logical. Recode
|
palette |
Named character vector mapping outcome values to colours. Any outcome not in the vector gets a default ggplot colour. Default uses a preset palette for common outcome categories. |
ncol |
Integer. Facet columns ( |
base_size |
Numeric. Base font size. Default 14. |
title |
Character. Custom plot title. Auto-generated if
|
syndrome_col |
Character or |
syndrome_name |
Character or |
Deduplication: a patient may appear multiple times in a long-format dataset (one row per isolate or antibiotic). This function takes the first recorded outcome per patient per centre so each patient is counted once.
Referred merging: by default, "Transferred to other hospital"
is recoded to "Referred" since they represent the same clinical event
across different centres. Set merge_referred = FALSE to keep them
separate.
Supports three display modes:
"faceted" (default) – one panel per centre.
"overall" – all centres pooled into one chart.
"single" – one specific centre; pass the name via
center.
A ggplot object.
Produces a column chart showing the number of unique patients per hospital. Bars are sorted in descending order (highest count on the left) and each bar is labelled with its count.
plot_patients_by_hospital( data, patient_col = "PatientInformation_id", center_col = "center_name", colour = "#4393C3", bar_width = 0.68, base_size = 14, title = NULL, syndrome_col = NULL, syndrome_name = NULL )plot_patients_by_hospital( data, patient_col = "PatientInformation_id", center_col = "center_name", colour = "#4393C3", bar_width = 0.68, base_size = 14, title = NULL, syndrome_col = NULL, syndrome_name = NULL )
data |
Data frame. Must contain the columns named by
|
patient_col |
Character. Column containing patient identifiers.
Default |
center_col |
Character. Column containing hospital / centre names.
Default |
colour |
Character. Fill colour for the bars. Default
|
bar_width |
Numeric. Width of bars (0-1). Default |
base_size |
Numeric. Base font size. Default |
title |
Character. Custom plot title. Auto-generated if
|
syndrome_col |
Character or |
syndrome_name |
Character or |
A ggplot object.
Splits the fixed-effect ("beta") parameter group by which covariate family each coefficient belongs to (Intercept / Hospital / Age / Sex / Specimen / Ward-ICU / Other, by covariate-name pattern), so a reviewer can see directly whether e.g. hospital contrasts specifically are destabilising the fit, rather than only a single aggregate Rhat/ESS for all of "beta".
plot_probit_beta_family_diagnostics(fit, title_base = "")plot_probit_beta_family_diagnostics(fit, title_base = "")
fit |
List returned by |
title_base |
Character. Prefixed to plot titles. |
Named list with table (a formatted summary page) and
bar (a percent-Rhat-above-1.01-by-family bar chart), or
NULL if fixed-effect parameter diagnostics are unavailable.
Generate diagnostic plots for a fitted Bayesian multivariate probit model
plot_probit_diagnostics( fit_obj, output_dir, experiment_id, pathogen, max_params = 30L )plot_probit_diagnostics( fit_obj, output_dir, experiment_id, pathogen, max_params = 30L )
fit_obj |
Named list returned by |
output_dir |
Directory where the PDF will be saved. |
experiment_id |
Character. Experiment identifier (used in filename and titles). |
pathogen |
Character. Pathogen name (used in plot titles). |
max_params |
Integer. Maximum number of parameters shown in trace/rank plots.
Defaults to 30. Includes |
Invisibly returns the path to the saved PDF, or NULL if skipped.
Returns a named list of up to two ggplot objects: other (every
non-hospital-dummy covariate – intercept, age, gender, etc.) and
hospital (hospital contrasts only, if the fit used hospital as a
fixed effect rather than a random effect). Both facet by antimicrobial
class rather than putting every class's coefficients on one axis.
plot_probit_fixed_effect_diagnostics(fit, title_base = "", ci_level = 0.95)plot_probit_fixed_effect_diagnostics(fit, title_base = "", ci_level = 0.95)
fit |
List returned by |
title_base |
Character. Prefixed to plot titles. |
ci_level |
Numeric. Credible interval level. Default |
Named list of ggplot objects (other, hospital),
either of which may be absent if that group has no covariates in this
fit. NULL if fit$draws or fit$X_event is missing.
Compact multi-page PDF: observed-vs-replicated marginal resistance,
number-resistant-per-event distribution, observed-vs-replicated pairwise
RR/RS/SR/SS, complete-profile concentration/entropy, hospital
heterogeneity, admission/patient clustering, and (when
ppc_replicates with materialised replicate arrays is supplied) a
small-multiples page comparing the observed data against
n_small_multiples randomly selected posterior replications. A
good posterior predictive plot makes it visually apparent whether the
observed data look typical among the replicated datasets.
plot_probit_posterior_predictive_checks( ppc_statistics, ppc_replicates = NULL, output_pdf_path, title_base, n_small_multiples = 10L, small_multiple_seed = 123L )plot_probit_posterior_predictive_checks( ppc_statistics, ppc_replicates = NULL, output_pdf_path, title_base, n_small_multiples = 10L, small_multiple_seed = 123L )
ppc_statistics |
Tibble returned by
|
ppc_replicates |
Optional |
output_pdf_path |
Path to the PDF to write. |
title_base |
Character; prefixed to every page's title (e.g.
|
n_small_multiples |
Integer; number of replicate states to show on the small-multiples page. Default 10. |
small_multiple_seed |
Integer seed for selecting which replicate states appear on the small-multiples page. Default 123. |
Invisibly returns the path to the saved PDF, or NULL if
skipped.
Auto-selects the union of the top n_worst parameters by Rhat and
the top n_worst by lowest bulk ESS (from
fit$diagnostics_detail$monitored_parameters), and shows their
chain trace and rank-overlay plots with human-readable facet labels
(covariate x class, or correlation pair) instead of raw Stan parameter
names – enough to tell slow-mixing, chain separation, a sticky region,
and multimodality apart, which a single Rhat number cannot.
plot_probit_worst_offender_diagnostics( fit, draws, title_base = "", n_worst = 6L )plot_probit_worst_offender_diagnostics( fit, draws, title_base = "", n_worst = 6L )
fit |
List returned by |
draws |
A |
title_base |
Character. Prefixed to plot titles. |
n_worst |
Integer. How many parameters to select by each criterion
(Rhat, bulk ESS) before deduplicating. Default |
Named list with trace and rank ggplot objects, or
NULL if no structural parameter diagnostics are available.
Replaces raw Stan parameter names (e.g. "beta[12,2]") with the
substantive covariate/class (or correlation pair) they refer to, and shows
only parameters that actually exceed the Rhat threshold – not an
arbitrary fixed top-N – alongside their bulk and tail ESS: a high Rhat
with healthy ESS is a different diagnostic situation than a high Rhat with
very low ESS, and showing only one of the two obscures that distinction.
plot_probit_worst_parameters( fit, title_base = "", rhat_threshold = 1.01, max_rows = 40L )plot_probit_worst_parameters( fit, title_base = "", rhat_threshold = 1.01, max_rows = 40L )
fit |
List returned by |
title_base |
Character. Prefixed to plot titles. |
rhat_threshold |
Numeric. Only parameters with Rhat above this are shown. Default |
max_rows |
Integer cap on rows shown, in case very many parameters fail. Default |
A ggplot object (table page), or NULL if no structural
parameter exceeds the threshold, or diagnostics are unavailable.
100
vs Susceptible patients within each age bin. A patient is classified as
Resistant if they have ANY (organism × antibiotic) result of "R";
Susceptible only when every result is "S" (worst-phenotype rule
applied at patient × organism × antibiotic level, then collapsed to patient
level).
plot_resistance_by_agebin( data, mode = c("faceted", "overall", "single"), center = NULL, patient_col = "patient_id", organism_col = "organism_normalized", antibiotic_col = "antibiotic_name", value_col = "result", agebin_col = "Age_bin", center_col = "center_name", colours = NULL, base_size = 11, ncol = 3, title = NULL, syndrome_col = NULL, syndrome_name = NULL )plot_resistance_by_agebin( data, mode = c("faceted", "overall", "single"), center = NULL, patient_col = "patient_id", organism_col = "organism_normalized", antibiotic_col = "antibiotic_name", value_col = "result", agebin_col = "Age_bin", center_col = "center_name", colours = NULL, base_size = 11, ncol = 3, title = NULL, syndrome_col = NULL, syndrome_name = NULL )
data |
Data frame (one row per patient × organism × antibiotic result). |
mode |
One of |
center |
Centre name used when |
patient_col |
Column for patient ID. |
organism_col |
Column for organism name. |
antibiotic_col |
Column for antibiotic name. |
value_col |
Column for resistance result ( |
agebin_col |
Column for age bin label. |
center_col |
Column for centre name. |
colours |
Named character vector with |
base_size |
Base font size for |
ncol |
Facet columns (faceted mode only). |
title |
Optional title override. |
syndrome_col |
Optional column used to pre-filter by syndrome. |
syndrome_name |
Optional value of |
100
vs Susceptible patients for the top n organisms (ranked by total
distinct patient count). A patient x organism pair is classified as
Resistant if any antibiotic result for that pair is "R"
(worst-phenotype rule at patient x organism x antibiotic level).
plot_resistance_by_organism( data, n = 5, mode = c("faceted", "overall", "single"), center = NULL, patient_col = "patient_id", organism_col = "organism_normalized", antibiotic_col = "antibiotic_name", value_col = "result", center_col = "center_name", colours = NULL, base_size = 11, ncol = 3, title = NULL, syndrome_col = NULL, syndrome_name = NULL )plot_resistance_by_organism( data, n = 5, mode = c("faceted", "overall", "single"), center = NULL, patient_col = "patient_id", organism_col = "organism_normalized", antibiotic_col = "antibiotic_name", value_col = "result", center_col = "center_name", colours = NULL, base_size = 11, ncol = 3, title = NULL, syndrome_col = NULL, syndrome_name = NULL )
data |
Data frame (one row per patient x organism x antibiotic result). |
n |
Number of top organisms to display. |
mode |
One of |
center |
Centre name used when |
patient_col |
Column for patient ID. |
organism_col |
Column for organism name. |
antibiotic_col |
Column for antibiotic name. |
value_col |
Column for resistance result ( |
center_col |
Column for centre name. |
colours |
Named character vector with |
base_size |
Base font size for |
ncol |
Facet columns (faceted mode only). |
title |
Optional title override. |
syndrome_col |
Optional column used to pre-filter by syndrome. |
syndrome_name |
Optional value of |
Produces a horizontal 100% stacked bar chart showing the proportion of
Resistant (R) and Susceptible (S) deduplicated AST results for the top
n sample types. Each bar sums to 100% and is labelled with the R
and S percentages.
plot_resistance_by_sample( data, n = 10, mode = c("faceted", "overall", "single"), center = NULL, patient_col = "PatientInformation_id", sample_col = "sample_type", organism_col = "organism_name", antibiotic_col = "antibiotic_name", value_col = "antibiotic_value", center_col = "center_name", colours = c(R = "#D73027", S = "#1A9850"), ncol = 2, base_size = 14, title = NULL, syndrome_col = NULL, syndrome_name = NULL )plot_resistance_by_sample( data, n = 10, mode = c("faceted", "overall", "single"), center = NULL, patient_col = "PatientInformation_id", sample_col = "sample_type", organism_col = "organism_name", antibiotic_col = "antibiotic_name", value_col = "antibiotic_value", center_col = "center_name", colours = c(R = "#D73027", S = "#1A9850"), ncol = 2, base_size = 14, title = NULL, syndrome_col = NULL, syndrome_name = NULL )
data |
Data frame. Long-format AMR dataset. |
n |
Integer. Number of top sample types to show (ranked by deduplicated test count). Default 10. |
mode |
Character. One of |
center |
Character. Required when |
patient_col |
Character. Patient ID column. Used for deduplication.
Default |
sample_col |
Character. Sample/specimen type column.
Default |
organism_col |
Character. Organism name column. Used for
deduplication. Default |
antibiotic_col |
Character. Antibiotic name column.
Default |
value_col |
Character. Susceptibility result column (R/S values).
Default |
center_col |
Character. Centre/facility column.
Default |
colours |
Named character vector for R and S bars.
Default |
ncol |
Integer. Facet columns ( |
base_size |
Numeric. Base font size. Default 14. |
title |
Character. Custom title. Auto-generated if
|
syndrome_col |
Character or |
syndrome_name |
Character or |
Deduplication (worst-phenotype): before counting, rows are collapsed by patient x centre x sample type x organism x antibiotic. If the same antibiotic appears more than once for a patient-organism-sample combination (data entry error or repeat test), any single R result marks the episode as R. This prevents duplicate rows from inflating counts.
Counting unit: deduplicated AST test results – one record per patient x organism x antibiotic x sample type combination.
Top N ranking: sample types are ranked by total deduplicated test count, so the most-tested specimen types appear first.
Default sample column: "sample_type" – the raw column.
Switch to "specimen_normalized" for standardised values.
Supports three display modes:
"faceted" (default) – top n sample types per centre independently, one panel per centre.
"overall" – all centres pooled; top n globally.
"single" – one specific centre.
A ggplot object.
Produces a column chart showing the number of unique patients per
infectious syndrome. Supports three modes: pooled across all centres
("overall"), faceted by centre ("faceted"), or a single
specified centre ("single").
plot_syndrome_distribution( data, mode = c("overall", "faceted", "single"), center = NULL, patient_col = "PatientInformation_id", syndrome_col = "infectious_syndrome", center_col = "center_name", colour = "#4393C3", ncol = 2, base_size = 14, title = NULL )plot_syndrome_distribution( data, mode = c("overall", "faceted", "single"), center = NULL, patient_col = "PatientInformation_id", syndrome_col = "infectious_syndrome", center_col = "center_name", colour = "#4393C3", ncol = 2, base_size = 14, title = NULL )
data |
Data frame. Must contain the columns named by
|
mode |
Character. One of |
center |
Character or |
patient_col |
Character. Column containing patient identifiers.
Default |
syndrome_col |
Character. Column containing infectious syndrome
labels. Default |
center_col |
Character. Column containing hospital / centre names.
Default |
colour |
Character. Fill colour for the bars. Default
|
ncol |
Integer. Number of columns in faceted layout.
Default |
base_size |
Numeric. Base font size. Default |
title |
Character. Custom plot title. Auto-generated if
|
A ggplot object.
Produces a horizontal bar chart of the top n organisms ranked by
unique patient count. Supports three display modes:
"faceted" – one panel per centre, top n organisms within each centre independently. Facet strips show patient and organism counts for that centre.
"overall" – all centres pooled; single chart of the top n organisms across the entire dataset.
"single" – one specific centre; pass the centre name via
center.
plot_top_organisms( data, n = 5, mode = c("faceted", "overall", "single"), center = NULL, patient_col = "PatientInformation_id", organism_col = "organism_name", center_col = "center_name", fill_colour = "steelblue", ncol = 2, base_size = 14, title = NULL, syndrome_col = NULL, syndrome_name = NULL )plot_top_organisms( data, n = 5, mode = c("faceted", "overall", "single"), center = NULL, patient_col = "PatientInformation_id", organism_col = "organism_name", center_col = "center_name", fill_colour = "steelblue", ncol = 2, base_size = 14, title = NULL, syndrome_col = NULL, syndrome_name = NULL )
data |
Data frame. Long-format AMR dataset (one row per isolate/antibiotic record). |
n |
Integer. Number of top organisms to show. Default 5. |
mode |
Character. One of |
center |
Character. Required when |
patient_col |
Character. Column name for patient identifiers.
Default |
organism_col |
Character. Column name for organism names.
Default |
center_col |
Character. Column name for centre/facility names.
Default |
fill_colour |
Character. Bar fill colour (any R colour string or hex).
Default |
ncol |
Integer. Number of columns in the facet grid
( |
base_size |
Numeric. Base font size passed to |
title |
Character. Custom plot title. If |
syndrome_col |
Character or |
syndrome_name |
Character or |
Labels on each bar show absolute count and percentage of that centre's (or overall) unique patient total.
A ggplot object. Print it or pass to ggsave().
Produces a two-column tile heatmap where the x-axis shows YLD Associated and YLD Attributable, the y-axis shows organism groups (or individual pathogens), and each cell's fill reflects the YLD burden per 1 000 admissions.
plot_yld_heatmap( data, n_admissions = NULL, pathogen_col = "pathogen", assoc_col = "YLD_associated", attr_col = "YLD_attributable", group_col = NULL, syndrome_col = NULL, syndrome_name = NULL, show_values = TRUE, value_digits = 2, palette = "Blues", coord_fixed = TRUE, base_size = 14, title = NULL, subtitle = NULL )plot_yld_heatmap( data, n_admissions = NULL, pathogen_col = "pathogen", assoc_col = "YLD_associated", attr_col = "YLD_attributable", group_col = NULL, syndrome_col = NULL, syndrome_name = NULL, show_values = TRUE, value_digits = 2, palette = "Blues", coord_fixed = TRUE, base_size = 14, title = NULL, subtitle = NULL )
data |
Data frame. Must contain the columns named by
|
n_admissions |
Numeric or |
pathogen_col |
Character. Column containing pathogen names.
Default |
assoc_col |
Character. Column containing YLD associated values.
Default |
attr_col |
Character. Column containing YLD attributable values.
Default |
group_col |
Character or |
syndrome_col |
Character or |
syndrome_name |
Character or |
show_values |
Logical. Print rounded values inside each cell.
Default |
value_digits |
Integer. Decimal places for cell labels. Default 2. |
palette |
Character. RColorBrewer palette for the fill scale.
Default |
coord_fixed |
Logical. Whether to apply |
base_size |
Numeric. Base font size. Default 14. |
title |
Character. Custom plot title. Auto-generated if
|
subtitle |
Character. Custom subtitle. Auto-generated if
|
The input data should contain one row per pathogen with
YLD_associated and YLD_attributable columns – typically
the output of daly_calc_yld_attributable() (which augments the
data frame with both columns). If an organism-group column has been
pre-joined (e.g. org_group), supply its name via group_col
to aggregate cells to the group level.
A ggplot object.
Produces a tile heatmap where the x-axis shows resistance classes (dominant AMR profiles), the y-axis shows pathogen groups (or individual pathogens), and each cell's fill reflects the associated or attributable YLL burden per 1 000 admissions.
plot_yll_heatmap( data, type = c("associated", "attributable"), value_col, n_admissions = NULL, pathogen_col = "pathogen", class_col = "profile", group_col = NULL, syndrome_col = NULL, syndrome_name = NULL, show_values = TRUE, value_digits = 2, palette = "Spectral", base_size = 14, title = NULL, subtitle = NULL )plot_yll_heatmap( data, type = c("associated", "attributable"), value_col, n_admissions = NULL, pathogen_col = "pathogen", class_col = "profile", group_col = NULL, syndrome_col = NULL, syndrome_name = NULL, show_values = TRUE, value_digits = 2, palette = "Spectral", base_size = 14, title = NULL, subtitle = NULL )
data |
Data frame. Must contain the columns named by
|
type |
Character. |
value_col |
Character. Required. Column containing the YLL value to
plot (e.g. |
n_admissions |
Numeric or |
pathogen_col |
Character. Column containing pathogen names.
Default |
class_col |
Character. Column containing the resistance class /
dominant profile. Default |
group_col |
Character or |
syndrome_col |
Character or |
syndrome_name |
Character or |
show_values |
Logical. Print rounded values inside each cell.
Default |
value_digits |
Integer. Decimal places for cell labels. Default 2. |
palette |
Character. RColorBrewer palette for the fill scale.
Default |
base_size |
Numeric. Base font size. Default 14. |
title |
Character. Custom plot title. Auto-generated if
|
subtitle |
Character. Custom subtitle. Auto-generated if
|
The input data should be the $by_class slot (for associated)
or the $by_profile slot (for attributable) returned by
daly_calc_yll_associated() / daly_calc_yll_attributable().
Both slots contain columns pathogen, profile, and
YLL_Kdelta.
If an organism-group column has been pre-joined onto data (e.g.
org_group), supply its name via group_col and the function
will aggregate to the group x class level. When group_col is
NULL or absent, individual pathogen names are used on the y-axis.
A ggplot object.
Renames data frame columns using a standard_name = raw_name map. Warns on unmapped columns; does not drop them.
prep_apply_column_map(data, column_map)prep_apply_column_map(data, column_map)
data |
Data frame. |
column_map |
Named character vector from |
Data frame with standard column names where mapping existed.
Confirms that a column mapping succeeded for critical standard columns. Stops on failure when strict = TRUE.
prep_assert_standard_names(data, required_standard_names, strict = TRUE)prep_assert_standard_names(data, required_standard_names, strict = TRUE)
data |
Data frame after column mapping. |
required_standard_names |
Character vector of standard column names that must be present. |
strict |
Logical. Stop on failure. Default TRUE. |
Invisibly returns data. Stops or warns on missing columns.
Categorizes age into bins for stratification using GBD standard or custom break points. Supports ages stored as a single column in years, months, or days, as well as compound datasets where years, months, and days are in separate columns (e.g. neonatal records).
prep_assign_age_bins( data, age_col = "Age", bins = "GBD_standard", age_unit = "years", age_months_col = NULL, age_days_col = NULL, negative_age_strategy = c("fallback", "na"), fallback_years_col = "year", fallback_months_col = "months", fallback_days_col = "age_days", fallback_dob_col = "dob", fallback_admission_col = "admission_date" )prep_assign_age_bins( data, age_col = "Age", bins = "GBD_standard", age_unit = "years", age_months_col = NULL, age_days_col = NULL, negative_age_strategy = c("fallback", "na"), fallback_years_col = "year", fallback_months_col = "months", fallback_days_col = "age_days", fallback_dob_col = "dob", fallback_admission_col = "admission_date" )
data |
Data frame with an age column. |
age_col |
Character. Primary age column. Default |
bins |
Character or character vector. Preset name ( |
age_unit |
Character. Unit of |
age_months_col |
Character or NULL. Optional column holding the months
component of age (0-11). Added to |
age_days_col |
Character or NULL. Optional column holding the days
component of age (0-30). Added to |
negative_age_strategy |
Character. How to handle negative ages in
|
fallback_years_col |
Character or NULL. Optional years column used when
|
fallback_months_col |
Character or NULL. Optional months column used
when |
fallback_days_col |
Character or NULL. Optional days column used when
|
fallback_dob_col |
Character or NULL. Optional DOB column used with
|
fallback_admission_col |
Character or NULL. Optional admission/reference
date column used with |
When age_months_col or age_days_col are supplied they are
treated as the fractional remainder on top of age_col (e.g.
age_years = 0, age_months = 3, age_days = 5 -> 0.27 years). Missing values
in the component columns are treated as zero so that a partially-recorded
age is still binnable.
Data frame with resolved numeric age in Age_years,
Age_bin factor column, and Age_resolved (decimal years
rounded to one decimal place, derived from whatever year / month / day
components were available — e.g. 45 months with no year value yields
Age_resolved = 3.8) added.
Adds a column that labels each row's facility with a category defined by the
caller (for example "Government" vs "Private", "Urban" vs "Rural", or a
region). The function is deliberately generic: it contains no hardcoded
facility names, so any dataset can be classified by passing an appropriate
mapping.
prep_assign_facility_type( data, facility_col = "center_name", mapping, new_col = "facility_type", default = NA_character_, case_insensitive = TRUE )prep_assign_facility_type( data, facility_col = "center_name", mapping, new_col = "facility_type", default = NA_character_, case_insensitive = TRUE )
data |
A data frame. |
facility_col |
Name of the column holding facility names.
Default |
mapping |
A named character vector where names are facility values and
values are the type/sector to assign, e.g.
|
new_col |
Name of the column to create. Default |
default |
Value assigned to facilities not found in |
case_insensitive |
Logical. If |
data with new_col added.
df <- data.frame(center_name = c("AFMC", "SGRH", "Unknown")) m <- c(AFMC = "Government", SGRH = "Private") prep_assign_facility_type(df, mapping = m)df <- data.frame(center_name = c("AFMC", "SGRH", "Unknown")) m <- c(AFMC = "Government", SGRH = "Private") prep_assign_facility_type(df, mapping = m)
Assign Organism Group
prep_assign_organism_group(data, organism_col = "organism_normalized")prep_assign_organism_group(data, organism_col = "organism_normalized")
data |
Data frame. |
organism_col |
Character. Normalized organism column. Default "organism_normalized". |
Data frame with org_group column added.
Selects the highest-priority syndrome per patient using the infectious syndrome hierarchy. Matching is case-insensitive (uses normalized names).
prep_assign_patient_syndrome( data, patient_col = "patient_id", syndrome_col = "syndrome", score_col = "icd_score", hierarchy_ref = NULL, hierarchy_syndrome_col = "infectious_syndrome", hierarchy_rank_col = "rank", keep_all_candidates = TRUE, collapse_unspecified_respiratory = FALSE, keep_only_burden_syndromes = FALSE )prep_assign_patient_syndrome( data, patient_col = "patient_id", syndrome_col = "syndrome", score_col = "icd_score", hierarchy_ref = NULL, hierarchy_syndrome_col = "infectious_syndrome", hierarchy_rank_col = "rank", keep_all_candidates = TRUE, collapse_unspecified_respiratory = FALSE, keep_only_burden_syndromes = FALSE )
data |
Data frame with one row per syndrome candidate. |
patient_col |
Character. Patient or event ID column. Default |
syndrome_col |
Character. Syndrome column. Default |
score_col |
Character or NULL. ICD match score column for secondary priority.
Default |
hierarchy_ref |
Data frame or NULL. Syndrome hierarchy (from
|
hierarchy_syndrome_col |
Character. Syndrome column in hierarchy. Default |
hierarchy_rank_col |
Character. Rank column in hierarchy. Default |
keep_all_candidates |
Logical. TRUE -> return all rows with |
collapse_unspecified_respiratory |
Logical. Map "Other unspecified respiratory site infections" -> "Lower respiratory infections" before selection. Default FALSE. |
keep_only_burden_syndromes |
Logical. Retain only syndromes where
|
Priority order per patient:
Hierarchy rank (lower = higher priority)
ICD match score (higher = higher priority), when score_col present
Alphabetical tie-break
This function absorbs the logic of the former infer_patient_syndrome_long():
use collapse_unspecified_respiratory = TRUE and
keep_only_burden_syndromes = TRUE to replicate that behaviour.
Data frame. When keep_all_candidates = FALSE, includes
contributes_to_amr_burden column from the hierarchy.
Records a stage entry in an attrition flow table. Call once per pipeline stage to build up a cumulative record of how many rows and patients are retained after each step.
prep_attrition_flow( flow, data, stage_name, reason = "", patient_col = "patient_id", event_col = "event_id" )prep_attrition_flow( flow, data, stage_name, reason = "", patient_col = "patient_id", event_col = "event_id" )
flow |
Data frame of previous attrition stages (or NULL to start). |
data |
Current data frame at this stage. |
stage_name |
Character. Short label for this stage. |
reason |
Character. Description of what changed at this stage. |
patient_col |
Character. Patient ID column. Default "patient_id". |
event_col |
Character. Event ID column (optional). Default "event_id". |
Usage pattern:
flow <- NULL flow <- prep_attrition_flow(flow, data_raw, "raw_intake", "All raw records") flow <- prep_attrition_flow(flow, data_dated, "dates_parsed", "After date coercion") flow <- prep_attrition_flow(flow, data_ready, "analysis_ready","After all filters") print(flow)
Updated attrition flow data frame.
Validates a user-supplied column map against the actual columns present in a data frame. Reports which mappings are present, which are absent, and which data columns are not covered.
prep_build_column_map(data, column_map = NULL, custom_map = NULL)prep_build_column_map(data, column_map = NULL, custom_map = NULL)
data |
Data frame with raw column names. |
column_map |
Named character vector: standard_name = raw_name. Pass a dataset-specific map from your analysis layer. If NULL, generic alias detection is attempted. |
custom_map |
Named character vector. Additional raw -> standard overrides
applied on top of |
Dataset-specific maps (ICMR stewardship, surveillance, AIIMS, etc.) should
be defined in the analysis layer and passed in via column_map.
If no map is supplied, falls back to auto-detection using
default_column_mappings aliases.
Named character vector with only mappings whose raw names exist in data.
Extracts records for patients who died, for use in YLL calculation.
prep_build_fatal_cohort( data, outcome_col = "final_outcome", died_value = "Died" )prep_build_fatal_cohort( data, outcome_col = "final_outcome", died_value = "Died" )
data |
Analysis-ready data frame. |
outcome_col |
Character. Final outcome column. Default "final_outcome". |
died_value |
Character. Value indicating death. Default "Died". |
Data frame with only fatal episodes.
Extracts records for patients who survived, for use in YLD calculation.
prep_build_nonfatal_cohort( data, outcome_col = "final_outcome", survived_value = "Survived" )prep_build_nonfatal_cohort( data, outcome_col = "final_outcome", survived_value = "Survived" )
data |
Analysis-ready data frame. |
outcome_col |
Character. Final outcome column. Default "final_outcome". |
survived_value |
Character. Value indicating survival. Default "Survived". |
Data frame with only non-fatal episodes.
Runs before any table is merged. Reports missing columns, type mismatches, and blank/duplicate column names. Stops on hard failures; warns on soft ones.
prep_check_columns( data, required = character(), expected_types = character(), table_label = "table", stop_on_missing = TRUE )prep_check_columns( data, required = character(), expected_types = character(), table_label = "table", stop_on_missing = TRUE )
data |
Data frame to inspect. |
required |
Character vector of column names that must be present. |
expected_types |
Named character vector mapping column names to expected
R classes (e.g. |
table_label |
Character. Label used in messages (e.g. "patient_KGMU"). |
stop_on_missing |
Logical. Stop if required columns are absent (default TRUE). |
Invisibly returns a tibble summarising every checked column.
Reports missing, blank, duplicate, and placeholder keys in a column before a merge. Run this on both sides of every planned join.
prep_check_keys( data, key_col, table_label = "table", warn_missing_pct = 5, admission_col = "date_of_admission", culture_col = "date_of_culture" )prep_check_keys( data, key_col, table_label = "table", warn_missing_pct = 5, admission_col = "date_of_admission", culture_col = "date_of_culture" )
data |
Data frame. |
key_col |
Character. Name of the key column. |
table_label |
Character. Label used in messages. |
warn_missing_pct |
Numeric. Warn when proportion of missing keys exceeds this threshold (0-100). Default 5. |
admission_col |
Character. Admission date column used for the optional paired missingness check. Default "date_of_admission". |
culture_col |
Character. Culture date column used for the optional paired missingness check. Default "date_of_culture". |
Invisibly returns a one-row summary tibble.
Flags impossible/implausible AST results where a drug is inappropriate for the organism type (e.g., a Gram-positive organism tested against a Gram-negative-only drug).
prep_check_organism_ast_consistency( data, organism_col = "organism_normalized", antibiotic_col = "antibiotic_normalized" )prep_check_organism_ast_consistency( data, organism_col = "organism_normalized", antibiotic_col = "antibiotic_normalized" )
data |
Data frame with organism and antibiotic columns. |
organism_col |
Character. Normalized organism column. Default "organism_normalized". |
antibiotic_col |
Character. Normalized antibiotic column. Default "antibiotic_normalized". |
Uses inst/extdata/Organism_AST_drugs.csv which maps organism groups
to expected antibiotic panels.
Data frame with is_ast_inconsistent logical column added.
Maps antibiotic names to WHO antibiotic classes.
prep_classify_antibiotic_class( data, antibiotic_col = "antibiotic_normalized", who_table = NULL )prep_classify_antibiotic_class( data, antibiotic_col = "antibiotic_normalized", who_table = NULL )
data |
Data frame. |
antibiotic_col |
Character. Normalized antibiotic column. Default "antibiotic_normalized". |
who_table |
Data frame. WHO classification table. If NULL uses built-in. |
Data frame with antibiotic_class column added.
Assigns WHO AWaRe (Access, Watch, Reserve) categories to antibiotics.
prep_classify_aware( data, antibiotic_col = "antibiotic_normalized", who_table = NULL )prep_classify_aware( data, antibiotic_col = "antibiotic_normalized", who_table = NULL )
data |
Data frame. |
antibiotic_col |
Character. Antibiotic column. Default "antibiotic_normalized". |
who_table |
Data frame. WHO AWaRe table. If NULL, uses built-in. |
Data frame with aware_category column added.
Classifies isolates as MDR (Multidrug Resistant) and XDR (Extensively Drug Resistant) in a single pass using Magiorakos 2012 criteria.
prep_classify_mdr_xdr( data, definition = "Magiorakos", organism_group_col = "org_group" )prep_classify_mdr_xdr( data, definition = "Magiorakos", organism_group_col = "org_group" )
data |
Data frame with class-level resistance data. |
definition |
Character. Classification criteria. Default "Magiorakos". |
organism_group_col |
Character. Organism group column for pathogen-specific thresholds. Default "org_group". |
MDR: resistant to at least one agent in three or more antimicrobial categories. XDR: susceptible to at most two antimicrobial categories.
Requires class_result_event column (run
prep_collapse_class_level() first, then rename class_resistance
to class_result_event).
Data frame with mdr, mdr_confidence, mdr_method, n_resistant_categories, resistant_categories, xdr, xdr_confidence, and xdr_method columns added.
Magiorakos AP et al. Clin Microbiol Infect. 2012;18(3):268-281.
Determines if death was related to infection using date window logic. Implements proxy logic when dates are missing.
prep_classify_mortality( data, outcome_col = "final_outcome", event_date_col = "date_of_culture", outcome_date_col = "date_of_final_outcome", window = 14 )prep_classify_mortality( data, outcome_col = "final_outcome", event_date_col = "date_of_culture", outcome_date_col = "date_of_final_outcome", window = 14 )
data |
Data frame |
outcome_col |
Character. Outcome column. Default "final_outcome". |
event_date_col |
Character. Event/culture date. Default "date_of_culture". |
outcome_date_col |
Character. Outcome date. Default "date_of_final_outcome". |
window |
Numeric. Days after event to classify death as infection-related. Default 14. |
Data frame with mortality_infection, mortality_method, mortality_confidence columns
Applies readmission classification rules to a data frame that already has a
readmission_class column, re-standardizing the values.
prep_classify_readmission(data, readmission_col = "readmission_class")prep_classify_readmission(data, readmission_col = "readmission_class")
data |
Data frame. |
readmission_col |
Character. Readmission column to standardize. Default "readmission_class". |
Useful when data arrives with non-standard labels that need mapping to the
controlled vocabulary used by prep_flag_readmission().
Data frame with standardized readmission classification.
Extracts clean S/I/R values from messy antibiotic result columns. Handles common patterns like "S (HIGH LEVEL)", "R Escherichia coli", etc.
prep_clean_ast_values(data, value_col = "antibiotic_value", strict = FALSE)prep_clean_ast_values(data, value_col = "antibiotic_value", strict = FALSE)
data |
Data frame with antibiotic susceptibility data. |
value_col |
Character. Column containing susceptibility values. Default "antibiotic_value". |
strict |
Logical. If TRUE, only accept S/I/R values. If FALSE, attempt to parse from messy strings. Default FALSE. |
Data frame with cleaned antibiotic_value column.
Cleans and standardizes all optional columns in a single pass. Handles value normalization, whitespace trimming, and consistency checks.
prep_clean_optional_columns(data, optional_cols = NULL)prep_clean_optional_columns(data, optional_cols = NULL)
data |
Data frame. |
optional_cols |
Character vector. Optional column names to groom. If NULL, grooms all known optional columns. Default NULL. |
Data frame with groomed optional columns.
Auto-detects columns with date/time-like names (or uses a supplied list),
then calls prep_parse_date_column() on each.
prep_coerce_dates(data, cols = NULL, table_label = "table")prep_coerce_dates(data, cols = NULL, table_label = "table")
data |
Data frame. |
cols |
Character vector of column names to convert. When |
table_label |
Character. Label used in messages. |
Data frame with date columns converted to Date.
Aggregates resistance at antibiotic class level instead of individual drugs. Uses "any R in class -> class R" logic.
prep_collapse_class_level( data, event_col = "event_id", organism_col = "organism_normalized", class_col = "antibiotic_class", susceptibility_col = "antibiotic_value", extra_cols = NULL )prep_collapse_class_level( data, event_col = "event_id", organism_col = "organism_normalized", class_col = "antibiotic_class", susceptibility_col = "antibiotic_value", extra_cols = NULL )
data |
Data frame with antibiotic class information |
event_col |
Character. Event ID column. Default "event_id". |
organism_col |
Character. Organism column. Default "organism_normalized". |
class_col |
Character. Antibiotic class column. Default "antibiotic_class". |
susceptibility_col |
Character. Susceptibility column. Default "antibiotic_value". |
extra_cols |
Character vector or NULL. Additional columns to carry through the aggregation. Default NULL. |
Aggregated data frame (one row per event-organism-class)
## Not run: class_level <- prep_collapse_class_level(data) ## End(Not run)## Not run: class_level <- prep_collapse_class_level(data) ## End(Not run)
Calculates proportional weights for polymicrobial infections. Monomicrobial patients always receive weight = 1.0. For polymicrobial patients, weight is computed per organism within each episode using one of three methods.
prep_compute_poly_weights( data, episode_col = "episode_id", organism_col = "organism_normalized", polymicrobial_col = "is_polymicrobial", method = "monomicrobial_proportion", weight_map = NULL, facility_col = NULL, facility_name = NULL, syndrome_col = NULL, syndrome_name = NULL ) compute_polymicrobial_weight( data, episode_col = "episode_id", organism_col = "organism_normalized", polymicrobial_col = "is_polymicrobial", method = "monomicrobial_proportion", weight_map = NULL, facility_col = NULL, facility_name = NULL, syndrome_col = NULL, syndrome_name = NULL )prep_compute_poly_weights( data, episode_col = "episode_id", organism_col = "organism_normalized", polymicrobial_col = "is_polymicrobial", method = "monomicrobial_proportion", weight_map = NULL, facility_col = NULL, facility_name = NULL, syndrome_col = NULL, syndrome_name = NULL ) compute_polymicrobial_weight( data, episode_col = "episode_id", organism_col = "organism_normalized", polymicrobial_col = "is_polymicrobial", method = "monomicrobial_proportion", weight_map = NULL, facility_col = NULL, facility_name = NULL, syndrome_col = NULL, syndrome_name = NULL )
data |
Data frame with |
episode_col |
Character. Episode ID column. Default "episode_id". |
organism_col |
Character. Organism column. Default "organism_normalized". |
polymicrobial_col |
Character. Polymicrobial flag column (0/1). Default "is_polymicrobial". |
method |
Character. One of "monomicrobial_proportion" (default), "equal", or "manual". |
weight_map |
Named numeric vector. Custom organism weights when
|
facility_col |
Character or NULL. Scope monomicrobial reference pool per facility. |
facility_name |
Character or NULL. Filter to this facility. |
syndrome_col |
Character or NULL. Scope reference pool per syndrome. |
syndrome_name |
Character or NULL. Filter to this syndrome. |
Data frame with poly_weight, weight_method, and
weight_confidence columns.
Converts patient-level isolate data to event-level data by grouping repeat cultures from the same infection episode.
prep_create_event_ids( data, patient_col = "patient_id", date_col = "date_of_culture", organism_col = "organism_normalized", specimen_col = "specimen_type", antibiotic_col = "antibiotic_name", value_col = "antibiotic_value", gap_days = 14, culture_col = "id_organisminfo", admission_col = "date_of_admission", keep_event_culture = c("all", "closest_to_admission") )prep_create_event_ids( data, patient_col = "patient_id", date_col = "date_of_culture", organism_col = "organism_normalized", specimen_col = "specimen_type", antibiotic_col = "antibiotic_name", value_col = "antibiotic_value", gap_days = 14, culture_col = "id_organisminfo", admission_col = "date_of_admission", keep_event_culture = c("all", "closest_to_admission") )
data |
Data frame (long format – one row per antibiotic test). |
patient_col |
Patient ID column. Default "patient_id". |
date_col |
Culture date column. Default "date_of_culture". |
organism_col |
Organism column. Default "organism_normalized". |
specimen_col |
Specimen type column. Default "specimen_type". |
antibiotic_col |
Antibiotic name column. Default "antibiotic_name". |
value_col |
Susceptibility result column (S/I/R). Default "antibiotic_value". |
gap_days |
Days threshold: gap > gap_days triggers a new event. Default 14. |
culture_col |
Culture/isolate identifier column. When present, same-day
cultures from the same site and organism are evaluated separately before
duplicate culture removal. Default |
admission_col |
Admission date column. Used when |
keep_event_culture |
Character. |
Event classification rules (in order of precedence):
| Scenario | Result | |—————————————————–|—————–| | Different body sites (any date) | Separate events | | Same site, same day, same organism, same ABG | One event | | Same site, same day, same organism, diff ABG | Separate events | | Same site, same organism, within gap_days, same ABG | Same event | | Same site, same organism, within gap_days, ABG changed | New event | | Same site, same organism, after > gap_days | New event | | Same site, same day, different organisms | Separate events |
Event IDs are numbered GLOBALLY per patient in chronological order.
Original data frame with event_id column added.
Generates a resistance profile string for each event summarizing resistance patterns. Useful for identifying common resistance phenotypes.
prep_create_resistance_profile( data, event_col = "event_id", antibiotic_col = "antibiotic_normalized", susceptibility_col = "antibiotic_value", format = "resistant_list", class_col = "antibiotic_class" )prep_create_resistance_profile( data, event_col = "event_id", antibiotic_col = "antibiotic_normalized", susceptibility_col = "antibiotic_value", format = "resistant_list", class_col = "antibiotic_class" )
data |
Data frame with resistance data |
event_col |
Character. Event ID column. Default "event_id". |
antibiotic_col |
Character. Antibiotic column. Default "antibiotic_normalized". |
susceptibility_col |
Character. Susceptibility column. Default "antibiotic_value". |
format |
Character. Output format: - "resistant_list": List resistant drugs only (default) - "full_pattern": Full S/R pattern string - "class_summary": Resistant classes only |
class_col |
Character. Class column (required for format = "class_summary"). Default "antibiotic_class". |
Data frame with resistance_profile column added
## Not run: # List resistant drugs data_with_profile <- prep_create_resistance_profile(data) # Full S/R pattern data_with_profile <- prep_create_resistance_profile( data, format = "full_pattern" ) # Resistant classes only data_with_profile <- prep_create_resistance_profile( data, format = "class_summary" ) ## End(Not run)## Not run: # List resistant drugs data_with_profile <- prep_create_resistance_profile(data) # Full S/R pattern data_with_profile <- prep_create_resistance_profile( data, format = "full_pattern" ) # Resistant classes only data_with_profile <- prep_create_resistance_profile( data, format = "class_summary" ) ## End(Not run)
Converts long format (one row per organism-antibiotic) to wide format (one row per event with antibiotic columns). Useful for analysis and machine learning applications.
prep_create_wide_ast_matrix( data, event_col = "event_id", antibiotic_col = "antibiotic_normalized", susceptibility_col = "antibiotic_value", prefix = "abx_", keep_cols = c("patient_id", "organism_normalized", "date_of_culture") )prep_create_wide_ast_matrix( data, event_col = "event_id", antibiotic_col = "antibiotic_normalized", susceptibility_col = "antibiotic_value", prefix = "abx_", keep_cols = c("patient_id", "organism_normalized", "date_of_culture") )
data |
Data frame in long format |
event_col |
Character. Event ID column. Default "event_id". |
antibiotic_col |
Character. Antibiotic/class column to pivot. Default "antibiotic_normalized". |
susceptibility_col |
Character. Susceptibility column. Default "antibiotic_value". |
prefix |
Character. Prefix for pivoted columns. Default "abx_". |
keep_cols |
Character vector. Additional columns to keep from original data. Default c("patient_id", "organism_normalized", "date_of_culture"). |
Wide format data frame (one row per event)
## Not run: # Basic wide format wide_data <- prep_create_wide_ast_matrix(data) # Class-level wide format wide_data <- prep_create_wide_ast_matrix( data, antibiotic_col = "antibiotic_class", prefix = "class_" ) ## End(Not run)## Not run: # Basic wide format wide_data <- prep_create_wide_ast_matrix(data) # Class-level wide format wide_data <- prep_create_wide_ast_matrix( data, antibiotic_col = "antibiotic_class", prefix = "class_" ) ## End(Not run)
Converts antibiotic short codes (e.g. AMK, AMP, AMPSUL) to full antibiotic names using a caller-supplied code map CSV.
prep_decode_antibiotic_code( data, code_col = "antibiotic_name_raw", map_path = NULL, output_col = "antibiotic_name_std" )prep_decode_antibiotic_code( data, code_col = "antibiotic_name_raw", map_path = NULL, output_col = "antibiotic_name_std" )
data |
Data frame with a column of antibiotic codes. |
code_col |
Character. Column containing antibiotic codes. Default "antibiotic_name_raw". |
map_path |
Character. Path to the code map CSV file. Must have columns
|
output_col |
Character. Name of the output column for decoded names. Default "antibiotic_name_std". |
The code map must have columns code and antibiotic_name_full.
This function is dataset-agnostic: the code map and the column containing
the codes are supplied by the caller (typically from the analysis layer).
Data frame with output_col column added.
Deduplicates AST records in two sequential steps:
Exact-duplicate removal: drops rows that are fully identical across all five key columns (patient + organism + antibiotic + date + value). These are true redundant records with no ambiguity.
Conflict resolution: handles the remaining cases where the same patient + organism + antibiotic + date group has different values.
prep_deduplicate_ast( data, mode = c("detect", "remove"), strategy = c("resistant_wins", "susceptible_wins", "first"), patient_col = "patient_id", organism_col = "organism_normalized", antibiotic_col = "antibiotic_normalized", date_col = "culture_date", ast_col = "ast_value_harmonized" )prep_deduplicate_ast( data, mode = c("detect", "remove"), strategy = c("resistant_wins", "susceptible_wins", "first"), patient_col = "patient_id", organism_col = "organism_normalized", antibiotic_col = "antibiotic_normalized", date_col = "culture_date", ast_col = "ast_value_harmonized" )
data |
Data frame with AST data in long format. |
mode |
Character. |
strategy |
Character. Resolution strategy used only when |
patient_col |
Character. Patient ID column. Default |
organism_col |
Character. Organism column. Default |
antibiotic_col |
Character. Antibiotic column. Default |
date_col |
Character. Culture date column. Default |
ast_col |
Character. Harmonized AST value column. Default |
"detect"After exact-dedup, flags conflicting rows with
is_ast_duplicate = TRUE and prints a QC summary. Returns the data
with the flag column so you can inspect before deciding how to resolve.
"remove"Runs both steps: removes exact duplicates, then applies
strategy to keep one row per key combination for any remaining conflicts.
mode = "detect": original data with is_ast_duplicate logical column added.
mode = "remove": data with conflicts resolved (one row per key) and no flag column.
Removes duplicate rows within groups. Two modes:
prep_deduplicate_events( data, event_col = "event_id", organism_col = "organism_normalized", antibiotic_col = "antibiotic_normalized", key_cols = NULL, keep = "first" )prep_deduplicate_events( data, event_col = "event_id", organism_col = "organism_normalized", antibiotic_col = "antibiotic_normalized", key_cols = NULL, keep = "first" )
data |
Data frame. |
event_col |
Character. Event ID column (event-aware mode). Default "event_id". |
organism_col |
Character. Organism column (event-aware mode). Default "organism_normalized". |
antibiotic_col |
Character. Antibiotic column (event-aware mode). Default "antibiotic_normalized". |
key_cols |
Character vector. When supplied, switches to generic mode and uses these columns for duplicate detection. NULL uses event-aware mode. Default NULL. |
keep |
Character. "first", "last", or "none" (drop all duplicates). Default "first". |
Groups by event_col + organism_col
+ antibiotic_col and keeps first/last antibiotic test per group.
Requires event_col to be present.
Groups by key_cols and drops
duplicates. When keep = "none", both copies of every duplicate
are removed. Replaces the former remove_duplicate_rows() helper.
Deduplicated data frame.
Stewardship-specific helper: DOB is sometimes stored as separate year/month/day components or as a decimal age in years. This function reconstructs an approximate DOB or derives age directly when DOB is absent.
prep_derive_dob_from_components( data, dob_year_col = "dob_year", dob_month_col = "dob_month", dob_day_col = "dob_day", age_years_col = "age_years", reference_date_col = "admission_date", dob_output_col = "dob" )prep_derive_dob_from_components( data, dob_year_col = "dob_year", dob_month_col = "dob_month", dob_day_col = "dob_day", age_years_col = "age_years", reference_date_col = "admission_date", dob_output_col = "dob" )
data |
Data frame. |
dob_year_col |
Character. Year component column. Default "dob_year". |
dob_month_col |
Character. Month component column. Default "dob_month". |
dob_day_col |
Character. Day component column. Default "dob_day". |
age_years_col |
Character. Decimal age in years. Default "age_years". |
reference_date_col |
Character. Reference date for age-based DOB estimation. Default "admission_date". |
dob_output_col |
Character. Output DOB column. Default "dob". |
Strategies (applied in order):
If dob_year_col, dob_month_col, and dob_day_col
are present, assemble into a Date.
If age_years_col is present and a reference date exists,
estimate DOB as reference_date - age_years * 365.25.
Data frame with dob column added/populated.
Infers Community-Acquired (CAI) vs Hospital-Acquired (HAI) infection using the admission-to-culture date gap (default cutoff: 2 days / 48 hours).
prep_derive_hai_cai( data, infection_type_col = "infection_type", admission_col = "date_of_admission", culture_col = "date_of_culture", hai_cutoff = 2, overwrite = FALSE )prep_derive_hai_cai( data, infection_type_col = "infection_type", admission_col = "date_of_admission", culture_col = "date_of_culture", hai_cutoff = 2, overwrite = FALSE )
data |
Data frame. |
infection_type_col |
Character. Infection type column. Default "infection_type". |
admission_col |
Character. Admission date column. Default "date_of_admission". |
culture_col |
Character. Culture date column. Default "date_of_culture". |
hai_cutoff |
Numeric. Days after admission to classify as HAI. Default 2. |
overwrite |
Logical. Recalculate even when already present. Default FALSE. |
Data frame with infection_type enriched.
Sets icu_flag = TRUE where ward/department information indicates
the patient was in an ICU at the time of culture.
prep_derive_icu_flag( data, ward_col = "ward_icu", dept_col = "hospital_department" )prep_derive_icu_flag( data, ward_col = "ward_icu", dept_col = "hospital_department" )
data |
Data frame. |
ward_col |
Character. Ward/unit column. Default "ward_icu". |
dept_col |
Character. Department column. Default "hospital_department". |
Data frame with icu_flag logical column added.
Computes LOS when missing (or always when overwrite = TRUE).
Adds los_method and los_confidence audit columns.
For AIIMS data, uses unit_admission_date + unit_duration_days
as a fallback when primary date columns are absent.
prep_derive_los_from_dates( data, admission_col = "admission_date", outcome_col = "outcome_date", los_col = "los_days", unit_admission_col = "unit_admission_date", unit_duration_col = "unit_duration_days", overwrite = FALSE )prep_derive_los_from_dates( data, admission_col = "admission_date", outcome_col = "outcome_date", los_col = "los_days", unit_admission_col = "unit_admission_date", unit_duration_col = "unit_duration_days", overwrite = FALSE )
data |
Data frame. |
admission_col |
Character. Admission date column. Default "admission_date". |
outcome_col |
Character. Outcome/discharge date column. Default "outcome_date". |
los_col |
Character. Target LOS column to populate. Default "los_days". |
unit_admission_col |
Character. AIIMS unit admission date fallback. Default "unit_admission_date". |
unit_duration_col |
Character. AIIMS unit duration fallback. Default "unit_duration_days". |
overwrite |
Logical. Recalculate even when |
Priority order:
outcome_col - admission_col
unit_admission_date + unit_duration_days (AIIMS fallback)
Already-present los_col value retained as-is
Data frame with los_col, los_method, and
los_confidence populated where possible.
Compares column sets across a list of centre data frames. Flags columns present in some centres but not others.
prep_detect_schema_drift(data_list, reference_centre = NULL)prep_detect_schema_drift(data_list, reference_centre = NULL)
data_list |
Named list of data frames (one per centre). |
reference_centre |
Character or NULL. Name of the centre to treat as the reference schema. If NULL, the union of all columns is used. |
Tibble: column | present_in (comma-separated centres) | missing_from | n_centres_present
Combines a primary diagnosis column with an optional fallback column, trims whitespace, and collapses repeated separators. Optionally appends the organism name to the text (as the notebook does for context-aware embedding).
prep_diagnosis_text( data, diagnosis_col, fallback_col = NULL, output_col = "diagnosis_text", include_organism = FALSE, organism_col = "organism_normalized", keep_original = TRUE )prep_diagnosis_text( data, diagnosis_col, fallback_col = NULL, output_col = "diagnosis_text", include_organism = FALSE, organism_col = "organism_normalized", keep_original = TRUE )
data |
Data frame. |
diagnosis_col |
Character. Primary diagnosis column. |
fallback_col |
Character or NULL. Used when |
output_col |
Character. Name for the output text column.
Default |
include_organism |
Logical. Append organism name to the text. Default FALSE. |
organism_col |
Character. Organism column. Used only when
|
keep_original |
Logical. Keep the original diagnosis columns. Default TRUE. |
Data frame with output_col added.
Extract Genus from Organism Name
prep_extract_genus(data, organism_col = "organism_normalized")prep_extract_genus(data, organism_col = "organism_normalized")
data |
Data frame. |
organism_col |
Character. Organism column. Default "organism_normalized". |
Data frame with org_genus column added.
Extract Species from Organism Name
prep_extract_species(data, organism_col = "organism_normalized")prep_extract_species(data, organism_col = "organism_normalized")
data |
Data frame. |
organism_col |
Character. Organism column. Default "organism_normalized". |
Data frame with org_species column added.
Fills missing Age by computing from DOB and a reference date. Tracks derivation method and confidence for each record.
prep_fill_age( data, age_col = "Age", dob_col = "DOB", date_col = "date_of_culture", overwrite = FALSE )prep_fill_age( data, age_col = "Age", dob_col = "DOB", date_col = "date_of_culture", overwrite = FALSE )
data |
Data frame. |
age_col |
Character. Age column. Default "Age". |
dob_col |
Character. Date of birth column. Default "DOB". |
date_col |
Character. Reference date column. Default "date_of_culture". |
overwrite |
Logical. Recalculate even when Age is present. Default FALSE. |
Data frame with Age enriched plus age_method and
age_confidence columns.
Keeps records that meet the full burden-analysis readiness criteria:
Patient ID present
Culture date present
Organism name present and standardized
Antibiotic name present and standardized
Harmonized AST value in S/I/R
Not flagged as a contaminant (if column present)
prep_filter_analysis_ready( data, patient_col = "patient_id", culture_date_col = "culture_date", organism_col = "organism_name", antibiotic_col = "antibiotic_name", ast_col = "ast_value_harmonized", exclude_contaminants = TRUE, contaminant_col = "contaminant_flag" )prep_filter_analysis_ready( data, patient_col = "patient_id", culture_date_col = "culture_date", organism_col = "organism_name", antibiotic_col = "antibiotic_name", ast_col = "ast_value_harmonized", exclude_contaminants = TRUE, contaminant_col = "contaminant_flag" )
data |
Data frame after preprocessing. |
patient_col |
Character. Patient ID column. Default "patient_id". |
culture_date_col |
Character. Culture date column. Default "culture_date". |
organism_col |
Character. Organism column. Default "organism_name". |
antibiotic_col |
Character. Antibiotic column. Default "antibiotic_name". |
ast_col |
Character. Harmonized AST column. Default "ast_value_harmonized". |
exclude_contaminants |
Logical. Exclude rows flagged as contaminants. Default TRUE. |
contaminant_col |
Character. Contaminant flag column. Default "contaminant_flag". |
Filtered data frame.
Removes rows where the organism belongs to a fungal group. Logs the count of rows removed.
prep_filter_fungal( data, group_col = "organism_group", organism_col = "organism_normalized" )prep_filter_fungal( data, group_col = "organism_group", organism_col = "organism_normalized" )
data |
Data frame. |
group_col |
Character. Organism group column. Default "organism_group". |
organism_col |
Character. Normalized organism column used as fallback
when |
Data frame with fungal rows removed.
Keeps records that have the bare minimum fields needed for any analysis:
a patient identifier, a culture date, an organism name, and at least one
non-NA AST result. This is a looser filter than prep_filter_analysis_ready().
prep_filter_minimally_usable( data, patient_col = "patient_id", culture_date_col = "culture_date", organism_col = "organism_name", ast_col = "ast_value_harmonized" )prep_filter_minimally_usable( data, patient_col = "patient_id", culture_date_col = "culture_date", organism_col = "organism_name", ast_col = "ast_value_harmonized" )
data |
Data frame after preprocessing. |
patient_col |
Character. Patient ID column. Default "patient_id". |
culture_date_col |
Character. Culture date column. Default "culture_date". |
organism_col |
Character. Organism column. Default "organism_name". |
ast_col |
Character. Harmonized AST column. Default "ast_value_harmonized". |
Filtered data frame with only minimally usable rows.
Identifies likely contaminant organisms using multi-path logic (provided flags, device-based context, or heuristic organism+specimen matching).
prep_flag_contaminants( data, method = "auto", context = c("general", "icu_device"), organism_col = "organism_normalized", specimen_col = "specimen_type" )prep_flag_contaminants( data, method = "auto", context = c("general", "icu_device"), organism_col = "organism_normalized", specimen_col = "specimen_type" )
data |
Data frame. |
method |
Character. "auto" (try all methods), "device_based", "heuristic", or "provided". Default "auto". |
context |
Character. "general" or "icu_device". Default "general". |
organism_col |
Character. Normalized organism column. Default "organism_normalized". |
specimen_col |
Character. Specimen type column. Default "specimen_type". |
When context = "icu_device" (AIIMS ICU BSI data), CoNS in blood with
a central line present AND line in place > 2 days are classified as CLABSI
pathogens rather than contaminants.
Data frame with is_contaminant, contaminant_confidence,
and contaminant_method columns.
Adds an infection_type_src column indicating whether the infection type
was present in the raw data ("observed"), derived from dates ("inferred"), or
could not be determined ("unknown").
prep_flag_hai_inferred( data, infection_type_col = "infection_type", infection_type_method_col = "infection_type_method" )prep_flag_hai_inferred( data, infection_type_col = "infection_type", infection_type_method_col = "infection_type_method" )
data |
Data frame. |
infection_type_col |
Character. Raw/observed infection type column. Default "infection_type". |
infection_type_method_col |
Character. Method column added by
|
Data frame with infection_type_src column added.
Adds a logical column is_ast_invalid that is TRUE when the harmonized
AST value is not in c("S", "I", "R") and not NA.
prep_flag_invalid_ast(data, col = "ast_value_harmonized")prep_flag_invalid_ast(data, col = "ast_value_harmonized")
data |
Data frame. |
col |
Character. Harmonized AST column. Default "ast_value_harmonized". |
Data frame with is_ast_invalid column added.
Flags organisms that could not be matched to the reference organisms.csv.
Adds a logical column is_organism_unmatched.
prep_flag_organism_unmatched(data, organism_col = "organism_normalized")prep_flag_organism_unmatched(data, organism_col = "organism_normalized")
data |
Data frame with organism_normalized column. |
organism_col |
Character. Standard organism column. Default "organism_normalized". |
Data frame with is_organism_unmatched column.
Flags polymicrobial status by counting distinct organisms per patient (optionally scoped within facility and/or syndrome).
prep_flag_polymicrobial( data, patient_col = "patient_id", organism_col = "organism_normalized", facility_col = NULL, facility_name = NULL, syndrome_col = NULL, syndrome_name = NULL ) flag_polymicrobial( data, patient_col = "patient_id", organism_col = "organism_normalized", facility_col = NULL, facility_name = NULL, syndrome_col = NULL, syndrome_name = NULL )prep_flag_polymicrobial( data, patient_col = "patient_id", organism_col = "organism_normalized", facility_col = NULL, facility_name = NULL, syndrome_col = NULL, syndrome_name = NULL ) flag_polymicrobial( data, patient_col = "patient_id", organism_col = "organism_normalized", facility_col = NULL, facility_name = NULL, syndrome_col = NULL, syndrome_name = NULL )
data |
Data frame. |
patient_col |
Character. Patient ID column. Default "patient_id". |
organism_col |
Character. Organism column. Default "organism_normalized". |
facility_col |
Character or NULL. Facility column for scoped counting. |
facility_name |
Character or NULL. Filter to this facility before flagging. |
syndrome_col |
Character or NULL. Syndrome column for scoped counting. |
syndrome_name |
Character or NULL. Filter to this syndrome before flagging. |
Data frame with n_organisms and is_polymicrobial (0/1).
For each patient, classifies admissions into:
First admission for this patient.
Readmission within gap_linked_days – treated
as the same episode. Excluded from HAI incidence counts.
Readmission between gap_linked_days and
gap_new_days.
Readmission after gap_new_days – fully new
event.
prep_flag_readmission( data, patient_col = "patient_id", admission_col = "admission_date", gap_linked_days = 30, gap_new_days = 90 )prep_flag_readmission( data, patient_col = "patient_id", admission_col = "admission_date", gap_linked_days = 30, gap_new_days = 90 )
data |
Data frame. |
patient_col |
Character. Patient ID column. Default "patient_id". |
admission_col |
Character. Admission date column. Default "admission_date". |
gap_linked_days |
Numeric. Gap threshold for linked readmissions. Default 30. |
gap_new_days |
Numeric. Gap threshold for new vs late readmissions. Default 90. |
Data frame with readmission_class column added.
Loads contaminant organisms from common_commensals.csv and filters
by syndrome and/or specimen type.
prep_get_contaminant_list( syndrome = NULL, specimen_type = NULL, return_all = FALSE )prep_get_contaminant_list( syndrome = NULL, specimen_type = NULL, return_all = FALSE )
syndrome |
Character. Syndrome name to filter (e.g., "Bloodstream infections"). |
specimen_type |
Character. Specimen type to filter (e.g., "Blood culture"). |
return_all |
Logical. If TRUE, returns all contaminants across syndromes. Default FALSE. |
A list with names (character vector) and patterns
(list of pattern information for flexible matching).
Wrapper that applies the full AST cleaning pipeline in sequence:
prep_clean_ast_values() - extract clean S/I/R from raw strings
(handles exact matches, regex patterns, and keyword scanning in one pass)
prep_recode_intermediate_ast() - resolve I values
Retains the original ast_col column as ast_value_raw and adds
ast_value_harmonized and intermediate_recoded.
prep_harmonize_ast( data, antibiotic_col = "antibiotic_name_std", ast_col = "ast_value_raw", colistin_to_s = TRUE, others_to_r = TRUE )prep_harmonize_ast( data, antibiotic_col = "antibiotic_name_std", ast_col = "ast_value_raw", colistin_to_s = TRUE, others_to_r = TRUE )
data |
Data frame with AST data. |
antibiotic_col |
Character. Standardized antibiotic name column. Default "antibiotic_name_std". |
ast_col |
Character. Raw AST value column. Default "ast_value_raw". |
colistin_to_s |
Logical. Recode Colistin I -> S. Default TRUE. |
others_to_r |
Logical. Recode non-Colistin I -> R. Default TRUE. |
Data frame with ast_value_harmonized and
intermediate_recoded columns added.
Heuristically infers hospital department from specimen type, diagnosis, and patient age. Low-confidence inference; used only to fill missing values.
prep_infer_department( data, department_col = "hospital_department", specimen_col = "specimen_type", diagnosis_col = "diagnosis_1", age_col = "Age", overwrite = FALSE )prep_infer_department( data, department_col = "hospital_department", specimen_col = "specimen_type", diagnosis_col = "diagnosis_1", age_col = "Age", overwrite = FALSE )
data |
Data frame. |
department_col |
Character. Department column. Default "hospital_department". |
specimen_col |
Character. Specimen type column. Default "specimen_type". |
diagnosis_col |
Character. Diagnosis column. Default "diagnosis_1". |
age_col |
Character. Age column. Default "Age". |
overwrite |
Logical. Overwrite existing values. Default FALSE. |
Data frame with hospital_department enriched.
Returns a tibble describing every column: class, distinct values, and missingness. Used to detect completely empty columns and schema drift.
prep_inventory_columns(data)prep_inventory_columns(data)
data |
Data frame. |
Tibble: col_name | class | n_distinct | pct_missing | has_any_value
Checks whether an organism name matches any known contaminant for a specific syndrome or specimen type using flexible pattern matching.
prep_is_contaminant(organism_name, syndrome = NULL, specimen_type = NULL)prep_is_contaminant(organism_name, syndrome = NULL, specimen_type = NULL)
organism_name |
Character vector of organism name(s) to check. |
syndrome |
Character. Optional syndrome filter. |
specimen_type |
Character. Optional specimen type filter. |
Logical vector (same length as organism_name).
Records metadata about the source of data entering the pipeline. Returns a provenance metadata list attached as an attribute.
prep_log_source( data, study_type = "generic", centre_name = NULL, file_path = NULL, sheet_name = NULL )prep_log_source( data, study_type = "generic", centre_name = NULL, file_path = NULL, sheet_name = NULL )
data |
Data frame. |
study_type |
Character. One of "stewardship", "surveillance", "aiims_icu_bsi", "generic". |
centre_name |
Character. Name of the contributing centre. |
file_path |
Character. Path to the source file (optional). |
sheet_name |
Character. Sheet name within Excel file (optional). |
Data frame with .provenance attribute attached.
Maps free-text diagnosis strings to ICD-10 candidate descriptions using one of three methods:
prep_map_diagnosis_to_icd( data, text_col = "diagnosis_text", reference = NULL, method = c("exact", "fuzzy", "python_embedding"), icd_desc_col = "description3", icd_code_col = "icd_code_who_eq", top_k = 5L, threshold = 0, model = "FremyCompany/BioLORD-2023", id_col = NULL )prep_map_diagnosis_to_icd( data, text_col = "diagnosis_text", reference = NULL, method = c("exact", "fuzzy", "python_embedding"), icd_desc_col = "description3", icd_code_col = "icd_code_who_eq", top_k = 5L, threshold = 0, model = "FremyCompany/BioLORD-2023", id_col = NULL )
data |
Data frame. |
text_col |
Character. Column containing prepared diagnosis text
(output of |
reference |
Data frame or NULL. ICD-10 reference table. If NULL,
loads from |
method |
Character. One of |
icd_desc_col |
Character. Column in |
icd_code_col |
Character. Column in |
top_k |
Integer. Maximum ICD candidates to return per input string.
Default 5. Ignored for |
threshold |
Numeric. Minimum similarity score (0-1) to retain a
candidate. Default 0.0 (keep all). For |
model |
Character. Sentence-transformers model name. Used only for
|
id_col |
Character or NULL. Identifier column to carry through into the output. Default NULL (output contains only match columns). |
"exact"Case-insensitive exact string match against ICD descriptions. Fast, high precision, low recall.
"fuzzy"String distance matching via stringdist. Handles typos and minor variations. Requires stringdist.
"python_embedding"Semantic embedding similarity using the
Python alethia package via reticulate. Highest recall.
Requires Python, alethia, and a sentence-transformers model.
Long data frame with columns:
diagnosis_text, icd_prediction, icd_code,
icd_score, icd_rank, icd_method.
If id_col is supplied, it is included as the first column.
Joins an ICD-to-syndrome reference table onto the data. The reference must have at minimum two columns: an ICD code/description column and a syndrome column. Typically this is a manually curated mapping CSV.
prep_map_icd_to_syndrome( data, icd_col = "icd_code", icd_to_syndrome_ref, ref_icd_col = "icd_code", ref_syndrome_col = "infectious_syndrome", output_col = "syndrome", unmatched_label = NA_character_ )prep_map_icd_to_syndrome( data, icd_col = "icd_code", icd_to_syndrome_ref, ref_icd_col = "icd_code", ref_syndrome_col = "infectious_syndrome", output_col = "syndrome", unmatched_label = NA_character_ )
data |
Data frame (output of |
icd_col |
Character. Column in |
icd_to_syndrome_ref |
Data frame. Reference table with at minimum
|
ref_icd_col |
Character. The ICD column name in |
ref_syndrome_col |
Character. The syndrome column name in the reference.
Default |
output_col |
Character. Name for the syndrome column added to |
unmatched_label |
Character. Label for rows with no syndrome match.
Default |
Data frame with output_col added.
Generates a per-column summary of missing values. Flags columns where missingness exceeds a threshold.
prep_missingness_report(data, threshold = 20, cols = NULL)prep_missingness_report(data, threshold = 20, cols = NULL)
data |
Data frame. |
threshold |
Numeric. Percentage threshold (0-100) above which a column is flagged as high-missingness. Default 20. |
cols |
Character vector. Subset of columns to report on. NULL = all. |
Data frame with columns: col_name, n_total, n_missing, pct_missing, is_high_missing.
Inspects a column for date-like content and automatically selects the correct parsing strategy (Excel serial, Unix timestamp ms, ISO/DMY/MDY strings, reversed YYYYDDMM).
prep_parse_date_column(x, col_name = "date", table_label = "table")prep_parse_date_column(x, col_name = "date", table_label = "table")
x |
Vector (character, numeric, or Date-like) to parse. |
col_name |
Character. Column name used in messages. |
table_label |
Character. Table label used in messages. |
A Date vector of the same length as x.
Converts wide format data (where each antibiotic is a column) to long format (one row per organism-antibiotic combination). This is the first step before normalization and analysis.
prep_pivot_ast_wide_to_long( data, antibiotic_cols = NULL, pattern = NULL, id_cols = c("patient_id", "event_id", "organism_name", "date_of_culture"), antibiotic_name_col = "antibiotic_name", antibiotic_value_col = "antibiotic_value", remove_missing = TRUE, create_event_id = FALSE )prep_pivot_ast_wide_to_long( data, antibiotic_cols = NULL, pattern = NULL, id_cols = c("patient_id", "event_id", "organism_name", "date_of_culture"), antibiotic_name_col = "antibiotic_name", antibiotic_value_col = "antibiotic_value", remove_missing = TRUE, create_event_id = FALSE )
data |
Data frame in wide format (antibiotics as columns) |
antibiotic_cols |
Character vector. Names of antibiotic columns to pivot. If NULL, will auto-detect based on pattern. Default NULL. |
pattern |
Character. Regex pattern to identify antibiotic columns if antibiotic_cols not provided. Default NULL (no auto-detection). |
id_cols |
Character vector. Columns to keep as identifiers (not pivoted). Default c("patient_id", "event_id", "organism_name", "date_of_culture"). |
antibiotic_name_col |
Character. Name for the new column containing antibiotic names. Default "antibiotic_name". |
antibiotic_value_col |
Character. Name for the new column containing susceptibility results. Default "antibiotic_value". |
remove_missing |
Logical. Remove rows where antibiotic_value is NA, empty, or "-". Default TRUE. |
create_event_id |
Logical. Create event_id column if it doesn't exist (uses row numbers). Default FALSE. |
Data frame in long format
## Not run: # Specify antibiotic columns explicitly long_data <- prep_pivot_ast_wide_to_long( data = raw_data, antibiotic_cols = c("AMIKACIN", "GENTAMICIN", "CIPROFLOXACIN") ) # Auto-detect columns by pattern (columns 12-53) long_data <- prep_pivot_ast_wide_to_long( data = raw_data, antibiotic_cols = names(raw_data)[12:53] ) # Auto-detect uppercase antibiotic names long_data <- prep_pivot_ast_wide_to_long( data = raw_data, pattern = "^[A-Z]+$" ) ## End(Not run)## Not run: # Specify antibiotic columns explicitly long_data <- prep_pivot_ast_wide_to_long( data = raw_data, antibiotic_cols = c("AMIKACIN", "GENTAMICIN", "CIPROFLOXACIN") ) # Auto-detect columns by pattern (columns 12-53) long_data <- prep_pivot_ast_wide_to_long( data = raw_data, antibiotic_cols = names(raw_data)[12:53] ) # Auto-detect uppercase antibiotic names long_data <- prep_pivot_ast_wide_to_long( data = raw_data, pattern = "^[A-Z]+$" ) ## End(Not run)
Converts "I" (Intermediate) values to either "S" or "R" based on antibiotic. For Colistin: I -> S (clinical guideline). For all other antibiotics: I -> R (conservative surveillance approach).
prep_recode_intermediate_ast( data, antibiotic_col = "antibiotic_name", value_col = "antibiotic_value", colistin_to_s = TRUE, others_to_r = TRUE )prep_recode_intermediate_ast( data, antibiotic_col = "antibiotic_name", value_col = "antibiotic_value", colistin_to_s = TRUE, others_to_r = TRUE )
data |
Data frame with antibiotic susceptibility data. |
antibiotic_col |
Character. Column with antibiotic names. Default "antibiotic_name". |
value_col |
Character. Column with S/I/R values. Default "antibiotic_value". |
colistin_to_s |
Logical. Convert Colistin I to S. Default TRUE. |
others_to_r |
Logical. Convert other antibiotics' I to R. Default TRUE. |
Data frame with recoded intermediate values.
Where both an observed (raw) infection type and an inferred (date-derived) type exist, flags rows where they disagree. Retains observed classification by default and marks discordant records.
prep_reconcile_hai_observed_inferred( data, observed_col = "infection_type_observed", inferred_col = "infection_type_inferred", output_col = "infection_type" )prep_reconcile_hai_observed_inferred( data, observed_col = "infection_type_observed", inferred_col = "infection_type_inferred", output_col = "infection_type" )
data |
Data frame. |
observed_col |
Character. Observed infection type column. Default "infection_type_observed". |
inferred_col |
Character. Inferred infection type column. Default "infection_type_inferred". |
output_col |
Character. Reconciled output column. Default "infection_type". |
Data frame with reconciled infection_type and
hai_discordant logical flag.
Prints a human-readable summary of which preprocessing steps can be run given the current data columns.
prep_report_capabilities(data)prep_report_capabilities(data)
data |
Data frame after column mapping. Or pass the result of
|
Invisibly returns the capabilities vector.
Applies a chosen strategy for handling polymicrobial episodes:
Keep all rows; poly_weight is applied downstream
during DALY calculation.
Drop polymicrobial episodes from the main analysis frame.
Retain polymicrobial episodes in a separate data frame
stored in attr(result, "poly_data") for sensitivity analyses.
prep_split_poly_episode( data, strategy = c("fractional", "exclude", "separate"), polymicrobial_col = "is_polymicrobial" )prep_split_poly_episode( data, strategy = c("fractional", "exclude", "separate"), polymicrobial_col = "is_polymicrobial" )
data |
Data frame with |
strategy |
Character. "fractional" (default), "exclude", or "separate". |
polymicrobial_col |
Character. Polymicrobial flag column (0/1). Default "is_polymicrobial". |
Data frame with polymicrobial rows handled per strategy. When
strategy = "separate", the poly subset is in attr(result, "poly_data").
Standardizes antibiotic names using fuzzy matching against WHO AWaRe reference.
prep_standardize_antibiotics( data, antibiotic_col = "antibiotic_name", who_table = NULL, add_class = TRUE, add_aware = TRUE )prep_standardize_antibiotics( data, antibiotic_col = "antibiotic_name", who_table = NULL, add_class = TRUE, add_aware = TRUE )
data |
Data frame with antibiotic data. |
antibiotic_col |
Character. Column name with antibiotic names. Default "antibiotic_name". |
who_table |
Data frame. WHO AWaRe classification table. If NULL, loads from inst/extdata/WHO_aware_class.csv. |
add_class |
Logical. Add antibiotic_class column. Default TRUE. |
add_aware |
Logical. Add aware_category column. Default TRUE. |
Data frame with antibiotic_normalized, antibiotic_class, aware_category.
Convenience wrapper around prep_build_column_map() +
prep_apply_column_map(). Builds an exact-match map from
mapping aliases, optionally extends it with fuzzy matching, then
applies the rename in one call.
prep_standardize_column_names( data, mapping = default_column_mappings, fuzzy_match = TRUE, fuzzy_threshold = 0.3, interactive = FALSE )prep_standardize_column_names( data, mapping = default_column_mappings, fuzzy_match = TRUE, fuzzy_threshold = 0.3, interactive = FALSE )
data |
A data frame with raw column names. |
mapping |
Named list of standard_name -> aliases vectors. Default uses
|
fuzzy_match |
Logical. Enable fuzzy matching for unresolved standards. Default TRUE. |
fuzzy_threshold |
Numeric. Max Jaro-Winkler distance (0-1). Default 0.3. |
interactive |
Logical. Prompt user to confirm fuzzy matches. Default FALSE. |
For more control (e.g. dataset-specific maps, post-rename assertions) use
the staged API directly:
prep_build_column_map() -> prep_apply_column_map() ->
prep_assert_standard_names().
List: data (renamed), mapping_log, unmapped.
Normalizes outcome variants to a two-level controlled vocabulary: "Survived", "Died", or NA.
prep_standardize_final_outcome(data, col = "final_outcome")prep_standardize_final_outcome(data, col = "final_outcome")
data |
Data frame. |
col |
Character. Outcome column. Default "final_outcome". |
Survived / Alive / Discharge / Discharged / Recovered
Died / Death / Expired / Deceased / Dead
Unknown / Missing / Absconded / LAMA / DAMA
Data frame with outcome_std column added.
Normalizes HAI/CAI variants to a controlled vocabulary: "HAI", "CAI", or NA.
prep_standardize_infection_type(data, col = "infection_type")prep_standardize_infection_type(data, col = "infection_type")
data |
Data frame. |
col |
Character. Infection type column. Default "infection_type". |
Data frame with standardized infection_type column.
Standardizes organism names using organisms.csv reference file. Automatically handles abbreviations (E. coli), case variations, and typos.
prep_standardize_organisms( data, organism_col = "organism_name", add_organism_group = TRUE, add_resistance_flags = TRUE )prep_standardize_organisms( data, organism_col = "organism_name", add_organism_group = TRUE, add_resistance_flags = TRUE )
data |
Data frame with organism column. |
organism_col |
Character. Organism column name. Default "organism_name". |
add_organism_group |
Logical. Add organism_group column. Default TRUE. |
add_resistance_flags |
Logical. Add MRSA/MRCONS flags. Default TRUE. |
Data frame with organism_normalized, organism_group, and optionally resistance flag columns.
Deprecated. Use prep_standardize_final_outcome() instead, which
adds outcome_std ("Survived"/"Died"/NA) without overwriting the
original column.
prep_standardize_outcome(data, col = "final_outcome")prep_standardize_outcome(data, col = "final_outcome")
data |
Data frame containing outcome column. |
col |
Character. Name of outcome column. Default "final_outcome". |
Data frame with outcome_std column added.
Maps various gender/sex representations to standard "M" or "F".
prep_standardize_sex(data, col = "gender")prep_standardize_sex(data, col = "gender")
data |
Data frame containing gender column. |
col |
Character. Name of gender column. Default "gender". |
Data frame with standardized gender values.
Normalizes specimen/sample type names and adds sample_category and a collapsed sterile_classification from the reference CSV file. Includes rule-based text cleaning and fuzzy matching for common shorthand and minor misspellings.
prep_standardize_specimens( data, specimen_col = "specimen_type", add_categories = TRUE )prep_standardize_specimens( data, specimen_col = "specimen_type", add_categories = TRUE )
data |
Data frame with specimen column. |
specimen_col |
Character. Specimen column name. Default "specimen_type". |
add_categories |
Logical. Add sample_category and sterile_classification. sterile_classification is collapsed to Sterile, Non-Sterile, or Others/Ambiguous using specimen-specific rules for body-fluid, drain/device-associated, and unspecified samples. Default TRUE. |
Data frame with specimen_normalized, sample_category, and sterile_classification columns.
Final gate check before burden estimation. Confirms that the minimum standard AMR schema fields are present and have acceptable completeness.
prep_validate_analysis_ready( data, min_rows = 10L, max_missing_pct = 30, stop_on_failure = FALSE )prep_validate_analysis_ready( data, min_rows = 10L, max_missing_pct = 30, stop_on_failure = FALSE )
data |
Analysis-ready data frame. |
min_rows |
Integer. Minimum acceptable row count. Default 10. |
max_missing_pct |
Numeric. Maximum percent missing allowed for core fields. Default 30. |
stop_on_failure |
Logical. Stop if validation fails. Default FALSE. |
Invisibly returns a list: passes (logical), issues (character vector).
Checks that date sequences and derived values are internally consistent. Consolidates all cross-column date/age checks in one place: 1. admission_date <= culture_date <= outcome_date 2. dob <= admission_date 3. age in [0, 120] 4. age vs DOB-computed age within 2-year tolerance 5. "Died" rows must have an outcome date
prep_validate_date_logic( data, admission_col = "admission_date", culture_col = "culture_date", outcome_col = "outcome_date", dob_col = "dob", age_col = "age", outcome_value_col = "final_outcome" )prep_validate_date_logic( data, admission_col = "admission_date", culture_col = "culture_date", outcome_col = "outcome_date", dob_col = "dob", age_col = "age", outcome_value_col = "final_outcome" )
data |
Data frame with standard column names. |
admission_col |
Character. Admission date column. Default "admission_date". |
culture_col |
Character. Culture/event date column. Default "culture_date". |
outcome_col |
Character. Outcome date column. Default "outcome_date". |
dob_col |
Character. Date of birth column. Default "dob". |
age_col |
Character. Age column. Default "age". |
outcome_value_col |
Character. Outcome value column for death check. Default "final_outcome". |
Reports violations as warnings; does not drop or modify rows.
Invisibly returns data. Prints violation summary.
Convenience wrapper that calls prep_check_columns(),
prep_check_keys(), and prep_coerce_dates() in sequence.
Returns the date-coerced data along with a check report.
prep_validate_table( data, required_cols = character(), key_col = NULL, expected_types = character(), date_cols = NULL, table_label = "table", stop_on_missing = TRUE )prep_validate_table( data, required_cols = character(), key_col = NULL, expected_types = character(), date_cols = NULL, table_label = "table", stop_on_missing = TRUE )
data |
Data frame. |
required_cols |
Character vector of required column names. |
key_col |
Character. Primary/foreign key column to quality-check. |
expected_types |
Named character vector of expected column classes. |
date_cols |
Character vector of date column names to coerce. NULL triggers auto-detection. |
table_label |
Character. Label used in all messages. |
stop_on_missing |
Logical. Passed to |
A list with data (date-coerced) and report (check summary).
Calculates length of stay from admission and outcome dates, filters to discharged patients with valid LOS within a plausible range.
prepare_los_data( data, admission_col = "date_of_admission", outcome_date_col = "final_outcome_date", outcome_col = "final_outcome", patient_id_col = "PatientInformation_id", max_los = 200 )prepare_los_data( data, admission_col = "date_of_admission", outcome_date_col = "final_outcome_date", outcome_col = "final_outcome", patient_id_col = "PatientInformation_id", max_los = 200 )
data |
Data frame with patient-level records. |
admission_col |
Character. Column name for admission date.
Default |
outcome_date_col |
Character. Column name for outcome/discharge date.
Default |
outcome_col |
Character. Column name for outcome status.
Default |
patient_id_col |
Character. Column name for patient identifier.
Default |
max_los |
Numeric. Maximum plausible LOS in days. Default 200. |
Data frame with one row per patient-admission, including
LOS_days.
Flattens an arbitrary number of declared random-intercept blocks into the representation used by the generic Stan models and by every downstream mu-reconstruction site (profile generation, DALY aggregation, validation).
prepare_random_effects( data, random_effects, min_repeated_levels = NULL, singleton_threshold = 0.9, on_mostly_singleton = c("warn", "stop") )prepare_random_effects( data, random_effects, min_repeated_levels = NULL, singleton_threshold = 0.9, on_mostly_singleton = c("warn", "stop") )
data |
Data frame containing every declared block's group_col. |
random_effects |
Character vector (legacy) or list-of-blocks (see .normalize_random_effects_spec()). |
min_repeated_levels |
Optional integer. If supplied, a block whose number of levels with >=2 observations falls below this is checked INDEPENDENTLY of singleton_threshold below (previously this was bugged: nested inside the singleton_fraction check, so it was silently skipped whenever singleton_fraction fell at or below the threshold even if n_repeated_levels was itself too low). Triggers a stop (via on_mostly_singleton = "stop") or warning. NULL (default) never checks this – eligibility gating belongs in the analysis layer (see anumaan-analysis's random_effect_eligibility.R), not hardcoded into the package. |
singleton_threshold |
Numeric in (0, 1]. A block whose fraction of singleton levels (exactly 1 observation) exceeds this triggers a separate warning/stop, evaluated independently of min_repeated_levels. Default 0.90. |
on_mostly_singleton |
"warn" (default) or "stop" – applies to BOTH the min_repeated_levels check and the singleton_threshold check. |
An object of class "amr_random_effects": block metadata, level maps, per-event flattened group indices, nesting diagnostics.
Orchestrates the full preprocessing pipeline required before marginal
resistance computation and convex optimisation. Calls existing
prep_* package functions in sequence and returns a wide tibble
(one row per isolate) with antibiotic-class columns ready for
compute_marginals_from_data().
preprocess_for_profiles( data, col_map = list(isolate_col = "isolate_id", pathogen_col = "pathogen", ast_col = "ast_value", patient_col = "patient_id", date_col = "date_of_culture", geography_col = "state", specimen_col = "specimen_type", age_col = "age", dob_col = "dob", antibiotic_col = "antibiotic_name", class_col = "antibiotic_class", location_col = NULL, outcome_col = NULL), panel_map, stratify_by = NULL, outcome_col = NULL, who_table = NULL )preprocess_for_profiles( data, col_map = list(isolate_col = "isolate_id", pathogen_col = "pathogen", ast_col = "ast_value", patient_col = "patient_id", date_col = "date_of_culture", geography_col = "state", specimen_col = "specimen_type", age_col = "age", dob_col = "dob", antibiotic_col = "antibiotic_name", class_col = "antibiotic_class", location_col = NULL, outcome_col = NULL), panel_map, stratify_by = NULL, outcome_col = NULL, who_table = NULL )
data |
Data frame. Raw AST data in long or wide format. |
col_map |
Named list mapping logical roles to actual column names.
Same structure as in |
panel_map |
Named list. Mandatory. Maps each pathogen name to
a character vector of antibiotic class names to include in profile
estimation. Classes not in the panel are excluded and logged with reason
code |
stratify_by |
Character vector or |
outcome_col |
Character or |
who_table |
Data frame or |
Pipeline steps (in order):
Input validation via validate_profile_inputs().
Wide -> long conversion if wide format detected
(prep_pivot_ast_wide_to_long()).
AST value harmonisation – clean messy strings, resolve I values
(prep_harmonize_ast()).
Antibiotic name standardisation if no class column
(prep_standardize_antibiotics()).
Class assignment if still absent
(prep_classify_antibiotic_class()).
Class-level collapse: any R in class => class = R
(prep_collapse_class_level()). Counting unit is isolate_id.
Year derivation from date_col when "year" is in
stratify_by.
Organism-specific panel filter: retain only user-specified classes per pathogen.
Long -> wide pivot with antibiotic-class columns
(prep_create_wide_ast_matrix()).
Counting unit: All statistics are computed per unique
isolate_id. A patient with multiple isolates contributes one count
per isolate, not one count per patient.
A named list:
data_wideTibble. One row per isolate_id. Columns:
all metadata columns + one column per antibiotic class (values S / R / NA).
preprocessing_logTibble. One row per pipeline step with
columns step, n_rows_in, n_rows_out, message,
status.
panel_exclusionsTibble. All organism-class combinations
removed by the panel filter, with reason_code and
reason_text.
col_map_resolvedNamed list. Updated col_map with
any column names derived during preprocessing (e.g. the harmonised AST
column name, the resolved class column name).
detected_formatCharacter. "long" or "wide".
## Not run: result <- preprocess_for_profiles( data = raw_ast, col_map = list( isolate_col = "isolate_id", pathogen_col = "organism", ast_col = "result", patient_col = "pid", date_col = "culture_date", geography_col = "state", specimen_col = "specimen", age_col = "age", antibiotic_col = "drug_name" ), panel_map = list( "Klebsiella pneumoniae" = c("3GC", "Carbapenems", "Fluoroquinolones"), "Escherichia coli" = c("3GC", "Fluoroquinolones", "Aminoglycosides") ), stratify_by = c("geography", "year"), outcome_col = "final_outcome" ) result$data_wide # ready for compute_marginals_from_data() result$preprocessing_log # step-by-step row counts result$panel_exclusions # classes dropped per organism ## End(Not run)## Not run: result <- preprocess_for_profiles( data = raw_ast, col_map = list( isolate_col = "isolate_id", pathogen_col = "organism", ast_col = "result", patient_col = "pid", date_col = "culture_date", geography_col = "state", specimen_col = "specimen", age_col = "age", antibiotic_col = "drug_name" ), panel_map = list( "Klebsiella pneumoniae" = c("3GC", "Carbapenems", "Fluoroquinolones"), "Escherichia coli" = c("3GC", "Fluoroquinolones", "Aminoglycosides") ), stratify_by = c("geography", "year"), outcome_col = "final_outcome" ) result$data_wide # ready for compute_marginals_from_data() result$preprocessing_log # step-by-step row counts result$panel_exclusions # classes dropped per organism ## End(Not run)
Print AMR Configuration
## S3 method for class 'amr_config' print(x, ...)## S3 method for class 'amr_config' print(x, ...)
x |
An amr_config object |
... |
Additional arguments (not used) |
Print Preprocessing Report
## S3 method for class 'amr_preprocessing_report' print(x, ...)## S3 method for class 'amr_preprocessing_report' print(x, ...)
x |
An amr_preprocessing_report object |
... |
Additional arguments (not used) |
Print Method for AMR Preprocessing Results
## S3 method for class 'amr_result' print(x, ...)## S3 method for class 'amr_result' print(x, ...)
x |
amr_result object |
... |
Additional arguments (not used) |
Invisibly returns the object
Compute each event's total random-effect contribution from a flattened re_effect[D, total_re_levels] matrix (as emitted by the generic Stan models' generated re_effect, or reconstructed R-side from posterior draws of z_re/tau_re/L_corr_re). This is the SINGLE generic helper every downstream mu-reconstruction site should call instead of hand-summing hospital_effect/patient_effect/admission_effect.
re_contribution(re_effect, flat_group_index)re_contribution(re_effect, flat_group_index)
re_effect |
D x total_re_levels numeric matrix (one posterior draw). |
flat_group_index |
n_events x R integer matrix (see prepare_random_effects()$flat_group_index), or a single event's R-length integer vector. |
If flat_group_index is a matrix: n_events x D matrix of summed RE contributions. If a vector: length-D vector for one event.
Rounds a numeric vector so that the individual rounded values sum exactly to
a target total. Uses the largest-remainder method (Hamilton method).
Input is coerced with as.numeric(); non-numeric values become
NA.
round_to_sum(x, target = round(sum(x, na.rm = TRUE)))round_to_sum(x, target = round(sum(x, na.rm = TRUE)))
x |
Numeric vector to round. |
target |
Integer target sum. Default is
|
Integer vector of the same length as x whose sum equals
target across non-missing entries; missing values are preserved as
NA.
round_to_sum(c(3.3, 3.3, 3.4), target = 10)round_to_sum(c(3.3, 3.3, 3.4), target = 10)
Master function that orchestrates the complete AMR data preprocessing pipeline. Applies standardization, enrichment, and derivation in sequence.
run_preprocess( data, config = NULL, phases = "all", verbose = TRUE, validate = TRUE, generate_report = TRUE )run_preprocess( data, config = NULL, phases = "all", verbose = TRUE, validate = TRUE, generate_report = TRUE )
data |
Data frame. Raw AMR dataset. |
config |
Configuration object from amr_config(). If NULL, uses defaults. |
phases |
Character vector. Which phases to run: "standardize", "enrich", "derive", or "all" (default). Allows partial pipeline execution. |
verbose |
Logical. Print detailed progress messages. Default TRUE. |
validate |
Logical. Run validation checks before and after. Default TRUE. |
generate_report |
Logical. Generate preprocessing report. Default TRUE. |
Pipeline phases: 1. **Standardization**: Column mapping, value normalization, date parsing 2. **Enrichment**: Derive missing optional variables (Age, LOS, infection type) 3. **Derivation**: Create analytical variables (event IDs, MDR/XDR, weights)
List with class "amr_result": - data: Preprocessed data frame - config: Configuration used - log: List of processing logs and summaries - report: Preprocessing report (if generate_report = TRUE) - metadata: Pipeline execution metadata
## Not run: # Full pipeline with defaults result <- run_preprocess(raw_data) clean_data <- result$data # Custom configuration config <- amr_config( hai_cutoff = 3, mdr_definition = "CDC", fuzzy_match = TRUE ) result <- run_preprocess(raw_data, config = config) # Run only standardization phase result <- run_preprocess(raw_data, phases = "standardize") # Summary summary(result) ## End(Not run)## Not run: # Full pipeline with defaults result <- run_preprocess(raw_data) clean_data <- result$data # Custom configuration config <- amr_config( hai_cutoff = 3, mdr_definition = "CDC", fuzzy_match = TRUE ) result <- run_preprocess(raw_data, config = config) # Run only standardization phase result <- run_preprocess(raw_data, phases = "standardize") # Summary summary(result) ## End(Not run)
Wrapper around fitdistrplus::fitdist that returns NULL
instead of throwing an error when fitting fails.
safe_fit(x, dist)safe_fit(x, dist)
x |
Numeric vector of positive values (e.g., LOS in days). |
dist |
Character. Distribution name: |
A fitdist object, or NULL on failure.
safe_fit(rlnorm(100), "lnorm")safe_fit(rlnorm(100), "lnorm")
Selects a single resistance class per event using beta-lactam hierarchy and relative risk (RR) values. Prevents double-counting in DALY burden estimation by choosing the most clinically relevant resistant class.
select_resistance_class( data, event_col = "event_id", class_col = "antibiotic_class", susceptibility_col = "antibiotic_value", rr_col = "rr_value", hierarchy = NULL, filter_resistant = TRUE )select_resistance_class( data, event_col = "event_id", class_col = "antibiotic_class", susceptibility_col = "antibiotic_value", rr_col = "rr_value", hierarchy = NULL, filter_resistant = TRUE )
data |
Data frame with class-level resistance and RR columns. |
event_col |
Character. Event ID column. Default "event_id". |
class_col |
Character. Antibiotic class column. Default "antibiotic_class". |
susceptibility_col |
Character. Susceptibility column. Default "antibiotic_value". |
rr_col |
Character. RR value column. Default "rr_value". If missing, only hierarchy is used. |
hierarchy |
Named numeric vector. Custom hierarchy (class name -> rank).
If NULL, uses |
filter_resistant |
Logical. If TRUE, only consider resistant (R) classes. Default TRUE. |
Selection order: 1. Beta-lactam hierarchy rank (Carbapenems > 4GC > 3GC > ...) 2. RR value (higher relative risk = higher priority) 3. Alphabetical tie-breaker
Data frame filtered to one resistance class per event.
Maps long antibiotic class names to common abbreviations used in GBD-style figures.
shorten_drug_class(x)shorten_drug_class(x)
x |
Character vector of antibiotic class names. |
Character vector of shortened names.
shorten_drug_class(c("Carbapenems", "Third-generation-cephalosporins"))shorten_drug_class(c("Carbapenems", "Third-generation-cephalosporins"))
For each requested block in blocks_to_replicate, retains
the posterior draws of and the block's own fitted
cross-class correlation (a generated quantity
already stored in fitted_model$draws), but draws
n_new_levels_per_block ENTIRELY NEW synthetic level effects
per posterior
state, where . Every real fitted event
is deterministically (seeded) reassigned to one of the
n_new_levels_per_block new synthetic levels for each replicated
block, so a complete replicate outcome matrix can be generated exactly as
in simulate_probit_posterior_predictive. Blocks NOT in
blocks_to_replicate use their FITTED posterior random effects
(unreplicated_block_behavior = "retain_fitted", default) or cause
an error ("error") if any declared block is left unhandled.
simulate_probit_mixed_predictive( fitted_model, blocks_to_replicate, n_states = 500L, seed = 123L, n_new_levels_per_block = 1L, unreplicated_block_behavior = c("retain_fitted", "error") )simulate_probit_mixed_predictive( fitted_model, blocks_to_replicate, n_states = 500L, seed = 123L, n_new_levels_per_block = 1L, unreplicated_block_behavior = c("retain_fitted", "error") )
fitted_model |
A fitted model object as returned by
|
blocks_to_replicate |
Character vector; a subset of
|
n_states |
Integer; number of posterior states to use. Default 500. |
seed |
Integer seed (deterministic). |
n_new_levels_per_block |
Integer; how many new synthetic levels to draw per replicated block. Default 1. |
unreplicated_block_behavior |
|
This is NOT standard posterior predictive checking (which conditions on
the observed groups' own fitted random effects) – do not conflate the
two. blocks_to_replicate is currently exercised for a single
block at a time in this package's own tests (the hospital-level use case
explicitly scoped by Part 13 of the predictive-checking specification);
multi-block replication is implemented generically but not yet covered
by synthetic recovery tests.
An object of class c("amr_mixed_predictive_draws",
"amr_ppc_draws") with setup, generate_state, and the
other fields shared with
simulate_probit_posterior_predictive's return value, plus
blocks_to_replicate, unreplicated_blocks,
n_new_levels_per_block, unreplicated_block_behavior.
Stan Development Team. "Posterior and Prior Predictive Checks." Stan User's Guide. https://mc-stan.org/docs/stan-users-guide/posterior-predictive-checks.html
For each of n_states saved posterior states and each fitted
event , reconstructs
using the existing generic random-effect machinery
(prepare_random_effects/re_contribution –
never hardcoded block names), then draws a COMPLETE replicate outcome
matrix unconditionally from : Bernoulli(Phi(mu)) per class for identity residual
models, or Z ~ MVN(mu, Omega); Y = I(Z > 0) for correlated residual
models (see Stan User's Guide,
https://mc-stan.org/docs/stan-users-guide/posterior-predictive-checks.html).
simulate_probit_posterior_predictive( fitted_model, n_states = 500L, seed = 123L, preserve_observation_mask = TRUE, return_replicates = FALSE, replicate_random_effects = FALSE, random_effect_blocks_to_replicate = NULL )simulate_probit_posterior_predictive( fitted_model, n_states = 500L, seed = 123L, preserve_observation_mask = TRUE, return_replicates = FALSE, replicate_random_effects = FALSE, random_effect_blocks_to_replicate = NULL )
fitted_model |
A fitted model object as returned by
|
n_states |
Integer; number of saved posterior states to use (a random subsample, seeded, if fewer than the total number of saved draws). Default 500; use 1000-2000 for shortlisted models. |
seed |
Integer seed for state subsampling and stochastic generation. |
preserve_observation_mask |
Logical, default |
return_replicates |
Logical, default |
replicate_random_effects, random_effect_blocks_to_replicate
|
Reserved
for API compatibility with the (distinct) mixed predictive check. Not
implemented here – passing a non-default value errors with a pointer to
|
This function NEVER calls the internal DALY conditional-completion helper
(.gibbs_conditional_profile_probs()) – that function samples
missing cells conditional on an event's own observed AST signs, which is a
fundamentally different (and, for this purpose, wrong) generative
mechanism. See the file header of probit_posterior_predictive.R and
test-probit-posterior-predictive.R for the explicit distinction and
regression test.
By default (return_replicates = FALSE), no S x N_events x D
array is ever materialised – this function returns a lightweight
generator object (class "amr_ppc_draws") that
compute_probit_ppc_statistics drives one state at a time,
streaming, to bound peak memory at O(N_events x D) rather than
O(S x N_events x D). Each state's replicate is generated under a
temporary, locally-seeded RNG state derived deterministically from
(seed, s) alone (restoring the caller's global RNG state
afterwards) – so a given state's draw depends only on seed,
s, and that state's posterior parameters, never on call order, on
interleaving with any other generator object, or on any other RNG use
elsewhere in the calling session. Draws are cached per state, so calling
the generator repeatedly for the same s is idempotent.
return_replicates = TRUE additionally materialises the full
replicate arrays and is intended for small debugging datasets only; a
safety ceiling refuses to silently run this on a large realistic dataset
(reduce n_states or leave return_replicates = FALSE
instead).
An object of class "amr_ppc_draws": a list with
setup (internal draw-setup object), generate_state
(a function of one integer argument s returning
list(Y_rep_complete, Y_rep) for that state), n_states_used,
seed_used, preserve_observation_mask, residual_structure,
return_replicates, and (only when return_replicates = TRUE)
Y_rep_array/Y_rep_complete_array.
Stan Development Team. "Posterior and Prior Predictive Checks." Stan User's Guide. https://mc-stan.org/docs/stan-users-guide/posterior-predictive-checks.html
Draws n_states independent parameter states directly from the
declared priors (no NUTS/no conditioning on outcomes) and generates a
complete replicate outcome matrix from each, using the REAL fixed-effect
design matrix and random-effect grouping structure of fitted_model
as conditioning predictors (per Stan User's Guide-style prior predictive
simulation). Reuses the identical generative mechanism as
simulate_probit_posterior_predictive (Bernoulli(Phi(mu)) for
identity residual, Z ~ MVN(mu, Omega); Y = I(Z>0) for correlated
residual) – only the source of theta differs (prior vs. posterior
draws).
simulate_probit_prior_predictive( fitted_model, n_states = 1000L, seed = 123L, prior_config_override = NULL, preserve_observation_mask = TRUE, return_replicates = FALSE )simulate_probit_prior_predictive( fitted_model, n_states = 1000L, seed = 123L, prior_config_override = NULL, preserve_observation_mask = TRUE, return_replicates = FALSE )
fitted_model |
A fitted model object as returned by
|
n_states |
Integer; number of independent prior states to draw. Default 1000. |
seed |
Integer seed (deterministic). |
prior_config_override |
Optional named list overriding any of
|
preserve_observation_mask, return_replicates
|
Returns an object of class c("amr_prior_predictive_draws",
"amr_ppc_draws") – structurally compatible with
compute_probit_ppc_statistics (which accepts any
"amr_ppc_draws"-classed object), so the same AMR-specific
discrepancy-statistic machinery can summarise the prior predictive
distribution's own properties (see
compute_prior_predictive_status, which additionally derives
the prior-specific plausibility summaries in Part 11 of the predictive-
checking specification: fraction of event-class probabilities near 0/1,
fraction of degenerate all-resistant/all-susceptible profiles, and
hospital-level spread).
An "amr_prior_predictive_draws"/"amr_ppc_draws"
object with the same shape as
simulate_probit_posterior_predictive's return value.
Stan Development Team. "Posterior and Prior Predictive Checks." Stan User's Guide. https://mc-stan.org/docs/stan-users-guide/posterior-predictive-checks.html
Extracts mean, median, SD, and parameter values from a fitdist
object for Weibull, Lognormal, or Gamma distributions.
summarise_distribution(fit, dist)summarise_distribution(fit, dist)
fit |
A |
dist |
Character. One of |
Data frame with columns Mean_LOS, Median_LOS,
SD_LOS, Parameters.
fit <- fitdistrplus::fitdist(rlnorm(200), "lnorm") summarise_distribution(fit, "lnorm")fit <- fitdistrplus::fitdist(rlnorm(200), "lnorm") summarise_distribution(fit, "lnorm")
Documents how original column names were mapped to standard names.
summarize_column_mapping(raw_data, processed_data, mapping_log)summarize_column_mapping(raw_data, processed_data, mapping_log)
raw_data |
Original data |
processed_data |
Processed data |
mapping_log |
Column mapping log from preprocessing |
Data frame with mapping details
Computes data quality metrics before and after preprocessing.
summarize_data_quality(raw_data, processed_data, include_plots = TRUE)summarize_data_quality(raw_data, processed_data, include_plots = TRUE)
raw_data |
Original data |
processed_data |
Processed data |
include_plots |
Logical. Generate plots. Default TRUE. |
List with quality metrics
Extracts posterior mean/median/CI for each off-diagonal cell of a named correlation-matrix generated quantity (e.g. "Omega", "R_hospital", "R_patient", "R_admission"). These are three distinct quantities and must not be combined into one table: Omega is the event-level residual cross-class correlation (only estimated when residual_structure == "correlated"); R_hospital/R_patient/R_admission are the correlation, across antibiotic classes, of that random effect's own tendencies (estimated regardless of residual_structure, since the hospital/patient/admission random effects always use a diag_pre_multiply(tau, L_corr) parameterisation). Returns NULL if the requested matrix_var is not present in fit$draws (e.g. Omega on an identity-residual fit, or R_admission on a 1- or 2-RE fit).
summarize_fit_correlation_matrix( fit, matrix_var, class_cols, ci_level = 0.95, block_index = NULL )summarize_fit_correlation_matrix( fit, matrix_var, class_cols, ci_level = 0.95, block_index = NULL )
fit |
A fitted_model object (or its lightweight saved form) with a
|
matrix_var |
Character. One of "Omega", "R_hospital", "R_patient", "R_admission". |
class_cols |
Character vector of antibiotic class column names, in the same order used to fit the model (dimension order of matrix_var). |
ci_level |
Numeric credible-interval level. Default 0.95. |
block_index |
Integer or NULL. When the fit used the generic
random-effect architecture (Stage 1), per-block correlation matrices are
emitted as |
A tibble with one row per off-diagonal class pair, or NULL if matrix_var was not estimated for this fit.
Creates summary statistics for the original input dataset.
summarize_raw_data(data)summarize_raw_data(data)
data |
Raw input data frame |
List with raw data summaries
Documents all transformations applied to data values.
summarize_transformations(raw_data, processed_data, preprocessing_log)summarize_transformations(raw_data, processed_data, preprocessing_log)
raw_data |
Original data |
processed_data |
Processed data |
preprocessing_log |
Full preprocessing log |
List with transformation summaries
Prints a formatted summary of preprocessing pipeline results.
## S3 method for class 'amr_result' summary(object, ...)## S3 method for class 'amr_result' summary(object, ...)
object |
amr_result object from run_preprocess() |
... |
Additional arguments (not used) |
Invisibly returns the object
## Not run: result <- run_preprocess(data) summary(result) ## End(Not run)## Not run: result <- run_preprocess(data) summary(result) ## End(Not run)
Validates a pre-computed marginal resistance table (e.g. from GBD or a
surveillance network) before it is passed to estimate_profiles_convex().
Checks prevalence bounds, duplicate rows, zero-denominator cells, impossible
pairwise values, and minimum class counts per pathogen.
validate_aggregate_inputs( marginals, pairwise = NULL, pathogen_col = "pathogen", class_col = "antibiotic_class", rate_col = "marginal_resistance", n_tested_col = "n_tested", n_resistant_col = "n_resistant", class1_col = "antibiotic_class_1", class2_col = "antibiotic_class_2", pairwise_rate_col = "pairwise_resistance_prevalence", min_classes_per_pathogen = 2L )validate_aggregate_inputs( marginals, pairwise = NULL, pathogen_col = "pathogen", class_col = "antibiotic_class", rate_col = "marginal_resistance", n_tested_col = "n_tested", n_resistant_col = "n_resistant", class1_col = "antibiotic_class_1", class2_col = "antibiotic_class_2", pairwise_rate_col = "pairwise_resistance_prevalence", min_classes_per_pathogen = 2L )
marginals |
Data frame with at minimum columns |
pairwise |
Data frame or |
pathogen_col |
Character. Default |
class_col |
Character. Default |
rate_col |
Character. Marginal resistance rate column.
Default |
n_tested_col |
Character or |
n_resistant_col |
Character or |
class1_col |
Character. Default |
class2_col |
Character. Default |
pairwise_rate_col |
Character. Default |
min_classes_per_pathogen |
Integer. Pathogens with fewer classes are
flagged. Default |
Tibble of check results (same schema as
validate_profile_inputs()). Stops on any "fail".
For hospital x pathogen panels (from .resolve_profile_class_panel(),
the same approved-eligibility panel used for DALY profiles) with at least
min_complete_events events that have every panel class
actually observed (no imputation involved), compares the empirical
complete-profile frequency distribution against the model-implied profile
probability distribution for that same event cohort. With identity residuals
it uses the analytic product of per-class ; with
correlated residuals it uses correlated MVN simulation with ,
as if the classes had not been observed – i.e. the model's unconditional
prediction, deliberately NOT using
compute_event_profile_probabilities()'s observed-cell-preserving
logic, since the point here is to check whether the model's predictions
agree with what was actually measured). Panels without enough complete
events are skipped and the reason is recorded in the status column
rather than silently omitted.
validate_complete_profile_calibration( fitted_model, n_posterior_draws_for_validation = 2000L, seed = 123L, ci_level = 0.95, min_complete_events = 30L, n_mc_profile_replicates = 200L )validate_complete_profile_calibration( fitted_model, n_posterior_draws_for_validation = 2000L, seed = 123L, ci_level = 0.95, min_complete_events = 30L, n_mc_profile_replicates = 200L )
fitted_model |
List returned by |
n_posterior_draws_for_validation |
Integer. Posterior draws used.
Default |
seed |
Integer. Random seed (draw subsampling only). Default |
ci_level |
Numeric. Credible interval coverage. Default |
min_complete_events |
Integer. Minimum number of fully-observed-panel
events required to evaluate a hospital-pathogen panel. Default |
n_mc_profile_replicates |
Integer. Correlated residual structure only:
inner Monte Carlo replicate count |
Tibble with one row per hospital x pathogen x profile for evaluated
panels (status = "evaluated": empirical_count/frequency,
model_frequency_mean/lower/upper, absolute_error,
interval_contains_observed) and one row per skipped panel
(status starts with "skipped_", numeric columns NA).
Validates a compute configuration for CPU or OpenCL execution. This checks only package/toolchain availability and the structure of the requested configuration; it does not inspect machine-specific GPU inventories.
validate_compute_backend(compute = list())validate_compute_backend(compute = list())
compute |
Named list. Supported fields are |
A canonical validated list with fields
backend, opencl_platform_id, opencl_device_id, and
allow_cpu_fallback.
Checks that configuration parameters are valid.
validate_config(config)validate_config(config)
config |
An amr_config object |
Logical. TRUE if valid, stops with error if invalid.
Runs quality checks: minimum row count, required column presence, and maximum missing-value percentage per column.
validate_data_quality( data, min_rows = 10, max_missing_pct = 50, required_cols = c("patient_id", "organism_normalized"), stop_on_failure = FALSE )validate_data_quality( data, min_rows = 10, max_missing_pct = 50, required_cols = c("patient_id", "organism_normalized"), stop_on_failure = FALSE )
data |
Data frame to validate. |
min_rows |
Integer. Minimum acceptable number of rows. Default 10. |
max_missing_pct |
Numeric. Maximum acceptable percent missing per column (0-100). Default 50. |
required_cols |
Character vector. Columns that must be present. |
stop_on_failure |
Logical. Stop with error on failure. Default FALSE. |
List with quality assessment.
For every hospital x pathogen x antibiotic-class cell with adequate
observed testing support, compares the observed marginal resistance rate
against the model's fitted probability , averaged over
the same tested-event cohort and over posterior draws. This is a
model-validation calculation: it uses the fitted probability for TESTED
cells (unlike compute_event_profile_probabilities(), which never
overwrites an observed value). A calibration residual near 0 and interval
coverage near the nominal CI level indicate the model reproduces the
observed marginal resistance rates; it does not by itself validate joint
(pairwise/profile) structure.
validate_marginal_calibration( fitted_model, n_posterior_draws_for_validation = 2000L, seed = 123L, ci_level = 0.95, min_tested = NULL, min_resistant = NULL, min_susceptible = NULL )validate_marginal_calibration( fitted_model, n_posterior_draws_for_validation = 2000L, seed = 123L, ci_level = 0.95, min_tested = NULL, min_resistant = NULL, min_susceptible = NULL )
fitted_model |
List returned by |
n_posterior_draws_for_validation |
Integer. Posterior draws used.
Default |
seed |
Integer. Random seed (draw subsampling only). Default |
ci_level |
Numeric. Credible interval coverage. Default |
min_tested, min_resistant, min_susceptible
|
Integer or |
Tibble, one row per eligible hospital x pathogen x class cell:
n_events, n_tested, n_resistant, n_susceptible,
observed_resistance, model_resistance_mean/lower/upper,
absolute_error, calibration_residual,
interval_contains_observed.
For every adequately co-tested hospital x pathogen x class-pair
combination, compares the observed pairwise resistance rate
() against the model's implied joint
probability, computed differently by residual structure:
– the two classes are combined
only through the shared fixed and random effects in , not
through any residual correlation (the identity model has none).
This checks whether the identity-residual model reproduces
observed pairwise resistance through shared covariates and random
effects; it is not evidence that a residual-independence assumption
is correct. Persistent pairwise miscalibration despite good marginal
calibration suggests unmodelled class-to-class dependence that a
correlated-residual fit might capture.
– the standard
bivariate-probit identity
for , with
from the fitted residual
correlation matrix (computed via pbivnorm). This actually uses
the fitted correlation structure, unlike the identity-model product
formula – checking whether reproduces observed
co-resistance.
validate_pairwise_calibration( fitted_model, n_posterior_draws_for_validation = 2000L, seed = 123L, ci_level = 0.95, min_cotested = NULL )validate_pairwise_calibration( fitted_model, n_posterior_draws_for_validation = 2000L, seed = 123L, ci_level = 0.95, min_cotested = NULL )
fitted_model |
List returned by |
n_posterior_draws_for_validation |
Integer. Posterior draws used.
Default |
seed |
Integer. Random seed (draw subsampling only). Default |
ci_level |
Numeric. Credible interval coverage. Default |
min_cotested |
Integer or |
Tibble, one row per eligible hospital x pathogen x class-pair:
n_cotested, observed_RR/RS/SR/SS,
observed_pairwise_resistance, model_pairwise_mean/lower/upper,
absolute_error, interval_contains_observed.
Checks that all mandatory columns exist, detects long vs wide format, validates AST content, and verifies that columns required for any requested stratification are present. Returns a tibble of check results and stops on any failed mandatory check.
validate_profile_inputs( data, col_map = list(isolate_col = "isolate_id", pathogen_col = "pathogen", ast_col = "ast_value", patient_col = "patient_id", date_col = "date_of_culture", geography_col = "state", specimen_col = "specimen_type", age_col = "age", dob_col = "dob", antibiotic_col = "antibiotic_name", class_col = "antibiotic_class", location_col = NULL, outcome_col = NULL), stratify_by = NULL, outcome_col = NULL )validate_profile_inputs( data, col_map = list(isolate_col = "isolate_id", pathogen_col = "pathogen", ast_col = "ast_value", patient_col = "patient_id", date_col = "date_of_culture", geography_col = "state", specimen_col = "specimen_type", age_col = "age", dob_col = "dob", antibiotic_col = "antibiotic_name", class_col = "antibiotic_class", location_col = NULL, outcome_col = NULL), stratify_by = NULL, outcome_col = NULL )
data |
Data frame to validate. |
col_map |
Named list mapping logical roles to actual column names.
Defaults use standard package column names. Set any entry to |
stratify_by |
Character vector or |
outcome_col |
Character or |
Mandatory columns (always):
isolate_col – unique isolate identifier; the counting unit
for all resistance statistics. One patient may have multiple isolates.
pathogen_col – organism / pathogen name.
ast_col – susceptibility result; must contain S / I / R.
patient_col – patient identifier (retained for context, not counted).
date_col – culture date; used to derive year when
"year" is in stratify_by.
geography_col – geographic unit (state / district).
specimen_col – specimen type (blood, urine, etc.).
age_col OR dob_col – at least one must be present.
Mandatory in long format only:
antibiotic_col – antibiotic / drug name column.
Optional (warn if absent, do not stop):
class_col – antibiotic class; derived from antibiotic_col
via WHO AWaRe reference if absent.
location_col – ward / ICU / OPD; retained for subgroup outputs.
outcome_col – patient outcome; required for outcome stratification.
A tibble with columns check_name, status
("pass" / "warn" / "fail"), message, and
n_affected. The attribute detected_format ("long" or
"wide") is attached. Stops with an informative message if any
mandatory check fails.
## Not run: report <- validate_profile_inputs( data = my_ast_data, col_map = list( isolate_col = "isolate_id", pathogen_col = "organism", ast_col = "result", patient_col = "pid", date_col = "culture_date", geography_col = "state", specimen_col = "specimen", age_col = "age_years", dob_col = NULL, antibiotic_col = "drug_name", class_col = NULL, location_col = "ward", outcome_col = "discharge_status" ), stratify_by = c("geography", "year"), outcome_col = "discharge_status" ) ## End(Not run)## Not run: report <- validate_profile_inputs( data = my_ast_data, col_map = list( isolate_col = "isolate_id", pathogen_col = "organism", ast_col = "result", patient_col = "pid", date_col = "culture_date", geography_col = "state", specimen_col = "specimen", age_col = "age_years", dob_col = NULL, antibiotic_col = "drug_name", class_col = NULL, location_col = "ward", outcome_col = "discharge_status" ), stratify_by = c("geography", "year"), outcome_col = "discharge_status" ) ## End(Not run)
Validate required fields exist and meet completeness threshold
validate_required_fields( data, required_cols, stop_on_failure = TRUE, allow_na = FALSE, min_completeness = 0.8 )validate_required_fields( data, required_cols, stop_on_failure = TRUE, allow_na = FALSE, min_completeness = 0.8 )
data |
Data frame. |
required_cols |
Character vector of required column names. |
stop_on_failure |
Logical. Stop if validation fails. Default TRUE. |
allow_na |
Logical. Skip completeness checks if TRUE. Default FALSE. |
min_completeness |
Numeric (0-1). Minimum completeness required. Default 0.8. |
List with validation result details.