diff --git a/DESCRIPTION b/DESCRIPTION
index 83f5cdad3..ef0803dcf 100644
--- a/DESCRIPTION
+++ b/DESCRIPTION
@@ -1,6 +1,6 @@
Package: AMR
-Version: 1.7.1.9021
-Date: 2021-07-12
+Version: 1.7.1.9022
+Date: 2021-07-23
Title: Antimicrobial Resistance Data Analysis
Authors@R: c(
person(role = c("aut", "cre"),
@@ -57,6 +57,7 @@ Suggests:
skimr,
tidyr,
tinytest,
+ vctrs,
xml2
VignetteBuilder: knitr,rmarkdown
URL: https://github.com/msberends/AMR, https://msberends.github.io/AMR
diff --git a/NEWS.md b/NEWS.md
index 86077f58c..dd8b8c492 100755
--- a/NEWS.md
+++ b/NEWS.md
@@ -1,8 +1,8 @@
-# `AMR` 1.7.1.9021
-## Last updated: 12 July 2021
+# `AMR` 1.7.1.9022
+## Last updated: 23 July 2021
### Changed
-* Previously implemented `ggplot2::gggplot()` generics for classes ``, ``, `` and `` did not follow the `ggplot2` logic, and were replaced with `autoplot()` generics.
+* Previously implemented `ggplot2::ggplot()` generics for classes ``, ``, `` and `` did not follow the `ggplot2` logic, and were replaced with `autoplot()` generics.
* Antibiotic class selectors (see `ab_class()`)
* They now also work in R-3.0 and R-3.1, supporting every version of R since 2013
* Added more selectors: `aminopenicillins()`, `lincosamides()`, `lipoglycopeptides()`, `polymyxins()`, `quinolones()`, `streptogramins()` and `ureidopenicillins()`
@@ -17,12 +17,13 @@
* `as.rsi()` can now correct for textual input (such as "Susceptible", "Resistant") in Dutch, English, French, German, Italian, Portuguese and Spanish
* When warnings are thrown because of too few isolates in any `count_*()`, `proportion_*()` function (or `resistant()` or `susceptible()`), the `dplyr` group will be shown, if available
* `ab_name()` gained argument `snake_case`, which is useful for column renaming
-* Fix for legends created with `scale_rsi_colours()` when using `ggplot2` v3.3.4 or higher (this is bug ggplot2#4511, soon to be fixed)
+* Fix for legends created with `scale_rsi_colours()` when using `ggplot2` v3.3.4 or higher (this is ggplot2 bug 4511, soon to be fixed)
* Fix for minor translation errors
* Fix for the MIC interpretation of *Morganellaceae* (such as *Morganella* and *Proteus*) when using the EUCAST 2021 guideline
+* Improved algorithm for generating random MICs with `random_mic()`
+* Improved plot legends for MICs and disk diffusion values
-
-# `AMR` 1.7.1
+# AMR 1.7.1
### Breaking change
* All antibiotic class selectors (such as `carbapenems()`, `aminoglycosides()`) can now be used for filtering as well, making all their accompanying `filter_*()` functions redundant (such as `filter_carbapenems()`, `filter_aminoglycosides()`). These functions are now deprecated and will be removed in a next release. Examples of how the selectors can be used for filtering:
@@ -96,7 +97,7 @@
* All unit tests are now processed by the `tinytest` package, instead of the `testthat` package. The `testthat` package unfortunately requires tons of dependencies that are also heavy and only usable for recent R versions, disallowing developers to test a package under any R 3.* version. On the contrary, the `tinytest` package is very lightweight and dependency-free.
-# `AMR` 1.6.0
+# AMR 1.6.0
### New
* Support for EUCAST Clinical Breakpoints v11.0 (2021), effective in the `eucast_rules()` function and in `as.rsi()` to interpret MIC and disk diffusion values. This is now the default guideline in this package.
@@ -190,7 +191,7 @@
* Loading the package (i.e., `library(AMR)`) now is ~50 times faster than before, in costs of package size (which increased by ~3 MB)
-# `AMR` 1.5.0
+# AMR 1.5.0
### New
* Functions `get_episode()` and `is_new_episode()` to determine (patient) episodes which are not necessarily based on microorganisms. The `get_episode()` function returns the index number of the episode per group, while the `is_new_episode()` function returns values `TRUE`/`FALSE` to indicate whether an item in a vector is the start of a new episode. They also support `dplyr`s grouping (i.e. using `group_by()`):
@@ -267,7 +268,7 @@
* Added CodeFactor as a continuous code review to this package:
* Added Dr. Rogier Schade as contributor
-# `AMR` 1.4.0
+# AMR 1.4.0
### New
* Support for 'EUCAST Expert Rules' / 'EUCAST Intrinsic Resistance and Unusual Phenotypes' version 3.2 of May 2020. With this addition to the previously implemented version 3.1 of 2016, the `eucast_rules()` function can now correct for more than 180 different antibiotics and the `mdro()` function can determine multidrug resistance based on more than 150 different antibiotics. All previously implemented versions of the EUCAST rules are now maintained and kept available in this package. The `eucast_rules()` function consequently gained the arguments `version_breakpoints` (at the moment defaults to v10.0, 2020) and `version_expertrules` (at the moment defaults to v3.2, 2020). The `example_isolates` data set now also reflects the change from v3.1 to v3.2. The `mdro()` function now accepts `guideline == "EUCAST3.1"` and `guideline == "EUCAST3.2"`.
@@ -339,7 +340,7 @@
* Removed unnecessary references to the `base` package
* Added packages that could be useful for some functions to the `Suggests` field of the `DESCRIPTION` file
-# `AMR` 1.3.0
+# AMR 1.3.0
### New
* Function `ab_from_text()` to retrieve antimicrobial drug names, doses and forms of administration from clinical texts in e.g. health care records, which also corrects for misspelling since it uses `as.ab()` internally
@@ -392,7 +393,7 @@
### Other
* Moved primary location of this project from GitLab to [GitHub](https://github.com/msberends/AMR), giving us native support for automated syntax checking without being dependent on external services such as AppVeyor and Travis CI.
-# `AMR` 1.2.0
+# AMR 1.2.0
### Breaking
* Removed code dependency on all other R packages, making this package fully independent of the development process of others. This is a major code change, but will probably not be noticeable by most users.
@@ -430,7 +431,7 @@
* Removed previously deprecated function `p.symbol()` - it was replaced with `p_symbol()`
* Removed function `read.4d()`, that was only useful for reading data from an old test database.
-# `AMR` 1.1.0
+# AMR 1.1.0
### New
* Support for easy principal component analysis for AMR, using the new `pca()` function
@@ -452,7 +453,7 @@
* Support for the upcoming `dplyr` version 1.0.0
* More robust assigning for classes `rsi` and `mic`
-# `AMR` 1.0.1
+# AMR 1.0.1
### Changed
* Fixed important floating point error for some MIC comparisons in EUCAST 2020 guideline
@@ -468,7 +469,7 @@
* Added `uti` (as abbreviation of urinary tract infections) as argument to `as.rsi()`, so interpretation of MIC values and disk zones can be made dependent on isolates specifically from UTIs
* Info printing in functions `eucast_rules()`, `first_isolate()`, `mdro()` and `resistance_predict()` will now at default only print when R is in an interactive mode (i.e. not in RMarkdown)
-# `AMR` 1.0.0
+# AMR 1.0.0
This software is now out of beta and considered stable. Nonetheless, this package will be developed continually.
@@ -516,7 +517,7 @@ This software is now out of beta and considered stable. Nonetheless, this packag
* Full support for the upcoming R 4.0
* Removed unnecessary `AMR::` calls
-# `AMR` 0.9.0
+# AMR 0.9.0
### Breaking
* Adopted Adeolu *et al.* (2016), [PMID 27620848](https:/pubmed.ncbi.nlm.nih.gov/27620848/) for the `microorganisms` data set, which means that the new order Enterobacterales now consists of a part of the existing family Enterobacteriaceae, but that this family has been split into other families as well (like *Morganellaceae* and *Yersiniaceae*). Although published in 2016, this information is not yet in the Catalogue of Life version of 2019. All MDRO determinations with `mdro()` will now use the Enterobacterales order for all guidelines before 2016 that were dependent on the Enterobacteriaceae family.
@@ -582,7 +583,7 @@ This software is now out of beta and considered stable. Nonetheless, this packag
* Change dependency on `clean` to `cleaner`, as this package was renamed accordingly upon CRAN request
* Added Dr. Sofia Ny as contributor
-# `AMR` 0.8.0
+# AMR 0.8.0
### Breaking
* Determination of first isolates now **excludes** all 'unknown' microorganisms at default, i.e. microbial code `"UNKNOWN"`. They can be included with the new argument `include_unknown`:
@@ -711,7 +712,7 @@ This software is now out of beta and considered stable. Nonetheless, this packag
* Added Prof. Dr. Casper Albers as doctoral advisor and added Dr. Judith Fonville, Eric Hazenberg, Dr. Bart Meijer, Dr. Dennis Souverein and Annick Lenglet as contributors
* Cleaned the coding style of every single syntax line in this package with the help of the `lintr` package
-# `AMR` 0.7.1
+# AMR 0.7.1
#### New
* Function `rsi_df()` to transform a `data.frame` to a data set containing only the microbial interpretation (S, I, R), the antibiotic, the percentage of S/I/R and the number of available isolates. This is a convenient combination of the existing functions `count_df()` and `portion_df()` to immediately show resistance percentages and number of available isolates:
@@ -772,7 +773,7 @@ This software is now out of beta and considered stable. Nonetheless, this packag
#### Other
* Fixed a note thrown by CRAN tests
-# `AMR` 0.7.0
+# AMR 0.7.0
#### New
* Support for translation of disk diffusion and MIC values to RSI values (i.e. antimicrobial interpretations). Supported guidelines are EUCAST (2011 to 2019) and CLSI (2011 to 2019). Use `as.rsi()` on an MIC value (created with `as.mic()`), a disk diffusion value (created with the new `as.disk()`) or on a complete date set containing columns with MIC or disk diffusion values.
@@ -830,13 +831,13 @@ This software is now out of beta and considered stable. Nonetheless, this packag
#### Other
* Support for R 3.6.0 and later by providing support for [staged install](https://developer.r-project.org/Blog/public/2019/02/14/staged-install/index.html)
-# `AMR` 0.6.1
+# AMR 0.6.1
#### Changed
* Fixed a critical bug when using `eucast_rules()` with `verbose = TRUE`
* Coercion of microbial IDs are now written to the package namespace instead of the user's home folder, to comply with the CRAN policy
-# `AMR` 0.6.0
+# AMR 0.6.0
**New website!**
@@ -1029,7 +1030,7 @@ We've got a new website: [https://msberends.gitlab.io/AMR](https://msberends.git
#### Other
* Updated licence text to emphasise GPL 2.0 and that this is an R package.
-# `AMR` 0.5.0
+# AMR 0.5.0
#### New
* Repository moved to GitLab
@@ -1112,7 +1113,7 @@ We've got a new website: [https://msberends.gitlab.io/AMR](https://msberends.git
* Updated vignettes to comply with README
-# `AMR` 0.4.0
+# AMR 0.4.0
#### New
* The data set `microorganisms` now contains **all microbial taxonomic data from ITIS** (kingdoms Bacteria, Fungi and Protozoa), the Integrated Taxonomy Information System, available via https://itis.gov. The data set now contains more than 18,000 microorganisms with all known bacteria, fungi and protozoa according ITIS with genus, species, subspecies, family, order, class, phylum and subkingdom. The new data set `microorganisms.old` contains all previously known taxonomic names from those kingdoms.
@@ -1223,7 +1224,7 @@ We've got a new website: [https://msberends.gitlab.io/AMR](https://msberends.git
#### Other
* More unit tests to ensure better integrity of functions
-# `AMR` 0.3.0
+# AMR 0.3.0
#### New
* **BREAKING**: `rsi_df` was removed in favour of new functions `portion_R`, `portion_IR`, `portion_I`, `portion_SI` and `portion_S` to selectively calculate resistance or susceptibility. These functions are 20 to 30 times faster than the old `rsi` function. The old function still works, but is deprecated.
@@ -1293,7 +1294,7 @@ We've got a new website: [https://msberends.gitlab.io/AMR](https://msberends.git
* Windows: https://ci.appveyor.com/project/msberends/amr
* Added thesis advisors to DESCRIPTION file
-# `AMR` 0.2.0
+# AMR 0.2.0
#### New
* Full support for Windows, Linux and macOS
@@ -1328,7 +1329,7 @@ We've got a new website: [https://msberends.gitlab.io/AMR](https://msberends.git
* Added build tests for Linux and macOS using Travis CI (https://travis-ci.org/msberends/AMR)
* Added line coverage checking using CodeCov (https://codecov.io/gh/msberends/AMR/tree/master/R)
-# `AMR` 0.1.1
+# AMR 0.1.1
* `EUCAST_rules` applies for amoxicillin even if ampicillin is missing
* Edited column names to comply with GLIMS, the laboratory information system
@@ -1336,6 +1337,6 @@ We've got a new website: [https://msberends.gitlab.io/AMR](https://msberends.git
* Renamed 'Daily Defined Dose' to 'Defined Daily Dose'
* Added barplots for `rsi` and `mic` classes
-# `AMR` 0.1.0
+# AMR 0.1.0
* First submission to CRAN.
diff --git a/R/aa_helper_functions.R b/R/aa_helper_functions.R
index bfd64d593..687093047 100755
--- a/R/aa_helper_functions.R
+++ b/R/aa_helper_functions.R
@@ -135,7 +135,6 @@ check_dataset_integrity <- function() {
" the AMR package from working correctly: ",
vector_and(overwritten, quotes = "'"),
".\nPlease rename your object", plural[3], ".", call = FALSE)
- remember_thrown_message("dataset_overwritten")
}
}
# check if other packages did not overwrite our data sets
@@ -258,7 +257,6 @@ search_type_in_df <- function(x, type, info = TRUE) {
msg <- paste(msg, "Use", font_bold(paste0("col_", type), "= FALSE"), "to prevent this.")
}
message_(msg)
- remember_thrown_message(fn = paste0("search_", type))
}
}
found
@@ -771,10 +769,11 @@ get_current_data <- function(arg_name, call) {
} else {
examples <- ""
}
- stop_("this function must be used inside valid dplyr selection verbs or inside a data.frame call",
+ stop_("this function must be used inside a `dplyr` verb or `data.frame` call",
examples,
call = call)
} else {
+ # mimic a base R error that the argument is missing
stop_("argument `", arg_name, "` is missing with no default", call = call)
}
}
@@ -840,16 +839,18 @@ unique_call_id <- function(entire_session = FALSE) {
}
}
-remember_thrown_message <- function(fn, entire_session = FALSE) {
+message_not_thrown_before <- function(fn, entire_session = FALSE) {
# this is to prevent that messages/notes will be printed for every dplyr group
# e.g. this would show a msg 4 times: example_isolates %>% group_by(hospital_id) %>% filter(mo_is_gram_negative())
- assign(x = paste0("thrown_msg.", fn),
- value = unique_call_id(entire_session = entire_session),
- envir = pkg_env)
-}
-
-message_not_thrown_before <- function(fn, entire_session = FALSE) {
- is.null(pkg_env[[paste0("thrown_msg.", fn)]]) || !identical(pkg_env[[paste0("thrown_msg.", fn)]], unique_call_id(entire_session))
+ test_out <- is.null(pkg_env[[paste0("thrown_msg.", fn)]]) || !identical(pkg_env[[paste0("thrown_msg.", fn)]],
+ unique_call_id(entire_session = entire_session))
+ if (isTRUE(test_out)) {
+ # message was not thrown before - remember this so on the next run it will return FALSE:
+ assign(x = paste0("thrown_msg.", fn),
+ value = unique_call_id(entire_session = entire_session),
+ envir = pkg_env)
+ }
+ test_out
}
has_colour <- function() {
diff --git a/R/ab_class_selectors.R b/R/ab_class_selectors.R
index 306eac651..bbbee930e 100644
--- a/R/ab_class_selectors.R
+++ b/R/ab_class_selectors.R
@@ -33,7 +33,7 @@
#' @details
#' These functions can be used in data set calls for selecting columns and filtering rows. They are heavily inspired by the [Tidyverse selection helpers][tidyselect::language] such as [`everything()`][tidyselect::everything()], but also work in base \R and not only in `dplyr` verbs. Nonetheless, they are very convenient to use with `dplyr` functions such as [`select()`][dplyr::select()], [`filter()`][dplyr::filter()] and [`summarise()`][dplyr::summarise()], see *Examples*.
#'
-#' All columns in the data in which these functions are called will be searched for known antibiotic names, abbreviations, brand names, and codes (ATC, EARS-Net, WHO, etc.) in the [antibiotics] data set. This means that a selector such as [aminoglycosides()] will pick up column names like 'gen', 'genta', 'J01GB03', 'tobra', 'Tobracin', etc. Use the [ab_class()] function to filter/select on a manually defined antibiotic class.
+#' All columns in the data in which these functions are called will be searched for known antibiotic names, abbreviations, brand names, and codes (ATC, EARS-Net, WHO, etc.) according to the [antibiotics] data set. This means that a selector such as [aminoglycosides()] will pick up column names like 'gen', 'genta', 'J01GB03', 'tobra', 'Tobracin', etc. Use the [ab_class()] function to filter/select on a manually defined antibiotic class.
#'
#' @section Full list of supported agents:
#'
@@ -312,7 +312,6 @@ ab_selector <- function(function_name,
sort = TRUE), ". They can be included using `", function_name, "(only_treatable = FALSE)`. ",
"This warning will be shown once per session.",
call = FALSE)
- remember_thrown_message(paste0("ab_class.untreatable.", function_name), entire_session = TRUE)
}
ab_in_data <- ab_in_data[!names(ab_in_data) %in% untreatable]
}
@@ -343,8 +342,8 @@ ab_selector <- function(function_name,
# get the columns with a group names in the chosen ab class
agents <- ab_in_data[names(ab_in_data) %in% abx]
-
- if (message_not_thrown_before(paste0(function_name, ".", paste(pkg_env$get_column_abx.out, collapse = "|")))) {
+
+ if (message_not_thrown_before(paste0(function_name, ".", paste(sort(agents), collapse = "|")))) {
if (length(agents) == 0) {
message_("No antimicrobial agents of class '", ab_group, "' found", examples, ".")
} else {
@@ -360,21 +359,10 @@ ab_selector <- function(function_name,
ifelse(length(agents) == 1, "column ", "columns "),
vector_and(agents_formatted, quotes = FALSE, sort = FALSE))
}
- remember_thrown_message(paste0(function_name, ".", paste(pkg_env$get_column_abx.out, collapse = "|")))
}
- if (!is.null(attributes(vars_df)$type) &&
- attributes(vars_df)$type %in% c("dplyr_cur_data_all", "base_R") &&
- !any(as.character(sys.calls()) %like% paste0("(across|if_any|if_all)\\((c\\()?[a-z(), ]*", function_name))) {
- structure(unname(agents),
- class = c("ab_selector", "character"))
- } else {
- # don't return with "ab_selector" class if method is a dplyr selector,
- # dplyr::select() will complain:
- # > Subscript has the wrong type `ab_selector`.
- # > It must be numeric or character.
- unname(agents)
- }
+ structure(unname(agents),
+ class = c("ab_selector", "character"))
}
#' @method c ab_selector
@@ -412,7 +400,6 @@ all_any_ab_selector <- function(type, ..., na.rm = TRUE) {
#' @export
#' @noRd
all.ab_selector <- function(..., na.rm = FALSE) {
- # this is all() for
all_any_ab_selector("all", ..., na.rm = na.rm)
}
@@ -458,7 +445,6 @@ any.ab_selector_any_all <- function(..., na.rm = FALSE) {
`==.ab_selector` <- function(e1, e2) {
calls <- as.character(match.call())
fn_name <- calls[2]
- # keep only the ... in c(...)
fn_name <- gsub("^(c\\()(.*)(\\))$", "\\2", fn_name)
if (is_any(fn_name)) {
type <- "any"
@@ -481,7 +467,6 @@ any.ab_selector_any_all <- function(..., na.rm = FALSE) {
`!=.ab_selector` <- function(e1, e2) {
calls <- as.character(match.call())
fn_name <- calls[2]
- # keep only the ... in c(...)
fn_name <- gsub("^(c\\()(.*)(\\))$", "\\2", fn_name)
if (is_any(fn_name)) {
type <- "any"
diff --git a/R/count.R b/R/count.R
index 83ede9ba3..24626bf8c 100755
--- a/R/count.R
+++ b/R/count.R
@@ -149,7 +149,6 @@ count_R <- function(..., only_all_tested = FALSE) {
count_IR <- function(..., only_all_tested = FALSE) {
if (message_not_thrown_before("count_IR", entire_session = TRUE)) {
message_("Using `count_IR()` is discouraged; use `count_resistant()` instead to not consider \"I\" being resistant. This note will be shown once for this session.", as_note = FALSE)
- remember_thrown_message("count_IR")
}
tryCatch(
rsi_calc(...,
@@ -186,7 +185,6 @@ count_SI <- function(..., only_all_tested = FALSE) {
count_S <- function(..., only_all_tested = FALSE) {
if (message_not_thrown_before("count_S", entire_session = TRUE)) {
message_("Using `count_S()` is discouraged; use `count_susceptible()` instead to also consider \"I\" being susceptible. This note will be shown once for this session.", as_note = FALSE)
- remember_thrown_message("count_S")
}
tryCatch(
rsi_calc(...,
diff --git a/R/eucast_rules.R b/R/eucast_rules.R
index 38df612b8..37ceff993 100755
--- a/R/eucast_rules.R
+++ b/R/eucast_rules.R
@@ -1072,7 +1072,6 @@ eucast_dosage <- function(ab, administration = "iv", version_breakpoints = 11.0)
message_("Dosages for antimicrobial drugs, as meant for ",
format_eucast_version_nr(version_breakpoints, markdown = FALSE), ". ",
font_red("This note will be shown once per session."))
- remember_thrown_message(paste0("eucast_dosage_v", gsub("[^0-9]", "", version_breakpoints)), entire_session = TRUE)
}
ab <- as.ab(ab)
diff --git a/R/first_isolate.R b/R/first_isolate.R
index 0243d9c21..9a157c9b5 100755
--- a/R/first_isolate.R
+++ b/R/first_isolate.R
@@ -264,7 +264,6 @@ first_isolate <- function(x = NULL,
"")),
as_note = FALSE,
add_fn = font_black)
- remember_thrown_message("first_isolate.method")
}
# try to find columns based on type
@@ -364,7 +363,6 @@ first_isolate <- function(x = NULL,
message_("Excluding test codes: ", toString(paste0("'", testcodes_exclude, "'")),
add_fn = font_black,
as_note = FALSE)
- remember_thrown_message("first_isolate.excludingtestcodes")
}
if (is.null(col_specimen)) {
@@ -378,7 +376,6 @@ first_isolate <- function(x = NULL,
message_("Excluding other than specimen group '", specimen_group, "'",
add_fn = font_black,
as_note = FALSE)
- remember_thrown_message("first_isolate.excludingspecimen")
}
}
if (!is.null(col_keyantimicrobials)) {
@@ -474,7 +471,6 @@ first_isolate <- function(x = NULL,
add_fn = font_black,
as_note = FALSE)
}
- remember_thrown_message("first_isolate.type")
}
type_param <- type
diff --git a/R/ggplot_rsi.R b/R/ggplot_rsi.R
index 481cb3919..265c6c280 100755
--- a/R/ggplot_rsi.R
+++ b/R/ggplot_rsi.R
@@ -389,10 +389,11 @@ scale_rsi_colours <- function(...,
names_susceptible <- c("S", "SI", "IS", "S+I", "I+S", "susceptible", "Susceptible",
unique(TRANSLATIONS[which(TRANSLATIONS$pattern == "Susceptible"),
"replacement", drop = TRUE]))
- names_incr_exposure <- c("I", "intermediate", "increased exposure", "incr. exposure", "Increased exposure", "Incr. exposure",
+ names_incr_exposure <- c("I", "intermediate", "increased exposure", "incr. exposure",
+ "Increased exposure", "Incr. exposure", "Susceptible, incr. exp.",
unique(TRANSLATIONS[which(TRANSLATIONS$pattern == "Intermediate"),
"replacement", drop = TRUE]),
- unique(TRANSLATIONS[which(TRANSLATIONS$pattern == "Incr. exposure"),
+ unique(TRANSLATIONS[which(TRANSLATIONS$pattern == "Susceptible, incr. exp."),
"replacement", drop = TRUE]))
names_resistant <- c("R", "IR", "RI", "R+I", "I+R", "resistant", "Resistant",
unique(TRANSLATIONS[which(TRANSLATIONS$pattern == "Resistant"),
diff --git a/R/guess_ab_col.R b/R/guess_ab_col.R
index cc6fc27b9..ea782ec83 100755
--- a/R/guess_ab_col.R
+++ b/R/guess_ab_col.R
@@ -121,7 +121,7 @@ get_column_abx <- function(x,
# these columns did not exist in the last call, so add them
new_cols_rsi <- get_column_abx(x[, new_cols, drop = FALSE], reuse_previous_result = FALSE, info = FALSE, sort = FALSE)
current <- c(current, new_cols_rsi)
- # order according to data in current call
+ # order according to columns in current call
current <- current[match(colnames(x)[colnames(x) %in% current], current)]
}
diff --git a/R/italicise_taxonomy.R b/R/italicise_taxonomy.R
index 14eb7b0cb..89f9dafb7 100644
--- a/R/italicise_taxonomy.R
+++ b/R/italicise_taxonomy.R
@@ -44,11 +44,11 @@
#' cat(italicise_taxonomy("An overview of S. aureus isolates", type = "ansi"))
#'
#' # since ggplot2 supports no markdown (yet), use
-#' # italicise_taxonomy() and the `ggtext` pkg for titles:
+#' # italicise_taxonomy() and the `ggtext` package for titles:
#' \donttest{
#' if (require("ggplot2") && require("ggtext")) {
-#' ggplot(example_isolates$AMC,
-#' title = italicise_taxonomy("Amoxi/clav in E. coli")) +
+#' autoplot(example_isolates$AMC,
+#' title = italicise_taxonomy("Amoxi/clav in E. coli")) +
#' theme(plot.title = ggtext::element_markdown())
#' }
#' }
diff --git a/R/key_antimicrobials.R b/R/key_antimicrobials.R
index c1c2b1d2e..49da34c18 100755
--- a/R/key_antimicrobials.R
+++ b/R/key_antimicrobials.R
@@ -177,7 +177,6 @@ key_antimicrobials <- function(x = NULL,
paste0("Only using ", values_new_length, " out of ", values_old_length, " defined columns ")),
"as key antimicrobials for ", name, "s. See ?key_antimicrobials.",
call = FALSE)
- remember_thrown_message(paste0("key_antimicrobials.", name))
}
generate_antimcrobials_string(x[which(filter), c(universal, values), drop = FALSE])
diff --git a/R/mdro.R b/R/mdro.R
index fb3d0a376..b4ba8efdc 100755
--- a/R/mdro.R
+++ b/R/mdro.R
@@ -187,13 +187,9 @@ mdro <- function(x = NULL,
check_dataset_integrity()
info.bak <- info
- if (message_not_thrown_before("mdro")) {
- remember_thrown_message("mdro")
- } else {
- # don't thrown info's more than once per call
- info <- FALSE
- }
-
+ # don't thrown info's more than once per call
+ info <- message_not_thrown_before("mdro")
+
if (interactive() & verbose == TRUE & info == TRUE) {
txt <- paste0("WARNING: In Verbose mode, the mdro() function does not return the MDRO results, but instead returns a data set in logbook form with extensive info about which isolates would be MDRO-positive, or why they are not.",
"\n\nThis may overwrite your existing data if you use e.g.:",
@@ -1416,7 +1412,6 @@ mdro <- function(x = NULL,
if (message_not_thrown_before("mdro.availability")) {
warning_("NA introduced for isolates where the available percentage of antimicrobial classes was below ",
percentage(pct_required_classes), " (set with `pct_required_classes`)", call = FALSE)
- remember_thrown_message("mdro.availability")
}
# set these -1s to NA
x[which(x$MDRO == -1), "MDRO"] <- NA_integer_
diff --git a/R/mo_property.R b/R/mo_property.R
index 000e94dee..039d3bfee 100755
--- a/R/mo_property.R
+++ b/R/mo_property.R
@@ -481,7 +481,6 @@ mo_is_intrinsic_resistant <- function(x, ab, language = get_locale(), ...) {
message_("Determining intrinsic resistance based on ",
format_eucast_version_nr(3.2, markdown = FALSE), ". ",
font_red("This note will be shown once per session."))
- remember_thrown_message("intrinsic_resistant_version", entire_session = TRUE)
}
# runs against internal vector: INTRINSIC_R (see zzz.R)
@@ -758,7 +757,6 @@ find_mo_col <- function(fn) {
if (!is.null(df) && !is.null(mo) && is.data.frame(df)) {
if (message_not_thrown_before(fn = fn)) {
message_("Using column '", font_bold(mo), "' as input for `", fn, "()`")
- remember_thrown_message(fn = fn)
}
return(df[, mo, drop = TRUE])
} else {
diff --git a/R/plot.R b/R/plot.R
index c68b4f9d6..6a9d6751f 100644
--- a/R/plot.R
+++ b/R/plot.R
@@ -265,7 +265,7 @@ autoplot.mic <- function(object,
if (any(colours_RSI %in% cols_sub$cols)) {
vals <- c("Resistant" = colours_RSI[1],
"Susceptible" = colours_RSI[2],
- "Incr. exposure" = colours_RSI[3],
+ "Susceptible, incr. exp." = colours_RSI[3],
"Intermediate" = colours_RSI[3])
names(vals) <- translate_AMR(names(vals), language = language)
p <- p +
@@ -482,7 +482,7 @@ autoplot.disk <- function(object,
if (any(colours_RSI %in% cols_sub$cols)) {
vals <- c("Resistant" = colours_RSI[1],
"Susceptible" = colours_RSI[2],
- "Incr. exposure" = colours_RSI[3],
+ "Susceptible, incr. exp." = colours_RSI[3],
"Intermediate" = colours_RSI[3])
names(vals) <- translate_AMR(names(vals), language = language)
p <- p +
@@ -686,7 +686,7 @@ plot_prepare_table <- function(x, expand) {
plot_name_of_I <- function(guideline) {
if (guideline %unlike% "CLSI" && as.double(gsub("[^0-9]+", "", guideline)) >= 2019) {
# interpretation since 2019
- "Incr. exposure"
+ "Susceptible, incr. exp."
} else {
# interpretation until 2019
"Intermediate"
diff --git a/R/random.R b/R/random.R
index 8ac2988d2..d0531e697 100644
--- a/R/random.R
+++ b/R/random.R
@@ -27,7 +27,7 @@
#'
#' These functions can be used for generating random MIC values and disk diffusion diameters, for AMR data analysis practice. By providing a microorganism and antimicrobial agent, the generated results will reflect reality as much as possible.
#' @inheritSection lifecycle Stable Lifecycle
-#' @param size desired size of the returned vector
+#' @param size desired size of the returned vector. If used in a [data.frame] call or `dplyr` verb, will get the current (group) size if left blank.
#' @param mo any [character] that can be coerced to a valid microorganism code with [as.mo()]
#' @param ab any [character] that can be coerced to a valid antimicrobial agent code with [as.ab()]
#' @param prob_RSI a vector of length 3: the probabilities for R (1st value), S (2nd value) and I (3rd value)
@@ -55,27 +55,36 @@
#' random_disk(100, "Klebsiella pneumoniae", "ampicillin") # range 11-17
#' random_disk(100, "Streptococcus pneumoniae", "ampicillin") # range 12-27
#' }
-random_mic <- function(size, mo = NULL, ab = NULL, ...) {
- meet_criteria(size, allow_class = c("numeric", "integer"), has_length = 1, is_positive = TRUE, is_finite = TRUE)
+random_mic <- function(size = NULL, mo = NULL, ab = NULL, ...) {
+ meet_criteria(size, allow_class = c("numeric", "integer"), has_length = 1, is_positive = TRUE, is_finite = TRUE, allow_NULL = TRUE)
meet_criteria(mo, allow_class = "character", has_length = 1, allow_NULL = TRUE)
meet_criteria(ab, allow_class = "character", has_length = 1, allow_NULL = TRUE)
+ if (is.null(size)) {
+ size <- NROW(get_current_data(arg_name = "size", call = -3))
+ }
random_exec("MIC", size = size, mo = mo, ab = ab)
}
#' @rdname random
#' @export
-random_disk <- function(size, mo = NULL, ab = NULL, ...) {
- meet_criteria(size, allow_class = c("numeric", "integer"), has_length = 1, is_positive = TRUE, is_finite = TRUE)
+random_disk <- function(size = NULL, mo = NULL, ab = NULL, ...) {
+ meet_criteria(size, allow_class = c("numeric", "integer"), has_length = 1, is_positive = TRUE, is_finite = TRUE, allow_NULL = TRUE)
meet_criteria(mo, allow_class = "character", has_length = 1, allow_NULL = TRUE)
meet_criteria(ab, allow_class = "character", has_length = 1, allow_NULL = TRUE)
+ if (is.null(size)) {
+ size <- NROW(get_current_data(arg_name = "size", call = -3))
+ }
random_exec("DISK", size = size, mo = mo, ab = ab)
}
#' @rdname random
#' @export
-random_rsi <- function(size, prob_RSI = c(0.33, 0.33, 0.33), ...) {
- meet_criteria(size, allow_class = c("numeric", "integer"), has_length = 1, is_positive = TRUE, is_finite = TRUE)
+random_rsi <- function(size = NULL, prob_RSI = c(0.33, 0.33, 0.33), ...) {
+ meet_criteria(size, allow_class = c("numeric", "integer"), has_length = 1, is_positive = TRUE, is_finite = TRUE, allow_NULL = TRUE)
meet_criteria(prob_RSI, allow_class = c("numeric", "integer"), has_length = 3)
+ if (is.null(size)) {
+ size <- NROW(get_current_data(arg_name = "size", call = -3))
+ }
sample(as.rsi(c("R", "S", "I")), size = size, replace = TRUE, prob = prob_RSI)
}
@@ -111,23 +120,22 @@ random_exec <- function(type, size, mo = NULL, ab = NULL) {
warning_("No rows found that match ab '", ab, "', ignoring argument `ab`", call = FALSE)
}
}
-
+
if (type == "MIC") {
- # all valid MIC levels
- valid_range <- as.mic(levels(as.mic(1)))
- set_range_max <- max(df$breakpoint_R)
- if (log(set_range_max, 2) %% 1 == 0) {
- # return powers of 2
- valid_range <- unique(as.double(valid_range))
- # add 1-3 higher MIC levels to set_range_max
- set_range_max <- 2 ^ (log(set_range_max, 2) + sample(c(1:3), 1))
- set_range <- as.mic(valid_range[log(valid_range, 2) %% 1 == 0 & valid_range <= set_range_max])
- } else {
- # no power of 2, return factors of 2 to left and right side
- valid_mics <- suppressWarnings(as.mic(set_range_max / (2 ^ c(-3:3))))
- set_range <- valid_mics[!is.na(valid_mics)]
+ # set range
+ mic_range <- c(0.001, 0.002, 0.005, 0.010, 0.025, 0.0625, 0.125, 0.250, 0.5, 1, 2, 4, 8, 16, 32, 64, 128, 256)
+
+ # get highest/lowest +/- random 1 to 3 higher factors of two
+ max_range <- mic_range[min(length(mic_range),
+ which(mic_range == max(df$breakpoint_R)) + sample(c(1:3), 1))]
+ min_range <- mic_range[max(1,
+ which(mic_range == min(df$breakpoint_S)) - sample(c(1:3), 1))]
+
+ mic_range_new <- mic_range[mic_range <= max_range & mic_range >= min_range]
+ if (length(mic_range_new) == 0) {
+ mic_range_new <- mic_range
}
- out <- as.mic(sample(set_range, size = size, replace = TRUE))
+ out <- as.mic(sample(mic_range_new, size = size, replace = TRUE))
# 50% chance that lowest will get <= and highest will get >=
if (stats::runif(1) > 0.5) {
out[out == min(out)] <- paste0("<=", out[out == min(out)])
diff --git a/R/rsi.R b/R/rsi.R
index bb23ca0a9..33855263d 100755
--- a/R/rsi.R
+++ b/R/rsi.R
@@ -294,16 +294,15 @@ as.rsi.default <- function(x, ...) {
LANGUAGES_SUPPORTED[LANGUAGES_SUPPORTED %in% colnames(TRANSLATIONS)]])
trans_S <- unlist(TRANSLATIONS[which(TRANSLATIONS$pattern == "Susceptible"),
LANGUAGES_SUPPORTED[LANGUAGES_SUPPORTED %in% colnames(TRANSLATIONS)]])
- trans_I <- unlist(TRANSLATIONS[which(TRANSLATIONS$pattern %in% c("Incr. exposure", "Intermediate")),
+ trans_I <- unlist(TRANSLATIONS[which(TRANSLATIONS$pattern %in% c("Incr. exposure", "Susceptible, incr. exp.", "Intermediate")),
LANGUAGES_SUPPORTED[LANGUAGES_SUPPORTED %in% colnames(TRANSLATIONS)]])
x <- gsub(paste0(unique(trans_R[!is.na(trans_R)]), collapse = "|"), "R", x, ignore.case = TRUE)
x <- gsub(paste0(unique(trans_S[!is.na(trans_S)]), collapse = "|"), "S", x, ignore.case = TRUE)
x <- gsub(paste0(unique(trans_I[!is.na(trans_I)]), collapse = "|"), "I", x, ignore.case = TRUE)
# replace all English textual input
- x <- gsub("res(is(tant)?)?", "R", x, ignore.case = TRUE)
- x <- gsub("sus(cep(tible)?)?", "S", x, ignore.case = TRUE)
- x <- gsub("int(er(mediate)?)?", "I", x, ignore.case = TRUE)
- x <- gsub("inc(r(eased)?)? exp[a-z]*", "I", x, ignore.case = TRUE)
+ x[x %like% "([^a-z]|^)res(is(tant)?)?"] <- "R"
+ x[x %like% "([^a-z]|^)sus(cep(tible)?)?"] <- "S"
+ x[x %like% "([^a-z]|^)int(er(mediate)?)?|incr.*exp"] <- "I"
# remove all spaces
x <- gsub(" +", "", x)
# remove all MIC-like values: numbers, operators and periods
@@ -776,7 +775,6 @@ exec_as.rsi <- function(method,
if (guideline_coerced != guideline) {
if (message_not_thrown_before("as.rsi")) {
message_("Using guideline ", font_bold(guideline_coerced), " as input for `guideline`.")
- remember_thrown_message("as.rsi")
}
}
@@ -815,7 +813,6 @@ exec_as.rsi <- function(method,
if (guideline_coerced %unlike% "EUCAST") {
if (message_not_thrown_before("as.rsi2")) {
warning_("Using 'add_intrinsic_resistance' is only useful when using EUCAST guidelines, since the rules for intrinsic resistance are based on EUCAST.", call = FALSE)
- remember_thrown_message("as.rsi2")
}
} else {
new_rsi[i] <- "R"
@@ -880,7 +877,6 @@ exec_as.rsi <- function(method,
message_("WARNING.", add_fn = list(font_yellow, font_bold), as_note = FALSE)
if (message_not_thrown_before("as.rsi3")) {
warning_("Found intrinsic resistance in some bug/drug combinations, although it was not applied.\nUse `as.rsi(..., add_intrinsic_resistance = TRUE)` to apply it.", call = FALSE)
- remember_thrown_message("as.rsi3")
}
warned <- TRUE
}
diff --git a/R/rsi_calc.R b/R/rsi_calc.R
index 214991a20..4f8dd6728 100755
--- a/R/rsi_calc.R
+++ b/R/rsi_calc.R
@@ -152,7 +152,6 @@ rsi_calc <- function(...,
" your_data %>% mutate_if(is.rsi.eligible, as.rsi)\n",
" your_data %>% mutate(across(where(is.rsi.eligible), as.rsi))",
call = FALSE)
- remember_thrown_message("rsi_calc")
}
}
diff --git a/R/sysdata.rda b/R/sysdata.rda
index e10d4816b..255d25848 100644
Binary files a/R/sysdata.rda and b/R/sysdata.rda differ
diff --git a/R/vctrs.R b/R/vctrs.R
new file mode 100644
index 000000000..af5dbe0a8
--- /dev/null
+++ b/R/vctrs.R
@@ -0,0 +1,74 @@
+# ==================================================================== #
+# TITLE #
+# Antimicrobial Resistance (AMR) Data Analysis for R #
+# #
+# SOURCE #
+# https://github.com/msberends/AMR #
+# #
+# LICENCE #
+# (c) 2018-2021 Berends MS, Luz CF et al. #
+# Developed at the University of Groningen, the Netherlands, in #
+# collaboration with non-profit organisations Certe Medical #
+# Diagnostics & Advice, and University Medical Center Groningen. #
+# #
+# 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://msberends.github.io/AMR/ #
+# ==================================================================== #
+
+# These are all S3 implementations for the vctrs package,
+# that is used internally by tidyverse packages such as dplyr.
+# They are to convert AMR-specific classes to bare characters and integers.
+# All of them will be exported using s3_register() in R/zzz.R when loading the package.
+
+# S3: ab
+vec_ptype2.character.ab <- function(x, y, ...) {
+ x
+}
+vec_ptype2.ab.character <- function(x, y, ...) {
+ y
+}
+vec_cast.character.ab <- function(x, to, ...) {
+ unclass(x)
+}
+
+# S3: mo
+vec_ptype2.character.mo <- function(x, y, ...) {
+ x
+}
+vec_ptype2.mo.character <- function(x, y, ...) {
+ y
+}
+vec_cast.character.mo <- function(x, to, ...) {
+ unclass(x)
+}
+
+# S3: disk
+vec_ptype2.integer.disk <- function(x, y, ...) {
+ x
+}
+vec_ptype2.disk.integer <- function(x, y, ...) {
+ y
+}
+vec_cast.integer.disk <- function(x, to, ...) {
+ unclass(x)
+}
+
+# S3: ab_selector
+# see https://github.com/tidyverse/dplyr/issues/5955 why this is required
+vec_ptype2.character.ab_selector <- function(x, y, ...) {
+ x
+}
+vec_ptype2.ab_selector.character <- function(x, y, ...) {
+ y
+}
+vec_cast.character.ab_selector <- function(x, to, ...) {
+ unclass(x)
+}
diff --git a/R/zzz.R b/R/zzz.R
index 7acf1074a..035ec599c 100755
--- a/R/zzz.R
+++ b/R/zzz.R
@@ -56,15 +56,29 @@ if (utf8_supported && !is_latex) {
# Support for frequency tables from the cleaner package
s3_register("cleaner::freq", "mo")
s3_register("cleaner::freq", "rsi")
- # Support from skim() from the skimr package
+ # Support for skim() from the skimr package
s3_register("skimr::get_skimmers", "mo")
s3_register("skimr::get_skimmers", "rsi")
s3_register("skimr::get_skimmers", "mic")
s3_register("skimr::get_skimmers", "disk")
+ # Support for autoplot() from the ggplot2 package
s3_register("ggplot2::autoplot", "rsi")
s3_register("ggplot2::autoplot", "mic")
s3_register("ggplot2::autoplot", "disk")
s3_register("ggplot2::autoplot", "resistance_predict")
+ # Support vctrs package for use in e.g. dplyr verbs
+ s3_register("vctrs::vec_ptype2", "ab.character")
+ s3_register("vctrs::vec_ptype2", "character.ab")
+ s3_register("vctrs::vec_cast", "character.ab")
+ s3_register("vctrs::vec_ptype2", "mo.character")
+ s3_register("vctrs::vec_ptype2", "character.mo")
+ s3_register("vctrs::vec_cast", "character.mo")
+ s3_register("vctrs::vec_ptype2", "ab_selector.character")
+ s3_register("vctrs::vec_ptype2", "character.ab_selector")
+ s3_register("vctrs::vec_cast", "character.ab_selector")
+ s3_register("vctrs::vec_ptype2", "disk.integer")
+ s3_register("vctrs::vec_ptype2", "integer.disk")
+ s3_register("vctrs::vec_cast", "integer.disk")
# if mo source exists, fire it up (see mo_source())
try({
@@ -75,6 +89,7 @@ if (utf8_supported && !is_latex) {
# reference data - they have additional columns compared to `antibiotics` and `microorganisms` to improve speed
+ # they can't be part of R/sysdata.rda since CRAN thinks it would make the package too large (+3 MB)
assign(x = "AB_lookup", value = create_AB_lookup(), envir = asNamespace("AMR"))
assign(x = "MO_lookup", value = create_MO_lookup(), envir = asNamespace("AMR"))
assign(x = "MO.old_lookup", value = create_MO.old_lookup(), envir = asNamespace("AMR"))
diff --git a/_pkgdown.yml b/_pkgdown.yml
index 22de77d9f..6847ea676 100644
--- a/_pkgdown.yml
+++ b/_pkgdown.yml
@@ -32,6 +32,7 @@ development:
news:
one_page: true
+ cran_dates: true
navbar:
title: "AMR (for R)"
diff --git a/data-raw/AMR_latest.tar.gz b/data-raw/AMR_latest.tar.gz
index fce2ac1e0..e064252c2 100644
Binary files a/data-raw/AMR_latest.tar.gz and b/data-raw/AMR_latest.tar.gz differ
diff --git a/data-raw/translations.tsv b/data-raw/translations.tsv
index 803901ecc..4d77530f3 100644
--- a/data-raw/translations.tsv
+++ b/data-raw/translations.tsv
@@ -32,8 +32,10 @@ vegetative TRUE TRUE FALSE FALSE vegetativ vegetatief vegetativo vegetativo vég
([([ ]*?)Group TRUE TRUE FALSE FALSE \\1Gruppe \\1Groep \\1Grupo \\1Gruppo \\1Groupe \\1Grupo
no .*growth TRUE FALSE FALSE FALSE keine? .*wachstum geen .*groei no .*crecimientonon sem .*crescimento pas .*croissance sem .*crescimento
no|not TRUE FALSE FALSE FALSE keine? geen|niet no|sin sem non sem
-Susceptible TRUE FALSE FALSE FALSE Empfindlich Gevoelig Susceptible
Intermediate TRUE FALSE FALSE FALSE Mittlere Intermediair Intermedio
+Susceptible, incr. exp. FALSE TRUE FALSE FALSE Empfindlich, erh Belastung Gevoelig, hoge dosis
+susceptible, incr. exp. FALSE TRUE FALSE FALSE empfindlich, erh Belastung gevoelig, hoge dosis
+Susceptible TRUE FALSE FALSE FALSE Empfindlich Gevoelig Susceptible
Incr. exposure TRUE FALSE FALSE FALSE Empfindlich, erh Belastung 'Incr. exposure' 'Incr. exposure'
Resistant TRUE FALSE FALSE FALSE Resistent Resistent Resistente
antibiotic TRUE TRUE FALSE FALSE Antibiotikum antibioticum antibiótico
diff --git a/docs/404.html b/docs/404.html
index 022953e02..37f49db60 100644
--- a/docs/404.html
+++ b/docs/404.html
@@ -1,76 +1,35 @@
-
-
-
-
+
+
+
+
-
Page not found (404) • AMR (for R)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
-
-
-
-
-
Note: values on this page will change with every website update since they are based on randomly created values and the page was written in R Markdown. However, the methodology remains unchanged. This page was generated on 06 July 2021.
+
Note: values on this page will change with every website update since they are based on randomly created values and the page was written in R Markdown. However, the methodology remains unchanged. This page was generated on 23 July 2021.
-Introduction
+Introduction
Conducting AMR data analysis unfortunately requires in-depth knowledge from different scientific fields, which makes it hard to do right. At least, it requires:
Good questions (always start with those!)
@@ -220,7 +222,7 @@
-Preparation
+Preparation
For this tutorial, we will create fake demonstration data to work with.
You can skip to Cleaning the data if you already have your own data ready. If you start your analysis, try to make the structure of your data generally look like this:
@@ -233,21 +235,21 @@
-
2021-07-06
+
2021-07-23
abcd
Escherichia coli
S
S
-
2021-07-06
+
2021-07-23
abcd
Escherichia coli
S
R
-
2021-07-06
+
2021-07-23
efgh
Escherichia coli
R
@@ -257,14 +259,14 @@
-Needed R packages
-
As with many uses in R, we need some additional packages for AMR data analysis. Our package works closely together with the tidyverse packagesdplyr and ggplot2 by RStudio. The tidyverse tremendously improves the way we conduct data science - it allows for a very natural way of writing syntaxes and creating beautiful plots in R.
+Needed R packages
+
As with many uses in R, we need some additional packages for AMR data analysis. Our package works closely together with the tidyverse packagesdplyr and ggplot2 by RStudio. The tidyverse tremendously improves the way we conduct data science - it allows for a very natural way of writing syntaxes and creating beautiful plots in R.
We will also use the cleaner package, that can be used for cleaning data and creating frequency tables.
We will create some fake example data to use for analysis. For AMR data analysis, we need at least: a patient ID, name or code of a microorganism, a date and antimicrobial results (an antibiogram). It could also include a specimen type (e.g. to filter on blood or urine), the ward type (e.g. to filter on ICUs).
With additional columns (like a hospital name, the patients gender of even [well-defined] clinical properties) you can do a comparative analysis, as this tutorial will demonstrate too.
-Patients
+Patients
To start with patients, we need a unique list of patients.
The LETTERS object is available in R - it’s a vector with 26 characters: A to Z. The patients object we just created is now a vector of length 260, with values (patient IDs) varying from A1 to Z10. Now we we also set the gender of our patients, by putting the ID and the gender in a table:
The first 135 patient IDs are now male, the other 125 are female.
-Dates
+Dates
Let’s pretend that our data consists of blood cultures isolates from between 1 January 2010 and 1 January 2018.
-dates<-seq(as.Date("2010-01-01"), as.Date("2018-01-01"), by ="day")
+dates<-seq(as.Date("2010-01-01"), as.Date("2018-01-01"), by ="day")
This dates object now contains all days in our date range.
-Microorganisms
+Microorganisms
For this tutorial, we will uses four different microorganisms: Escherichia coli, Staphylococcus aureus, Streptococcus pneumoniae, and Klebsiella pneumoniae:
Using the sample() function, we can randomly select items from all objects we defined earlier. To let our fake data reflect reality a bit, we will also approximately define the probabilities of bacteria and the antibiotic results, using the random_rsi() function.
+Put everything together
+
Using the sample() function, we can randomly select items from all objects we defined earlier. To let our fake data reflect reality a bit, we will also approximately define the probabilities of bacteria and the antibiotic results, using the random_rsi() function.
We also created a package dedicated to data cleaning and checking, called the cleaner package. It freq() function can be used to create frequency tables.
+Cleaning the data
+
We also created a package dedicated to data cleaning and checking, called the cleaner package. It freq() function can be used to create frequency tables.
Class: character
Length: 20,000
@@ -441,63 +443,63 @@ Longest: 1
1
M
-
10,365
-
51.83%
-
10,365
-
51.83%
+
10,388
+
51.94%
+
10,388
+
51.94%
2
F
-
9,635
-
48.18%
+
9,612
+
48.06%
20,000
100.00%
So, we can draw at least two conclusions immediately. From a data scientists perspective, the data looks clean: only values M and F. From a researchers perspective: there are slightly more men. Nothing we didn’t already know.
-
The data is already quite clean, but we still need to transform some variables. The bacteria column now consists of text, and we want to add more variables based on microbial IDs later on. So, we will transform this column to valid IDs. The mutate() function of the dplyr package makes this really easy:
+
The data is already quite clean, but we still need to transform some variables. The bacteria column now consists of text, and we want to add more variables based on microbial IDs later on. So, we will transform this column to valid IDs. The mutate() function of the dplyr package makes this really easy:
We also want to transform the antibiotics, because in real life data we don’t know if they are really clean. The as.rsi() function ensures reliability and reproducibility in these kind of variables. The is.rsi.eligible() can check which columns are probably columns with R/SI test results. Using mutate() and across(), we can apply the transformation to the formal <rsi> class:
We also want to transform the antibiotics, because in real life data we don’t know if they are really clean. The as.rsi() function ensures reliability and reproducibility in these kind of variables. The is.rsi.eligible() can check which columns are probably columns with R/SI test results. Using mutate() and across(), we can apply the transformation to the formal <rsi> class:
Finally, we will apply EUCAST rules on our antimicrobial results. In Europe, most medical microbiological laboratories already apply these rules. Our package features their latest insights on intrinsic resistance and exceptional phenotypes. Moreover, the eucast_rules() function can also apply additional rules, like forcing ampicillin = R when amoxicillin/clavulanic acid = R.
Finally, we will apply EUCAST rules on our antimicrobial results. In Europe, most medical microbiological laboratories already apply these rules. Our package features their latest insights on intrinsic resistance and exceptional phenotypes. Moreover, the eucast_rules() function can also apply additional rules, like forcing ampicillin = R when amoxicillin/clavulanic acid = R.
Because the amoxicillin (column AMX) and amoxicillin/clavulanic acid (column AMC) in our data were generated randomly, some rows will undoubtedly contain AMX = S and AMC = R, which is technically impossible. The eucast_rules() fixes this:
We also need to know which isolates we can actually use for analysis.
-
To conduct an analysis of antimicrobial resistance, you must only include the first isolate of every patient per episode (Hindler et al., Clin Infect Dis. 2007). If you would not do this, you could easily get an overestimate or underestimate of the resistance of an antibiotic. Imagine that a patient was admitted with an MRSA and that it was found in 5 different blood cultures the following weeks (yes, some countries like the Netherlands have these blood drawing policies). The resistance percentage of oxacillin of all isolates would be overestimated, because you included this MRSA more than once. It would clearly be selection bias.
+
To conduct an analysis of antimicrobial resistance, you must only include the first isolate of every patient per episode (Hindler et al., Clin Infect Dis. 2007). If you would not do this, you could easily get an overestimate or underestimate of the resistance of an antibiotic. Imagine that a patient was admitted with an MRSA and that it was found in 5 different blood cultures the following weeks (yes, some countries like the Netherlands have these blood drawing policies). The resistance percentage of oxacillin of all isolates would be overestimated, because you included this MRSA more than once. It would clearly be selection bias.
The Clinical and Laboratory Standards Institute (CLSI) appoints this as follows:
-
(…) When preparing a cumulative antibiogram to guide clinical decisions about empirical antimicrobial therapy of initial infections, only the first isolate of a given species per patient, per analysis period (eg, one year) should be included, irrespective of body site, antimicrobial susceptibility profile, or other phenotypical characteristics (eg, biotype). The first isolate is easily identified, and cumulative antimicrobial susceptibility test data prepared using the first isolate are generally comparable to cumulative antimicrobial susceptibility test data calculated by other methods, providing duplicate isolates are excluded. M39-A4 Analysis and Presentation of Cumulative Antimicrobial Susceptibility Test Data, 4th Edition. CLSI, 2014. Chapter 6.4
+
(…) When preparing a cumulative antibiogram to guide clinical decisions about empirical antimicrobial therapy of initial infections, only the first isolate of a given species per patient, per analysis period (eg, one year) should be included, irrespective of body site, antimicrobial susceptibility profile, or other phenotypical characteristics (eg, biotype). The first isolate is easily identified, and cumulative antimicrobial susceptibility test data prepared using the first isolate are generally comparable to cumulative antimicrobial susceptibility test data calculated by other methods, providing duplicate isolates are excluded. M39-A4 Analysis and Presentation of Cumulative Antimicrobial Susceptibility Test Data, 4th Edition. CLSI, 2014. Chapter 6.4
-
This AMR package includes this methodology with the first_isolate() function and is able to apply the four different methods as defined by Hindler et al. in 2007: phenotype-based, episode-based, patient-based, isolate-based. The right method depends on your goals and analysis, but the default phenotype-based method is in any case the method to properly correct for most duplicate isolates. This method also takes into account the antimicrobial susceptibility test results using all_microbials(). Read more about the methods on the first_isolate() page.
+
This AMR package includes this methodology with the first_isolate() function and is able to apply the four different methods as defined by Hindler et al. in 2007: phenotype-based, episode-based, patient-based, isolate-based. The right method depends on your goals and analysis, but the default phenotype-based method is in any case the method to properly correct for most duplicate isolates. This method also takes into account the antimicrobial susceptibility test results using all_microbials(). Read more about the methods on the first_isolate() page.
The outcome of the function can easily be added to our data:
data<-data%>%
- mutate(first =first_isolate(info =TRUE))
+ mutate(first =first_isolate(info =TRUE))# Determining first isolates using the 'phenotype-based' method and an# episode length of 365 days# ℹ Using column 'bacteria' as input for `col_mo`.
@@ -505,20 +507,20 @@ Longest: 1
# ℹ Using column 'patient_id' as input for `col_patient_id`.# Basing inclusion on all antimicrobial results, using a points threshold of# 2
-# => Found 10,656 first weighted isolates (phenotype-based, 53.3% of total
+# => Found 10,659 first weighted isolates (phenotype-based, 53.3% of total# where a microbial ID was available)
-
So only 53.3% is suitable for resistance analysis! We can now filter on it with the filter() function, also from the dplyr package:
+
So only 53.3% is suitable for resistance analysis! We can now filter on it with the filter() function, also from the dplyr package:
You might want to start by getting an idea of how the data is distributed. It’s an important start, because it also decides how you will continue your analysis. Although this package contains a convenient function to make frequency tables, exploratory data analysis (EDA) is not the primary scope of this package. Use a package like DataExplorer for that, or read the free online book Exploratory Data Analysis with R by Roger D. Peng.
+Analysing the data
+
You might want to start by getting an idea of how the data is distributed. It’s an important start, because it also decides how you will continue your analysis. Although this package contains a convenient function to make frequency tables, exploratory data analysis (EDA) is not the primary scope of this package. Use a package like DataExplorer for that, or read the free online book Exploratory Data Analysis with R by Roger D. Peng.
-Dispersion of species
-
To just get an idea how the species are distributed, create a frequency table with our freq() function. We created the genus and species column earlier based on the microbial ID. With paste(), we can concatenate them together.
-
The freq() function can be used like the base R language was intended:
+Dispersion of species
+
To just get an idea how the species are distributed, create a frequency table with our freq() function. We created the genus and species column earlier based on the microbial ID. With paste(), we can concatenate them together.
+
The freq() function can be used like the base R language was intended:
All these functions contain a minimum argument, denoting the minimum required number of test results for returning a value. These functions will otherwise return NA. The default is minimum = 30, following the CLSI M39-A4 guideline for applying microbial epidemiology.
+
All these functions contain a minimum argument, denoting the minimum required number of test results for returning a value. These functions will otherwise return NA. The default is minimum = 30, following the CLSI M39-A4 guideline for applying microbial epidemiology.
As per the EUCAST guideline of 2019, we calculate resistance as the proportion of R (proportion_R(), equal to resistance()) and susceptibility as the proportion of S and I (proportion_SI(), equal to susceptibility()). These functions can be used on their own:
Of course it would be very convenient to know the number of isolates responsible for the percentages. For that purpose the n_rsi() can be used, which works exactly like n_distinct() from the dplyr package. It counts all isolates available for every group (i.e. values S, I or R):
+
Of course it would be very convenient to know the number of isolates responsible for the percentages. For that purpose the n_rsi() can be used, which works exactly like n_distinct() from the dplyr package. It counts all isolates available for every group (i.e. values S, I or R):
These functions can also be used to get the proportion of multiple antibiotics, to calculate empiric susceptibility of combination therapies very easily:
data_1st%>%# group by hospital
- group_by(hospital)%>%
+ group_by(hospital)%>%# / -> select all penicillins in the data for calculation# | / -> use resistance() for all peni's per hospital# | | / -> print as percentages
- summarise(across(penicillins(), resistance, as_percent =TRUE))%>%
+ summarise(across(penicillins(), resistance, as_percent =TRUE))%>%# format the antibiotic column names, using so-called snake case,# so 'Amoxicillin/clavulanic acid' becomes 'amoxicillin_clavulanic_acid'
- rename_with(.fn =ab_name, .cols =penicillins(), snake_case =TRUE)
To show results in plots, most R users would nowadays use the ggplot2 package. This package lets you create plots in layers. You can read more about it on their website. A quick example would look like these syntaxes:
+Plots
+
To show results in plots, most R users would nowadays use the ggplot2 package. This package lets you create plots in layers. You can read more about it on their website. A quick example would look like these syntaxes:
-ggplot(data =a_data_set,
- mapping =aes(x =year,
+ggplot(data =a_data_set,
+ mapping =aes(x =year,
y =value))+
- geom_col()+
- labs(title ="A title",
+ geom_col()+
+ labs(title ="A title",
subtitle ="A subtitle",
x ="My X axis",
y ="My Y axis")# or as short as:
-ggplot(a_data_set)+
- geom_bar(aes(year))
The AMR package contains functions to extend this ggplot2 package, for example geom_rsi(). It automatically transforms data with count_df() or proportion_df() and show results in stacked bars. Its simplest and shortest example:
Omit the translate_ab = FALSE to have the antibiotic codes (AMX, AMC, CIP, GEN) translated to official WHO names (amoxicillin, amoxicillin/clavulanic acid, ciprofloxacin, gentamicin).
If we group on e.g. the genus column and add some additional functions from our package, we can create this:
# group the data on `genus`
-ggplot(data_1st%>%group_by(genus))+
+ggplot(data_1st%>%group_by(genus))+# create bars with genus on x axis# it looks for variables with class `rsi`,# of which we have 4 (earlier created with `as.rsi`)
@@ -1177,55 +1179,55 @@ Longest: 24
# show percentages on y axisscale_y_percent(breaks =0:4*25)+# turn 90 degrees, to make it bars instead of columns
- coord_flip()+
+ coord_flip()+# add labels
- labs(title ="Resistance per genus and antibiotic",
+ labs(title ="Resistance per genus and antibiotic",
subtitle ="(this is fake data)")+# and print genus in italic to follow our convention# (is now y axis because we turned the plot)
- theme(axis.text.y =element_text(face ="italic"))
The AMR package also extends the plot() and ggplot2::autoplot() functions for plotting minimum inhibitory concentrations (MIC, created with as.mic()) and disk diffusion diameters (created with as.disk()).
+Plotting MIC and disk diffusion values
+
The AMR package also extends the plot() and ggplot2::autoplot() functions for plotting minimum inhibitory concentrations (MIC, created with as.mic()) and disk diffusion diameters (created with as.disk()).
With the random_mic() and random_disk() functions, we can generate sampled values for the new data types (S3 classes) <mic> and <disk>:
But we could also be more specific, by generating MICs that are likely to be found in E. coli for ciprofloxacin:
mic_values<-random_mic(size =100, mo ="E. coli", ab ="cipro")
-
For the plot() and autoplot() function, we can define the microorganism and an antimicrobial agent the same way. This will add the interpretation of those values according to a chosen guidelines (defaults to the latest EUCAST guideline).
+
For the plot() and autoplot() function, we can define the microorganism and an antimicrobial agent the same way. This will add the interpretation of those values according to a chosen guidelines (defaults to the latest EUCAST guideline).
Default colours are colour-blind friendly, while maintaining the convention that e.g. ‘susceptible’ should be green and ‘resistant’ should be red:
# base R:
@@ -1233,7 +1235,7 @@ Longest: 24
# ggplot2:
-autoplot(mic_values, mo ="E. coli", ab ="cipro")
# base R:plot(disk_values, mo ="E. coli", ab ="cipro")
-
And when using the ggplot2 package, but now choosing the latest implemented CLSI guideline (notice that the EUCAST-specific term “Incr. exposure” has changed to “Intermediate”):
+
And when using the ggplot2 package, but now choosing the latest implemented CLSI guideline (notice that the EUCAST-specific term “Susceptible, incr. exp.” has changed to “Intermediate”):
-autoplot(disk_values,
+autoplot(disk_values,
mo ="E. coli",
ab ="cipro",
guideline ="CLSI")
@@ -1261,22 +1263,22 @@ Longest: 24
-Independence test
+Independence test
The next example uses the example_isolates data set. This is a data set included with this package and contains 2,000 microbial isolates with their full antibiograms. It reflects reality and can be used to practice AMR data analysis.
-
We will compare the resistance to fosfomycin (column FOS) in hospital A and D. The input for the fisher.test() can be retrieved with a transformation like this:
+
We will compare the resistance to fosfomycin (column FOS) in hospital A and D. The input for the fisher.test() can be retrieved with a transformation like this:
# use package 'tidyr' to pivot data:
-library(tidyr)
+library(tidyr)check_FOS<-example_isolates%>%
- filter(hospital_id%in%c("A", "D"))%>%# filter on only hospitals A and D
- select(hospital_id, FOS)%>%# select the hospitals and fosfomycin
- group_by(hospital_id)%>%# group on the hospitals
+ filter(hospital_id%in%c("A", "D"))%>%# filter on only hospitals A and D
+ select(hospital_id, FOS)%>%# select the hospitals and fosfomycin
+ group_by(hospital_id)%>%# group on the hospitalscount_df(combine_SI =TRUE)%>%# count all isolates per group (hospital_id)
- pivot_wider(names_from =hospital_id, # transform output so A and D are columns
+ pivot_wider(names_from =hospital_id, # transform output so A and D are columns
values_from =value)%>%
- select(A, D)%>%# and only select these columns
- as.matrix()# transform to a good old matrix for fisher.test()
+ select(A, D)%>%# and only select these columns
+ as.matrix()# transform to a good old matrix for fisher.test()check_FOS# A D
@@ -1285,7 +1287,7 @@ Longest: 24
We can apply the test now with:
# do Fisher's Exact Test
-fisher.test(check_FOS)
+fisher.test(check_FOS)# # Fisher's Exact Test for Count Data#
@@ -1313,11 +1315,13 @@ Longest: 24
@@ -1326,5 +1330,7 @@ Longest: 24
+
+