(v3.0.1.9116) New sir_combine() for combination therapy as one engine for antibiogram(), wisca(), count_*() and proportion_*() (#321), and make all suggested packages runtime-only with a new CI workflow without dplyr

- New sir_combine() to combine SIR results of multiple antimicrobials into one variable; antibiogram(), wisca() and the count/proportion functions now use the same engine (antibiogram() and wisca() output unchanged)
- With multiple antimicrobials, count_*() and proportion_*() now follow the documented combination therapy rules: resistance() is the proportion of failing combinations, count_all() excludes isolates with an unknown combination result, and WT/NWT/NS/NI are handled correctly
- where() is now decided at runtime instead of at installation, fixing antibiogram() and wisca() without tidyselect (e.g. CRAN binaries without dplyr)
- Imports from data.table and cli moved to .onLoad(); data.table functions are only used while it is loaded; the like() example no longer unloads data.table, which crashed R
- Static test that fails on code outside functions depending on suggested packages
- New check-without-dplyr workflow: installs AMR with all suggested packages, removes dplyr (and tidyselect), then runs all unit tests and examples against the installed package
- g.test() now returns the degrees of freedom as 'parameter', so they are printed
- Fix R CMD check NOTEs (hidden .claude folder, lost braces in inherited g.test and ggplot_pca docs)
This commit is contained in:
dr. M.S. (Matthijs) Berends committed 2026-10-11 20:36:31 +02:00
1 parent 80afedeb8c
commit 53d0704271
30 files changed
+939 -268

No files matched your search

+30 -29
View File
@@ -1715,40 +1715,41 @@ readRDS_AMR <- function(file, refhook = NULL) {
readRDS(con, refhook = refhook)
}
# Support `where()` if tidyselect not installed ----
if (!is.null(import_fn("where", "tidyselect", error_on_fail = FALSE))) {
# tidyselect::where() exists, retrieve from their namespace to make `where()`s work across the package in default arguments
where <- tidyselect::where
} else {
where <- function(fn) {
# based on https://github.com/nathaneastwood/poorman/blob/52eb6947e0b4430cd588976ed8820013eddf955f/R/where.R#L17-L32
if (!is.function(fn)) {
stop_("{.fun ", deparse(substitute(fn)), "} is not a valid predicate function.")
}
df <- pm_select_env$.data
cols <- pm_select_env$get_colnames()
if (is.null(df)) {
df <- get_current_data("where", call = FALSE)
cols <- colnames(df)
}
preds <- unlist(lapply(
df,
function(x, fn) {
do.call("fn", list(x))
},
fn
))
if (!is.logical(preds)) stop_("{.fun where} must be used with functions that return {.code TRUE} or {.code FALSE}.")
data_cols <- cols
cols <- data_cols[preds]
which(data_cols %in% cols)
# Support `where()`, also if tidyselect not installed ----
# this must be decided at runtime, not at installation: a copy of tidyselect::where() made during installation fails if tidyselect is not available at runtime, e.g. for binary packages built on a machine with tidyselect
where <- function(fn) {
if (pkg_is_available("tidyselect") && !is.null(tryCatch(tidyselect::peek_vars(fn = "where"), error = function(e) NULL))) {
# called inside a tidyselect selection, such as dplyr::select(), so let tidyselect handle it
return(tidyselect::where(fn))
}
# based on https://github.com/nathaneastwood/poorman/blob/52eb6947e0b4430cd588976ed8820013eddf955f/R/where.R#L17-L32
if (!is.function(fn)) {
stop_("{.fun ", deparse(substitute(fn)), "} is not a valid predicate function.")
}
df <- pm_select_env$.data
cols <- pm_select_env$get_colnames()
if (is.null(df)) {
df <- get_current_data("where", call = FALSE)
cols <- colnames(df)
}
preds <- unlist(lapply(
df,
function(x, fn) {
do.call("fn", list(x))
},
fn
))
if (!is.logical(preds)) stop_("{.fun where} must be used with functions that return {.code TRUE} or {.code FALSE}.")
data_cols <- cols
cols <- data_cols[preds]
which(data_cols %in% cols)
}
# Faster data.table implementations ----
match <- function(x, table, ...) {
if (!is.null(AMR_env$chmatch) && inherits(x, "character") && inherits(table, "character")) {
# data.table must still be loaded: calling its compiled code after it was unloaded (e.g., using detach("package:data.table", unload = TRUE)) crashes R
if (!is.null(AMR_env$chmatch) && inherits(x, "character") && inherits(table, "character") && isNamespaceLoaded("data.table")) {
# data.table::chmatch() is much faster than base::match() for character
tryCatch(AMR_env$chmatch(x, table, ...), error = function(e) base::match(x, table, ...))
} else {
@@ -1756,7 +1757,7 @@ match <- function(x, table, ...) {
}
}
`%in%` <- function(x, table) {
if (!is.null(AMR_env$chin) && inherits(x, "character") && inherits(table, "character")) {
if (!is.null(AMR_env$chin) && inherits(x, "character") && inherits(table, "character") && isNamespaceLoaded("data.table")) {
# data.table::`%chin%`() is much faster than base::`%in%`() for character
tryCatch(AMR_env$chin(x, table), error = function(e) base::`%in%`(x, table))
} else {
+6 -30
View File
@@ -137,26 +137,7 @@
#'
#' ### Inclusion in Combination Antibiograms
#'
#' Note that for combination antibiograms, it is important to realise that susceptibility can be calculated in two ways, which can be set with the `only_all_tested` argument (default is `FALSE`). See this example for two antimicrobials, Drug A and Drug B, about how [antibiogram()] works to calculate the %SI:
#'
#' ```
#' --------------------------------------------------------------------
#' only_all_tested = FALSE only_all_tested = TRUE
#' ----------------------- -----------------------
#' Drug A Drug B considered considered considered considered
#' susceptible tested susceptible tested
#' -------- -------- ----------- ---------- ----------- ----------
#' S or I S or I X X X X
#' R S or I X X X X
#' <NA> S or I X X - -
#' S or I R X X X X
#' R R - X - X
#' <NA> R - - - -
#' S or I <NA> X X - -
#' R <NA> - - - -
#' <NA> <NA> - - - -
#' --------------------------------------------------------------------
#' ```
#' For combination antibiograms, the results of the antimicrobials are combined using the same rules as [sir_combine()], see the section *Combination Therapy* below. Whether isolates must be tested for all antimicrobials can be set with the `only_all_tested` argument (default is `FALSE`). The 'I' and 'SDD' categories are considered susceptible if `combine_SI = TRUE` (default), which also determines whether a missing result can be ignored. To use a combination in other analyses as well, create a new variable with [sir_combine()].
#'
#' ### Plotting
#'
@@ -177,6 +158,7 @@
#' **Interpreting the output:** Overlapping credible intervals between regimens indicate no significant difference in coverage; if a narrower-spectrum regimen overlaps with a broader one, the narrower-spectrum option may be preferred on stewardship grounds. Non-overlapping intervals indicate a clinically meaningful difference. For small sample sizes, consider pooling data from multiple sites to improve precision, provided pathogen distributions are sufficiently similar (Bielicki *et al.*, 2016).
#'
#' For the full mathematical derivation and worked examples, see the [WISCA vignette](https://amr-for-r.org/articles/WISCA.html).
#' @inheritSection sir_combine Combination Therapy
#' @references
#' * Hebert C *et al.* (2012). **Demonstration of the weighted-incidence syndromic combination antibiogram: an empiric prescribing decision aid.** *Infection Control & Hospital Epidemiology* 33(4):381-388; \doi{10.1086/664768}
#' * Bielicki JA *et al.* (2016). **Selecting appropriate empirical antibiotic regimens for paediatric bloodstream infections: application of a Bayesian decision model to local and pooled antimicrobial resistance surveillance data.** *Journal of Antimicrobial Chemotherapy* 71(3):794-802; \doi{10.1093/jac/dkv397}
@@ -625,16 +607,10 @@ antibiogram.default <- function(x,
if (isTRUE(combine_SI)) {
S_values <- c(S_values, "SDD", "I")
}
other_values <- setdiff(c("S", "SDD", "I", "R", "WT", "NWT", "NS"), S_values)
x_transposed <- as.list(as.data.frame(t(x[, abx, drop = FALSE]), stringsAsFactors = FALSE))
if (isTRUE(only_all_tested)) {
x[new_colname] <- as.sir(vapply(FUN.VALUE = character(1), x_transposed, function(x) ifelse(anyNA(x), NA_character_, ifelse(any(x %in% S_values), "S", "R")), USE.NAMES = FALSE))
} else {
x[new_colname] <- as.sir(vapply(
FUN.VALUE = character(1), x_transposed, function(x) ifelse(any(x %in% S_values, na.rm = TRUE), "S", ifelse(anyNA(x), NA_character_, "R")),
USE.NAMES = FALSE
))
}
# same rules as sir_combine(), after which the result is reduced to S or R
combined <- as.character(sir_combine_engine(as.list(x[, abx, drop = FALSE]), S_values = S_values, only_all_tested = only_all_tested))
combined[!is.na(combined)] <- ifelse(combined[!is.na(combined)] %in% S_values, "S", "R")
x[new_colname] <- as_sir_structure(combined)
}
antimicrobials[[i]] <- new_colname
}
+4 -2
View File
@@ -42,10 +42,10 @@
#' @inheritSection as.sir Interpretation of SIR
#' @details These functions are meant to count isolates. Use the [resistance()]/[susceptibility()] functions to calculate microbial resistance/susceptibility.
#'
#' The function [n_sir()] is an alias of [count_all()]. They can be used to count all available isolates, i.e. where all input antimicrobials have an available result (S, I or R). Their use is equal to `dplyr`'s `n_distinct()`. Their function is equal to `count_susceptible(...) + count_resistant(...)`.
#' The function [n_sir()] is an alias of [count_all()]. They can be used to count all available isolates, i.e. where the input antimicrobial has an available result (S, I or R), or for multiple antimicrobials, where the result of the combination is available (see *Combination Therapy* below). Their use is equal to `dplyr`'s `n_distinct()`. Their function is equal to `count_susceptible(...) + count_resistant(...)`.
#'
#' The function [count_df()] takes any variable from `data` that has an [`sir`] class (created with [as.sir()]) and counts the number of S's, I's and R's. It also supports grouped variables. The function [sir_df()] works exactly like [count_df()], but adds the percentage of S, I and R.
#' @inheritSection proportion Combination Therapy
#' @inheritSection sir_combine Combination Therapy
#' @seealso [`proportion_*`][proportion] to calculate microbial resistance and susceptibility.
#' @return An [integer]
#' @rdname count
@@ -143,6 +143,7 @@ count_resistant <- function(...,
if (identical(guideline, "CLSI")) "I"
),
only_all_tested = only_all_tested,
guideline = guideline,
only_count = TRUE
),
error = function(e) stop_(gsub("in sir_calc(): ", "", conditionMessage(e), fixed = TRUE), call = -5)
@@ -172,6 +173,7 @@ count_susceptible <- function(...,
if (identical(guideline, "EUCAST")) "I"
),
only_all_tested = only_all_tested,
guideline = guideline,
only_count = TRUE
),
error = function(e) stop_(gsub("in sir_calc(): ", "", conditionMessage(e), fixed = TRUE), call = -5)
+14 -2
View File
@@ -30,7 +30,17 @@
#' *G*-test for Count Data
#'
#' [g.test()] performs chi-squared contingency table tests and goodness-of-fit tests, just like [chisq.test()] but is more reliable (1). A *G*-test can be used to see whether the number of observations in each category fits a theoretical expectation (called a ***G*-test of goodness-of-fit**), or to see whether the proportions of one variable are different for different values of the other variable (called a ***G*-test of independence**).
#' @inherit stats::chisq.test params return
#' @inherit stats::chisq.test params
#' @return A [list] with class `"htest"` containing the following components:
#' * `statistic`: the value of the test statistic
#' * `parameter`: the degrees of freedom of the approximate chi-squared distribution of the test statistic, `NA` if the p-value is computed by Monte Carlo simulation
#' * `p.value`: the p-value for the test
#' * `method`: a character string indicating the type of test performed, and whether Monte Carlo simulation was used
#' * `data.name`: a character string giving the name(s) of the data
#' * `observed`: the observed counts
#' * `expected`: the expected counts under the null hypothesis
#' * `residuals`: the Pearson residuals, `(observed - expected) / sqrt(expected)`
#' * `stdres`: standardised residuals, `(observed - expected) / sqrt(V)`, where `V` is the residual cell variance (Agresti 2007, section 2.4.5) for the case where `x` is a matrix, `n * p * (1 - p)` otherwise
#' @details If `x` is a [matrix] with one row or column, or if `x` is a vector and `y` is not given, then a *goodness-of-fit test* is performed (`x` is treated as a one-dimensional contingency table). The entries of `x` must be non-negative integers. In this case, the hypothesis tested is whether the population probabilities equal those in `p`, or are all equal if `p` is not given.
#'
#' If `x` is a [matrix] with at least two rows and columns, it is taken as a two-dimensional contingency table: the entries of `x` must be non-negative integers. Otherwise, `x` and `y` must be vectors or factors of the same length; cases with missing values are removed, the objects are coerced to factors, and the contingency table is computed from these. Then Pearson's chi-squared test is performed of the null hypothesis that the joint distribution of the cell counts in a 2-dimensional contingency table is the product of the row and column marginals.
@@ -73,6 +83,8 @@
#' If there are more than two categories and you want to find out which ones are significantly different from their null expectation, you can use the same method of testing each category vs. the sum of all categories, with the Bonferroni correction. You use *G*-tests for each category, of course.
#' @seealso [chisq.test()]
#' @references 1. McDonald, J.H. 2014. **Handbook of Biological Statistics (3rd ed.)**. Sparky House Publishing, Baltimore, Maryland.
#'
#' 2. Agresti, A. 2007. **An Introduction to Categorical Data Analysis (2nd ed.)**. Wiley, New York.
#' @source The code for this function is identical to that of [chisq.test()], except that:
#' - The calculation of the statistic was changed to \eqn{2 * sum(x * log(x / E))}
#' - Yates' continuity correction was removed as it does not apply to a *G*-test
@@ -218,7 +230,7 @@ g.test <- function(x,
}
structure(list(
statistic = STATISTIC, argument = PARAMETER,
statistic = STATISTIC, parameter = PARAMETER,
p.value = PVAL, method = METHOD, data.name = DNAME,
observed = x, expected = E, residuals = (x - E) / sqrt(E),
stdres = (x - E) / sqrt(V)
+2
View File
@@ -32,6 +32,7 @@
#' Produces a `ggplot2` variant of a so-called [biplot](https://en.wikipedia.org/wiki/Biplot) for PCA (principal component analysis), but is more flexible and more appealing than the base \R [biplot()] function.
#' @param x An object returned by [pca()], [prcomp()] or [princomp()].
#' @inheritParams stats::biplot.prcomp
#' @param pc.biplot If `TRUE`, use what Gabriel (1971) refers to as a 'principal component biplot', with `lambda = 1` and observations scaled up by `sqrt(n)` and variables scaled down by `sqrt(n)`. Then inner products between variables approximate covariances and distances between observations approximate Mahalanobis distance.
#' @param labels An optional vector of labels for the observations. If set, the labels will be placed below their respective points. When using the [pca()] function as input for `x`, this will be determined automatically based on the attribute `non_numeric_cols`, see [pca()].
#' @param labels_textsize The size of the text used for the labels.
#' @param labels_text_placement Adjustment factor the placement of the variable names (`>=1` means further away from the arrow head).
@@ -51,6 +52,7 @@
#' @param arrows_alpha The alpha (transparency) of the arrows and their text.
#' @param base_textsize The text size for all plot elements except the labels and arrows.
#' @param ... Arguments passed on to functions.
#' @references Gabriel, K.R. 1971. **The biplot graphical display of matrices with application to principal component analysis**. *Biometrika* 58(3):453-467. \doi{10.1093/biomet/58.3.453}
#' @source The [ggplot_pca()] function is based on the `ggbiplot()` function from the `ggbiplot` package by Vince Vu, as found on GitHub: <https://github.com/vqv/ggbiplot> (retrieved: 2 March 2020, their latest commit: [`7325e88`](https://github.com/vqv/ggbiplot/commit/7325e880485bea4c07465a0304c470608fffb5d9); 12 February 2015).
#'
#' As per their GPL-2 licence that demands documentation of code changes, the changes made based on the source code were:
+2 -2
View File
@@ -49,8 +49,8 @@
#' @seealso [grepl()]
#' @examples
#' # data.table has a more limited version of %like%, so unload it:
#' try(detach("package:data.table", unload = TRUE), silent = TRUE)
#' # data.table has a more limited version of %like%, so detach it (without unloading it, as data.table does not support being unloaded):
#' try(detach("package:data.table"), silent = TRUE)
#'
#' a <- "This is a test"
#' b <- "TEST"
+4 -39
View File
@@ -35,7 +35,7 @@
#' @param ... One or more vectors (or columns) with antibiotic interpretations. They will be transformed internally with [as.sir()] if needed. Use multiple columns to calculate (the lack of) co-resistance: the probability where one of two drugs have a resistant or susceptible result. See *Examples*.
#' @param minimum The minimum allowed number of available (tested) isolates. Any isolate count lower than `minimum` will return `NA` with a warning. The default number of `30` isolates is advised by the Clinical and Laboratory Standards Institute (CLSI) as best practice, see *Source*.
#' @param as_percent A [logical] to indicate whether the output must be returned as a hundred fold with % sign (a character). A value of `0.123456` will then be returned as `"12.3%"`.
#' @param only_all_tested (for combination therapies, i.e. using more than one variable for `...`): a [logical] to indicate that isolates must be tested for all antimicrobials, see section *Combination Therapy* below.
#' @param only_all_tested (for combination therapies, i.e. using more than one variable for `...`): a [logical] to indicate that isolates must be tested for all antimicrobials, see section *Combination Therapy* below. Use [sir_combine()] to create a new variable for a combination therapy.
#' @param data A [data.frame] containing columns with class [`sir`] (see [as.sir()]).
#' @param translate_ab A column name of the [antimicrobials] data set to translate the antibiotic abbreviations to, using [ab_property()].
#' @param guideline Either `"EUCAST"` (default) or `"CLSI"`. With EUCAST, the 'I' category will be considered as susceptible (see [EUCAST website](https://www.eucast.org/bacteria/clinical-breakpoints-and-interpretation/definition-of-s-i-and-r/)), but with with CLSI, it will be considered resistant. Therefore:
@@ -62,44 +62,7 @@
#' These functions are not meant to count isolates, but to calculate the proportion of resistance/susceptibility. Use the [`count_*()`][AMR::count()] functions to count isolates. The function [susceptibility()] is essentially equal to [count_susceptible()]` / `[count_all()]. *Low counts can influence the outcome - the `proportion_*()` functions may camouflage this, since they only return the proportion (albeit dependent on the `minimum` argument).*
#'
#' The function [proportion_df()] takes any variable from `data` that has an [`sir`] class (created with [as.sir()]) and calculates the proportions S, I, and R. It also supports grouped variables. The function [sir_df()] works exactly like [proportion_df()], but adds the number of isolates.
#' @section Combination Therapy:
#' When using more than one variable for `...` (= combination therapy), use `only_all_tested` to only count isolates that are tested for all antimicrobials/variables that you test them for. See this example for two antimicrobials, Drug A and Drug B, about how [susceptibility()] works to calculate the %SI:
#'
#'
#' ```
#' --------------------------------------------------------------------
#' only_all_tested = FALSE only_all_tested = TRUE
#' ----------------------- -----------------------
#' Drug A Drug B considered considered considered considered
#' susceptible tested susceptible tested
#' -------- -------- ----------- ---------- ----------- ----------
#' S or I S or I X X X X
#' R S or I X X X X
#' <NA> S or I X X - -
#' S or I R X X X X
#' R R - X - X
#' <NA> R - - - -
#' S or I <NA> X X - -
#' R <NA> - - - -
#' <NA> <NA> - - - -
#' --------------------------------------------------------------------
#' ```
#'
#' Please note that, in combination therapies, for `only_all_tested = TRUE` applies that:
#'
#' ```
#' count_S() + count_I() + count_R() = count_all()
#' proportion_S() + proportion_I() + proportion_R() = 1
#' ```
#'
#' and that, in combination therapies, for `only_all_tested = FALSE` applies that:
#'
#' ```
#' count_S() + count_I() + count_R() >= count_all()
#' proportion_S() + proportion_I() + proportion_R() >= 1
#' ```
#'
#' Using `only_all_tested` has no impact when only using one antibiotic as input.
#' @inheritSection sir_combine Combination Therapy
#' @references **M39 Analysis and Presentation of Cumulative Antimicrobial Susceptibility Test Data, 5th Edition**, 2022, *Clinical and Laboratory Standards Institute (CLSI)*. <https://clsi.org/standards/products/microbiology/documents/m39/>.
#' @seealso [AMR::count()] to count resistant and susceptible isolates.
#' @return A [double] or, when `as_percent = TRUE`, a [character].
@@ -255,6 +218,7 @@ resistance <- function(...,
minimum = minimum,
as_percent = as_percent,
only_all_tested = only_all_tested,
guideline = guideline,
only_count = FALSE
),
error = function(e) stop_(gsub("in sir_calc(): ", "", conditionMessage(e), fixed = TRUE), call = -5)
@@ -288,6 +252,7 @@ susceptibility <- function(...,
minimum = minimum,
as_percent = as_percent,
only_all_tested = only_all_tested,
guideline = guideline,
only_count = FALSE
),
error = function(e) stop_(gsub("in sir_calc(): ", "", conditionMessage(e), fixed = TRUE), call = -5)
+15 -33
View File
@@ -40,7 +40,8 @@ sir_calc <- function(...,
minimum = 0,
as_percent = FALSE,
only_all_tested = FALSE,
only_count = FALSE) {
only_count = FALSE,
guideline = getOption("AMR_guideline", "EUCAST")) {
meet_criteria(ab_result, allow_class = c("character", "sir"), has_length = seq_along(VALID_SIR_LEVELS), is_in = VALID_SIR_LEVELS)
meet_criteria(minimum, allow_class = c("numeric", "integer"), has_length = 1, is_positive_or_zero = TRUE, is_finite = TRUE)
meet_criteria(as_percent, allow_class = "logical", has_length = 1)
@@ -129,42 +130,23 @@ sir_calc <- function(...,
# this will give a warning for invalid results, of all input columns (so only 1 warning)
sir_integrity_check <- as.sir(sir_integrity_check)
}
x_transposed <- as.list(as.data.frame(t(x), stringsAsFactors = FALSE))
if (isTRUE(only_all_tested)) {
# no NAs in any column
y <- apply(
X = as.data.frame(lapply(x, as.double), stringsAsFactors = FALSE),
MARGIN = 1,
FUN = min
)
if ("SDD" %in% ab_result && "SDD" %in% y && message_not_thrown_before("sir_calc", only_count, ab_result, entire_session = TRUE)) {
message_("Note that {.fun ", ifelse(only_count, "count", "proportion"), "_", ifelse("S" %in% ab_result, "S", ""), "I", ifelse("R" %in% ab_result, "R", ""), "} will also include dose-dependent susceptibility, {.val SDD}. This note will be shown once for this session.", as_note = FALSE)
}
numerator <- sum(!is.na(y) & y %in% as.double(ab_result), na.rm = TRUE)
denominator <- sum(vapply(FUN.VALUE = logical(1), x_transposed, function(y) !(anyNA(y))))
if (ncol(x) == 1) {
x <- x[, 1, drop = TRUE]
} else {
# may contain NAs in any column
other_values <- setdiff(c(NA, denominator_vals), ab_result)
if ("SDD" %in% ab_result && "SDD" %in% unlist(x_transposed) && message_not_thrown_before("sir_calc", only_count, ab_result, entire_session = TRUE)) {
message_("Note that {.fun ", ifelse(only_count, "count", "proportion"), "_", ifelse("S" %in% ab_result, "S", ""), "I", ifelse("R" %in% ab_result, "R", ""), "} will also include dose-dependent susceptibility, {.val SDD}. This note will be shown once for this session.", as_note = FALSE)
}
numerator <- sum(vapply(FUN.VALUE = logical(1), x_transposed, function(y) any(y %in% ab_result, na.rm = TRUE)))
denominator <- sum(vapply(FUN.VALUE = logical(1), x_transposed, function(y) !(all(y %in% other_values) & anyNA(y))))
# combination therapy: determine the result of the combination for every isolate, see ?sir_combine
x <- sir_combine_engine(as.list(x), S_values = get_susceptible_values(guideline), only_all_tested = only_all_tested)
}
} else {
# x is not a data.frame
if (!is.sir(x)) {
x <- as.sir(x)
print_warning <- TRUE
}
if ("SDD" %in% ab_result && "SDD" %in% x && message_not_thrown_before("sir_calc", only_count, ab_result, entire_session = TRUE)) {
message_("Note that `", ifelse(only_count, "count", "proportion"), "_", ifelse("S" %in% ab_result, "S", ""), "I", ifelse("R" %in% ab_result, "R", ""), "()` will also include dose-dependent susceptibility, {.val SDD}. This note will be shown once for this session.", as_note = FALSE)
}
numerator <- sum(x %in% ab_result, na.rm = TRUE)
denominator <- sum(x %in% denominator_vals, na.rm = TRUE)
} else if (!is.sir(x)) {
x <- as.sir(x)
print_warning <- TRUE
}
if ("SDD" %in% ab_result && "SDD" %in% x && message_not_thrown_before("sir_calc", only_count, ab_result, entire_session = TRUE)) {
message_("Note that {.fun ", ifelse(only_count, "count", "proportion"), "_", ifelse("S" %in% ab_result, "S", ""), "I", ifelse("R" %in% ab_result, "R", ""), "} will also include dose-dependent susceptibility, {.val SDD}. This note will be shown once for this session.", as_note = FALSE)
}
numerator <- sum(x %in% ab_result, na.rm = TRUE)
denominator <- sum(x %in% denominator_vals, na.rm = TRUE)
if (print_warning == TRUE) {
if (message_not_thrown_before("sir_calc")) {
warning_("Increase speed by transforming to class {.cls sir} on beforehand:\n",
+182
View File
@@ -0,0 +1,182 @@
# ==================================================================== #
# TITLE: #
# AMR: An R Package for Working with Antimicrobial Resistance Data #
# #
# SOURCE CODE: #
# https://github.com/msberends/AMR #
# #
# PLEASE CITE THIS SOFTWARE AS: #
# Berends MS, Luz CF, Friedrich AW, et al. (2022). #
# AMR: An R Package for Working with Antimicrobial Resistance Data. #
# Journal of Statistical Software, 104(3), 1-31. #
# https://doi.org/10.18637/jss.v104.i03 #
# #
# Developed at the University of Groningen and the University Medical #
# Center Groningen in the Netherlands, in collaboration with many #
# colleagues from around the world, see our website. #
# #
# This R package is free software; you can freely use and distribute #
# it for both personal and commercial purposes under the terms of the #
# GNU General Public License version 2.0 (GNU GPL-2), as published by #
# the Free Software Foundation. #
# We created this package for both routine data analysis and academic #
# research and it was publicly released in the hope that it will be #
# useful, but it comes WITHOUT ANY WARRANTY OR LIABILITY. #
# #
# Visit our website for the full manual and a complete tutorial about #
# how to conduct AMR data analysis: https://amr-for-r.org #
# ==================================================================== #
#' Combine SIR Results of Multiple Antimicrobials
#'
#' @description Combine the SIR results of two or more antimicrobials into one SIR result per isolate, e.g. to create a variable `TZP_GEN` for the combination therapy of piperacillin/tazobactam with gentamicin. The result is the best result of the antimicrobials, as a combination therapy covers the isolate if any of its antimicrobials is active. See *Combination Therapy* below for the exact rules.
#'
#' The same rules are used by [antibiogram()] and [wisca()] for combination antibiograms, and by the [`count_*()`][count()] and [`proportion_*()`][proportion()] functions when more than one variable is used, so the result of [sir_combine()] can be used in any further analysis.
#' @param ... Two or more vectors (or columns) with antimicrobial interpretations, or a data frame with such columns. They will be transformed internally with [as.sir()] if needed. All vectors must be of the same length.
#' @param only_all_tested A [logical] to indicate that isolates must be tested for all antimicrobials. If `TRUE`, the result is `NA` for isolates with a missing result for any of the antimicrobials. If `FALSE` (default), a missing result only leads to `NA` if a result for the missing antimicrobial could have changed the result of the combination, see *Combination Therapy* below.
#' @param guideline Either `"EUCAST"` (default) or `"CLSI"`, to determine whether the 'I' category is considered susceptible. This only affects isolates with a missing result for any of the antimicrobials when `only_all_tested = FALSE`, see *Combination Therapy* below. The default can be changed with the `AMR_guideline` option, see [AMR-options].
#' @section Combination Therapy:
#' A combination of antimicrobials is considered as good as its most active antimicrobial. Results are ranked as follows, from best to worst:
#'
#' 1. `"S"` and `"WT"`
#' 2. `"SDD"`
#' 3. `"I"`
#' 4. `"R"`, `"NWT"`, and `"NS"`
#'
#' The result of the combination is the best result of the antimicrobials, i.e., the result keeps its original category instead of being reduced to only S or R. If antimicrobials have an equally ranked result, `"S"` is preferred over `"WT"`, and `"R"` over `"NWT"` and `"NS"`. The value `"NI"` (non-interpretable) is considered a missing result.
#'
#' A missing result can only be ignored if the result of the combination is susceptible regardless of the missing result, which depends on the `only_all_tested` argument and on the guideline: under EUCAST, the 'I' category is considered susceptible (*susceptible, increased exposure*), and under CLSI, it is not. This is an example for two antimicrobials, Drug A and Drug B (the order of the antimicrobials does not matter):
#'
#' ```
#' -------------------------------------------------------------------------
#' Result of the combination
#' -----------------------------------------------------
#' Drug A Drug B only_all_tested = FALSE only_all_tested = TRUE
#' -------- -------- ---------------------------- ----------------------
#' S S, I, R S S
#' I I, R I I
#' R R R R
#' S <NA> S <NA>
#' I <NA> I (EUCAST), <NA> (CLSI) <NA>
#' R <NA> <NA> <NA>
#' <NA> <NA> <NA> <NA>
#' -------------------------------------------------------------------------
#' ```
#'
#' The [`count_*()`][count()] and [`proportion_*()`][proportion()] functions, such as [susceptibility()] and [resistance()], apply exactly these rules when more than one variable is used: an isolate is considered tested if the result of the combination is not `NA`, and is then counted by the result of the combination. Consequently, [count_susceptible()] `+` [count_resistant()] `=` [count_all()], and [susceptibility()] `+` [resistance()] `= 1`, for both values of `only_all_tested`. The guideline is taken from their `guideline` argument if they have one, and otherwise from the `AMR_guideline` option.
#'
#' In [antibiogram()] and [wisca()], the 'I' and 'SDD' categories are considered susceptible if `combine_SI = TRUE` (default), and the result of the combination is then reduced to S or R.
#' @return A [`sir`] vector with the same length as the input.
#' @seealso [count()] and [proportion()] for counting and calculating susceptibility of (combinations of) antimicrobials, and [antibiogram()] for combination antibiograms.
#' @export
#' @examples
#' drug_a <- as.sir(c("S", "R", "R", "I", "I", NA, "R", "SDD"))
#' drug_b <- as.sir(c("R", "S", "R", "R", NA, NA, NA, "I"))
#'
#' sir_combine(drug_a, drug_b)
#' sir_combine(drug_a, drug_b, guideline = "CLSI")
#' sir_combine(drug_a, drug_b, only_all_tested = TRUE)
#'
#' # the count and proportion functions use the same rules
#' susceptibility(drug_a, drug_b, minimum = 0)
#' susceptibility(sir_combine(drug_a, drug_b), minimum = 0)
#'
#' \donttest{
#' if (require("dplyr")) {
#' # create a new variable for piperacillin/tazobactam + gentamicin
#' example_isolates %>%
#' mutate(TZP_GEN = sir_combine(TZP, GEN)) %>%
#' select(mo, TZP, GEN, TZP_GEN)
#' }
#' if (require("dplyr")) {
#' # combine any number of antimicrobials
#' example_isolates %>%
#' mutate(any_aminoglycoside = sir_combine(GEN, TOB, AMK, KAN)) %>%
#' count(any_aminoglycoside)
#' }
#' if (require("dplyr")) {
#' # use the new variable in further analyses
#' example_isolates %>%
#' mutate(TZP_GEN = sir_combine(TZP, GEN)) %>%
#' group_by(ward) %>%
#' summarise(
#' TZP = susceptibility(TZP),
#' TZP_GEN = susceptibility(TZP_GEN)
#' )
#' }
#' }
sir_combine <- function(..., only_all_tested = FALSE, guideline = getOption("AMR_guideline", "EUCAST")) {
meet_criteria(only_all_tested, allow_class = "logical", has_length = 1)
meet_criteria(guideline, allow_class = "character", has_length = 1)
if (guideline %like% "EUCAST") {
guideline <- "EUCAST"
} else if (guideline %like% "CLSI") {
guideline <- "CLSI"
}
meet_criteria(guideline, allow_class = "character", is_in = c("EUCAST", "CLSI"), has_length = 1)
# unpack data frames, so that e.g. sir_combine(df[, c("GEN", "TOB")], CIP) works
cols <- list()
for (dot in list(...)) {
if (is.data.frame(dot)) {
cols <- c(cols, unname(as.list(dot)))
} else {
cols <- c(cols, list(dot))
}
}
stop_if(length(cols) < 2, "at least two vectors or columns must be provided to combine, but ", length(cols), " ", ifelse(length(cols) == 1, "was", "were"), " provided.")
col_lengths <- vapply(FUN.VALUE = integer(1), cols, length)
stop_if(length(unique(col_lengths)) > 1, "all vectors or columns must be of the same length, but they have lengths ", vector_and(sort(unique(col_lengths)), quotes = FALSE), ".")
cols <- lapply(cols, function(x) if (is.sir(x)) x else as.sir(x))
out <- sir_combine_engine(cols, S_values = get_susceptible_values(guideline), only_all_tested = only_all_tested)
if (isFALSE(only_all_tested) && is.null(getOption("AMR_guideline")) && missing(guideline)) {
# only notify about the assumed guideline if it affected the result
any_missing <- Reduce(`|`, lapply(cols, function(x) is.na(x) | as.character(x) == "NI"))
if (any(any_missing & as.character(out) %in% "I") && message_not_thrown_before("sir_combine", "eucast_default", entire_session = TRUE)) {
message_("{.help [{.fun sir_combine}](AMR::sir_combine)} assumes the EUCAST guideline and thus considers the 'I' category susceptible, so a missing result does not change a combination with an 'I' result. Set the {.arg guideline} argument or the {.code AMR_guideline} option to either \"CLSI\" or \"EUCAST\", see {.topic [AMR-options](AMR::AMR-options)}.")
message_("This message will be shown once per session.")
}
}
out
}
get_susceptible_values <- function(guideline) {
# the SIR values considered susceptible, as in count_susceptible() and susceptibility()
if (!is.null(guideline) && guideline %like% "CLSI") {
c("S", "SDD", "WT")
} else {
c("S", "SDD", "I", "WT")
}
}
sir_combine_engine <- function(cols, S_values, only_all_tested = FALSE) {
# this is the engine for combination therapy, used by sir_combine(), sir_calc() and antibiogram()
# - cols: a list of vectors of equal length, with class 'sir' or with SIR values as character
# - S_values: the values considered susceptible, so that a missing result cannot change the result of the combination
# the order of preference: the first value is the best result, values with equal rank are resolved by this order
preference <- c("S", "WT", "SDD", "I", "R", "NWT", "NS")
ranks <- c(1L, 1L, 2L, 3L, 4L, 4L, 4L)
cols <- lapply(cols, as.character)
if (length(cols) == 0) {
return(as_sir_structure(character(0)))
}
# 'NI' and NA get no rank, so they are missing results
col_ranks <- lapply(cols, function(x) ranks[match(x, preference)])
best <- do.call(pmin, c(col_ranks, list(na.rm = TRUE)))
out <- rep(NA_character_, length(best))
for (i in seq_along(preference)) {
is_present <- Reduce(`|`, lapply(cols, function(x) x %in% preference[i]))
out[is.na(out) & best %in% ranks[i] & is_present] <- preference[i]
}
any_missing <- Reduce(`|`, lapply(col_ranks, is.na))
if (isTRUE(only_all_tested)) {
out[any_missing] <- NA_character_
} else {
# a missing result could have been better, unless the combination is already susceptible
out[any_missing & !out %in% S_values] <- NA_character_
}
as_sir_structure(out)
}
+10 -10
View File
@@ -76,18 +76,18 @@ AMR_env$custom_ab_synonyms <- data.frame(ab = character(0), synonym = character(
AMR_env$custom_mo_codes <- character(0)
AMR_env$is_dark_theme <- NULL
AMR_env$supports_colour <- NULL
AMR_env$chmatch <- import_fn("chmatch", "data.table", error_on_fail = FALSE)
AMR_env$chin <- import_fn("%chin%", "data.table", error_on_fail = FALSE)
# take cli symbols and error function if available
AMR_env$bullet_icon <- import_fn("symbol", "cli", error_on_fail = FALSE)$bullet %||% "*"
AMR_env$ellipsis_icon <- import_fn("symbol", "cli", error_on_fail = FALSE)$ellipsis %||% "..."
AMR_env$info_icon <- import_fn("symbol", "cli", error_on_fail = FALSE)$info %||% "i"
AMR_env$sup_1_icon <- import_fn("symbol", "cli", error_on_fail = FALSE)$sup_1 %||% "*"
AMR_env$cli_abort <- import_fn("cli_abort", "cli", error_on_fail = FALSE)
AMR_env$cross_icon <- if (isTRUE(base::l10n_info()$`UTF-8`)) "\u00d7" else "x"
.onLoad <- function(libname, pkgname) {
# functions and symbols from suggested packages must be retrieved here, at runtime: code outside functions runs at installation, so it would store what was available on the machine that built the package (e.g., CRAN), which fails if these packages are not available to the user
AMR_env$chmatch <- import_fn("chmatch", "data.table", error_on_fail = FALSE)
AMR_env$chin <- import_fn("%chin%", "data.table", error_on_fail = FALSE)
# take cli symbols and error function if available
AMR_env$bullet_icon <- import_fn("symbol", "cli", error_on_fail = FALSE)$bullet %||% "*"
AMR_env$ellipsis_icon <- import_fn("symbol", "cli", error_on_fail = FALSE)$ellipsis %||% "..."
AMR_env$info_icon <- import_fn("symbol", "cli", error_on_fail = FALSE)$info %||% "i"
AMR_env$sup_1_icon <- import_fn("symbol", "cli", error_on_fail = FALSE)$sup_1 %||% "*"
AMR_env$cross_icon <- if (isTRUE(base::l10n_info()$`UTF-8`)) "\u00d7" else "x"
# if mo source exists, fire it up (see mo_source())
if (tryCatch(file.exists(getOption("AMR_mo_source", "~/mo_source.rds")), error = function(e) FALSE)) {
try(invisible(get_mo_source()), silent = TRUE)